diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 70315fa3..6daef416 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -31,7 +31,9 @@ repos: hooks: - id: mypy name: mypy - entry: uv run --group test mypy src tests + # Type-check against spatialdata pre-releases when they're newer than the latest stable. + # Needs uv >= 0.12.1 for --prerelease-package. + entry: uv run --group test --prerelease-package spatialdata=allow --upgrade-package spatialdata mypy src tests language: system types: [python] files: ^(src|tests)/ diff --git a/docs/conf.py b/docs/conf.py index 0acb81f3..81e1ae7f 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -121,6 +121,15 @@ # This pattern also affects html_static_path and html_extra_path. exclude_patterns = ["_build", "Thumbs.db", ".DS_Store", "**.ipynb_checkpoints"] +# entries for which missing API links are to be ignored +nitpick_ignore = [ + # Add an entry here when a missing link is outside our control. + # type alias used in public signatures, but not part of spatialdata's API docs + ( + "py:obj", + "spatialdata.models.chunks_utils.Chunks_t", + ), +] # -- Options for HTML output ------------------------------------------------- diff --git a/src/spatialdata_io/converters/legacy_anndata.py b/src/spatialdata_io/converters/legacy_anndata.py index 04e4c452..c5a5cf19 100644 --- a/src/spatialdata_io/converters/legacy_anndata.py +++ b/src/spatialdata_io/converters/legacy_anndata.py @@ -14,8 +14,9 @@ ) from spatialdata._core.operations._utils import transform_to_data_extent from spatialdata._logging import logger -from spatialdata.models import Image2DModel, ShapesModel, TableModel, get_table_keys +from spatialdata.models import Image2DModel, ShapesModel, SpatialElement, TableModel, get_table_keys from spatialdata.transformations import Identity, Scale +from xarray import DataArray, DataTree if TYPE_CHECKING: from anndata import AnnData @@ -132,7 +133,7 @@ def to_legacy_anndata( else: assert table_name in sdata.tables, f"The table {table_name} is not present in the SpatialData object." - table = sdata[table_name] + table = sdata.tables[table_name] ( region, _, @@ -141,12 +142,25 @@ def to_legacy_anndata( if not isinstance(region, list): region = [region] - # the table needs to annotate exactly one Shapes element + # the table needs to annotate exactly one Shapes or Labels element if len(region) != 1: - raise ValueError(f"The table needs to annotate exactly one element. Found {len(region)}.") - if region[0] not in sdata.shapes and region[0] not in sdata.labels: - raise ValueError("The table needs to annotate a Shapes or Labels element, not Points.") - element = sdata[region[0]] + raise ValueError(f"The table needs to annotate exactly one element. Found {len(region)}: {region}.") + (region_name,) = region + + element: SpatialElement + if region_name in sdata.shapes: + element = sdata.shapes[region_name] + elif region_name in sdata.labels: + element = sdata.labels[region_name] + elif region_name in sdata.points: + raise ValueError( + f"The table annotates the Points element '{region_name}', but only Shapes or Labels elements are supported." + ) + else: + raise ValueError( + f"The element '{region_name}' annotated by the table '{table_name}' is not present in the SpatialData " + f"object after filtering for the coordinate system '{coordinate_system}'." + ) region_name = region[0] # convert polygons, multipolygons and labels to circles @@ -157,8 +171,9 @@ def to_legacy_anndata( sdata=circles_sdata, spatial_element_names=region_name, table_name=table_name, how="inner", match_rows="left" ) + # the table must not be none # the table after the filtering must not be empty - assert len(new_table) > 0, ( + assert new_table is not None and len(new_table) > 0, ( "The table does not annotate any geometry in the Shapes element. This could also be caused by a mismatch " "between the type of the indices of the geometries and the type of the INSTANCE_KEY column of the table." ) @@ -180,7 +195,7 @@ def to_legacy_anndata( bb = get_extent(sdata_images, coordinate_system=coordinate_system) parameters_dict = {"x": "target_width", "y": "target_height", "z": "target_depth"} - longest_side = max(bb, key=bb.get) + longest_side = max(bb, key=bb.get) # type: ignore[arg-type] parameter_hires = {parameters_dict[longest_side]: DOWNSCALED_HIRES_LENGTH} parameter_lowres = {parameters_dict[longest_side]: DOWNSCALED_LOWRES_LENGTH} downscaled_hires = transform_to_data_extent( @@ -190,13 +205,13 @@ def to_legacy_anndata( sdata_pre_rasterize, coordinate_system=coordinate_system, maintain_positioning=False, **parameter_lowres ) for image_name in sdata_images.images.keys(): - downscaled_images_hires[image_name] = downscaled_hires[image_name] - downscaled_images_lowres[image_name] = downscaled_lowres[image_name] + downscaled_images_hires[image_name] = downscaled_hires.images[image_name] + downscaled_images_lowres[image_name] = downscaled_lowres.images[image_name] if sdata_post_rasterize is None: sdata_post_rasterize = downscaled_hires - adata = sdata_post_rasterize[table_name].copy() + adata = sdata_post_rasterize.tables[table_name].copy() if len(downscaled_images_hires) > 0: for image_name in sdata_images.images.keys(): @@ -217,7 +232,7 @@ def to_legacy_anndata( pass adata.obsm["spatial"] = ( - get_centroids(sdata_post_rasterize[region_name], coordinate_system=coordinate_system).compute().values + get_centroids(sdata_post_rasterize.shapes[region_name], coordinate_system=coordinate_system).compute().values ) return adata @@ -263,7 +278,7 @@ def from_legacy_anndata(adata: AnnData, rgb: bool | None = None) -> SpatialData: INSTANCE_KEY = "instance_id" SPOT_DIAMETER_FULLRES_DEFAULT = 10 - images = {} + images: dict[str, DataArray | DataTree] = {} shapes = {} spot_diameter_fullres_list = [] shapes_transformations = {} diff --git a/src/spatialdata_io/readers/codex.py b/src/spatialdata_io/readers/codex.py index 925ed077..61ca71d1 100644 --- a/src/spatialdata_io/readers/codex.py +++ b/src/spatialdata_io/readers/codex.py @@ -21,6 +21,8 @@ if TYPE_CHECKING: from collections.abc import Mapping + from xarray import DataArray, DataTree + __all__ = ["codex"] @@ -79,7 +81,7 @@ def codex( path_files = [i for i in os.listdir(path) if im_patt.match(i)] if path_files and CodexKeys.IMAGE_TIF in path_files[0]: image = imread(path_files[0], **imread_kwargs) - images = { + images: dict[str, DataArray | DataTree] = { "images": Image2DModel.parse( image, scale_factors=[2, 2], diff --git a/src/spatialdata_io/readers/cosmx.py b/src/spatialdata_io/readers/cosmx.py index 382b0f63..d593a468 100644 --- a/src/spatialdata_io/readers/cosmx.py +++ b/src/spatialdata_io/readers/cosmx.py @@ -134,10 +134,13 @@ def cosmx( assert isinstance(adata_obs, pd.DataFrame) fovs_counts = list(map(str, adata_obs.fov.astype(int).unique())) + table_obs = table.obs + assert isinstance(table_obs, pd.DataFrame) + affine_transforms_to_global = {} for fov in fovs_counts: - idx = table.obs.fov.astype(str) == fov + idx = table_obs.fov.astype(str) == fov loc = table[idx, :].obs[[CosmxKeys.X_LOCAL_CELL, CosmxKeys.Y_LOCAL_CELL]].values glob = table[idx, :].obs[[CosmxKeys.X_GLOBAL_CELL, CosmxKeys.Y_GLOBAL_CELL]].values out = estimate_transform(ttype="affine", src=loc, dst=glob) @@ -148,9 +151,9 @@ def cosmx( output_axes=("x", "y"), ) - table.obsm["global"] = table.obs[[CosmxKeys.X_GLOBAL_CELL, CosmxKeys.Y_GLOBAL_CELL]].to_numpy() - table.obsm["spatial"] = table.obs[[CosmxKeys.X_LOCAL_CELL, CosmxKeys.Y_LOCAL_CELL]].to_numpy() - table.obs.drop( + table.obsm["global"] = table_obs[[CosmxKeys.X_GLOBAL_CELL, CosmxKeys.Y_GLOBAL_CELL]].to_numpy() + table.obsm["spatial"] = table_obs[[CosmxKeys.X_LOCAL_CELL, CosmxKeys.Y_LOCAL_CELL]].to_numpy() + table_obs.drop( columns=[CosmxKeys.X_LOCAL_CELL, CosmxKeys.Y_LOCAL_CELL, CosmxKeys.X_GLOBAL_CELL, CosmxKeys.Y_GLOBAL_CELL], inplace=True, ) diff --git a/src/spatialdata_io/readers/generic.py b/src/spatialdata_io/readers/generic.py index ac2e7e03..8843fe5d 100644 --- a/src/spatialdata_io/readers/generic.py +++ b/src/spatialdata_io/readers/generic.py @@ -1,7 +1,7 @@ from __future__ import annotations from pathlib import Path -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, overload import dask.array as da import numpy as np @@ -11,6 +11,7 @@ from spatialdata._logging import logger from spatialdata.models import Image2DModel, ShapesModel from spatialdata.models._utils import DEFAULT_COORDINATE_SYSTEM +from spatialdata.models.pyramids_utils import ScaleFactors_t from spatialdata.transformations import Identity if TYPE_CHECKING: @@ -19,7 +20,8 @@ from geopandas import GeoDataFrame from numpy.typing import NDArray - from xarray import DataArray + from spatialdata.models.chunks_utils import Chunks_t + from xarray import DataArray, DataTree from spatialdata.models.chunks_utils import normalize_chunks @@ -163,9 +165,41 @@ def _dask_image_imread(input: Path, data_axes: Sequence[str], chunks_cyx: dict[s raise ValueError(f"Expected image with {len(data_axes)} dimensions, got {im.ndim}") im = im.transpose(*[data_axes.index(ax) for ax in ["c", "y", "x"]]) - return im.rechunk((chunks_cyx["c"], chunks_cyx["y"], chunks_cyx["x"])) + return im.rechunk((chunks_cyx["c"], chunks_cyx["y"], chunks_cyx["x"])) # type: ignore[no-any-return] +@overload +def image( + input: Path, + data_axes: Sequence[str], + coordinate_system: str, + use_tiff_memmap: bool = ..., + chunks: Chunks_t | None = ..., + scale_factors: None = ..., +) -> DataArray: ... + + +@overload +def image( + input: Path, + data_axes: Sequence[str], + coordinate_system: str, + use_tiff_memmap: bool = ..., + chunks: Chunks_t | None = ..., + *, + scale_factors: Sequence[int], +) -> DataTree: ... + + +@overload +def image( + input: Path, + data_axes: Sequence[str], + coordinate_system: str, + use_tiff_memmap: bool = ..., + chunks: Chunks_t | None = ..., + scale_factors: Sequence[int] | None = ..., +) -> DataArray | DataTree: ... def image( input: Path, data_axes: Sequence[str], @@ -176,8 +210,8 @@ def image( | tuple[tuple[int, ...], ...] | Mapping[Any, int | tuple[int, ...] | None] | None = None, - scale_factors: Sequence[int] | None = None, -) -> DataArray: + scale_factors: ScaleFactors_t | None = None, +) -> DataArray | DataTree: """Read an image file and returns a parsed Image2D spatial element. Parameters @@ -213,7 +247,7 @@ def image( im = None if input.suffix in [".tiff", ".tif"] and use_tiff_memmap: try: - im_chunks = _tiff_to_chunks(input, axes_dim_mapping=axes_dim_mapping, chunks_cyx=chunks_dict) + im_chunks = _tiff_to_chunks(input, axes_dim_mapping=axes_dim_mapping, chunks_cyx=chunks_dict) # type: ignore[arg-type] im = da.block(im_chunks, allow_unknown_chunksizes=True) # Edge case: Compressed images are not memory-mappable @@ -226,7 +260,7 @@ def image( use_tiff_memmap = False if input.suffix in [".tiff", ".tif"] and not use_tiff_memmap or input.suffix in [".png", ".jpg", ".jpeg"]: - im = _dask_image_imread(input=input, data_axes=data_axes, chunks_cyx=chunks_dict) + im = _dask_image_imread(input=input, data_axes=data_axes, chunks_cyx=chunks_dict) # type: ignore[arg-type] if im is None: raise NotImplementedError(f"File format {input.suffix} not implemented") diff --git a/src/spatialdata_io/readers/iss.py b/src/spatialdata_io/readers/iss.py index b439da20..ec2a161a 100644 --- a/src/spatialdata_io/readers/iss.py +++ b/src/spatialdata_io/readers/iss.py @@ -77,7 +77,7 @@ def iss( REGION_KEY = "region" path = Path(path) - adata = ad.read(path / h5ad_relative_path) + adata = ad.read_h5ad(path / h5ad_relative_path) if instance_key is None: instance_key = "instance_id" adata.obs[instance_key] = adata.obs.index.astype(int) @@ -110,6 +110,6 @@ def iss( sdata = SpatialData( images={f"{dataset_id}_raw_image": raw_image_parsed}, labels={REGION: labels_image_parsed}, - table=table, + tables={"table": table}, ) return _set_reader_metadata(sdata, "iss") diff --git a/src/spatialdata_io/readers/macsima.py b/src/spatialdata_io/readers/macsima.py index 20d9f859..9344a416 100644 --- a/src/spatialdata_io/readers/macsima.py +++ b/src/spatialdata_io/readers/macsima.py @@ -27,6 +27,9 @@ if TYPE_CHECKING: from collections.abc import Mapping + from spatialdata.transformations import BaseTransformation + from xarray import DataArray, DataTree + __all__ = ["macsima"] # Dictionary to harmonize imagetype across metadata versions @@ -889,9 +892,9 @@ def create_image_element( transformations: bool, pixels_to_microns: float, scale_factors: list[int] | None, - coordinate_system: str | None = None, -) -> sd.models.Image2DModel: - t_dict = None + coordinate_system: str, +) -> DataArray | DataTree: + t_dict: dict[str, BaseTransformation] | None = None if transformations: t_pixels_to_microns = sd.transformations.Scale([pixels_to_microns, pixels_to_microns], axes=("x", "y")) # 'microns' is also used in merscope example diff --git a/src/spatialdata_io/readers/mcmicro.py b/src/spatialdata_io/readers/mcmicro.py index 66272e60..380fde64 100644 --- a/src/spatialdata_io/readers/mcmicro.py +++ b/src/spatialdata_io/readers/mcmicro.py @@ -24,6 +24,8 @@ from multiscale_spatial_image.multiscale_spatial_image import MultiscaleSpatialImage from spatial_image import SpatialImage + from spatialdata.transformations import BaseTransformation + from xarray import DataArray, DataTree __all__ = ["mcmicro"] @@ -32,7 +34,7 @@ def _get_transformation( tma: int | None = None, tma_centroids: pd.DataFrame | None = None, raster_data: SpatialImage | MultiscaleSpatialImage | None = None, -) -> dict[str, Identity]: +) -> dict[str, BaseTransformation]: if tma is None: assert tma_centroids is None return {"global": Identity()} @@ -83,7 +85,7 @@ def mcmicro( assert markers.channel_number.is_monotonic_increasing marker_names = markers.marker_name.tolist() - images = {} + images: dict[str, DataArray | DataTree] = {} if tma: centroids_file = path / McmicroKeys.COREOGRAPH_CENTROIDS tma_centroids = pd.read_csv(centroids_file, header=None, names=["y", "x"], index_col=False, sep=" ") @@ -153,7 +155,7 @@ def mcmicro( samples_labels = list((path / McmicroKeys.LABELS_DIR).glob("*/*" + McmicroKeys.IMAGE_SUFFIX)) - labels = {} + labels: dict[str, DataArray | DataTree] = {} for labels_path in samples_labels: if not tma: # TODO: when support python >= 3.9 chance to str.removesuffix(McmicroKeys.IMAGE_SUFFIX) diff --git a/src/spatialdata_io/readers/merscope.py b/src/spatialdata_io/readers/merscope.py index d454d741..8250773e 100644 --- a/src/spatialdata_io/readers/merscope.py +++ b/src/spatialdata_io/readers/merscope.py @@ -28,6 +28,8 @@ if TYPE_CHECKING: from collections.abc import Callable, Mapping + from xarray import DataArray, DataTree + SUPPORTED_BACKENDS = ["dask_image", "rioxarray"] @@ -173,7 +175,7 @@ def merscope( microns_to_pixels = Affine( np.genfromtxt(images_dir / MerscopeKeys.TRANSFORMATION_FILE), input_axes=("x", "y"), output_axes=("x", "y") ) - transformations = {"global": microns_to_pixels} + transformations: dict[str, BaseTransformation] = {"global": microns_to_pixels} vizgen_region = path.name if region_name is None else region_name slide_name = path.parent.name if slide_name is None else slide_name @@ -233,7 +235,7 @@ def merscope( return _set_reader_metadata(sdata, "merscope") -def _get_reader(backend: str | None) -> Callable[..., Image2DModel]: +def _get_reader(backend: str | None) -> Callable[..., DataArray | DataTree]: if backend is not None: return _rioxarray_load_merscope if backend == "rioxarray" else _dask_image_load_merscope # `find_spec` only reports whether the module can be *found*: importing it can still fail, @@ -251,7 +253,7 @@ def _rioxarray_load_merscope( z_layer: int, image_models_kwargs: Mapping[str, Any], **kwargs: Any, -) -> Image2DModel: +) -> DataTree | DataArray: logger.info("Using rioxarray backend.") try: @@ -287,7 +289,7 @@ def _dask_image_load_merscope( z_layer: int, image_models_kwargs: Mapping[str, Any], **kwargs: Any, -) -> Image2DModel: +) -> DataArray | DataTree: im = da.stack( [imread(images_dir / f"mosaic_{stain}_z{z_layer}.tif", **kwargs).squeeze() for stain in stainings], axis=0, diff --git a/src/spatialdata_io/readers/seqfish.py b/src/spatialdata_io/readers/seqfish.py index 31482b7b..7a8fc6a2 100644 --- a/src/spatialdata_io/readers/seqfish.py +++ b/src/spatialdata_io/readers/seqfish.py @@ -32,6 +32,8 @@ if TYPE_CHECKING: from collections.abc import Mapping + from xarray import DataArray, DataTree + __all__ = ["seqfish"] LARGE_IMAGE_THRESHOLD = 100_000_000 @@ -195,8 +197,8 @@ def _get_scale_factors(raster_path: Path, raster_models_scale_factors: list[int] else: return raster_models_scale_factors + images: dict[str, DataArray | DataTree] = {} if load_images: - images = {} for x in rois_str: image_path = path / get_dapi_file(x) scale_factors = _get_scale_factors(image_path, raster_models_scale_factors) @@ -207,11 +209,9 @@ def _get_scale_factors(raster_path: Path, raster_models_scale_factors: list[int] scale_factors=scale_factors, transformations={x: scaled[x]}, ) - else: - images = {} + labels: dict[str, DataArray | DataTree] = {} if load_labels: - labels = {} for x in rois_str: labels_path = path / get_cell_segmentation_labels_file(x) scale_factors = _get_scale_factors(labels_path, raster_models_scale_factors) @@ -222,8 +222,6 @@ def _get_scale_factors(raster_path: Path, raster_models_scale_factors: list[int] scale_factors=scale_factors, transformations={x: scaled[x]}, ) - else: - labels = {} points = {} if load_points: diff --git a/src/spatialdata_io/readers/stereoseq.py b/src/spatialdata_io/readers/stereoseq.py index 58673ae9..e55fe380 100644 --- a/src/spatialdata_io/readers/stereoseq.py +++ b/src/spatialdata_io/readers/stereoseq.py @@ -319,6 +319,8 @@ def stereoseq( zip(x_coords.iterrows(), y_coords.iterrows(), strict=False), desc="creating polygons", total=len(df_coords) ): assert x_index == y_index + # AnnData obs_names are always strings; iterrows() can only type the index labels as Hashable + assert isinstance(x_index, str) and isinstance(y_index, str) # the polygonal cells coordinates are stored as offsets from the centroids, so let's add the centroids x = x_row[x_row != int(SK.PADDING_VALUE)] y = y_row[y_row != int(SK.PADDING_VALUE)] diff --git a/src/spatialdata_io/readers/visium.py b/src/spatialdata_io/readers/visium.py index 9d784121..a3a62cec 100644 --- a/src/spatialdata_io/readers/visium.py +++ b/src/spatialdata_io/readers/visium.py @@ -24,6 +24,8 @@ if TYPE_CHECKING: from collections.abc import Mapping + from xarray import DataTree + __all__ = ["visium"] @@ -223,7 +225,7 @@ def visium( if var_names_make_unique: table.var_names_make_unique() - images = {} + images: dict[str, DataArray | DataTree] = {} if fullres_image_file is not None: fullres_image_file = path / Path(fullres_image_file) if fullres_image_file.exists(): diff --git a/src/spatialdata_io/readers/visium_hd.py b/src/spatialdata_io/readers/visium_hd.py index c0adc433..f6ded767 100644 --- a/src/spatialdata_io/readers/visium_hd.py +++ b/src/spatialdata_io/readers/visium_hd.py @@ -333,7 +333,8 @@ def _get_bins(path_bins: Path) -> list[str]: if not bins_as_squares: shapes[shapes_name] = circles else: - squares_series = circles.buffer(radius, cap_style=3) + squares_series = circles.buffer(radius, cap_style=3) # type: ignore[call-overload] + # `cap_style=3` means square caps shapes[shapes_name] = ShapesModel.parse( GeoDataFrame(geometry=squares_series), transformations=transformations, diff --git a/src/spatialdata_io/readers/xenium.py b/src/spatialdata_io/readers/xenium.py index cd6700dd..aaed49f4 100644 --- a/src/spatialdata_io/readers/xenium.py +++ b/src/spatialdata_io/readers/xenium.py @@ -50,7 +50,8 @@ from collections.abc import Mapping from anndata import AnnData - from spatialdata._types import ArrayLike + from numpy.typing import NDArray + from spatialdata.transformations import BaseTransformation __all__ = ["xenium", "xenium_aligned_image", "xenium_explorer_selection"] @@ -459,7 +460,7 @@ def xenium( # --- read elements --- polygons = {} - labels = {} + labels: dict[str, DataArray | DataTree] = {} points = {} images = {} @@ -526,7 +527,11 @@ def xenium( return _set_reader_metadata(sdata, "xenium") -def _assert_arrays_equal_sampled(a: ArrayLike, b: ArrayLike, n: int = 1000) -> None: +def _assert_arrays_equal_sampled( + a: np.ndarray | pd.api.extensions.ExtensionArray, + b: np.ndarray | pd.api.extensions.ExtensionArray, + n: int = 1000, +) -> None: """Assert two arrays are equal by checking a random sample of entries.""" assert len(a) == len(b), f"Array lengths differ: {len(a)} != {len(b)}" idx = np.random.default_rng(0).choice(len(a), size=min(n, len(a)), replace=False) @@ -1174,6 +1179,7 @@ def xenium_aligned_image( for dim in to_squeeze: image = image.squeeze(dim) + transformation: BaseTransformation if alignment_file is None: transformation = Identity() else: @@ -1280,7 +1286,9 @@ def _parse_version_of_xenium_analyzer( return None -def _cell_id_str_from_prefix_suffix_uint32_reference(cell_id_prefix: ArrayLike, dataset_suffix: ArrayLike) -> ArrayLike: +def _cell_id_str_from_prefix_suffix_uint32_reference( + cell_id_prefix: NDArray[np.integer[Any]], dataset_suffix: NDArray[np.integer[Any]] +) -> NDArray[np.str_]: """Reference implementation of cell_id_str_from_prefix_suffix_uint32. Readable but slow for large arrays due to Python-level string operations. @@ -1305,7 +1313,9 @@ def _cell_id_str_from_prefix_suffix_uint32_reference(cell_id_prefix: ArrayLike, return np.array(cell_id_str) -def cell_id_str_from_prefix_suffix_uint32(cell_id_prefix: ArrayLike, dataset_suffix: ArrayLike) -> ArrayLike: +def cell_id_str_from_prefix_suffix_uint32( + cell_id_prefix: NDArray[np.integer[Any]], dataset_suffix: NDArray[np.integer[Any]] +) -> NDArray[np.str_]: """Convert cell ID prefix/suffix uint32 pairs to the Xenium string representation. Each uint32 prefix is converted to 8 hex nibbles, each mapped to a character @@ -1313,14 +1323,14 @@ def cell_id_str_from_prefix_suffix_uint32(cell_id_prefix: ArrayLike, dataset_suf See https://www.10xgenomics.com/support/software/xenium-onboard-analysis/latest/analysis/xoa-output-zarr#cellID """ - cell_id_prefix = np.asarray(cell_id_prefix, dtype=np.uint32) + cell_id_prefix_uint32 = np.asarray(cell_id_prefix, dtype=np.uint32) dataset_suffix = np.asarray(dataset_suffix) # Extract 8 hex nibbles (4 bits each) from each uint32, most significant first. # Each nibble maps to a character: 0->'a', 1->'b', ..., 9->'j', 10->'k', ..., 15->'p'. # Leading zero nibbles become 'a', equivalent to rjust(8, 'a') padding. shifts = np.array([28, 24, 20, 16, 12, 8, 4, 0], dtype=np.uint32) - nibbles = (cell_id_prefix[:, np.newaxis] >> shifts) & 0xF + nibbles = (cell_id_prefix_uint32[:, np.newaxis] >> shifts) & 0xF char_codes = (nibbles + ord("a")).astype(np.uint8) # View the (n, 8) uint8 array as n byte-strings of length 8 @@ -1331,8 +1341,8 @@ def cell_id_str_from_prefix_suffix_uint32(cell_id_prefix: ArrayLike, dataset_suf def prefix_suffix_uint32_from_cell_id_str( - cell_id_str: ArrayLike, -) -> tuple[ArrayLike, ArrayLike]: + cell_id_str: NDArray[np.str_], +) -> tuple[NDArray[np.uint32], NDArray[np.integer[Any]]]: # parse the string into the prefix and suffix cell_id_prefix_str, dataset_suffix = zip(*[x.split("-") for x in cell_id_str], strict=False) dataset_suffix_int = [int(x) for x in dataset_suffix] diff --git a/tests/converters/test_legacy_anndata.py b/tests/converters/test_legacy_anndata.py index c7268d64..61fa60de 100644 --- a/tests/converters/test_legacy_anndata.py +++ b/tests/converters/test_legacy_anndata.py @@ -1,4 +1,4 @@ -from typing import Literal +from typing import TYPE_CHECKING, Literal import pytest from anndata import AnnData @@ -14,15 +14,18 @@ to_legacy_anndata, ) +if TYPE_CHECKING: + from spatialdata.transformations import BaseTransformation + BlobsTypes = Literal["blobs_labels", "blobs_circles", "blobs_polygons", "blobs_multipolygons"] def blobs_annotating_element(name: BlobsTypes) -> SpatialData: sdata = blobs(length=50) if name == "blobs_labels": - instance_id = get_element_instances(sdata[name]).tolist() + instance_id = get_element_instances(sdata.labels[name]).tolist() else: - instance_id = sdata[name].index.tolist() + instance_id = sdata.shapes[name].index.tolist() n = len(instance_id) new_table = AnnData(shape=(n, 0), obs={"region": [name for _ in range(n)], "instance_id": instance_id}) new_table = TableModel.parse(new_table, region=name, region_key="region", instance_key="instance_id") @@ -39,8 +42,9 @@ def _adjust_table_for_idempotency_check(sdata: SpatialData, include_images: bool CS_NAME = "blobs_multiscale_image_downscaled_hires" sdata = sdata.filter_by_coordinate_system(CS_NAME) sdata.rename_coordinate_systems({CS_NAME: "global"}) - t = get_transformation(sdata["locations"], "global") - set_transformation(sdata["locations"], {"global": t}, set_all=True) + t = get_transformation(sdata.shapes["locations"], "global") + assert isinstance(t, BaseTransformation) + set_transformation(sdata.shapes["locations"], {"global": t}, set_all=True) IMG_NAME = "blobs_multiscale_image_hires_image" im = sdata.images[IMG_NAME] del sdata.images[IMG_NAME] @@ -56,7 +60,7 @@ def idempotency_check_to_anndata(sdata0: SpatialData, include_images: bool) -> N assert_equal(adata0, adata2) -def idempotency_check_from_anndata(adata0: SpatialData, include_images: bool) -> None: +def idempotency_check_from_anndata(adata0: AnnData, include_images: bool) -> None: sdata0 = from_legacy_anndata(adata0) sdata0 = _adjust_table_for_idempotency_check(sdata0, include_images=include_images) adata1 = to_legacy_anndata(sdata0, include_images=include_images) diff --git a/tests/test_generic.py b/tests/test_generic.py index 122f5354..d646254d 100644 --- a/tests/test_generic.py +++ b/tests/test_generic.py @@ -24,14 +24,14 @@ def save_temp_files() -> Generator[tuple[Path, Path, Path], None, None]: with tempfile.TemporaryDirectory() as tmpdir: sdata = blobs() # save the image as jpg - x = sdata["blobs_image"].data.compute() + x = sdata.images["blobs_image"].data.compute() x = np.clip(x * 255, 0, 255).astype(np.uint8).transpose(1, 2, 0) im = Image.fromarray(x) jpg_path = Path(tmpdir) / "blobs_image.jpg" im.save(jpg_path) # save the shapes as geojson - gdf = sdata["blobs_multipolygons"] + gdf = sdata.shapes["blobs_multipolygons"] geojson_path = Path(tmpdir) / "blobs_multipolygons.geojson" gdf.to_file(geojson_path, driver="GeoJSON") @@ -56,7 +56,7 @@ def save_tiff_files( sdata = blobs() # save the image as tiff - x = sdata["blobs_image"].transpose(*axes).data.compute() + x = sdata.images["blobs_image"].transpose(*axes).data.compute() tiff_path = Path(tmpdir) / "blobs_image.tiff" tiffwrite(tiff_path, x, compression=compression) diff --git a/tests/test_macsima.py b/tests/test_macsima.py index b8003b6c..11fbc539 100644 --- a/tests/test_macsima.py +++ b/tests/test_macsima.py @@ -235,7 +235,7 @@ def test_image_size(dataset: str, expected: dict[str, Any]) -> None: f = Path("./data") / dataset assert f.is_dir() sdata = macsima(f, transformations=False) # Do not transform to make it easier to compare against pixel dimensions - el = sdata[list(sdata.images.keys())[0]] + el = sdata.images[list(sdata.images.keys())[0]] cs = sdata.coordinate_systems[0] extent: dict[str, tuple[float, float]] = get_extent(el, coordinate_system=cs) @@ -290,7 +290,7 @@ def test_total_rounds(dataset: str, expected: list[int]) -> None: f = Path("./data") / dataset assert f.is_dir() sdata = macsima(f) - table = sdata[list(sdata.tables)[0]] + table = sdata.tables[list(sdata.tables)[0]] max_cycle = table.var["cycle"].max() assert max_cycle == expected @@ -420,11 +420,11 @@ def test_metadata_table(dataset: str, expected_df: pd.DataFrame) -> None: f = Path("./data") / dataset assert f.is_dir() sdata = macsima(f) - table = sdata[list(sdata.tables.keys())[0]] + table = sdata.tables[list(sdata.tables.keys())[0]] # Convert table.var to a DataFrame and align to expected columns actual = table.var[METADATA_COLUMN_ORDER] - + assert isinstance(actual, pd.DataFrame) pd.testing.assert_frame_equal(actual, expected_df) diff --git a/tests/test_visium.py b/tests/test_visium.py index 3dad176f..a9e87afb 100644 --- a/tests/test_visium.py +++ b/tests/test_visium.py @@ -7,10 +7,12 @@ import pandas as pd import pytest from click.testing import CliRunner +from scipy.sparse import csr_array, csr_matrix from shapely import Point from spatialdata import SpatialData, get_extent, read_zarr from spatialdata.models import ShapesModel, get_table_keys from spatialdata.transformations import get_transformation +from xarray import DataArray from spatialdata_io.__main__ import visium_wrapper from spatialdata_io._constants._constants import VisiumKeys @@ -72,8 +74,9 @@ def test_visium_data_extent(sdata: SpatialData, coordinate_system: str, expected def test_visium_images(sdata: SpatialData) -> None: """The two downscaled images are read as RGB, and each lives in its own coordinate system.""" - hires = sdata[f"{DATASET_ID}_hires_image"] - lowres = sdata[f"{DATASET_ID}_lowres_image"] + hires = sdata.images[f"{DATASET_ID}_hires_image"] + lowres = sdata.images[f"{DATASET_ID}_lowres_image"] + assert isinstance(hires, DataArray) and isinstance(lowres, DataArray) for image in (hires, lowres): assert image.dims == ("c", "y", "x") @@ -92,13 +95,15 @@ def test_visium_images(sdata: SpatialData) -> None: def test_visium_table(sdata: SpatialData) -> None: """The table holds the filtered counts, annotated by the spots.""" - table = sdata["table"] + table = sdata.tables["table"] assert table.shape == (4169, 18085) assert table.obs_names[:3].tolist() == ["AACACTTGGCAAGGAA-1", "AACAGGATTCATAGTT-1", "AACAGGCCAACGATTA-1"] assert table.var_names[:3].tolist() == ["SAMD11", "NOC2L", "KLHL17"] assert table.obs_names.is_unique assert table.var_names.is_unique + assert isinstance(table.obs, pd.DataFrame) + assert isinstance(table.X, (csr_matrix, csr_array)) assert np.array_equal(table.X.indices[:3], [3, 6, 7]) # the spot coordinates are moved to `obsm`, the remaining columns of `tissue_positions` are kept @@ -112,15 +117,18 @@ def test_visium_table(sdata: SpatialData) -> None: def test_visium_circles_are_the_spot_coordinates(sdata: SpatialData, dataset_path: Path) -> None: """The circles are the spot coordinates of the table, in the order of the table.""" - circles = sdata[DATASET_ID] - table = sdata["table"] + circles = sdata.shapes[DATASET_ID] + table = sdata.tables["table"] + assert isinstance(table.obs, pd.DataFrame) + spatial = table.obsm["spatial"] + assert isinstance(spatial, np.ndarray) # ground truth, read independently of the reader and reordered to follow the table positions = pd.read_csv(dataset_path / "spatial" / VisiumKeys.SPOTS_FILE_2, index_col=0) expected = positions.loc[table.obs_names, [VisiumKeys.SPOTS_X, VisiumKeys.SPOTS_Y]].to_numpy() assert np.array_equal(circles.get_coordinates().to_numpy(), expected) - assert np.array_equal(table.obsm["spatial"], expected) + assert np.array_equal(spatial, expected) assert circles.index.tolist() == table.obs["spot_id"].tolist() assert all(isinstance(geometry, Point) for geometry in circles.geometry)