Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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)/
Expand Down
9 changes: 9 additions & 0 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 -------------------------------------------------

Expand Down
43 changes: 29 additions & 14 deletions src/spatialdata_io/converters/legacy_anndata.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
_,
Expand All @@ -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
Expand All @@ -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."
)
Expand All @@ -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(
Expand All @@ -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():
Expand All @@ -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

Expand Down Expand Up @@ -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 = {}
Expand Down
4 changes: 3 additions & 1 deletion src/spatialdata_io/readers/codex.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
if TYPE_CHECKING:
from collections.abc import Mapping

from xarray import DataArray, DataTree

__all__ = ["codex"]


Expand Down Expand Up @@ -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],
Expand Down
11 changes: 7 additions & 4 deletions src/spatialdata_io/readers/cosmx.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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,
)
Expand Down
48 changes: 41 additions & 7 deletions src/spatialdata_io/readers/generic.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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:
Expand All @@ -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
Expand Down Expand Up @@ -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],
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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")
Expand Down
4 changes: 2 additions & 2 deletions src/spatialdata_io/readers/iss.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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")
9 changes: 6 additions & 3 deletions src/spatialdata_io/readers/macsima.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
8 changes: 5 additions & 3 deletions src/spatialdata_io/readers/mcmicro.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]

Expand All @@ -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()}
Expand Down Expand Up @@ -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=" ")
Expand Down Expand Up @@ -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)
Expand Down
10 changes: 6 additions & 4 deletions src/spatialdata_io/readers/merscope.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
if TYPE_CHECKING:
from collections.abc import Callable, Mapping

from xarray import DataArray, DataTree

SUPPORTED_BACKENDS = ["dask_image", "rioxarray"]


Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -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:
Expand Down Expand Up @@ -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,
Expand Down
Loading