Skip to content

Commit 91dd574

Browse files
refactor: Import fewer private modules (#1069)
* fix import * introduce compat * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * fix the rest * add download file func * precommit * unused import * apply type annotations --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 277b192 commit 91dd574

9 files changed

Lines changed: 67 additions & 34 deletions

File tree

src/squidpy/_compat.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
from __future__ import annotations
2+
3+
from importlib.metadata import version
4+
5+
from packaging.version import Version
6+
from scanpy.plotting._tools.scatterplots import _add_categorical_legend as add_categorical_legend
7+
from scanpy.plotting._tools.scatterplots import _panel_grid as panel_grid
8+
from scanpy.plotting._utils import add_colors_for_categorical_sample_annotation
9+
10+
__all__ = [
11+
# scanpy
12+
"set_default_colors_for_categorical_obs",
13+
"add_categorical_legend",
14+
"panel_grid",
15+
"add_colors_for_categorical_sample_annotation",
16+
# anndata
17+
"ArrayView",
18+
"SparseCSCView",
19+
"SparseCSRView",
20+
]
21+
22+
# See https://github.com/scverse/squidpy/issues/1061 for more details
23+
_SET_DEFAULT_COLORS_FOR_CATEGORICAL_OBS_CHANGED = Version(version("scanpy")) >= Version("0.12.0rc1")
24+
25+
if _SET_DEFAULT_COLORS_FOR_CATEGORICAL_OBS_CHANGED:
26+
from scanpy.plotting._utils import _set_default_colors_for_categorical_obs as set_default_colors_for_categorical_obs
27+
else:
28+
from scanpy.plotting._utils import set_default_colors_for_categorical_obs
29+
30+
31+
CAN_USE_SPARSE_ARRAY = Version(version("anndata")) >= Version("0.11.0rc1")
32+
if CAN_USE_SPARSE_ARRAY:
33+
from anndata._core.views import ArrayView
34+
from anndata._core.views import SparseCSCMatrixView as SparseCSCView
35+
from anndata._core.views import SparseCSRMatrixView as SparseCSRView
36+
else:
37+
from anndata._core.views import ArrayView, SparseCSCView, SparseCSRView

src/squidpy/datasets/_10x_datasets.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,9 @@
77
import spatialdata as sd
88
from anndata import AnnData
99
from scanpy import settings
10-
from scanpy._utils import check_presence_download
1110

1211
from squidpy._constants._constants import TenxVersions
13-
from squidpy.datasets._utils import DEFAULT_CACHE_DIR, PathLike, _get_zipped_dataset
12+
from squidpy.datasets._utils import DEFAULT_CACHE_DIR, PathLike, _get_zipped_dataset, download_file
1413

1514
__all__ = ["visium"]
1615

@@ -110,23 +109,20 @@ def visium(
110109

111110
# download spatial data
112111
tar_pth = sample_dir / visium_files.spatial_attrs
113-
check_presence_download(filename=tar_pth, backup_url=url_prefix + visium_files.spatial_attrs)
112+
download_file(filename=tar_pth, backup_url=url_prefix + visium_files.spatial_attrs)
114113
with tarfile.open(tar_pth) as f:
115114
for el in f:
116115
if not (sample_dir / el.name).exists():
117116
f.extract(el, sample_dir)
118117

119118
# download counts
120-
check_presence_download(
119+
download_file(
121120
filename=sample_dir / "filtered_feature_bc_matrix.h5",
122121
backup_url=url_prefix + visium_files.feature_matrix,
123122
)
124123

125124
if include_hires_tiff: # download image
126-
check_presence_download(
127-
filename=sample_dir / "image.tif",
128-
backup_url=url_prefix + visium_files.tif_image,
129-
)
125+
download_file(filename=sample_dir / "image.tif", backup_url=url_prefix + visium_files.tif_image)
130126
return read_visium(
131127
base_dir / sample_id,
132128
source_image_path=base_dir / sample_id / "image.tif",

src/squidpy/datasets/_utils.py

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,11 @@
1010
from typing import Any, TypeAlias
1111

1212
import anndata
13+
import pooch
1314
import spatialdata as sd
1415
from anndata import AnnData
1516
from scanpy import logging as logg
1617
from scanpy import read
17-
from scanpy._utils import check_presence_download
1818

1919
from squidpy.im import ImageContainer
2020

@@ -170,7 +170,7 @@ def _create_signature(self) -> Signature:
170170
)
171171

172172
def _download(self, fpath: PathLike, backup_url: str, **kwargs: Any) -> Any:
173-
check_presence_download(Path(fpath), backup_url)
173+
download_file(filename=Path(fpath), backup_url=backup_url)
174174

175175
img = ImageContainer()
176176
img.add_img(fpath, layer="image", library_id=self.library_id, **kwargs)
@@ -204,10 +204,7 @@ def _get_zipped_dataset(folderpath: Path, dataset_name: str, figshare_id: str) -
204204
if not download_zip.exists():
205205
logg.info(f"Downloading Visium H&E SpatialData to {download_zip}")
206206
try:
207-
check_presence_download(
208-
filename=download_zip,
209-
backup_url=f"https://ndownloader.figshare.com/files/{figshare_id}",
210-
)
207+
download_file(filename=download_zip, backup_url=f"https://ndownloader.figshare.com/files/{figshare_id}")
211208
except Exception as e:
212209
raise RuntimeError(f"Failed to download dataset: {e}") from e
213210

@@ -223,3 +220,16 @@ def _get_zipped_dataset(folderpath: Path, dataset_name: str, figshare_id: str) -
223220
raise RuntimeError(f"Expected extracted data at {extracted_path}, but not found")
224221

225222
return sd.read_zarr(extracted_path)
223+
224+
225+
def download_file(filename: PathLike, backup_url: str) -> None:
226+
"""
227+
Replacement for scanpy._utils.check_presence_download using Pooch.
228+
Saves to the exact local path specified in 'filename'.
229+
"""
230+
pooch.retrieve(
231+
url=backup_url,
232+
known_hash=None,
233+
fname=os.path.basename(filename),
234+
path=os.path.dirname(filename) or ".", # Handles current dir if no folder
235+
)

src/squidpy/gr/_utils.py

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,30 +4,21 @@
44

55
from collections.abc import Hashable, Iterable, Sequence
66
from contextlib import contextmanager
7-
from importlib.metadata import version
87
from typing import TYPE_CHECKING, Any
98

109
import numpy as np
1110
import pandas as pd
1211
from anndata import AnnData
1312
from anndata.utils import make_index_unique
14-
from packaging.version import Version
1513
from pandas import CategoricalDtype
1614
from pandas.api.types import infer_dtype
1715
from scanpy import logging as logg
1816
from scipy.sparse import csc_matrix, csr_matrix, issparse, spmatrix
1917

18+
from squidpy._compat import ArrayView, SparseCSCView, SparseCSRView
2019
from squidpy._docs import d
2120
from squidpy._utils import NDArrayA, _unique_order_preserving
2221

23-
CAN_USE_SPARSE_ARRAY = Version(version("anndata")) >= Version("0.11.0rc1")
24-
if CAN_USE_SPARSE_ARRAY:
25-
from anndata._core.views import ArrayView
26-
from anndata._core.views import SparseCSCMatrixView as SparseCSCView
27-
from anndata._core.views import SparseCSRMatrixView as SparseCSRView
28-
else:
29-
from anndata._core.views import ArrayView, SparseCSCView, SparseCSRView
30-
3122

3223
def _check_tuple_needles(
3324
needles: Sequence[tuple[Any, Any]],

src/squidpy/pl/_color_utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@
1111
from cycler import Cycler, cycler
1212
from matplotlib.colors import ListedColormap, to_hex, to_rgba
1313
from scanpy import logging as logg
14-
from scanpy.plotting._utils import add_colors_for_categorical_sample_annotation
1514

15+
from squidpy._compat import add_colors_for_categorical_sample_annotation
1616
from squidpy._constants._pkg_constants import Key
1717

1818
Palette_t: TypeAlias = str | ListedColormap | None

src/squidpy/pl/_interactive/_utils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,11 @@
77
from matplotlib.colors import to_hex, to_rgb
88
from numba import njit
99
from pandas import CategoricalDtype
10-
from pandas._libs.lib import infer_dtype
10+
from pandas.api.types import infer_dtype
1111
from scanpy import logging as logg
12-
from scanpy.plotting._utils import add_colors_for_categorical_sample_annotation
1312
from scipy.spatial import KDTree
1413

14+
from squidpy._compat import add_colors_for_categorical_sample_annotation
1515
from squidpy._constants._pkg_constants import Key
1616
from squidpy._utils import NDArrayA
1717

src/squidpy/pl/_spatial_utils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,12 +30,12 @@
3030
from pandas import CategoricalDtype
3131
from scanpy import logging as logg
3232
from scanpy import settings as sc_settings
33-
from scanpy.plotting._tools.scatterplots import _add_categorical_legend
3433
from skimage.color import label2rgb
3534
from skimage.morphology import erosion, square
3635
from skimage.segmentation import find_boundaries
3736
from skimage.util import map_array
3837

38+
from squidpy._compat import add_categorical_legend
3939
from squidpy._constants._constants import ScatterShape
4040
from squidpy._constants._pkg_constants import Key
4141
from squidpy._utils import NDArrayA
@@ -665,7 +665,7 @@ def _decorate_axs(
665665
palette=palette,
666666
alpha=alpha,
667667
)
668-
_add_categorical_legend(
668+
add_categorical_legend(
669669
ax,
670670
color_source_vector,
671671
palette=palette,

src/squidpy/pl/_utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
from mpl_toolkits.axes_grid1 import make_axes_locatable
2222
from numba import njit, prange
2323
from pandas import CategoricalDtype
24-
from pandas._libs.lib import infer_dtype
24+
from pandas.api.types import infer_dtype
2525
from pandas.core.dtypes.common import (
2626
is_bool_dtype,
2727
is_integer_dtype,

src/squidpy/pl/_var_by_distance.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,9 @@
1414
from cycler import Cycler
1515
from matplotlib import rcParams
1616
from matplotlib.axes import Axes
17-
from scanpy.plotting._tools.scatterplots import _panel_grid
18-
from scanpy.plotting._utils import _set_default_colors_for_categorical_obs
1917
from scipy.sparse import issparse
2018

19+
from squidpy._compat import panel_grid, set_default_colors_for_categorical_obs
2120
from squidpy._docs import d
2221
from squidpy.pl._utils import save_fig
2322

@@ -99,7 +98,7 @@ def var_by_distance(
9998

10099
# if several variables are plotted, make a panel grid
101100
if isinstance(var, list) and not stack_vars:
102-
fig, grid = _panel_grid(
101+
fig, grid = panel_grid(
103102
hspace=0.25,
104103
wspace=0.75 / rcParams["figure.figsize"][0] + 0.02,
105104
ncols=4,
@@ -174,7 +173,7 @@ def var_by_distance(
174173
elif covariate is not None and not stack_vars:
175174
# make a categorical color palette if none was specified and there are several regplots to be plotted
176175
if isinstance(line_palette, str) or line_palette is None:
177-
_set_default_colors_for_categorical_obs(adata, covariate)
176+
set_default_colors_for_categorical_obs(adata, covariate)
178177
line_palette = adata.uns[covariate + "_colors"]
179178
covariate_instances = df[covariate].unique()
180179

0 commit comments

Comments
 (0)