diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 322793040..4e006078c 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -19,3 +19,8 @@ updates: actions-deps: patterns: - "*" + # docs/tutorials/notebooks -> scverse/spatialdata-tutorials + - package-ecosystem: gitsubmodule + directory: / + schedule: + interval: weekly diff --git a/.github/workflows/autofix.yaml b/.github/workflows/autofix.yaml new file mode 100644 index 000000000..c094ca811 --- /dev/null +++ b/.github/workflows/autofix.yaml @@ -0,0 +1,32 @@ +# The workflow name is mandated by autofix.ci. +# It needs to be a dedicated workflow, as autofix.ci times out on long runs. +name: autofix.ci + +on: + pull_request: + +env: + FORCE_COLOR: "1" + UV_COMPILE_BYTECODE: "1" + +permissions: + contents: read + +jobs: + lint: + name: Pre-commit checks + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + filter: blob:none + persist-credentials: false + - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + with: + enable-cache: true + - run: uv tool install hatch + - name: Run pre-commit hooks + run: uvx prek run --all-files --show-diff-on-failure --color=always + - uses: autofix-ci/action@c5b2d67aa2274e7b5a18224e8171550871fc7e4a # v1.3.4 + if: ${{ !cancelled() }} diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 6cca7d4d7..352b9a2d0 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -17,13 +17,15 @@ jobs: package: runs-on: ubuntu-latest steps: - - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: filter: blob:none fetch-depth: 0 persist-credentials: false - name: Install uv - uses: astral-sh/setup-uv@11f9893b081a58869d3b5fccaea48c9e9e46f990 # v8.3.2 + uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + with: + enable-cache: false - name: Build package run: uv build - name: Check package diff --git a/.github/workflows/build_image.yml b/.github/workflows/build_image.yml index 031f1e480..921004b72 100644 --- a/.github/workflows/build_image.yml +++ b/.github/workflows/build_image.yml @@ -38,7 +38,7 @@ jobs: persist-credentials: false - name: Set up Python - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: "3.x" @@ -83,13 +83,13 @@ jobs: - name: Login to GitHub Container Registry if: ${{ env.skip_build == 'false' }} - uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0 + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - - uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7.3.0 + - uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 if: ${{ env.skip_build == 'false' }} env: IMAGE_TAG: ${{ env.REGISTRY }}/scverse/spatialdata:${{ env.IMAGE_TAG_SUFFIX }} diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index bb5a0bbf7..ced9482bc 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -18,16 +18,16 @@ jobs: contents: read id-token: write # IMPORTANT: this permission is mandatory for trusted publishing steps: - - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: filter: blob:none fetch-depth: 0 persist-credentials: false - name: Install uv - uses: astral-sh/setup-uv@11f9893b081a58869d3b5fccaea48c9e9e46f990 # v8.3.2 + uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 with: enable-cache: false - name: Build package run: uv build - name: Publish package distributions to PyPI - uses: pypa/gh-action-pypi-publish@cef221092ed1bacb1cc03d23a2d87d1d172e277b # v1.14.0 + uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3 diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index 7f92f751b..e8994af8d 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -6,7 +6,7 @@ on: pull_request: branches: [main] schedule: - - cron: "0 5 1,15 * *" + - cron: "0 5 * * 1" # weekly, Monday 05:00 UTC concurrency: group: ${{ github.workflow }}-${{ github.ref }} @@ -23,13 +23,15 @@ jobs: envs: ${{ steps.get-envs.outputs.envs }} steps: - &clone - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: filter: blob:none fetch-depth: 0 persist-credentials: false - &setup-uv - uses: astral-sh/setup-uv@11f9893b081a58869d3b5fccaea48c9e9e46f990 # v8.3.2 + uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + with: + prune-cache: true - name: Get test environments id: get-envs run: | @@ -47,8 +49,8 @@ jobs: test: needs: get-environments permissions: - id-token: write # for codecov OIDC - contents: read + id-token: write # for codecov OIDC + contents: read strategy: fail-fast: false @@ -58,7 +60,8 @@ jobs: name: ${{ matrix.env.label }} (${{ matrix.os }}) runs-on: ${{ matrix.os }} - continue-on-error: ${{ contains(matrix.env.name, 'pre') }} # make "all-green" pass even if pre-release job fails + # Pre-release failures must not block PRs, but scheduled runs should go red (and notify) so upstream breakage is noticed early. + continue-on-error: ${{ contains(matrix.env.name, 'pre') && github.event_name != 'schedule' }} env: UV_PYTHON: ${{ matrix.env.python }} @@ -82,20 +85,11 @@ jobs: uvx hatch run ${{ matrix.env.name }}:cov-report # report visibly uvx hatch run ${{ matrix.env.name }}:coverage xml # create report for upload - name: Upload coverage - uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v7.0.0 + uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1 with: fail_ci_if_error: true use_oidc: true - lint: - name: Pre-commit checks - runs-on: ubuntu-latest - steps: - - *clone - - *setup-uv - - run: uv tool install hatch - - run: uvx prek run --all-files --show-diff-on-failure --color=always - # One required check for branch protection, so it does not need updating whenever the matrix changes. check: name: Tests pass in all hatch environments @@ -103,9 +97,8 @@ jobs: needs: - get-environments - test - - lint runs-on: ubuntu-latest steps: - - uses: re-actors/alls-green@05ac9388f0aebcb5727afa17fcccfecd6f8ec5fe # v1.2.2 - with: - jobs: ${{ toJSON(needs) }} + - uses: re-actors/alls-green@b5b5b37504aa4183270bd3d855c52a67f212be35 # v1.3.0 + with: + jobs: ${{ toJSON(needs) }} diff --git a/.panache.toml b/.panache.toml new file mode 100644 index 000000000..fb9ac1428 --- /dev/null +++ b/.panache.toml @@ -0,0 +1,15 @@ +#:schema https://panache.bz/panache.schema.json +flavor = "myst" +extend-exclude = [".claude/"] + +[format] +wrap = "preserve" +smart-punctuation = "unicode" +tab-stops = "preserve" + +# MyST syntax extensions from `scverse_doc.config.MYST_ENABLE_EXTENSIONS` +[extensions] +myst-colon-fence = true # colon_fence +definition-lists = true # deflist +tex-math-dollars = true # dollarmath, amsmath +raw-html = true # html_image, html_admonition diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 5774a30cf..665a5a957 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -7,18 +7,24 @@ default_stages: minimum_pre_commit_version: 2.16.0 repos: - repo: https://github.com/biomejs/pre-commit - rev: v2.5.10 + rev: v2.6.7 hooks: - id: biome-format exclude: ^\.cruft\.json$ # inconsistent indentation with cruft - file never to be modified manually. groups: [format] + # further file exclusions and other options are configured in biome.jsonc + - repo: https://github.com/jolars/panache-pre-commit + rev: v3.18.0 + hooks: + - id: panache-format + groups: [format] - repo: https://github.com/tox-dev/pyproject-fmt - rev: v2.28.1 + rev: v2.30.6 hooks: - id: pyproject-fmt groups: [format] - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.16.4 + rev: v0.17.5 hooks: - id: ruff-check args: [--fix, --exit-non-zero-on-fix] @@ -39,7 +45,6 @@ repos: rev: v6.0.0 hooks: - id: detect-private-key - - id: check-ast - id: end-of-file-fixer groups: [format] - id: mixed-line-ending @@ -53,7 +58,7 @@ repos: args: [--assume-in-merge] - repo: https://github.com/zizmorcore/zizmor-pre-commit - rev: v1.29.0 + rev: v1.32.0 hooks: - id: zizmor args: [--no-progress, --fix] diff --git a/.readthedocs.yaml b/.readthedocs.yaml index 2f14a7802..ea75699d8 100644 --- a/.readthedocs.yaml +++ b/.readthedocs.yaml @@ -4,7 +4,6 @@ build: os: ubuntu-24.04 tools: python: "3.14" - nodejs: latest jobs: post_checkout: # unshallow so the version can be derived from the git tag diff --git a/.vscode/extensions.json b/.vscode/extensions.json index caaeb4f73..3e5224e31 100644 --- a/.vscode/extensions.json +++ b/.vscode/extensions.json @@ -14,5 +14,6 @@ "editorconfig.editorconfig", "charliermarsh.ruff", "biomejs.biome", + "jolars.panache", ], } diff --git a/.vscode/settings.json b/.vscode/settings.json index e034b91f7..015733be8 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,5 +1,5 @@ { - "[python][json][jsonc]": { + "[python][json][jsonc][yaml][markdown]": { "editor.formatOnSave": true, }, "[python]": { @@ -9,9 +9,12 @@ "source.organizeImports": "always", }, }, - "[json][jsonc]": { + "[json][jsonc][yaml]": { "editor.defaultFormatter": "biomejs.biome", }, + "[markdown]": { + "editor.defaultFormatter": "jolars.panache", + }, "python.analysis.typeCheckingMode": "basic", "python.testing.pytestEnabled": true, "python.testing.pytestArgs": ["-vv", "--color=yes"], diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 000000000..0531a65cd --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,67 @@ +# AGENTS.md + +## Typing guidelines + +- Avoid `typing.cast` and `# type: ignore`, especially as workarounds for narrowing problems; use the style above + instead. If one is truly unavoidable, keep it as narrow as possible and add a comment explaining why + (e.g. `# FIXME: ...`). +- Avoid creating functions that return unions (except if it's something like `T | None`). If a function has different + paths to return different types, it should probably be two functions or at least an overload. + +### Union narrowing style + +Narrow unions by asserting what a value is **not**, then use `typing.assert_type` to state (and have the type checker +verify) what it is: + +```python +from typing import assert_type + +transformation: BaseTransformation | dict = ... + +# Don't +assert isinstance(transformation, BaseTransformation) + +# Do +assert not isinstance(transformation, dict) +assert_type(transformation, BaseTransformation) +``` + +When all branches of a union have been handled, use `typing.assert_never` instead of a generic “should not reach here” +error, so the type checker tells us if a new type is added to the union and not handled: + +```python +from typing import assert_never + +if isinstance(data, DataArray): + ... +elif isinstance(data, DataTree): + ... +else: + assert_never(data) # instead of: raise RuntimeError("Should not reach here") +``` + +#### Why + +Because of Python’s (multiple-)inheritance model, a positive `isinstance` assertion can never be rejected by a type +checker, even when it contradicts the declared type: + +```python +a: int = 123 +assert isinstance(a, list) # accepted; the checker infers `a: ` +``` + +So a positive assertion can silently force a value to a type it should never have. + +#### Examples + +```python +transformations: BaseTransformation | dict[str, BaseTransformation] = get_transformation(element, get_all=True) +assert not isinstance(transformations, BaseTransformation) +assert_type(transformations, dict[str, BaseTransformation]) +``` + +Optional values are already narrowed “negatively”, so keep using `is not None`: + +```python +assert target_depth is not None +``` diff --git a/README.md b/README.md index 616715a46..6c2a815a9 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -![SpatialData banner](https://github.com/scverse/spatialdata/blob/main/docs/_static/img/spatialdata_horizontal.png?raw=true) +![SpatialData banner](https://github.com/scverse/spatialdata/blob/main/docs/_static/img/spatialdata_horizontal.svg?raw=true) # SpatialData: an open and universal framework for processing spatial omics data. @@ -31,33 +31,40 @@ If you like scverse® and want to support our mission, please consider making a The spatialdata project also received support by the Chan Zuckerberg Initiative. +SpatialData is an approved de.NBI service, your feedback helps us improve it. We would appreciate it if you could take a moment to complete [our short user survey][denbi-survey] (2 minutes). +
+      + + +

![SpatialDataOverview](https://github.com/scverse/spatialdata/assets/1120672/cb91071f-12a7-4b8e-9430-2b3a0f65e52f) -- **The library is currently under review.** We expect there to be changes as the community provides feedback. We have an announcement channel for communicating these changes, please see the contact section below. -- The SpatialData storage format is built on top of the [OME-NGFF](https://ngff.openmicroscopy.org/latest/) specification. +- The SpatialData data model and storage format are defined by the [SpatialData specifications](https://spatialdata-spec.scverse.org/); the storage format is built on top of the [OME-NGFF](https://ngff.openmicroscopy.org/latest/) specification. ## Getting started Please refer to the [documentation][link-docs]. In particular: - [API documentation][link-api]. -- [Design doc][link-design-doc] (includes the roadmap). +- [Design doc][link-design-doc] (historical; superseded by the [SpatialData specifications](https://spatialdata-spec.scverse.org/)). - [Example notebooks][link-notebooks]. Another useful resource to get started is the source code of the [`spatialdata-io`](https://github.com/scverse/spatialdata-io) package, which shows example of how to read data from common technologies. ## Installation -Check out the docs for more complete [installation instructions](https://spatialdata.scverse.org/en/stable/installation.html). To get started with the "batteries included" installation, you can install via pip: +Check out the docs for more complete [installation instructions](https://spatialdata.scverse.org/en/stable/installation.html). To get started with the “batteries included” installation, you can install via pip: ```bash pip install "spatialdata[extra]" @@ -98,3 +105,4 @@ Marconato, L., Palla, G., Yamauchi, K.A. et al. SpatialData: an open and univers [link-notebooks]: https://spatialdata.scverse.org/en/stable/tutorials/notebooks/notebooks.html [badge-tests]: https://github.com/scverse/spatialdata/actions/workflows/test.yaml/badge.svg [link-tests]: https://github.com/scverse/spatialdata/actions/workflows/test.yaml +[denbi-survey]: https://www.surveymonkey.de/r/denbi-service?sc=hd-hub&tool=spatialdata diff --git a/benchmarks/README.md b/benchmarks/README.md index 5af8369c5..fb18df7f3 100644 --- a/benchmarks/README.md +++ b/benchmarks/README.md @@ -14,7 +14,7 @@ pip install -e . --group dev --group test --group doc --group benchmark ## Usage -Running all the benchmarks is usually not needed. You run the benchmark using `asv run`. See the [asv documentation](https://asv.readthedocs.io/en/stable/commands.html#asv-run) for interesting arguments, like selecting the benchmarks you're interested in by providing a regex pattern `-b` or `--bench` that links to a function or class method. You can run the benchmark in your current environment with `--python=same`. Some example benchmarks: +Running all the benchmarks is usually not needed. You run the benchmark using `asv run`. See the [asv documentation](https://asv.readthedocs.io/en/stable/commands.html#asv-run) for interesting arguments, like selecting the benchmarks you’re interested in by providing a regex pattern `-b` or `--bench` that links to a function or class method. You can run the benchmark in your current environment with `--python=same`. Some example benchmarks: ### Import time benchmarks diff --git a/biome.jsonc b/biome.jsonc index 731044ba3..dad854d3a 100644 --- a/biome.jsonc +++ b/biome.jsonc @@ -1,7 +1,8 @@ { - "$schema": "https://biomejs.dev/schemas/2.2.0/schema.json", + "$schema": "https://biomejs.dev/schemas/2.6.6/schema.json", "vcs": { "enabled": true, "clientKind": "git", "useIgnoreFile": true }, "formatter": { "useEditorconfig": true }, + "markdown": { "formatter": { "enabled": false } }, // handled by panache "overrides": [ { "includes": ["./.vscode/*.json", "**/*.jsonc"], @@ -19,4 +20,11 @@ "json": { "parser": { "allowComments": true } }, }, ], + "files": { + "includes": [ + "**", + // Claude Code skills and settings, not project source. + "!.claude", + ], + }, } diff --git a/docs/_static/css/custom.css b/docs/_static/css/custom.css index ccb03c738..17485d8de 100644 --- a/docs/_static/css/custom.css +++ b/docs/_static/css/custom.css @@ -15,3 +15,17 @@ div.cell_output table.dataframe { font-size: 0.8em; } + +/* Pages superseded by the SpatialData specifications (design document, interoperability): dim their + sidebar entries (sidebar links already use the muted text color, so lower the opacity on top of it). */ +nav.bd-links li:not(.current) > a[href$="design_doc.html"], +nav.bd-links li:not(.current) > a[href$="interoperability.html"] { + opacity: 0.65; +} + +nav.bd-links li > a[href$="design_doc.html"]:hover, +nav.bd-links li > a[href$="design_doc.html"]:focus-visible, +nav.bd-links li > a[href$="interoperability.html"]:hover, +nav.bd-links li > a[href$="interoperability.html"]:focus-visible { + opacity: 1; +} diff --git a/docs/_static/img/spatialdata_horizontal.png b/docs/_static/img/spatialdata_horizontal.png index 5683233e5..30b14a7e5 100644 Binary files a/docs/_static/img/spatialdata_horizontal.png and b/docs/_static/img/spatialdata_horizontal.png differ diff --git a/docs/_static/img/spatialdata_horizontal.svg b/docs/_static/img/spatialdata_horizontal.svg new file mode 100644 index 000000000..786518784 --- /dev/null +++ b/docs/_static/img/spatialdata_horizontal.svg @@ -0,0 +1,109 @@ + + + SpatialData + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + SpatialData + + + + diff --git a/docs/api/data_formats.md b/docs/api/data_formats.md index 816382508..52657c90f 100644 --- a/docs/api/data_formats.md +++ b/docs/api/data_formats.md @@ -8,11 +8,19 @@ These format subclasses are useful to ensure backward compatibility whenever a m .. autoclass:: CurrentRasterFormat .. autoclass:: RasterFormatV01 +.. autoclass:: RasterFormatV02 +.. autoclass:: RasterFormatV03 .. autoclass:: CurrentShapesFormat .. autoclass:: ShapesFormatV01 .. autoclass:: ShapesFormatV02 +.. autoclass:: ShapesFormatV03 .. autoclass:: CurrentPointsFormat .. autoclass:: PointsFormatV01 +.. autoclass:: PointsFormatV02 .. autoclass:: CurrentTablesFormat .. autoclass:: TablesFormatV01 +.. autoclass:: TablesFormatV02 +.. autoclass:: CurrentSpatialDataContainerFormat +.. autoclass:: SpatialDataContainerFormatV01 +.. autoclass:: SpatialDataContainerFormatV02 ``` diff --git a/docs/api/io.md b/docs/api/io.md index 714f4ab22..39b99461f 100644 --- a/docs/api/io.md +++ b/docs/api/io.md @@ -1,6 +1,6 @@ # Input/Output -To read the data from a specific technology (e.g., Xenium, MERSCOPE, ...), you can +To read the data from a specific technology (e.g., Xenium, MERSCOPE, …), you can use any of the [spatialdata-io readers](https://spatialdata.scverse.org/projects/io/en/stable/api.html). ```{eval-rst} diff --git a/docs/changelog.md b/docs/changelog.md index 89658c92a..87f818afc 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -1,16 +1,4 @@ # Changelog Please refer directly to the [Releases](https://github.com/scverse/spatialdata/releases) section on GitHub, where you can find curated release notes for each release. -For developers, please consult the [contributing guide](https://github.com/scverse/spatialdata/blob/main/docs/contributing.md), which explains how to keep release notes are up-to-date at each release. - -## Unreleased - -### Changed - -- `SpatialData.read()` now only accepts a path or URL (`str`, `Path` or `UPath`) for `file_path`; passing an already-open `zarr.Group` raises a `TypeError`. Use `spatialdata.read_zarr()` to read from a `zarr.Group`. -- `SpatialData.attrs` is now typed as `dict[str, JSONValue]` instead of `dict[Any, Any]`, making explicit the pre-existing invariant that the attrs must be JSON-serializable (they are stored as Zarr attributes). Accordingly, `SpatialData.get_attrs()` is now typed as returning `JSONValue | pd.DataFrame`: the previous annotation did not cover attrs values such as lists, numbers, booleans and `None`, which have always been valid and are returned as-is when `return_as=None`. This is a typing-only change, the runtime behaviour is unchanged. -- `SpatialData.locate_element()` now accepts a table (`AnnData`) in addition to a `SpatialElement`; tables were already located correctly, but the annotation did not allow passing them. This is a typing-only change, the runtime behaviour is unchanged. - -### Fixed - -- Querying a `SpatialData` object with multiple (batched) bounding boxes now raises an explicit `NotImplementedError` instead of failing with an opaque `AssertionError`. Batched queries are supported when querying a `SpatialElement` directly, but not when querying a `SpatialData` object, since that would require returning one `SpatialData` object per bounding box. +For developers, please consult the [contributing guide](https://github.com/scverse/spatialdata/blob/main/docs/contributing.md), which explains how to keep release notes up-to-date at each release. diff --git a/docs/citation.md b/docs/citation.md new file mode 100644 index 000000000..115631941 --- /dev/null +++ b/docs/citation.md @@ -0,0 +1,5 @@ +# Citation + +If you use SpatialData in your work, please cite {cite:t}`marconatoSpatialDataOpenUniversal2024`: + +> Marconato, L., Palla, G., Yamauchi, K.A. et al. SpatialData: an open and universal data framework for spatial omics. *Nature Methods* (2024). doi: [10.1038/s41592-024-02212-x](https://doi.org/10.1038/s41592-024-02212-x). diff --git a/docs/conf.py b/docs/conf.py index ae6e531f6..f97b5d77c 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,121 +1,86 @@ -import shutil import sys from datetime import datetime from importlib.metadata import metadata -from pathlib import Path, PurePosixPath +from pathlib import Path -from sphinxcontrib import katex +from scverse_doc.config import DEFAULTS +from scverse_doc.registry import intersphinx HERE = Path(__file__).parent sys.path.insert(0, str(HERE / "extensions")) sys.path.insert(0, str(HERE / "tutorials" / "notebooks" / "extensions")) - -# -- Project information ----------------------------------------------------- - info = metadata("spatialdata") project = info["Name"] author = info["Author"] copyright = f"{datetime.now():%Y}, {author}" version = info["Version"] urls = dict(pu.split(", ") for pu in info.get_all("Project-URL")) -repository_url = urls["Source"] - +source_repository = urls["Source"] release = info["Version"] bibtex_bibfiles = ["references.bib"] bibtex_reference_style = "author_year" templates_path = ["_templates"] -needs_sphinx = "4.0" - -html_context = { - "display_github": True, # Integrate GitHub - "github_user": "scverse", - "github_repo": project, - "github_version": "main", - "conf_py_path": "/docs/", -} - -# -- General configuration --------------------------------------------------- extensions = [ - "git_ref", # needs to be before scanpydoc.rtd_github_links - "scanpydoc.rtd_github_links", # needs to be before sphinx.ext.linkcode - "myst_nb", - "sphinx_copybutton", - "sphinx.ext.autodoc", - "sphinx.ext.intersphinx", - "sphinx.ext.autosummary", + "scverse_doc", "sphinx.ext.linkcode", - "sphinx.ext.napoleon", "sphinxcontrib.bibtex", - "sphinxcontrib.katex", "sphinx_autodoc_typehints", - "sphinx_design", "IPython.sphinxext.ipython_console_highlighting", - "sphinxext.opengraph", "scverse_misc.sphinx_ext", *[p.stem for p in (HERE / "extensions").glob("*.py")], *[p.stem for p in (HERE / "tutorials" / "notebooks" / "extensions").glob("*.py")], ] -rtd_links_prefix = PurePosixPath("src") - autodoc_default_options = { "members": True, "inherited-members": True, "show-inheritance": True, } - -autosummary_generate = True autodoc_process_signature = True -autodoc_member_order = "groupwise" -default_role = "literal" -napoleon_google_docstring = False -napoleon_numpy_docstring = True -napoleon_include_init_with_doc = False -napoleon_use_rtype = True # having a separate entry generally helps readability -napoleon_use_param = True -myst_heading_anchors = 6 # create anchors for h1-h6 -myst_enable_extensions = [ - "amsmath", - "colon_fence", - "deflist", - "dollarmath", - "html_image", - "html_admonition", -] myst_url_schemes = ("http", "https", "mailto") -nb_output_stderr = "remove" -nb_execution_mode = "off" -nb_merge_streams = True +myst_enable_extensions = [*DEFAULTS.myst_enable_extensions, "substitution"] +myst_substitutions = { + "requires_python": info["Requires-Python"], +} typehints_defaults = "braces" always_use_bars_union = True # use `|` instead of `Union` in types even when building with Python ≤3.14 -source_suffix = { - ".rst": "restructuredtext", - ".ipynb": "myst-nb", - ".myst": "myst-nb", -} - -intersphinx_mapping = { - "python": ("https://docs.python.org/3", None), - "anndata": ("https://anndata.readthedocs.io/en/stable/", None), +intersphinx_mapping = intersphinx() | { "annsel": ("https://annsel.readthedocs.io/en/latest/", None), "dask": ("https://docs.dask.org/en/latest/", None), - "datatree": ("https://datatree.readthedocs.io/en/latest/", None), + "datashader": ("https://datashader.org/", None), "geopandas": ("https://geopandas.org/en/stable/", None), - "numpy": ("https://numpy.org/doc/stable/", None), - "scanpy": ("https://scanpy.readthedocs.io/en/stable/", None), + "ome_zarr": ("https://ome-zarr.readthedocs.io/en/stable/", None), + "pooch": ("https://www.fatiando.org/pooch/latest/", None), "shapely": ("https://shapely.readthedocs.io/en/stable", None), + "torch": ("https://docs.pytorch.org/docs/stable/", None), + "upath": ("https://universal-pathlib.readthedocs.io/en/latest/", None), "xarray": ("https://docs.xarray.dev/en/stable/", None), + "xrspatial": ("https://xarray-spatial.readthedocs.io/en/stable/", None), + "zarr": ("https://zarr.readthedocs.io/en/stable/", None), +} + +xref_overrides = { + # private paths of public objects, as they appear in type annotations + "numpy._typing._array_like.NDArray": ("py:data", "numpy.typing.NDArray"), + "zarr.storage._fsspec.FsspecStore": "zarr.storage.FsspecStore", + "zarr.storage._local.LocalStore": "zarr.storage.LocalStore", + # wrong names in the tutorials notebooks (scverse/spatialdata-tutorials); remove once fixed there + "spatialdata.ops.get_transformation_between_coordinate_systems": ( + "py:func", + "spatialdata.transformations.get_transformation_between_coordinate_systems", + ), + "spatialdata.transformations.Transformation.to_affine_matrix": ( + "py:meth", + "spatialdata.transformations.BaseTransformation.to_affine_matrix", + ), } exclude_patterns = [ - "_build", - "Thumbs.db", - ".DS_Store", - "**.ipynb_checkpoints", + *DEFAULTS.exclude_patterns, "tutorials/notebooks/index.md", "tutorials/notebooks/README.md", "tutorials/notebooks/references.md", @@ -128,34 +93,40 @@ "tutorials/notebooks/notebooks/examples/stereoseq_data/*", ] -nitpicky = False # TODO: solve upstream, then set back to True to warn about broken links. # no solution yet (7.4.7); using the workaround shown here: https://github.com/sphinx-doc/sphinx/issues/12589 + +ogp_image = "_static/img/spatialdata_horizontal.png" + suppress_warnings = [ "autosummary.import_cycle", ] - -# -- Options for HTML output ------------------------------------------------- - -html_theme = "sphinx_book_theme" html_static_path = ["_static"] html_css_files = ["css/custom.css"] html_title = project -html_logo = "_static/img/spatialdata_horizontal.png" - -html_theme_options = { - "repository_url": repository_url, - "use_repository_button": True, - "path_to_docs": "docs/", - "navigation_with_keys": False, - "show_toc_level": 4, -} +html_logo = "_static/img/spatialdata_horizontal.svg" -pygments_style = "default" -katex_prerender = shutil.which(katex.NODEJS_BINARY) is not None +html_theme_options = {"show_toc_level": 4} nitpick_ignore = [ # Add an entry here when a missing link is outside our control. ("py:class", "igraph.Graph"), + # upstream packages without an intersphinx inventory + ("py:class", "multiscale_spatial_image.to_multiscale.to_multiscale.Methods"), + # not in datashader's API docs (only the concrete reductions are) + ("py:class", "datashader.reductions.Reduction"), + # private classes that appear in public signatures and base classes, but are not part of the API docs + ("py:class", "spatialdata._core._elements.Images"), + ("py:class", "spatialdata._core._elements.Labels"), + ("py:class", "spatialdata._core._elements.Points"), + ("py:class", "spatialdata._core._elements.Shapes"), + ("py:class", "spatialdata._core._elements.Tables"), + ("py:class", "spatialdata._core.spatialdata.QueryManager"), + ("py:class", "spatialdata._io.format.CoordinateMixinV01"), + ("py:class", "spatialdata._io.format.PointsAttrsMixinV01"), + ("py:attr", "spatialdata._io._utils.BadFileHandleMethod.ERROR"), + ("py:attr", "spatialdata._io._utils.BadFileHandleMethod.WARN"), + ("py:class", "spatialdata.models.models.RasterSchema"), + ("py:type", "spatialdata._types.JSONValue"), ] diff --git a/docs/contributing.md b/docs/contributing.md index 955333fed..708319043 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -9,8 +9,7 @@ For more extensive tutorials, that also cover the absolute basics, please refer [scientific Python tutorials]: https://learn.scientific-python.org/development/tutorials/ [scanpy developer guide]: https://scanpy.scverse.org/page/dev/ -:::{tip} The *hatch* project manager - +:::{tip} The _hatch_ project manager We highly recommend to familiarize yourself with [`hatch`][hatch]. Hatch is a Python project manager that @@ -20,14 +19,13 @@ Hatch is a Python project manager that - allows to run tasks defined in `pyproject.toml`, e.g. to build documentation. While the project is setup with `hatch` in mind, it is still possible to use different tools to manage dependencies, such as `uv` or `pip`. - ::: [hatch]: https://hatch.pypa.io/latest/ ## Installing dev dependencies -In addition to the packages needed to _use_ this package, you need additional python packages to [run tests](#writing-tests) and [build the documentation](#docs-building). +In addition to the packages needed to *use* this package, you need additional python packages to [run tests](#writing-tests) and [build the documentation](#docs-building). :::::{tab-set} ::::{tab-item} Hatch @@ -46,9 +44,9 @@ hatch run docs:build # defined in the table [tool.hatch.envs.docs] If you are using VS code, install the [hatch-code][] extension. Additionally, make sure that the `vscode-python-environments` extension is installed (should be by default) and `"python.useEnvironmentsExtension": true` is activated in your `settings.json`. -Next, open the "Python Environment Managers" sidebar. +Next, open the “Python Environment Managers” sidebar. You can do so by opening the command palette (Ctrl+Shift+P) and searching for `Python: Focus on Environment Managers View`. -It will show a collapsible list where you can expand "Hatch" and activate an environment by clicking on the checkmark next to it. +It will show a collapsible list where you can expand “Hatch” and activate an environment by clicking on the checkmark next to it. As the main development environment, we recommend to use `hatch-test` with the latest supported Python version. ### Other IDEs @@ -93,8 +91,6 @@ hatch env find hatch-test.py3.14-stable ``` and manually point it to the python binary. - - :::: ::::{tab-item} uv @@ -111,7 +107,6 @@ uv sync --group=test --group=doc --extra=torch ``` The `.venv` directory is typically automatically discovered by IDEs such as VS Code. - :::: ::::{tab-item} Pip @@ -127,7 +122,6 @@ pip install -e . --group dev --group test --group doc ``` The `.venv` directory is typically automatically discovered by IDEs such as VS Code. - :::: ::::: @@ -155,7 +149,7 @@ prek will automatically download all dependencies when it is run for the first t If you didn’t run the checks locally, the `Pre-commit checks` job of the GitHub Actions CI runs them on your pull request and reports any failures. We strongly encourage installing and running the checks locally first to understand their usage. -Finally, most editors have an _autoformat on save_ feature. +Finally, most editors have an *autoformat on save* feature. Consider enabling this option for [ruff][ruff-editors] and [biome][biome-editors]. [pre-commit]: https://pre-commit.com/ @@ -184,7 +178,6 @@ hatch test # test with the highest supported Python version # or hatch test --all # test with all supported Python versions ``` - :::: ::::{tab-item} uv @@ -193,7 +186,6 @@ hatch test --all # test with all supported Python versions ```bash uv run pytest ``` - :::: ::::{tab-item} Pip @@ -203,7 +195,6 @@ uv run pytest source .venv/bin/activate pytest ``` - :::: ::::: @@ -256,16 +247,16 @@ The naming of the tag matters: it determines whether the package is displayed as #### Recommended: create the release via GitHub - Go to the [releases page on GitHub][releases] and press the “Draft a new release” button. - - Press “Choose a tag” and create a new tag. + - Press “Choose a tag” and create a new tag. - Please name the tag with the same string you intend for the release, including the `v` prefix. - Alternatively, go to the [tags page on GitHub][tags], select the latest tag, and press “Create release from tag”. - - Please name the release with the same string used for the tag (including the `v` prefix). + - Please name the release with the same string used for the tag (including the `v` prefix). - Both approaches lead to the same page and view. From there: - - Specify whether the release is a pre-release and whether it should be set as the latest release (use the checkboxes accordingly). + - Specify whether the release is a pre-release and whether it should be set as the latest release (use the checkboxes accordingly). - Fill in the release notes (explained in the next section). - Press “Publish release” to make the release available on GitHub. - The [release workflow][] will then build the package and [upload it to PyPI](https://pypi.org/project/spatialdata/#history) using [trusted publishing][]. - - The workflow may fail; check the [release workflow status badge in the README](https://github.com/scverse/spatialdata/actions/workflows/release.yaml). + - The workflow may fail; check the [release workflow status badge in the README](https://github.com/scverse/spatialdata/actions/workflows/release.yaml). [releases]: https://github.com/scverse/spatialdata/releases [tags]: https://github.com/scverse/spatialdata/tags @@ -349,7 +340,6 @@ If you are interested in automatically running notebooks as part of the continuo hatch run docs:build hatch run docs:open ``` - :::: ::::{tab-item} uv @@ -360,7 +350,6 @@ cd docs uv run sphinx-build -M html . _build -W (xdg-)open _build/html/index.html ``` - :::: ::::{tab-item} Pip @@ -372,7 +361,6 @@ cd docs sphinx-build -M html . _build -W (xdg-)open _build/html/index.html ``` - :::: ::::: diff --git a/docs/design_doc.md b/docs/design_doc.md index faf888858..3fe8c6e3a 100644 --- a/docs/design_doc.md +++ b/docs/design_doc.md @@ -1,14 +1,18 @@ # Design document for `SpatialData` +:::{warning} +**Superseded by the [SpatialData specifications](https://spatialdata-spec.scverse.org/).** The SpatialData data model and storage format are now defined in the [data model](https://spatialdata-spec.scverse.org/data-model.html) and [storage format](https://spatialdata-spec.scverse.org/storage-format.html) specifications. This document is kept for historical purposes and is no longer maintained. Where it disagrees with the specifications, the specifications are authoritative. +::: + This documents defines the specifications and design of SpatialData: an open and interoperable framework for storage and processing of multi-modal spatial omics data. This is meant to be a living document that can be updated as the project evolves. ## Motivation and Scope -Recent advances in molecular profiling technologies allow to measure abundance of RNA and proteins in tissue, at high throughput, multiplexing and resolution. The variety of experimental techniques poses unique challenges in data handling and processing, in particular around data types and size. _SpatialData_ aims at implementing a performant in-memory representation in Python and an on-disk representation based on the Zarr and Parquet data formats and following, when applicable, the OME-NGFF specification. By maximing interoperability, performant implementations and efficient (cloud-based) IO operations, _SpatialData_ aims at laying the foundations for new methods and pipelines for the analysis of spatial omics data. +Recent advances in molecular profiling technologies allow to measure abundance of RNA and proteins in tissue, at high throughput, multiplexing and resolution. The variety of experimental techniques poses unique challenges in data handling and processing, in particular around data types and size. *SpatialData* aims at implementing a performant in-memory representation in Python and an on-disk representation based on the Zarr and Parquet data formats and following, when applicable, the OME-NGFF specification. By maximing interoperability, performant implementations and efficient (cloud-based) IO operations, *SpatialData* aims at laying the foundations for new methods and pipelines for the analysis of spatial omics data. ### Goals -The goals define _what_ SpatialData will be able to do (as opposed to _how_). Goals can have the following priority levels: +The goals define *what* SpatialData will be able to do (as opposed to *how*). Goals can have the following priority levels: - P0: highest priority, required for successful implementation (i.e., must have) - P1: high priority, but not required (i.e., nice to have) @@ -17,65 +21,65 @@ The goals define _what_ SpatialData will be able to do (as opposed to _how_). Go **1. Load data from modern spatial multiomics experiments** - P0. Data can be loaded from the OME-NGFF and saved to OME-NGFF. - - [x] multiscale images and labels, 2d and 3d + - [x] multiscale images and labels, 2d and 3d - [x] point clouds - [x] polygon-shaped regions of interest - [x] circle-shaped regions of interest - [x] tables - [x] graphs - P0. Data can be loaded lazily. - - [x] Images + - [x] Images - [x] Points - [ ] (P1) Shapes https://github.com/scverse/spatialdata/issues/359 - P1. - - [x] Loaded data can be iterated over to generate tiles for multiprocessing and deep learning. + - [x] Loaded data can be iterated over to generate tiles for multiprocessing and deep learning. **2. Align different datasets via affine transformations** - [x] P0. Transformations can be loaded from and written to OME-NGFF. - [x] P0. Identity transformation - [x] P0. Affine transformations. - - [x] scale + - [x] scale - [x] translation - [x] rotation - [x] P0. Support definition of common coordinate systems across datasets (i.e., extrinsic coordinate systems). - [x] P0. Sequence of transformation. - Utils - - [x] P0 permute axis + - [x] P0 permute axis - [ ] P2. non-linear - - [ ] coordinates and displacements + - [ ] coordinates and displacements **3. Performant spatial query of multimodal spatial datasets** - [x] P0. Support querying a multimodal dataset for all data in a specified region (at the cost of creating spatial index every time). - - [x] Arbitrary bounding boxes + - [x] Arbitrary bounding boxes - [x] Polygons or regions of interest (ball, shape) **4. Aggregate observations by regions of interest** - [x] P0. Support aggregation functions with standard summary statistics - - [x] mean + - [x] mean - [x] sum - [x] count - [x] P1. User-defined aggregation function ### Non-goals -- _SpatialData_ is not an analysis library. Instead the aim is to provide an infrastructure to analysis libraries for IO and spatial queries. -- _SpatialData_ is not a format converter. We should not support converting to/from too many formats and instead use OME-NGFF as the interchange format. Nevertheless,[spatialdata-io][] offers a place for some common data conversions (external contributions are highly encouraged). -- _SpatialData_ is based on standard on-disk storage formats (Zarr and Parquet) and on existing specifications (NGFF, AnnData) and uses existing solutions when possible. The resulting storage objects which brings together these technologies defines the _SpatialData on-disk format_, which is described in this document and finely characterized in [this online resource](https://github.com/scverse/spatialdata-notebooks/tree/main/notebooks/developers_resources/storage_format). +- *SpatialData* is not an analysis library. Instead the aim is to provide an infrastructure to analysis libraries for IO and spatial queries. +- *SpatialData* is not a format converter. We should not support converting to/from too many formats and instead use OME-NGFF as the interchange format. Nevertheless,[spatialdata-io][] offers a place for some common data conversions (external contributions are highly encouraged). +- *SpatialData* is based on standard on-disk storage formats (Zarr and Parquet) and on existing specifications (NGFF, AnnData) and uses existing solutions when possible. The resulting storage objects which brings together these technologies defines the *SpatialData on-disk format*, which is described in this document and finely characterized in [this online resource](https://github.com/scverse/spatialdata-notebooks/tree/main/notebooks/developers_resources/storage_format). ## Satellite projects We strongly encourage collaborations and community supports in all of these projects. -- [x] P0. _Visualization_: we are developing a napari plugin for interactive visualization of _SpatialData_ objects @ [napari-spatialdata][]. -- [x] P0. _Raw data IO_: we are implementing readers for raw data of common spatial omics technologies @ [spatialdata-io][]. -- [x] P1. _Static plotting_: a static plotting library for _SpatialData_ @ [spatialdata-plot][]. -- [ ] P2. _Image analysis_: Library to perform image analysis, wrapping common analysis library in python such as skimage. - Once ready, we will deprecate such functionalities in [squidpy][]. -- [ ] P2. _Spatial and graph analysis_: [squidpy][] will be refactor to accept SpatialData objects as input. -- [ ] P2. _Database_: Some form of update on released datasets with updated specs as development progresses. A temporary sandbox where we store downloader and converter scripts for representative datasets is available @ [spatialdata-sandbox][]. +- [x] P0. *Visualization*: we are developing a napari plugin for interactive visualization of *SpatialData* objects @ [napari-spatialdata][]. +- [x] P0. *Raw data IO*: we are implementing readers for raw data of common spatial omics technologies @ [spatialdata-io][]. +- [x] P1. *Static plotting*: a static plotting library for *SpatialData* @ [spatialdata-plot][]. +- [ ] P2. *Image analysis*: Library to perform image analysis, wrapping common analysis library in python such as skimage. + Once ready, we will deprecate such functionalities in [squidpy][]. +- [ ] P2. *Spatial and graph analysis*: [squidpy][] will be refactor to accept SpatialData objects as input. +- [ ] P2. *Database*: Some form of update on released datasets with updated specs as development progresses. A temporary sandbox where we store downloader and converter scripts for representative datasets is available @ [spatialdata-sandbox][]. @@ -89,15 +93,15 @@ We strongly encourage collaborations and community supports in all of these proj ### Terminology -_SpatialData_ is both the name of the Python library as well as the name of the framework (including [spatialdata-io][], [napari-spatialdata][], [spatialdata-plot][]) and the name of the in-memory Python object `SpatialData`. To distinguish between the three, we will use the _italics_ formatting for the _SpatialData_ library and the _SpatialData_ framework (the distinction between them will be clear from the context), and we will use the `code` formatting for the `SpatialData` object. +*SpatialData* is both the name of the Python library as well as the name of the framework (including [spatialdata-io][], [napari-spatialdata][], [spatialdata-plot][]) and the name of the in-memory Python object `SpatialData`. To distinguish between the three, we will use the *italics* formatting for the *SpatialData* library and the *SpatialData* framework (the distinction between them will be clear from the context), and we will use the `code` formatting for the `SpatialData` object. -**_SpatialData_** +***SpatialData*** -The _SpatialData_ library provides a set of specifications and in-memory representations for spatial omics datasets with the goal of unifying spatial omics pipelines and making raw and processed datasets interoperable with browser-based viewers. _SpatialData_ also provides basic operations to query and manipulate such data. The _SpatialData_ specs inherit the OME-NGFF specification for the storage of raster types (images and labels) and for storing several types of metadata. Additional storage requirements not covered by OME-NGFF are described in this document and in [this online resource](https://github.com/scverse/spatialdata-notebooks/tree/main/notebooks/developers_resources/storage_format). _SpatialData_ also implements Python objects to load, save, and interact with spatial data. +The *SpatialData* library provides a set of specifications and in-memory representations for spatial omics datasets with the goal of unifying spatial omics pipelines and making raw and processed datasets interoperable with browser-based viewers. *SpatialData* also provides basic operations to query and manipulate such data. The *SpatialData* specs inherit the OME-NGFF specification for the storage of raster types (images and labels) and for storing several types of metadata. Additional storage requirements not covered by OME-NGFF are described in this document and in [this online resource](https://github.com/scverse/spatialdata-notebooks/tree/main/notebooks/developers_resources/storage_format). *SpatialData* also implements Python objects to load, save, and interact with spatial data. **Elements** -_Elements_ are the building blocks of _SpatialData_ datasets. Each element represents a particular datatype (e.g., raster image, label image, expression table). SpatialData elements are not special classes, but are instead standard scientific Python classes (e.g., `xarray.DataArray`, `AnnData`) with specified metadata. The metadata provides the necessary information for displaying and integrating the different elements (e.g., coordinate systems and coordinate transformations). Elements can either be initialized with valid metadata from disk or from in memory objects (e.g., `numpy` arrays) via _SpatialData_ parser functions. See the Elements section below for a detailed description of the different types of elements. +*Elements* are the building blocks of *SpatialData* datasets. Each element represents a particular datatype (e.g., raster image, label image, expression table). SpatialData elements are not special classes, but are instead standard scientific Python classes (e.g., `xarray.DataArray`, `AnnData`) with specified metadata. The metadata provides the necessary information for displaying and integrating the different elements (e.g., coordinate systems and coordinate transformations). Elements can either be initialized with valid metadata from disk or from in memory objects (e.g., `numpy` arrays) via *SpatialData* parser functions. See the Elements section below for a detailed description of the different types of elements. **`SpatialData`** @@ -107,25 +111,25 @@ The `SpatialData` object contains a set of Elements to be used for analysis. Ele We model a spatial dataset as a composition of distinct elements, of any type. The elements correspond to: -- Pixel-based _Images_, 2D or 3D +- Pixel-based *Images*, 2D or 3D - Regions of interest - - _Shapes_ (circles, polygons, multipolygons), 2D - - Pixel masks (such as segmentation masks), aka _Labels_, 2D, or 3D + - *Shapes* (circles, polygons, multipolygons), 2D + - Pixel masks (such as segmentation masks), aka *Labels*, 2D, or 3D - Points (such as transcript locations, point clouds, ...), 2D or 3D -- _Tables_ of annotations +- *Tables* of annotations Each of these elements should be useful by itself, and in combination with other relevant elements. All elements are stored in the Zarr container in hierarchy store that MAY be flat; currently Zarr hierarchies are not supported, [see here](https://github.com/scverse/spatialdata/issues/340)). -There is no explicit link between elements (e.g. we don't save information equivalent to "this Labels element refers to this Image element"), and one is encouranged to use coordinate systems to semantically group elements together, based on spatial overlap. Coordinate systems are explained later in this document. +There is no explicit link between elements (e.g. we don’t save information equivalent to “this Labels element refers to this Image element”), and one is encouranged to use coordinate systems to semantically group elements together, based on spatial overlap. Coordinate systems are explained later in this document. By decomposing the data model into building blocks (i.e. Elements) we support the storage of any arbitrary combinations of elements, which can be added and modified independently at any moment. #### Assumptions -_SpatialData_ follows the OME-NGFF specifications whenever possible and therefore much of its assumptions are inherited from it. Extra assumptions will be discussed with the OME-NGFF community and adapted to the community-agreed design. The key assumptions are the following: +*SpatialData* follows the OME-NGFF specifications whenever possible and therefore much of its assumptions are inherited from it. Extra assumptions will be discussed with the OME-NGFF community and adapted to the community-agreed design. The key assumptions are the following: -- `Images`, `Labels`, `Points` and `Shapes` MUST have one or more _coordinate systems_ and _coordinate transformations_. -- `Tables` CAN NOT have a _coordinate system_ or _coordinate transforms_. Tables should not contain spatial coordinate: the user can decided to store them there, but they will not be processed by the library and needs to placed in a element and a coordinate system to be recognized by the framework. +- `Images`, `Labels`, `Points` and `Shapes` MUST have one or more *coordinate systems* and *coordinate transformations*. +- `Tables` CAN NOT have a *coordinate system* or *coordinate transforms*. Tables should not contain spatial coordinate: the user can decided to store them there, but they will not be processed by the library and needs to placed in a element and a coordinate system to be recognized by the framework. - `Labels` and `Shapes` are both instances of `Regions`, `Regions` are `Elements`. - Any `Element` MAY be annotated by `Tables`; also `Shapes` and `Points` MAY contain annotations within themselves as additional dataframe columns (e.g. intensity of point spread function of a each point, or gene id). - `Tables` CAN NOT be annotated by other `Tables`. @@ -173,7 +177,7 @@ More precisely, we are using the [spatial-image library][] and [multiscale-spati The coordinate systems and transforms are stored in `spatial_image.SpatialImage.attrs` or in `multiscale_spatial_image.MultiscaleSpatialImage.attrs`. -The xarray coordinates are not saved in the NGFF storage. APIs to take into account for the xarray coordinates, such as converting back and forth between NGFF transformations and xarray coordinates, will be implemented ([see this issue](https://github.com/scverse/spatialdata/issues/308)). In particular, the xarray coordinates will be converted to NGFF transformations before saving the images to disk, and will be reconstructed after reading the data from disk. Supporing the representation of xarray coordinates will allow raster data types to be assigned a coordinate systems; otherwise (as of now) they must be defined in the "pixel space" (this is done implicitly). +The xarray coordinates are not saved in the NGFF storage. APIs to take into account for the xarray coordinates, such as converting back and forth between NGFF transformations and xarray coordinates, will be implemented ([see this issue](https://github.com/scverse/spatialdata/issues/308)). In particular, the xarray coordinates will be converted to NGFF transformations before saving the images to disk, and will be reconstructed after reading the data from disk. Supporing the representation of xarray coordinates will allow raster data types to be assigned a coordinate systems; otherwise (as of now) they must be defined in the “pixel space” (this is done implicitly). @@ -224,15 +228,15 @@ We are considering using the [dask-geopandas library](https://dask-geopandas.rea #### Points -_This representation is still under discussion and it might change. -What is described here is the current implementation. See discussion [here](https://github.com/scverse/spatialdata/issues/233) and [here](https://github.com/scverse/spatialdata/issues/46)._ +*This representation is still under discussion and it might change. +What is described here is the current implementation. See discussion [here](https://github.com/scverse/spatialdata/issues/233) and [here](https://github.com/scverse/spatialdata/issues/46).* Coordinates of points for single molecule data. Each observation is a point, and might have additional information (intensity etc.). Current implementation represent points as a Parquet file and a [`dask.dataframe.DataFrame`](https://docs.dask.org/en/stable/dataframe.html) in memory. The requirements are the following: - The dataframe MUST contains axis name to represent the axes. - - If it's 2D, the axes should be `["x","y"]`. + - If it's 2D, the axes should be `["x","y"]`. - If it's 3D, the axes should be `["x","y","z"]`. - It MUST also contain coordinate transformations in `dask.dataframe.DataFrame().attrs["transform"]`. This information will be saved on-disk in JSON under a `"coordinateTransformations"` key in a `.zattrs` file (Zarr v2), or `zarr.json` file (Zarr v3), in a Zarr Group containing the Element. The specific way this information is stored in disk is described by the NGFF specification (the implementaiton of the latest version of the specs is ongoing). Precisely, the NGFF specification dscribes coordinate transformations for images, but we will reuse it also for Points and Shapes. @@ -240,7 +244,7 @@ Additional information is stored in `dask.dataframe.DataFrame().attrs["spatialda - It MAY also contains `"feature_key"`, that is, the column name of the dataframe that refers to the features. This `Series` MAY be of type `pandas.Categorical`. - It MAY contains additional information in `dask.dataframe.DataFrame().attrs["spatialdata_attrs"]`, specifically: - - `"instance_key"`: the column name of the dataframe where unique instance ids that this point refers to are stored, if available. + - `"instance_key"`: the column name of the dataframe where unique instance ids that this point refers to are stored, if available. #### Table (table of annotations for regions) @@ -252,11 +256,13 @@ Annotations of regions of interest. Each row in this table corresponds to a sing One region table can refer to multiple sets of Regions. But each row can map to only one region in its Regions element. For example, one region table can store annotation for multiple slides, though each slide would have its own label element. - * `region: str | list[str]`: Regions or list of regions this table refers to. - * `region_key: str`: Key in obs which says which Regions container - this obs exists in (e.g. "library_id"). - * `instance_key: str`: Key in obs that says which instance the obs - represents (e.g. "cell_id"). +``` +* `region: str | list[str]`: Regions or list of regions this table refers to. +* `region_key: str`: Key in obs which says which Regions container + this obs exists in (e.g. "library_id"). +* `instance_key: str`: Key in obs that says which instance the obs + represents (e.g. "cell_id"). +``` If any of `region`, `region_key` and `instance_key` are defined, they all MUST be defined. A table not defining them is still allowed, but it will not be mapped to any spatial element. @@ -269,7 +275,7 @@ In `spatialdata-io` we use a consistent naming scheme for the `region_key` and ` - Image `type: Image` - Regions `type: Labels | Shapes` - - Labels `type: Labels` + - Labels `type: Labels` - Shapes `type: Shapes` - Points `type: Points` - Tables `type: Table` @@ -324,7 +330,7 @@ We also have a constraint (that we will relax in the future, [see here](https:// We define classes that follow the NGFF specifications to represent the coordinate systems (class `NgffCoordinateSystem`) and coordinate transformations (classes inheriting from `NgffBaseTransformations`). Anyway, these classes are used only during input and output. For operations we define new classes (inheriting from `BaseTransformation`). -Classes inheriting from `NgffBaseTransformation` are: `NgffIdentity`, `NgffMapAxis`, `NgffTranslation`, `NgffScale`, `NgffAffine`, `NgffRotation`, `NgffSequence`, `NgffByDimension`. The following are not supported: `NgffMapIndex`, `NgffDisplacements`, `NgffCoordinates`, `NgffInverseOf`, `NgffBijection`. In the future these classes could be moved outside _SpatialData_, for instance in [ome-zarr-py](https://github.com/ome/ome-zarr-py). +Classes inheriting from `NgffBaseTransformation` are: `NgffIdentity`, `NgffMapAxis`, `NgffTranslation`, `NgffScale`, `NgffAffine`, `NgffRotation`, `NgffSequence`, `NgffByDimension`. The following are not supported: `NgffMapIndex`, `NgffDisplacements`, `NgffCoordinates`, `NgffInverseOf`, `NgffBijection`. In the future these classes could be moved outside *SpatialData*, for instance in [ome-zarr-py](https://github.com/ome/ome-zarr-py). Classes inheriting from `BaseTransformation` are: `Identity`, `MapAxis`, `Translation`, `Scale`, `Affine`, `Sequence`. @@ -336,11 +342,11 @@ The `NgffBaseTransformations` require full specification of the input and output On the contrary, each `BaseTransformation` is self-defined and does not require the information on coordinate systems. Almost (see below) any transformation can be applied unambiguously to any element and almost any pair of transformations can be chained together. The result is either uniquely defined, either an exception is raised when there is ambiguity. -Precisely, this is performed by "passing through" (keeping unaltered) those axis that are present in an element but not in a transformation, and by ignoring axes that are present in a transformation but not in an element. +Precisely, this is performed by “passing through” (keeping unaltered) those axis that are present in an element but not in a transformation, and by ignoring axes that are present in a transformation but not in an element. For example one can apply a `Scale([2, 3, 4], axes=('x', 'y', 'z'))` to a `cyx` image (the axes `c` is passed through unaltered, and the scaling on `z` is ignored since there is no `z` axis.) -An example of transformation that cannot be applied is an `Affine xy -> xyz` to `xyz` data, since `z` can't be passed through as it is also the output of the transformation. +An example of transformation that cannot be applied is an `Affine xy -> xyz` to `xyz` data, since `z` can’t be passed through as it is also the output of the transformation. To know more about the separation between the two set of classes see [this closed issue](https://github.com/scverse/spatialdata/issues/39), [this other closed issue](https://github.com/scverse/spatialdata/issues/47) and [this merged pr](https://github.com/scverse/spatialdata/pull/100). @@ -355,14 +361,14 @@ See [this notebook](https://github.com/scverse/spatialdata-notebooks/blob/main/n ### Roadmap -This section describes a more detailed timeline of future developments, including also more technical tasks like code refactoring of existing functionalities for improving stability/performance. Compared to the "goal" section above, here we provide an concrete timeline. +This section describes a more detailed timeline of future developments, including also more technical tasks like code refactoring of existing functionalities for improving stability/performance. Compared to the “goal” section above, here we provide an concrete timeline. #### 2024 - [x] Simplify data models - - [x] Use `xarray.DataArray` instead of the subclass `SpatialImage` and `xarray.DataTree` instad of the subclass `MultiscaleSpatialImage` + - [x] Use `xarray.DataArray` instead of the subclass `SpatialImage` and `xarray.DataTree` instad of the subclass `MultiscaleSpatialImage` - [x] More performant disk storage - - [x] Use `geoparquet` for shapes and points + - [x] Use `geoparquet` for shapes and points - [x] Start working on multiple tables - [x] Start working on the transformations refactoring - [x] Finalize multiple tables support @@ -375,7 +381,7 @@ This section describes a more detailed timeline of future developments, includin - [ ] Support Zarr v3 (sharding). - [ ] Remove Dask constraints ([latest `dask-expr` versions are not compatible](https://github.com/dask/dask/issues/11146)). ---- +-------------------------------------------------------------------------------- ### Examples diff --git a/docs/extensions/git_ref.py b/docs/extensions/git_ref.py deleted file mode 100644 index cd78bbd6b..000000000 --- a/docs/extensions/git_ref.py +++ /dev/null @@ -1,73 +0,0 @@ -"""Extension to inject the current git ref into ``html_context["github_version"]``. - -Without this, ``html_context["github_version"]`` is hardcoded and the source links -generated by :mod:`scanpydoc.rtd_github_links` always point at ``main``, so line -numbers on released docs drift away from the code the page documents. - -Adapted from scanpy's ``docs/extensions/git_ref.py``, which injects the ref into -``html_theme_options["repository_branch"]`` instead; ``scanpydoc.rtd_github_links`` -prefers ``html_context`` over ``html_theme_options``, and this project defines the -former, so we set it there. -""" - -from __future__ import annotations - -import os -import re -import subprocess -from functools import lru_cache -from typing import TYPE_CHECKING - -from sphinx.util.typing import ExtensionMetadata - -if TYPE_CHECKING: - from sphinx.application import Sphinx - from sphinx.config import Config - - -def git(*args: str) -> str: - """Run a git command and return the output as a string.""" - return subprocess.check_output(["git", *args]).strip().decode() - - -# https://github.com/DisnakeDev/disnake/blob/7853da70b13fcd2978c39c0b7efa59b34d298186/docs/conf.py#L192 -@lru_cache -def get() -> str | None: - """Get current git reference. - - Uses branch/tag name if found, otherwise uses commit hash. - """ - # On Read the Docs pull request previews, HEAD is a local branch such as - # "external-1185" that does not exist on GitHub, so use the commit instead. - # GitHub serves a pull request's head commit from the base repository, also - # when the branch itself lives on a fork. - if os.environ.get("READTHEDOCS_VERSION_TYPE") == "external" and ( - commit := os.environ.get("READTHEDOCS_GIT_COMMIT_HASH") - ): - return commit - - git_ref = None - try: - git_ref = git("name-rev", "--name-only", "--no-undefined", "HEAD") - git_ref = re.sub(r"^(remotes/[^/]+|tags)/", "", git_ref) - except Exception: # noqa: BLE001 - pass - - # (if no name found or relative ref, use commit hash instead) - if not git_ref or re.search(r"[\^~]", git_ref): - try: - git_ref = git("rev-parse", "HEAD") - except Exception: # noqa: BLE001 - git_ref = "main" - return git_ref - - -def set_ref(app: Sphinx, config: Config): - """`config-inited` hook to set `html_context["github_version"]`.""" - app.config["html_context"]["github_version"] = get() or "main" - - -def setup(app: Sphinx) -> ExtensionMetadata: - """App setup hook.""" - app.connect("config-inited", set_ref) - return ExtensionMetadata(parallel_read_safe=True) diff --git a/docs/extensions/tutorials_edit_link.py b/docs/extensions/tutorials_edit_link.py new file mode 100644 index 000000000..ce83db09f --- /dev/null +++ b/docs/extensions/tutorials_edit_link.py @@ -0,0 +1,29 @@ +"""Point "Edit on GitHub" on tutorial pages at scverse/spatialdata-tutorials. + +The tutorials are a git submodule at ``docs/tutorials/notebooks``, so the default +edit link (``spatialdata/edit//docs/tutorials/notebooks/...``) is a 404. +Edits go to the tutorials' ``main``, not to the pinned commit. +Notebooks open in github.dev, which edits them as cells; GitHub's own editor shows raw JSON. +""" + +from sphinx.application import Sphinx + +PREFIX = "tutorials/notebooks/" +REPO = "scverse/spatialdata-tutorials" + + +def _edit_link(app: Sphinx, pagename: str, templatename: str, context: dict, doctree: object) -> None: + if not pagename.startswith(PREFIX): + return + if context.get("page_source_suffix") == ".ipynb": + base = f"https://github.dev/{REPO}/blob/main/" + else: + base = f"https://github.com/{REPO}/edit/main/" + # pydata-sphinx-theme renders this template lazily; it must contain `file_name`. + context["edit_page_provider_name"] = "GitHub" + context["edit_page_url_template"] = base + "{{ file_name | replace('" + PREFIX + "', '', 1) }}" + + +def setup(app: Sphinx) -> dict[str, bool]: + app.connect("html-page-context", _edit_link) + return {"parallel_read_safe": True, "parallel_write_safe": True} diff --git a/docs/extensions/typed_returns.py b/docs/extensions/typed_returns.py deleted file mode 100644 index 5eefc02a6..000000000 --- a/docs/extensions/typed_returns.py +++ /dev/null @@ -1,31 +0,0 @@ -# code from https://github.com/theislab/scanpy/blob/master/docs/extensions/typed_returns.py -# with some minor adjustment -from __future__ import annotations - -import re - -from sphinx.application import Sphinx -from sphinx.ext.napoleon import NumpyDocstring - - -def _process_return(lines): - for line in lines: - m = re.fullmatch(r"(?P\w+)\s+:\s+(?P[\w.]+)", line) - if m: - # Once this is in scanpydoc, we can use the fancy hover stuff - yield f"-{m['param']} (:class:`~{m['type']}`)" - else: - yield line - - -def _parse_returns_section(self, section): - lines_raw = list(_process_return(self._dedent(self._consume_to_next_section()))) - lines = self._format_block(":returns: ", lines_raw) - if lines and lines[-1]: - lines.append("") - return lines - - -def setup(app: Sphinx): - """Set app.""" - NumpyDocstring._parse_returns_section = _parse_returns_section diff --git a/docs/glossary.md b/docs/glossary.md index 1ee2c98d6..d1e2c6fbd 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -28,7 +28,7 @@ Rasterization is the process of converting data from a vector format (see defini ## ROI -An ROI (_Region of Interest_) is a specific subset of a dataset that highlights an area of particular relevance, such as a niche, cell, or tissue location. For example, an ROI may be defined as a polygon outlining a lymphoid structure. +An ROI (*Region of Interest*) is a specific subset of a dataset that highlights an area of particular relevance, such as a niche, cell, or tissue location. For example, an ROI may be defined as a polygon outlining a lymphoid structure. ## Spatial query @@ -36,11 +36,11 @@ A spatial query subsets the data based on the location of the spatial elements. ## SpatialData Zarr format -An extension of the OME-Zarr format used to represent SpatialData objects on disk. Our aim is to converge the SpatialData Zarr format with the OME-Zarr format, by adapting to future versions of the NGFF specification and by contributing to the development of new features in NGFF. The OME-Zarr format was developed for bioimaging data and therefore and extension of the OME-Zarr format is necessary to accommodate spatial omics data. +An extension of the OME-Zarr format used to represent SpatialData objects on disk, defined by the [SpatialData storage format specification](https://spatialdata-spec.scverse.org/storage-format.html). Our aim is to converge the SpatialData Zarr format with the OME-Zarr format, by adapting to future versions of the NGFF specification and by contributing to the development of new features in NGFF. The OME-Zarr format was developed for bioimaging data and therefore and extension of the OME-Zarr format is necessary to accommodate spatial omics data. ## SpatialElements -_SpatialElements_ are the building blocks of _SpatialData_ datasets, and are split into multiple categories: `images`, `labels`, `shapes` and `points`. SpatialData SpatialElements are not special classes, but are instead standard scientific Python classes (e.g., `xarray.DataArray`, `geopandas.GeoDataFrame`) with specified metadata. The metadata provides the necessary information for displaying and integrating the different elements (e.g., coordinate systems and coordinate transformations). SpatialElements can be annotated by `tables`, which are represented as `anndata.AnnData` objects. Tables are a building block of SpatialData, but are not considered SpatialElements since they do not contain spatial information. +*SpatialElements* are the building blocks of *SpatialData* datasets, and are split into multiple categories: `images`, `labels`, `shapes` and `points`. SpatialData SpatialElements are not special classes, but are instead standard scientific Python classes (e.g., `xarray.DataArray`, `geopandas.GeoDataFrame`) with specified metadata. The metadata provides the necessary information for displaying and integrating the different elements (e.g., coordinate systems and coordinate transformations). SpatialElements can be annotated by `tables`, which are represented as `anndata.AnnData` objects. Tables are a building block of SpatialData, but are not considered SpatialElements since they do not contain spatial information. ## Tables @@ -50,7 +50,7 @@ A building block of SpatialData, represented as `anndata.AnnData` objeets. Table Vector data represents spatial information using geometric shapes such as points, circles, or polygons, each defined by mathematical coordinates. -Vectorization is the process of converting raster data (i.e. pixel-based images) into vector format. For instance, a "raster" cell boundary can be "vectorized" into a polygon represented by the coordinates of the vertices of the polygon. +Vectorization is the process of converting raster data (i.e. pixel-based images) into vector format. For instance, a “raster” cell boundary can be “vectorized” into a polygon represented by the coordinates of the vertices of the polygon. ## Zarr storage diff --git a/docs/index.md b/docs/index.md index 9ad5ca49d..0d6bfab8c 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,15 +1,21 @@ ```{eval-rst} -.. image:: _static/img/spatialdata_horizontal.png +.. image:: _static/img/spatialdata_horizontal.svg :class: dark-light p-2 :alt: SpatialData banner ``` # An open and universal framework for processing spatial omics data. -SpatialData is a data framework, a schema and a serialization format for uni- and multi-modal spatial omics datasets. It is supported by a growing suite of software libraries for performant access, manipulation and analysis in multiple languages, including Python, R and JavaScript. +SpatialData is a data framework, a schema and a serialization format for uni- and multi-modal spatial omics datasets. +It is supported by a growing suite of software libraries for performant access, manipulation and analysis in multiple languages, including Python, R and JavaScript. -This page provides documentation on how to install, use, and extend the core `spatialdata` library. See the links below to learn more about other packages in the SpatialData ecosystem. +The Python `spatialdata` library holds images, segmentation masks, points, shapes and annotation tables together in one {class}`~spatialdata.SpatialData` object, aligned through shared coordinate systems. +It lets you query, crop and aggregate across these elements, read and write the SpatialData Zarr format with lazy access to large data, and exchange data with AnnData, scanpy, squidpy and other tools ({doc}`interoperability`). +This site documents how to install, use and extend it. +See the links below to learn more about the specifications and other packages in the SpatialData ecosystem. + +- [SpatialData specifications](https://spatialdata-spec.scverse.org/): language-independent definitions of SpatialData datasets and their on-disk representation. - `spatialdata-io`: load data from common spatial omics technologies into `spatialdata` ([repository][spatialdata-io-repo], [documentation][spatialdata-io-docs]). - `spatialdata-plot`: Static plotting library for `spatialdata` ([repository][spatialdata-plot-repo], [documentation][spatialdata-plot-docs]). - `napari-spatialdata`: napari plugin for interactive exploration and annotation of `spatialdata` ([repository][napari-spatialdata-repo], [documentation][napari-spatialdata-docs]). @@ -19,20 +25,17 @@ This page provides documentation on how to install, use, and extend the core `sp Please see our publication {cite}`marconatoSpatialDataOpenUniversal2024` for citation and to learn more. :::{note} -With dask >= 2025.2.0, users can get an error as described in [#1077](https://github.com/scverse/spatialdata/issues/1064). While we tried implementing fixes in SpatialData, it can be that -users perform operations on the `Points` data themselves and get this error. In order to prevent it, users can use a context manager we created. +With dask’s partition fusion enabled (the default), user code that operates on multi-partition `Points` dataframes can fail as described in [#1064](https://github.com/scverse/spatialdata/issues/1064) and [dask#12193](https://github.com/dask/dask/issues/12193). +`spatialdata` avoids this internally; for your own operations, wrap them in `spatialdata.disable_dask_tune_optimization`: ```python -from spatialdata import disable_dask_tune_optimization import contextlib -... + +from spatialdata import disable_dask_tune_optimization with disable_dask_tune_optimization() if data.npartitions > 1 else contextlib.nullcontext(): - + ... # your operation on the points dask dataframe ``` - -This will disable dask graph optimization if the dataframe has more than 1 partition and otherwise keep it enabled. This solves -the problem discussed in this [dask issue](https://github.com/dask/dask/issues/12193). We are looking into an upstream fix. ::: [//]: # "numfocus-fiscal-sponsor-attribution" @@ -45,15 +48,11 @@ If you like scverse® and want to support our mission, please consider making a +> -```{eval-rst} -.. note:: - This library is currently under active development. We may make changes to the API between versions as the community provides feedback. To ensure reproducibility, please make note of the version you are developing against. -``` - + ```{eval-rst} .. card:: Installation :link: installation @@ -61,17 +60,17 @@ If you like scverse® and want to support our mission, please consider making a Learn how to install ``spatialdata``. -.. card:: User Guide +.. card:: How-to guides :link: user_guide :link-type: doc - Navigate your way through ``spatialdata`` tutorials. + Get help with common questions and tasks in ``spatialdata``. .. card:: Tutorials :link: tutorials/notebooks/notebooks :link-type: doc - Learn how to use ``spatialdata`` with hands-on examples. + Learn how to use ``spatialdata`` with detailed hands-on examples. .. card:: API :link: api @@ -98,22 +97,50 @@ If you like scverse® and want to support our mission, please consider making a Learn how to contribute to ``spatialdata``. ``` + + +```{toctree} +:caption: Getting started +:hidden: true +:maxdepth: 1 + +installation +quickstart +``` + +```{toctree} +:caption: Guides +:hidden: true +:maxdepth: 1 + +user_guide +tutorials/notebooks/notebooks +``` + +```{toctree} +:caption: Reference +:hidden: true +:maxdepth: 1 + +api +tutorials/notebooks/datasets/README +glossary +SpatialData specifications +design_doc +interoperability +``` ```{toctree} +:caption: Project :hidden: true :maxdepth: 1 -installation.md -user_guide.md -api.md -tutorials/notebooks/notebooks.md -tutorials/notebooks/datasets/README.md -glossary.md -design_doc.md -interoperability.md -contributing.md -changelog.md -references.md +changelog +contributing +citation +references +GitHub +Discourse ``` @@ -123,6 +150,6 @@ references.md [spatialdata-plot-repo]: https://github.com/scverse/spatialdata-plot [napari-spatialdata-docs]: https://spatialdata.scverse.org/projects/napari/en/stable/notebooks/spatialdata.html [spatialdata-io-docs]: https://spatialdata.scverse.org/projects/io/en/stable/ -[spatialdata-plot-docs]: https://spatialdata.scverse.org/projects/plot/en/stable/api.html +[spatialdata-plot-docs]: https://spatialdata.scverse.org/projects/plot/en/stable/ [spatialdata-r-repo]: https://github.com/HelenaLC/spatialdataR [spatialdata-js-repo]: https://github.com/Taylor-CCB-Group/SpatialData.js diff --git a/docs/installation.md b/docs/installation.md index d87f5819d..292ece56f 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -1,13 +1,14 @@ # Installation -`spatialdata` requires Python (the minimum required version is specified in PyPI) to run and the installation time requires a few minutes on a standard desktop computer. +`spatialdata` requires Python {{ requires_python }}. +Installation takes a few minutes on a standard desktop computer. ## PyPI Install `spatialdata` by running: ```bash - pip install spatialdata +pip install spatialdata ``` ## Visualization and readers @@ -74,7 +75,7 @@ Update: currently (Feb 2025), due to particular versions being unavailable on `c ## Docker -A `Dockerfile` is available in the repository; the image that can be built from it contains `spatialdata` (with `torch`), `spatialdata-io` and `spatialdata-plot` (not `napari-spatialdata`)'; the libaries are installed from PyPI. +A `Dockerfile` is available in the repository; the image that can be built from it contains `spatialdata` (with `torch`), `spatialdata-io` and `spatialdata-plot` (not `napari-spatialdata`)’; the libaries are installed from PyPI. To build the image, run: diff --git a/docs/interoperability.md b/docs/interoperability.md index 331450808..8267ccc3f 100644 --- a/docs/interoperability.md +++ b/docs/interoperability.md @@ -1,5 +1,9 @@ # Interoperability +:::{warning} +The list of software that reads and writes SpatialData is now maintained with the SpatialData specifications: see [storage format implementations](https://spatialdata-spec.scverse.org/storage-format-implementations.html) and [implementations of the data model](https://spatialdata-spec.scverse.org/implementations.html). This page may be out of date. +::: + The on-disk representation of SpatialData can be read from other languages. Here we list interfaces for working with SpatialData from your language of choice: ## R @@ -13,4 +17,4 @@ The on-disk representation of SpatialData can be read from other languages. Here ## File format -The SpatialData on-disk format builds on [OME-NGFF](https://ngff.openmicroscopy.org/latest/). See the [design document](design_doc.md) for details of the current on-disk layout. +The SpatialData storage format builds on [OME-NGFF](https://ngff.openmicroscopy.org/latest/). The [SpatialData specifications](https://spatialdata-spec.scverse.org/) define the data model and the on-disk layout, independently of this library; implementations in other languages should follow them. diff --git a/docs/quickstart.md b/docs/quickstart.md new file mode 100644 index 000000000..2b4b41314 --- /dev/null +++ b/docs/quickstart.md @@ -0,0 +1,55 @@ +# Quickstart + +A {class}`~spatialdata.SpatialData` object holds the images, labels, points, shapes and tables of a dataset, aligned through shared coordinate systems. +The example below builds one from scratch out of an image, a segmentation mask and a gene expression table, then crops it to a region of interest (ROI), measures image intensity per cell in the ROI, and writes the ROI to and reads it back from Zarr. + +```python +import anndata as ad +import numpy as np +import pandas as pd + +import spatialdata as sd +from spatialdata.models import Image2DModel, Labels2DModel, TableModel + +rng = np.random.default_rng(0) + +# A 3-channel image (c, y, x) ... +image = rng.random((3, 100, 100)) + +# ... a segmentation mask with three cells, labelled 1, 2, 3 (0 is background) ... +mask = np.zeros((100, 100), dtype=np.int32) +mask[10:30, 10:30] = 1 +mask[40:70, 15:45] = 2 +mask[30:60, 60:90] = 3 + +# ... and a cells x genes expression matrix, one row per cell in the mask. +expression = ad.AnnData( + X=rng.poisson(5, size=(3, 4)).astype(float), + obs=pd.DataFrame({"region": pd.Categorical(["cells"] * 3), "cell_id": [1, 2, 3]}, index=["a", "b", "c"]), + var=pd.DataFrame(index=["GeneA", "GeneB", "GeneC", "GeneD"]), +) + +sdata = sd.SpatialData( + images={"image": Image2DModel.parse(image, dims=("c", "y", "x"))}, + labels={"cells": Labels2DModel.parse(mask, dims=("y", "x"))}, + tables={"table": TableModel.parse(expression, region="cells", region_key="region", instance_key="cell_id")}, +) + +# Crop all elements to a region of interest; the table keeps only the cells inside it. +sdata_ROI = sd.bounding_box_query( + sdata, + axes=("x", "y"), + min_coordinate=[0, 0], + max_coordinate=[50, 50], + target_coordinate_system="global", +) + +# Mean intensity of each image channel per cell in the ROI. +intensities = sd.aggregate(values=sdata_ROI["image"], by=sdata_ROI["cells"], agg_func="mean") + +sdata_ROI.write("my_roi.zarr") +sdata_ROI = sd.read_zarr("my_roi.zarr") +``` + +To load data from a specific technology, see [spatialdata-io](https://spatialdata.scverse.org/projects/io/en/stable/), and to plot it, [spatialdata-plot](https://spatialdata.scverse.org/projects/plot/en/stable/). +For help with common questions and tasks, see {doc}`How-to guides `. For details on functions and classes, see the {doc}`API reference `. diff --git a/docs/references.md b/docs/references.md index 00ad6a6ea..9d9ebd4c5 100644 --- a/docs/references.md +++ b/docs/references.md @@ -1,4 +1,4 @@ -# References +# Bibliography ```{bibliography} :cited: diff --git a/docs/tutorials/notebooks b/docs/tutorials/notebooks index 90c40a721..4cfe92dd2 160000 --- a/docs/tutorials/notebooks +++ b/docs/tutorials/notebooks @@ -1 +1 @@ -Subproject commit 90c40a7212ad79c68065f1415620b855b1716f68 +Subproject commit 4cfe92dd2ae0c0139bcaf93ac2cf7bc8a4b92ab1 diff --git a/docs/user_guide.md b/docs/user_guide.md index 28a19d063..be1240c39 100755 --- a/docs/user_guide.md +++ b/docs/user_guide.md @@ -1,52 +1,42 @@ -# SpatialData User Guide +# How-to guides -Lotte Pollaris, Bishoy Wadie, Friedrich Preusser +::::{card} +:class-card: sd-mb-4 sd-shadow-sm -## Introduction +Authors: {bdg-secondary}`Lotte Pollaris` {bdg-secondary}`Bishoy Wadie` {bdg-secondary}`Friedrich Preusser` +:::: -The SpatialData user guide gives an overview of the SpatialData data framework and its documentation. Based on questions you might have, this guide points you to the correct tutorials. +Looking to do something specific with SpatialData? Check out the FAQs below for quick guides, code snippets and links to in-depth tutorials. If you want to read more about the framework, please have a look at our publication: [Marconato et al.](https://www.nature.com/articles/s41592-024-02212-x) -
-

How can I install SpatialData?

+## Getting started +:::{dropdown} How can I install SpatialData? ``` pip install spatialdata ``` This command installs barebone SpatialData. -For a more detailed description on the installation process including all bells and whistles, see [here](https://spatialdata.scverse.org/en/stable/installation.html). - -
- -
-

I have a SpatialData object—how do I open it and see what's inside?

+For a more detailed description of the installation process including all bells and whistles, see the [installation guide](https://spatialdata.scverse.org/en/stable/installation.html). +::: +:::{dropdown} I have a SpatialData object, how do I open it and see what's inside? ``` -sdata = sd.read_zarr(“your-dataset.zarr") +sdata = sd.read_zarr("your-dataset.zarr") ``` -Please see [this section](https://spatialdata.scverse.org/en/stable/tutorials/notebooks/notebooks/examples/models1.html#reading-spatialdata-zarr-data) that gives more context about how to read in a new zarr file. For a more detailed tutorial that also explains how to explore the different element types within the SpatialData object, see [here](https://spatialdata.scverse.org/en/stable/tutorials/notebooks/notebooks/examples/intro.html). - -
- -
-

How do I create a SpatialData object? -

- -
-

If you have an existing Squidpy object.

+For more details, see [the tutorial section on reading zarr data](https://spatialdata.scverse.org/en/stable/tutorials/notebooks/notebooks/examples/models1.html#reading-spatialdata-zarr-data). Additionaly, see [the introductory tutorial on SpatialData](https://spatialdata.scverse.org/en/stable/tutorials/notebooks/notebooks/examples/intro.html) to understand how to explore the different element types within a SpatialData object. +::: -Please have a look at [this tutorial](https://github.com/scverse/spatialdata-notebooks/blob/main/notebooks%2Fexamples%2Fsdata_from_scratch.ipynb). +::::{dropdown} How do I create a SpatialData object? +:::{dropdown} If you have an existing Squidpy object. +Checkout [the tutorial on creating a SpatialData object from scratch](https://spatialdata.scverse.org/en/stable/tutorials/notebooks/notebooks/examples/sdata_from_scratch.html). +::: -
- -
-

If you want to start from raw files

- -If you don’t have a SpatialData object or corresponding zarr file, you will have to create a SpatialData object to make use of the SpatialData framework. -You can create a SpatialData object directly from your raw files (e.g. CSVs, cell-gene matrix/cell-proteins matrix, images etc.) by using the [spatialdata-io](https://github.com/scverse/spatialdata-io) library that has reader functions for most spatial omics techniques. See [here](https://spatialdata.scverse.org/projects/io/en/latest/) for a list of currently supported technologies. +:::{dropdown} If you want to start from raw files +If you don’t have a SpatialData object or corresponding zarr data on disk, you will have to create a SpatialData object to make use of the SpatialData framework. +You can create a SpatialData object directly from your raw files (e.g. CSVs, cell-gene matrix/cell-proteins matrix, images etc.) by using the [spatialdata-io](https://github.com/scverse/spatialdata-io) library that has reader functions for most spatial omics techniques. See the [list of technologies currently supported by spatialdata-io](https://spatialdata.scverse.org/projects/io/en/latest/). For example, if you have data coming from a MERSCOPE®, just use: @@ -56,31 +46,19 @@ sdata = spatialdata_io.merscope( ) ``` -Please also see [this section](https://spatialdata.scverse.org/en/stable/tutorials/notebooks/notebooks/examples/models1.html#reader-functions-from-spatialdata-io) for a more technical tutorial with more details on how to create a SpatialData object from raw data using io-readers. - -If there is no reader implemented for your data type, please refer to [this section](https://spatialdata.scverse.org/en/stable/tutorials/notebooks/notebooks/examples/models1.html#construct-a-spatialdata-object-from-scratch) to learn about building SpatialData objects from scratch. - -
+For more technical details on creating a SpatialData object from raw data, see [the tutorial section on reader functions from spatialdata-io](https://spatialdata.scverse.org/en/stable/tutorials/notebooks/notebooks/examples/models1.html#reader-functions-from-spatialdata-io). -
-

If you want to play around with existing data.

+If there is no reader implemented for your data type, see [the tutorial section on constructing a SpatialData object from scratch](https://spatialdata.scverse.org/en/stable/tutorials/notebooks/notebooks/examples/models1.html#construct-a-spatialdata-object-from-scratch). +::: +:::: -Please see [here](https://spatialdata.scverse.org/en/stable/tutorials/notebooks/datasets/README.html) for a repository of demo datasets (already available as .zarr) generated with different spatial omics technologies. +:::{dropdown} Do you have datasets I can directly open and play around with? +Yes! Browse our [collection of demo datasets](https://spatialdata.scverse.org/en/stable/tutorials/notebooks/datasets/README.html) (already available as .zarr), generated with different spatial omics technologies. +::: -
-
+## Preparing your data -
-

How can I use SpatialData to analyze my data?

- -SpatialData is **not** intended to analyze data itself, but to provide data infrastucture to efficiently manipulate spatial omics data. If you want to learn more about analyzing spatial omics data, please browse [these other tutorials](https://spatialdata.scverse.org/en/stable/tutorials/notebooks/notebooks.html#external-tutorials) for a demo of how various analysis packages work with SpatialData. - -If you want to see how SpatialData and Squidpy can interact, please have a look [here](https://spatialdata.scverse.org/en/latest/tutorials/notebooks/notebooks/examples/squidpy_integration.html). - -
- -
-

How do I align my images?

+:::{dropdown} How do I align my images? Sometimes, you have multiple images containing information, but they have different pixels size/are rotated/are moved. For instance, you may have a multi-omics dataset with two images, each representing a different modality, but you need to align them within a single object while preserving their respective molecular signals. Here, we explain how you can spatially align(=register) these images. NOTE: SpatialData only allows for affine(=linear) transformations to map images onto each other. Do you know how to align your images (i.e. Do you have a transformation matrix)? @@ -88,22 +66,18 @@ Do you know how to align your images (i.e. Do you have a transformation matrix)? No → Check out our [Landmark annotation tutorial](https://spatialdata.scverse.org/en/stable/tutorials/notebooks/notebooks/examples/alignment_using_landmarks.html) Yes → Check out our [Transformation/coordinate system tutorial](https://spatialdata.scverse.org/en/stable/tutorials/notebooks/notebooks/examples/transformations.html) +::: -
- -
-

How do I annotate my data?

- +::::{dropdown} How do I annotate my data? Annotation can have a lot of meanings. You might want to annotate specific regions in your tissue as tumor, add more details about your cell shapes, group together specific transcripts, include celltype annotations or cell sizes for your cells etc. -
-

How can I spatially annotate regions in my data?

-This is possible within the SpatialData framework, making use of napari, like explained [in this tutorial](https://spatialdata.scverse.org/en/stable/tutorials/notebooks/notebooks/examples/napari_rois.html). +:::{dropdown} How can I interactively annotate regions in my data? +:name: annotate-regions-interactively -
-
-

I have annotated regions in an external tool, how do I add them to SpatialData?

+This is possible within the SpatialData framework, making use of napari, as explained in the [tutorial on ROI annotation with Napari](https://spatialdata.scverse.org/en/stable/tutorials/notebooks/notebooks/examples/napari_rois.html). +::: +:::{dropdown} I have annotated regions in an external tool, how do I add them to SpatialData? If the annotated regions are saved in a geojson, you can add them as follows: ``` @@ -111,46 +85,37 @@ from spatialdata.models import ShapesModel sdata['very_interesting_regions']=ShapesModel.parse('path_to_geojson') ``` -For more details, including information on how to add annotations for these regions, please have a look at [this tutorial](https://spatialdata.scverse.org/en/stable/tutorials/notebooks/notebooks/examples/tables.html). - -
- -
- -

I have cells in my dataset, how do I annotate them? (usage of AnnData)

+For more details, including information on how to add annotations for these regions, see the [tables tutorial](https://spatialdata.scverse.org/en/stable/tutorials/notebooks/notebooks/examples/tables.html). +::: +:::{dropdown} I have cells in my dataset, how do I annotate them? (usage of AnnData) One of the most obvious things to do for spatial omics data is to annotate cells using the [AnnData](https://anndata.readthedocs.io/en/stable/) format (called tables in SpatialData). These tables can contain count/intensity data, all types of annotations, and make it possible to make use of [scanpy](https://scanpy.readthedocs.io/en/stable/) functionality (normalization/clustering/DE calculation). -If you want more technical details on how to create a table from scratch to annotate your shapes/labels/points, you can have a look [here](https://spatialdata.scverse.org/en/stable/tutorials/notebooks/notebooks/examples/models2.html#tables). +For more technical details on how to create a table from scratch to annotate your shapes/labels/points, see [tutorial section on how tables are modeled in SpatialData](https://spatialdata.scverse.org/en/stable/tutorials/notebooks/notebooks/examples/models2.html#tables). +::: +:::: -
- -
- -
-

How do I analyze a spatial subset of my data? -

- -Eventually, you might want to know which cells are present in which region (e.g. 'Are immune cells infiltrating the tumor core?'). +::::{dropdown} How do I select a spatial subset of my data for further investigation? +Eventually, you might want to know which cells are present in which region (e.g. ‘Are immune cells infiltrating the tumor core?’). Therefore, subsampling your data based on spatial coordinates can be helpful. Other examples would be for instance if you want to target your analysis to a specific subregion of the tissue (e.g. tumor core), if you have multiple tissues on one slide, if you want to start small, or if you want to only focus on regions with good tissue quality. -
-

I want to annotate a specific region myself.

- -Please see the previous section ('How do I annotate my data?') and then specifically the section about spatially annotating regions. This will guide you through the process of extracting coordinates, which will be used for spatially subsetting the data. Next, see below. -
- -
-

I know the coordinates of the region I want to subsample.

+:::{dropdown} I want to annotate a specific region myself. +See {ref}`interactively annotating regions ` under ‘How do I annotate my data?’ above. This will guide you through the process of extracting coordinates, which will be used for spatially subsetting the data. Next, see ‘I know the coordinates of the region I want to subsample.’ below. +::: -You will need to perform a spatial query, which filters the data based on spatial coordinates. Please see [this tutorial](https://spatialdata.scverse.org/en/stable/tutorials/notebooks/notebooks/examples/spatial_query.html). +:::{dropdown} I know the coordinates of the region I want to subsample. +You will need to perform a spatial query, which filters the data based on spatial coordinates. See the [spatial query tutorial](https://spatialdata.scverse.org/en/stable/tutorials/notebooks/notebooks/examples/spatial_query.html). +::: +:::: -
+:::{dropdown} How do I summarize/aggregate my data? +You have annotated your object with regions or labels and want to determine which cells or transcripts are present in each area. For example, you may be interested in analyzing the composition of cell types within each region or generating a pseudobulk profile per region or label. Or maybe you just want to know your gene counts per cell. In SpatialData terminology, this corresponds to the **aggregate** function. -
+The method of aggregation depends on the type of elements in your SpatialData object. Learn how to do it in our [Integrate/aggregate signals across spatial layers tutorial](https://spatialdata.scverse.org/en/stable/tutorials/notebooks/notebooks/examples/aggregation.html). +::: -
-

How do I visualize my data?

+## Visualization and Analysis +:::{dropdown} How do I visualize my data? To make data visualization easier for each layer in your SpatialData object, we offer [spatialdata-plot](https://github.com/scverse/spatialdata-plot), a package that enhances SpatialData’s functionality for intuitive and detailed plotting. The standard format for plotting a specific layer follows this syntax: @@ -176,39 +141,28 @@ You can also chain different plots. For example, if you want to plot regions of For more details and examples on visualizing technology-specific datasets, explore our [technology-specific tutorials](https://spatialdata.scverse.org/en/stable/tutorials/notebooks/notebooks.html#technology-specific), which includes examples for various technologies (e.g., Visium-HD, Xenium, etc.). Keep in mind that the visualization methods demonstrated in these tutorials are broadly applicable and not limited to a specific technology. -If you run into scalability issues with your plotting, or everything feels very slow, [this tutorial](https://spatialdata.scverse.org/en/latest/tutorials/notebooks/notebooks/examples/speed_up_illustration.html) might help you out! +If you run into scalability issues with your plotting, or everything feels very slow, [the tutorial on speeding up plotting](https://spatialdata.scverse.org/en/latest/tutorials/notebooks/notebooks/examples/speed_up_illustration.html) might help you out! +::: -
+:::{dropdown} How can I use SpatialData to analyze my data? +SpatialData is **not** intended to analyze data itself, but to provide data infrastructure to efficiently manipulate spatial omics data. If you want to learn more about analyzing spatial omics data, please browse the [documentation section on extenal tools](https://spatialdata.scverse.org/en/stable/tutorials/notebooks/notebooks.html#external-tutorials) for demos of how various analysis packages work with SpatialData. -
-

How do I summarize/aggregate my data?

+To see how SpatialData and Squidpy interact, see the [Squidpy integration tutorial](https://spatialdata.scverse.org/en/latest/tutorials/notebooks/notebooks/examples/squidpy_integration.html). +::: -You have annotated your object with regions or labels and want to determine which cells or transcripts are present in each area. For example, you may be interested in analyzing the composition of cell types within each region or generating a pseudobulk profile per region or label. Or maybe you just want to know your gene counts per cell. In SpatialData terminology, this corresponds to the **aggregate** function. - -The method of aggregation depends on the type of elements in your SpatialData object. Learn how to do it in our [Integrate/aggregate signals across spatial layers tutorial](https://spatialdata.scverse.org/en/stable/tutorials/notebooks/notebooks/examples/aggregation.html). - -
-
- -

SpatialData looks amazing, I want to learn more. Give me all the technical details!

+## Going further +:::{dropdown} SpatialData looks amazing, I want to learn more. Give me all the technical details! Sure, no problem! There is much more to learn about SpatialData. -You want to learn how to combine SpatialData and deep learning? We got you covered [here](https://spatialdata.scverse.org/en/stable/tutorials/notebooks/notebooks/examples/densenet.html). - -If you want to create a labels layer from your shapes (rasterize), a shapes layer from you labels (vectorize, or convert your spot-based data to a labels layer [this tutorial](https://spatialdata.scverse.org/en/stable/tutorials/notebooks/notebooks/examples/labels_shapes_interchangeability.html) might help you out). This is mainly useful to unlock specific functionalities, or speed up calculations. - -Finally here is a more [advanced technical tutorial on transformations](https://spatialdata.scverse.org/en/latest/tutorials/notebooks/notebooks/examples/transformations_advanced.html#other-technical-topics). - -
- -
- -

I am sold, how can I get in touch and contribute to SpatialData? +You want to learn how to combine SpatialData and deep learning? Checkout the [tutorial on deep learning with DenseNet](https://spatialdata.scverse.org/en/stable/tutorials/notebooks/notebooks/examples/densenet.html). -

+If you want to create a labels layer from your shapes (rasterize), a shapes layer from your labels (vectorize), or convert your spot-based data to a labels layer, see the [labels/shapes interchangeability tutorial](https://spatialdata.scverse.org/en/stable/tutorials/notebooks/notebooks/examples/labels_shapes_interchangeability.html). This is mainly useful to unlock specific functionalities, or speed up calculations. -[Here](https://spatialdata.scverse.org/en/stable/contributing.html) is a guide that explains how to contribute to SpatialData as a developer. If you would like to contribute to satellite projects, such as `spatialdata-io`, `spatialdata-plot` etc, please consult the contribution guides also in those repositories. -For larger contributions, and especially regarding new APIs or new design choices, please before writing any code get in touch with us! We are happy to talk via GitHub, via chat or with a call. [In the README](https://github.com/scverse/spatialdata/#contact) you can find multiple ways for reaching out. +Finally, here is a more [advanced technical tutorial on transformations](https://spatialdata.scverse.org/en/latest/tutorials/notebooks/notebooks/examples/transformations_advanced.html#other-technical-topics). +::: -
+:::{dropdown} I am sold, how can I get in touch and contribute to SpatialData? +Thank you for your interest in contributing to SpatialData! The [contributing guide](https://spatialdata.scverse.org/en/stable/contributing.html) explains how to contribute to SpatialData as a developer. If you would like to contribute to satellite projects, such as `spatialdata-io`, `spatialdata-plot` etc, please consult the contribution guides also in those repositories. +For larger contributions, and especially regarding new APIs or new design choices, please before writing any code get in touch with us! We are happy to talk via GitHub, via chat or with a call. The [contact section of the README](https://github.com/scverse/spatialdata/#contact) lists multiple ways of reaching out. +::: diff --git a/pyproject.toml b/pyproject.toml index 4cc02bcb4..c034b9058 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -22,6 +22,7 @@ classifiers = [ "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Programming Language :: Python :: 3.14", + "Programming Language :: Python :: 3.15", "Typing :: Typed", ] dynamic = [ "version" ] @@ -87,20 +88,14 @@ benchmark = [ doc = [ "ipykernel", "ipython>=8.6", - "myst-nb>=1.1", "pandas", - "scanpydoc", + "scverse-doc[full]>=0.4", "scverse-misc[sphinx]>=0.1.2", "sphinx>=8.1", "sphinx-autobuild", "sphinx-autodoc-typehints", - "sphinx-book-theme>=1", - "sphinx-copybutton", - "sphinx-design", "sphinx-pytest", "sphinxcontrib-bibtex>=1", - "sphinxcontrib-katex", - "sphinxext-opengraph", ] typecheck = [ "mypy", @@ -124,6 +119,14 @@ envs.docs.scripts.build = "sphinx-build -M html docs docs/_build -W {args}" envs.docs.scripts.clean = "git clean -fdX -- {args:docs}" envs.docs.scripts.open = "python -m webbrowser -t docs/_build/html/index.html" envs.docs.dependency-groups = [ "doc" ] +envs.hatch-check-code.dependencies = [ "prek" ] +envs.hatch-check-code.scripts.lint-check = "echo 'try `hatch check code --fix`'; false" +envs.hatch-check-code.scripts.lint-fix = "prek run -a --no-group=format --no-group=typecheck" +envs.hatch-check-fmt.dependencies = [ "prek" ] +envs.hatch-check-fmt.scripts.format-check = "echo 'try `hatch check fmt --fix`'; false" +envs.hatch-check-fmt.scripts.format-fix = "prek run -a --group=format --no-group=typecheck" +envs.hatch-check-types.scripts.check = [ "mypy" ] +envs.hatch-check-types.dependency-groups = [ "typecheck", "test" ] envs.hatch-test.matrix = [ # Test the lowest and highest supported Python versions with normal deps { deps = [ "stable" ], python = [ "3.12", "3.14" ] }, @@ -142,14 +145,6 @@ envs.hatch-test.overrides.matrix.deps.extra-dependencies = [ { value = "distributed==2026.3.0", if = [ "min" ] }, ] envs.hatch-test.dependency-groups = [ "dev", "test" ] -envs.hatch-check-fmt.dependencies = [ "prek" ] -envs.hatch-check-fmt.scripts.format-check = "echo 'try `hatch check fmt --fix`'; false" -envs.hatch-check-fmt.scripts.format-fix = "prek run -a --group=format --no-group=typecheck" -envs.hatch-check-code.dependencies = [ "prek" ] -envs.hatch-check-code.scripts.lint-check = "echo 'try `hatch check code --fix`'; false" -envs.hatch-check-code.scripts.lint-fix = "prek run -a --no-group=format --no-group=typecheck" -envs.hatch-check-types.scripts.check = [ "mypy" ] -envs.hatch-check-types.dependency-groups = [ "typecheck", "test" ] # Not part of the CI matrix; run locally with `hatch run test-anndata-pandas:test`. envs.test-anndata-pandas.extra-dependencies = [ "zarr>=3" ] envs.test-anndata-pandas.scripts.test = [ "pip list|grep anndata && pip list|grep pandas && pytest {args}" ] diff --git a/src/spatialdata/_core/centroids.py b/src/spatialdata/_core/centroids.py index 9979b9f20..d17c5525a 100644 --- a/src/spatialdata/_core/centroids.py +++ b/src/spatialdata/_core/centroids.py @@ -47,10 +47,14 @@ def get_centroids( return_background If True, the centroid of the background label (0) is included in the output. + Returns + ------- + The centroids, as a points element (Dask DataFrame) in the given coordinate system. + Notes ----- - For :class:`~shapely.Multipolygon`s, the centroids are the average of the centroids of the polygons that constitute - each :class:`~shapely.Multipolygon`. + For :class:`~shapely.MultiPolygon` geometries, the centroids are the average of the centroids of the polygons that + constitute each :class:`~shapely.MultiPolygon`. """ raise ValueError(f"The object type {type(e)} is not supported.") diff --git a/src/spatialdata/_core/data_extent.py b/src/spatialdata/_core/data_extent.py index 32f05834b..267d2bba0 100644 --- a/src/spatialdata/_core/data_extent.py +++ b/src/spatialdata/_core/data_extent.py @@ -116,17 +116,8 @@ def get_extent( ---------- e The SpatialData object or SpatialElement to compute the extent of. - - Returns - ------- - The bounding box description. - - min_coordinate - The minimum coordinate of the bounding box. - max_coordinate - The maximum coordinate of the bounding box. - axes - The names of the dimensions of the bounding box. + coordinate_system + The coordinate system in which the extent is computed. exact Whether the extent is computed exactly or not. @@ -145,6 +136,10 @@ def get_extent( elements If not `None`, only the elements with the given names are included in the computation of the extent. + Returns + ------- + The bounding box description: a dictionary mapping each axis name to its `(min, max)` extent. + Notes ----- The extent of a `SpatialData` object is the extent of the union of the extents of all its elements. @@ -178,20 +173,7 @@ def _( has_shapes: bool = True, elements: list[str] | None = None, ) -> BoundingBoxDescription: - """ - Get the extent (bounding box) of a SpatialData object. - - The resulting extent is the union of the extents of all its elements. - - Parameters - ---------- - e - The SpatialData object. - - Returns - ------- - The bounding box description. - """ + """Get the extent of a SpatialData object (the union of the extents of its elements); see :func:`get_extent`.""" new_min_coordinates_dict: dict[str, list[float]] = defaultdict(list) new_max_coordinates_dict: dict[str, list[float]] = defaultdict(list) mask = [has_images, has_labels, has_points, has_shapes] @@ -256,20 +238,7 @@ def _get_extent_of_shapes(e: GeoDataFrame) -> BoundingBoxDescription: @get_extent.register def _(e: GeoDataFrame, coordinate_system: str = "global", exact: bool = True) -> BoundingBoxDescription: - """ - Get the extent (bounding box) of a SpatialData object. - - The resulting extent is the union of the extents of all its elements. - - Parameters - ---------- - e - The SpatialData object. - - Returns - ------- - The bounding box description. - """ + """Get the extent of a shapes element; see :func:`get_extent`.""" _check_element_has_coordinate_system(element=e, coordinate_system=coordinate_system) if not exact: extent = _get_extent_of_shapes(e) diff --git a/src/spatialdata/_core/operations/aggregate.py b/src/spatialdata/_core/operations/aggregate.py index b4772df1b..550c2f48c 100644 --- a/src/spatialdata/_core/operations/aggregate.py +++ b/src/spatialdata/_core/operations/aggregate.py @@ -20,6 +20,7 @@ from spatialdata._core.query.relational_query import get_values from spatialdata._core.spatialdata import SpatialData from spatialdata._types import ArrayLike +from spatialdata._utils import get_pyramid_levels from spatialdata.models import Image2DModel, Labels2DModel, PointsModel, ShapesModel, TableModel, get_model from spatialdata.transformations import BaseTransformation, Identity, get_transformation @@ -73,7 +74,7 @@ def aggregate( Defaults to `FEATURE_KEY` for points (if present). agg_func Aggregation function to apply over point values, e.g. `"mean"`, `"sum"`, `"count"`. - Passed to :func:`pandas.DataFrame.groupby.agg` or to :func:`xrspatial.zonal_stats` + Passed to :meth:`pandas.api.typing.DataFrameGroupBy.agg` or to :func:`xrspatial.zonal.stats` according to the type of `values`. target_coordinate_system Coordinate system to transform to before aggregating. @@ -108,7 +109,7 @@ def aggregate( Resolution parameter to pass to the of the .buffer() method to convert circles to polygons. A higher value results in a more accurate representation of the circle, but also in a more complex polygon and computation. kwargs - Additional keyword arguments to pass to :func:`xrspatial.zonal_stats`. + Additional keyword arguments to pass to :func:`xrspatial.zonal.stats`. Returns ------- @@ -230,7 +231,13 @@ def _create_sdata_from_table_and_regions( ) -> SpatialData: from spatialdata._core._deepcopy import deepcopy as _deepcopy - shapes_index_dtype = shapes.index.dtype if isinstance(shapes, GeoDataFrame) else shapes.dtype + if isinstance(shapes, GeoDataFrame): + shapes_index_dtype = shapes.index.dtype + elif isinstance(shapes, DataTree): + # multiscale labels: every scale has the dtype of the full-resolution one + shapes_index_dtype = get_pyramid_levels(shapes, attr="dtype", n=0) + else: + shapes_index_dtype = shapes.dtype try: table.obs[instance_key] = table.obs_names.copy().astype(shapes_index_dtype) except ValueError as err: @@ -273,9 +280,9 @@ def _aggregate_image_by_labels( Regions to aggregate by. agg_func Aggregation function to apply over point values, e.g. "mean", "sum", "count" - from :func:`xrspatial.zonal_stats`. + from :func:`xrspatial.zonal.stats`. kwargs - Additional keyword arguments to pass to :func:`xrspatial.zonal_stats`. + Additional keyword arguments to pass to :func:`xrspatial.zonal.stats`. Returns ------- @@ -366,6 +373,14 @@ def _aggregate_shapes( Aggregation function to apply over grouped values. Passed to pandas.DataFrame.groupby.agg. table_name Name of the table optionally containing the value_key column. + fractions + Whether to weight the values by the fraction of the `values` region overlapping the `by` region. + buffer_resolution + Resolution parameter passed to the `.buffer()` method when converting circles to polygons. + + Returns + ------- + An AnnData object with one row per region in `by` and the aggregated values as columns. """ from spatialdata._core.operations.vectorize import to_polygons from spatialdata.models import points_dask_dataframe_to_geopandas diff --git a/src/spatialdata/_core/operations/map.py b/src/spatialdata/_core/operations/map.py index b0738dbff..e4ab63afe 100644 --- a/src/spatialdata/_core/operations/map.py +++ b/src/spatialdata/_core/operations/map.py @@ -46,7 +46,7 @@ def map_raster( Parameters ---------- data - The data to process. It can be a :class:`xarray.DataArray` or :class:`datatree.DataTree`. + The data to process. It can be a :class:`xarray.DataArray` or :class:`xarray.DataTree`. If it's a `DataTree`, the callable is applied to the first scale (`scale0`, the full-resolution data). func The callable that is applied to the data. diff --git a/src/spatialdata/_core/operations/rasterize.py b/src/spatialdata/_core/operations/rasterize.py index 113d26fc7..071f1e108 100644 --- a/src/spatialdata/_core/operations/rasterize.py +++ b/src/spatialdata/_core/operations/rasterize.py @@ -1,11 +1,12 @@ from __future__ import annotations -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, NamedTuple, assert_never, assert_type, cast import numpy as np from dask.array import Array as DaskArray from dask.dataframe import DataFrame as DaskDataFrame from geopandas import GeoDataFrame +from numpy.typing import DTypeLike from shapely import Point from xarray import DataArray, DataTree @@ -30,7 +31,7 @@ get_axes_names, get_model, ) -from spatialdata.models._utils import get_spatial_axes +from spatialdata.models._utils import _get_uint_dtype, get_spatial_axes from spatialdata.transformations._utils import _get_scale, compute_coordinates from spatialdata.transformations.operations import get_transformation, remove_transformation, set_transformation from spatialdata.transformations.transformations import ( @@ -46,6 +47,12 @@ VALUES_COLUMN = "__values_column" +class TargetDimensions(NamedTuple): + target_width: float + target_height: float + target_depth: float | None + + def _compute_target_dimensions( spatial_axes: tuple[str, ...], min_coordinate: ListOrNDArrayFloating, @@ -54,7 +61,7 @@ def _compute_target_dimensions( target_width: float | None, target_height: float | None, target_depth: float | None, -) -> tuple[float, float, float | None]: +) -> TargetDimensions: """ Compute the pixel sizes (width, height, depth) of the image that will be produced by the rasterization. @@ -103,8 +110,6 @@ def _compute_target_dimensions( == 1 ), "you must specify only one of: target_unit_to_pixels, target_width, target_height, target_depth" assert set(spatial_axes) == {"x", "y"} or set(spatial_axes) == {"x", "y", "z"} - if "z" not in spatial_axes: - assert target_depth is None, "you cannot specify a target depth for 2D data" x_index = spatial_axes.index("x") y_index = spatial_axes.index("y") @@ -112,7 +117,7 @@ def _compute_target_dimensions( h_bb = max_coordinate[y_index] - min_coordinate[y_index] assert w_bb > 0, "all max_coordinate values must be greater than all min_coordinate values" assert h_bb > 0, "all max_coordinate values must be greater than all min_coordinate values" - w_to_h_bb = w_bb / h_bb + w_to_h_bb = float(w_bb / h_bb) d_bb = None d_to_h_bb = None @@ -120,7 +125,7 @@ def _compute_target_dimensions( z_index = spatial_axes.index("z") d_bb = max_coordinate[z_index] - min_coordinate[z_index] assert d_bb > 0, "all max_coordinate values must be greater than all min_coordinate values" - d_to_h_bb = d_bb / h_bb + d_to_h_bb = float(d_bb / h_bb) if target_unit_to_pixels is not None: target_width = w_bb * target_unit_to_pixels @@ -140,15 +145,18 @@ def _compute_target_dimensions( target_depth = target_height * d_to_h_bb elif target_depth is not None: assert d_to_h_bb is not None + assert "z" in spatial_axes, "you cannot specify a target depth for 2D data" target_height = target_depth / d_to_h_bb target_width = target_height * w_to_h_bb else: raise RuntimeError("Should not reach here") - assert target_width is not None assert isinstance(target_width, float) - assert target_height is not None assert isinstance(target_height, float) - return np.round(target_width), np.round(target_height), np.round(target_depth) if target_depth is not None else None + return TargetDimensions( + target_width=np.round(target_width), + target_height=np.round(target_height), + target_depth=np.round(target_depth) if target_depth is not None else None, + ) def rasterize( @@ -305,7 +313,8 @@ def rasterize( return_single_channel=return_single_channel if element_type in ("points", "shapes") else None, ) new_name = f"{name}_rasterized_{element_type}" - assert isinstance(rasterized, DataArray) + assert not isinstance(rasterized, SpatialData) + assert_type(rasterized, DataArray) model = get_model(rasterized) if model in (Image2DModel, Image3DModel): new_images[new_name] = rasterized @@ -335,7 +344,8 @@ def rasterize( target_depth=target_depth, ) transformations = get_transformation(rasterized, get_all=True) - assert isinstance(transformations, dict) + assert not isinstance(transformations, BaseTransformation) + assert_type(transformations, dict[str, BaseTransformation]) # adjust the return type if model in (Labels2DModel, Labels3DModel) and not return_regions_as_labels: model = Image2DModel if model == Labels2DModel else Image3DModel @@ -346,14 +356,14 @@ def rasterize( kwargs = {"sdata": sdata, "element_name": element_name} if element_name is not None else {"element": data} values = get_values(value_key, table_name=table_name, **kwargs).iloc[:, 0] # type: ignore[arg-type, union-attr] max_index: int = np.max(values.index) - assigner = np.zeros(max_index + 1, dtype=values.dtype) + dtype = cast(DTypeLike, values.dtype) # FIXME: try to assert instead + assigner = np.zeros(max_index + 1, dtype=dtype) assigner[values.index] = values - # call-arg is ignored because model is never TableModel (the error is that the transformation param is not - # accepted by TableModel.parse) - rasterized = model.parse(assigner[rasterized], transformations=transformations) # type: ignore[call-arg] + rasterized = model.parse(assigner[rasterized], transformations=transformations) return rasterized if model in (PointsModel, ShapesModel): - assert isinstance(parsed_data, GeoDataFrame | DaskDataFrame) + assert not isinstance(parsed_data, DataArray | DataTree) + assert_type(parsed_data, GeoDataFrame | DaskDataFrame) return rasterize_shapes_points( data=parsed_data, axes=axes, @@ -399,6 +409,8 @@ def _get_xarray_data_to_rasterize( The maximum coordinates of the bounding box for the data to be rasterized. target_sizes A dictionary containing the target size (in pixels) of each axis after rasterization. + target_coordinate_system + The coordinate system in which `min_coordinate` and `max_coordinate` are expressed. Returns ------- @@ -414,12 +426,14 @@ def _get_xarray_data_to_rasterize( latest_scale: str | None = None for scale in reversed(list(data.keys())): data_tree = data[scale] - assert isinstance(data_tree, DataTree) + assert not isinstance(data_tree, DataArray) + assert_type(data_tree, DataTree) latest_scale = scale v = list(data_tree.values()) assert len(v) == 1 scale_variable = v[0] - assert isinstance(scale_variable, DataArray) + assert not isinstance(scale_variable, DataTree) + assert_type(scale_variable, DataArray) xdata = scale_variable assert set(get_spatial_axes(tuple(str(dim) for dim in xdata.sizes))) == set(axes) @@ -457,9 +471,11 @@ def _get_xarray_data_to_rasterize( break assert latest_scale is not None latest_scale_tree = data[latest_scale] - assert isinstance(latest_scale_tree, DataTree) + assert not isinstance(latest_scale_tree, DataArray) + assert_type(latest_scale_tree, DataTree) latest_variable = next(iter(latest_scale_tree.values())) - assert isinstance(latest_variable, DataArray) + assert not isinstance(latest_variable, DataTree) + assert_type(latest_variable, DataArray) xdata = latest_variable if latest_scale != "scale0": transformations = xdata.attrs["transform"] @@ -467,7 +483,7 @@ def _get_xarray_data_to_rasterize( else: pyramid_scale = None else: - raise RuntimeError("Should not reach here") + assert_never(data) return xdata, pyramid_scale @@ -491,7 +507,8 @@ def _get_corrected_affine_matrix( """ transformation = get_transformation(data, target_coordinate_system) - assert isinstance(transformation, BaseTransformation) + assert not isinstance(transformation, dict) + assert_type(transformation, BaseTransformation) affine = _get_affine_for_element(data, transformation) target_axes_unordered = affine.output_axes assert set(target_axes_unordered) in [{"x", "y", "z"}, {"x", "y"}, {"c", "x", "y", "z"}, {"c", "x", "y"}] @@ -548,6 +565,8 @@ def rasterize_images_labels( offset = [min_coordinate[axes.index(ax)] for ax in axes] translation = Translation(offset, axes=axes) + assert not isinstance(data, GeoDataFrame | DaskDataFrame) + assert_type(data, DataArray | DataTree) xdata, pyramid_scale = _get_xarray_data_to_rasterize( data=data, axes=axes, @@ -620,7 +639,8 @@ def rasterize_images_labels( set_transformation(transformed_data, sequence, target_coordinate_system) computed = compute_coordinates(transformed_data) - assert isinstance(computed, DataArray) + assert not isinstance(computed, DataTree) + assert_type(computed, DataArray) schema.validate(computed) return computed @@ -747,10 +767,14 @@ def rasterize_shapes_points( max_label = next(iter(reversed(label_index_to_category.keys()))) else: max_label = int(agg.max().values) - max_uint16 = np.iinfo(np.uint16).max - if max_label > max_uint16: - raise ValueError(f"Maximum label index is {max_label}. Values higher than {max_uint16} are not supported.") - agg = agg.astype(np.uint16) + # datashader aggregates in float64: from 2**53 on, a value may be a rounded larger integer + # (from large input labels or from summing overlapping labels) + if max_label >= 2**53: + raise ValueError( + f"Maximum label is at least {max_label}. Labels of 2**53 or higher cannot be rasterized exactly " + "because datashader aggregates in float64." + ) + agg = agg.astype(_get_uint_dtype(max_label)) return Labels2DModel.parse(agg, transformations=transformations) agg = agg.expand_dims(dim={"c": 1}).transpose("c", "y", "x") diff --git a/src/spatialdata/_core/operations/transform.py b/src/spatialdata/_core/operations/transform.py index 410e92fc3..a140c0a96 100644 --- a/src/spatialdata/_core/operations/transform.py +++ b/src/spatialdata/_core/operations/transform.py @@ -318,7 +318,7 @@ def _( assert issubclass(schema, RasterSchema) from spatialdata.transformations import get_transformation - kwargs = {"prefilter": False, "order": 0} + kwargs = {"order": 0} axes = get_axes_names(data) transformed_dask, raster_translation = _transform_raster( data=data.data, axes=axes, transformation=transformation, **kwargs @@ -360,10 +360,10 @@ def _( from spatialdata.transformations import get_transformation, set_transformation from spatialdata.transformations.transformations import Identity, Sequence - # labels need to be preserved after the resizing of the image + # labels hold categorical ids, so they must be resampled with nearest neighbour (order=0): interpolating would + # create ids that are not present in the input, as for single-scale labels in the DataArray overload above if schema in (Labels2DModel, Labels3DModel): - # TODO: this should work, test better - kwargs = {"prefilter": False} + kwargs = {"order": 0} channel_names = None elif schema in (Image2DModel, Image3DModel): kwargs = {} diff --git a/src/spatialdata/_core/operations/vectorize.py b/src/spatialdata/_core/operations/vectorize.py index 431bdbd17..9176befcf 100644 --- a/src/spatialdata/_core/operations/vectorize.py +++ b/src/spatialdata/_core/operations/vectorize.py @@ -172,7 +172,7 @@ def to_polygons(data: SpatialElement, buffer_resolution: int | None = None) -> G """ Convert a set of geometries (2D labels, 2D shapes) to approximated 2D polygons/multypolygons. - For optimal performance when converting rasters (:class:`xarray.DataArray` or :class:`datatree.DataTree`) + For optimal performance when converting rasters (:class:`xarray.DataArray` or :class:`xarray.DataTree`) to polygons, it is recommended to configure `Dask` to use 'processes' rather than 'threads'. For example, you can set this configuration with: diff --git a/src/spatialdata/_core/query/relational_query.py b/src/spatialdata/_core/query/relational_query.py index 1a672eefc..bb3c3c08f 100644 --- a/src/spatialdata/_core/query/relational_query.py +++ b/src/spatialdata/_core/query/relational_query.py @@ -189,7 +189,7 @@ def _get_joined_table_indices( Returns ------- - The indices that of the table that match the SpatialElement indices. + The indices of the table that match the SpatialElement indices. """ mask = np.isin(table_instance_key_column.to_numpy(), element_indices) if joined_indices is None: @@ -259,7 +259,7 @@ def _get_masked_element( def _region_as_str_if_list_of_len_one(region: list[str]) -> str | list[str]: - return region if len(region) > 1 else region[0] + return region[0] if len(region) == 1 else region def _right_exclusive_join_spatialelement_table( @@ -891,6 +891,10 @@ def match_sdata_to_table( unfiltered and warns, ``False`` leaves them unfiltered silently. See :func:`spatialdata.join_spatialelement_table` for details. + Returns + ------- + A new SpatialData object containing the table and the matched elements. + Notes ----- For a graphical representation of the join operations, see the @@ -965,7 +969,7 @@ def filter_by_table_query( Returns ------- - The filtered SpatialData object. + The filtered SpatialData object. Notes ----- @@ -1246,7 +1250,7 @@ def _filter_labels_element(element: DataArray | DataTree, ids_to_keep: list[int] if isinstance(element, DataArray): return Labels2DModel.parse(_set_instance_ids_in_labels_to_zero(element, ids_to_remove)) scales = list(element.keys()) - scale_factors = [ + scale_factors: list[int] = [ round(element[scales[i]].image.shape[0] / element[scales[i + 1]].image.shape[0]) for i in range(len(scales) - 1) ] return Labels2DModel.parse( diff --git a/src/spatialdata/_core/query/spatial_query.py b/src/spatialdata/_core/query/spatial_query.py index f0360c310..b7e7f4ff5 100644 --- a/src/spatialdata/_core/query/spatial_query.py +++ b/src/spatialdata/_core/query/spatial_query.py @@ -39,12 +39,12 @@ ) MIN_COORDINATE_DOCS = """\ - The upper left hand corners of the bounding boxes (i.e., minimum coordinates along all dimensions). +The upper left hand corners of the bounding boxes (i.e., minimum coordinates along all dimensions). Shape: (n_boxes, n_axes) or (n_axes,) for a single box. """ MAX_COORDINATE_DOCS = """\ - The lower right hand corners of the bounding boxes (i.e., the maximum coordinates along all dimensions). - Shape: (n_boxes, n_axes) +The lower right hand corners of the bounding boxes (i.e., the maximum coordinates along all dimensions). + Shape: (n_boxes, n_axes) or (n_axes,) for a single box. """ @@ -65,9 +65,9 @@ def _get_bounding_box_corners_in_intrinsic_coordinates( axes The axes that min_coordinate and max_coordinate refer to. min_coordinate - {min_coordinate_docs} + {min_coordinate_docs} max_coordinate - {max_coordinate_docs} + {max_coordinate_docs} target_coordinate_system The coordinate system the bounding box is defined in. @@ -406,15 +406,9 @@ def _bounding_box_mask_points( axes The axes that min_coordinate and max_coordinate refer to. min_coordinate - PLACEHOLDER - The upper left hand corners of the bounding boxes (i.e., minimum coordinates along all dimensions). - Shape: (n_boxes, n_axes) or (n_axes,) for a single box. - {min_coordinate_docs} + {min_coordinate_docs} max_coordinate - The lower right hand corners of the bounding boxes (i.e., the maximum coordinates along all dimensions). - Shape: (n_boxes, n_axes) or (n_axes,) for a single box. - {max_coordinate_docs} - + {max_coordinate_docs} Returns ------- @@ -527,6 +521,10 @@ def bounding_box_query( ----- If the object has `points` element, depending on the number of points, it MAY suffer from performance issues. Please consider filtering the object before calling this function by calling the `subset()` method of `SpatialData`. + + Shapes are not cut to the bounding box: a shape that intersects it is returned whole. For a `MultiPolygon` this + includes components that lie entirely outside the bounding box. To cut the shapes to the bounding box, use + :func:`polygon_query` with `clip=True` and the bounding box as polygon, e.g. `shapely.box(xmin, ymin, xmax, ymax)`. """ raise RuntimeError("Unsupported type for bounding_box_query: " + str(type(element)) + ".") @@ -891,8 +889,10 @@ def polygon_query( Specifies whether to filter the tables to only include tables that annotate elements in the retrieved SpatialData object of the query. clip - If `True`, the shapes are clipped to the polygon. This behavior is implemented only when querying - polygons/multipolygons or circles, and it is ignored for other types of elements (images, labels, points). + If `True`, the shapes are clipped to the polygon. If `False`, a shape that intersects the polygon is returned + whole, and for a `MultiPolygon` this includes components that lie entirely outside the polygon. This behavior is + implemented only when querying polygons/multipolygons or circles, and it is ignored for other types of elements + (images, labels, points). Importantly, when clipping is enabled, the circles will be converted to polygons before the clipping. This may affect downstream operations that rely on the circle radius or on performance, so it is recommended to disable clipping when querying circles or when querying a `SpatialData` object that contains circles. diff --git a/src/spatialdata/_core/spatialdata.py b/src/spatialdata/_core/spatialdata.py index 8be3c2682..35c9825be 100644 --- a/src/spatialdata/_core/spatialdata.py +++ b/src/spatialdata/_core/spatialdata.py @@ -71,47 +71,48 @@ class SpatialData: The elements need to pass a validation step. To construct valid elements you can use the parsers that we provide: - - :class:`~spatialdata.Image2DModel`, - - :class:`~spatialdata.Image3DModel`, - - :class:`~spatialdata.Labels2DModel`, - - :class:`~spatialdata.Labels3DModel`, - - :class:`~spatialdata.PointsModel`, - - :class:`~spatialdata.ShapesModel`, - - :class:`~spatialdata.TableModel` + - :class:`~spatialdata.models.Image2DModel`, + - :class:`~spatialdata.models.Image3DModel`, + - :class:`~spatialdata.models.Labels2DModel`, + - :class:`~spatialdata.models.Labels3DModel`, + - :class:`~spatialdata.models.PointsModel`, + - :class:`~spatialdata.models.ShapesModel`, + - :class:`~spatialdata.models.TableModel` Parameters ---------- images - Dict of 2D and 3D image elements. The following parsers are available: :class:`~spatialdata.Image2DModel`, - :class:`~spatialdata.Image3DModel`. + Dict of 2D and 3D image elements. The following parsers are available: + :class:`~spatialdata.models.Image2DModel`, :class:`~spatialdata.models.Image3DModel`. labels Dict of 2D and 3D labels elements. Labels are regions, they can't contain annotation, but they can be - annotated by a table. The following parsers are available: :class:`~spatialdata.Labels2DModel`, - :class:`~spatialdata.Labels3DModel`. + annotated by a table. The following parsers are available: :class:`~spatialdata.models.Labels2DModel`, + :class:`~spatialdata.models.Labels3DModel`. points Dict of points elements. Points can contain annotations. The following parsers is available: - :class:`~spatialdata.PointsModel`. + :class:`~spatialdata.models.PointsModel`. shapes Dict of 2D shapes elements (circles, polygons, multipolygons). Shapes are regions, they can't contain annotation, but they can be annotated by a table. - The following parsers are available: :class:`~spatialdata.ShapesModel`. - table - AnnData table containing annotations for regions (labels and shapes). The following parsers is - available: :class:`~spatialdata.TableModel`. + The following parsers are available: :class:`~spatialdata.models.ShapesModel`. + tables + Dict of AnnData tables containing annotations for SpatialElements (labels, shapes and points). The + following parser is available: :class:`~spatialdata.models.TableModel`. + attrs + Dictionary of global attributes on this SpatialData object. Notes ----- The SpatialElements are stored with standard types: - - images and labels are stored as :class:`xarray.DataArray` or :class:`datatree.DataTree` objects. + - images and labels are stored as :class:`xarray.DataArray` or :class:`xarray.DataTree` objects. - points are stored as :class:`dask.dataframe.DataFrame` objects. - shapes are stored as :class:`geopandas.GeoDataFrame`. - the table are stored as :class:`anndata.AnnData` objects, with the spatial coordinates stored in the obsm slot. - The table can annotate regions (shapes or labels) and can be used to store additional information. - Points are not regions but 0-dimensional locations. They can't be annotated by a table, but they can store - annotation directly. + Tables can annotate SpatialElements (labels, shapes or points) and can be used to store additional + information. Points can also store annotations directly, as additional dataframe columns. """ def __init__( @@ -215,9 +216,9 @@ def validate_table_in_spatialdata(self, table: AnnData) -> None: else: dtype = element.index.dtype instance_dtype = self.get_instance_key_column(table).dtype - if dtype != instance_dtype and ( - pd.api.types.is_string_dtype(dtype) or pd.api.types.is_string_dtype(instance_dtype) - ): + # Only a string vs non-string mismatch is an error: string ids may be stored as `object` or + # as a pandas string dtype (the default with pandas>=3) depending on the reader. + if pd.api.types.is_string_dtype(dtype) != pd.api.types.is_string_dtype(instance_dtype): raise TypeError( f"Table instance_key column ({instance_key}) has a dtype " f"({instance_dtype}) that does not match the dtype of the indices of " @@ -1172,7 +1173,7 @@ def write( If `True`, overwrite the Zarr store if it already exists. If `False`, `write()` will fail if the Zarr store already exists. consolidate_metadata - If `True`, triggers :func:`zarr.convenience.consolidate_metadata`, which writes all the metadata in a single + If `True`, triggers :func:`zarr.consolidate_metadata`, which writes all the metadata in a single file at the root directory of the store. This makes the data cloud accessible, which is required for certain cloud stores (such as S3). update_sdata_path @@ -1206,7 +1207,7 @@ def write( `spatialdata._io.format.py`. shapes_geometry_encoding Whether to use the WKB or geoarrow encoding for GeoParquet. See :meth:`geopandas.GeoDataFrame.to_parquet` - for details. If None, uses the value from :attr:`spatialdata.settings.shapes_geometry_encoding`. + for details. If None, uses the value from ``spatialdata.settings.shapes_geometry_encoding``. raster_compressor A lenght-1 dictionary with as key the type of compression to use for images and labels and as value the compression level which should be inclusive between 0 and 9. For compression, `lz4` and `zstd` are @@ -1400,7 +1401,7 @@ def write_element( `SpatialData.write()`. shapes_geometry_encoding Whether to use the WKB or geoarrow encoding for GeoParquet. See :meth:`geopandas.GeoDataFrame.to_parquet` - for details. If None, uses the value from :attr:`spatialdata.settings.shapes_geometry_encoding`. + for details. If None, uses the value from ``spatialdata.settings.shapes_geometry_encoding``. raster_compressor A lenght-1 dictionary with as key the type of compression to use for images and labels and as value the compression level which should be inclusive between 0 and 9. For compression, `lz4` and `zstd` are @@ -2097,7 +2098,7 @@ def _gen_repr( Returns ------- - The string representation of the SpatialData object. + The string representation of the SpatialData object. """ from spatialdata._utils import _natural_keys @@ -2246,10 +2247,9 @@ def _gen_spatial_element_values(self) -> Generator[SpatialElement, None, None]: """ Generate spatial element objects contained in the SpatialData instance. - Returns - ------- - Generator[SpatialElement, None, None] - A generator that yields spatial element objects contained in the SpatialData instance. + Yields + ------ + The spatial element objects contained in the SpatialData instance. """ for _, _, element in self._gen_spatial_elements(): @@ -2259,9 +2259,9 @@ def _gen_spatial_elements(self) -> Generator[tuple[str, str, SpatialElement], No """ Generate the images, labels, points and shapes contained in the SpatialData instance. - Returns - ------- - A generator object that returns a tuple containing the type of the element, its name, and the element itself. + Yields + ------ + Tuples containing the type of the element, its name, and the element itself. """ for element_type, elements in ( ("images", self.images), @@ -2283,10 +2283,9 @@ def _gen_elements( include_tables Whether to also generate table elements. - Returns - ------- - A generator object that returns a tuple containing the type of the element, its name, and the element - itself. + Yields + ------ + Tuples containing the type of the element, its name, and the element itself. """ yield from self._gen_spatial_elements() if include_tables: @@ -2623,7 +2622,7 @@ def filter_by_table_query( Filter the SpatialData object based on a set of table queries. Please see - :func:`query.relational_query.filter_by_table_query` for the complete docstring. + :func:`spatialdata.filter_by_table_query` for the complete docstring. """ from spatialdata._core.query.relational_query import filter_by_table_query diff --git a/src/spatialdata/_core/validation.py b/src/spatialdata/_core/validation.py index dc2e4bf65..cbdd77912 100644 --- a/src/spatialdata/_core/validation.py +++ b/src/spatialdata/_core/validation.py @@ -295,6 +295,10 @@ def __call__( Tuple of strings identifying the parent element expected_exception The class of the exception to catch. Other exceptions are raised. + + Returns + ------- + The collector itself, to be used as a context manager. """ if isinstance(location, str): location = (location,) diff --git a/src/spatialdata/_io/_utils.py b/src/spatialdata/_io/_utils.py index ba10405bd..6ae9bfa92 100644 --- a/src/spatialdata/_io/_utils.py +++ b/src/spatialdata/_io/_utils.py @@ -59,12 +59,12 @@ def overwrite_coordinate_transformations_non_raster( Parameters ---------- - group: zarr.Group + group The zarr group containing the non-raster element for which to write the transformations, e.g. the zarr group containing sdata['points']. - axes: tuple[ValidAxis_t, ...] + axes The list with axes names in the same order as the coordinates of the non-raster element. - transformations: MappingToCoordinateSystem_t + transformations Mapping between names of the coordinate system and the transformations. """ _validate_mapping_to_coordinate_system_type(transformations) diff --git a/src/spatialdata/_io/io_raster.py b/src/spatialdata/_io/io_raster.py index 3806fabf7..9a73af5ef 100644 --- a/src/spatialdata/_io/io_raster.py +++ b/src/spatialdata/_io/io_raster.py @@ -69,6 +69,10 @@ def _is_regular_dask_chunk_grid(chunk_grid: Sequence[Sequence[int]]) -> bool: chunk_grid Per-axis tuple of chunk sizes, for instance as returned by ``dask_array.chunks``. + Returns + ------- + Whether the chunk grid is regular. + Examples -------- Triggers ``continue`` on the first ``if`` (single or empty axis): @@ -319,7 +323,7 @@ def _write_raster( The raster data to write. group The zarr group in the 'image' or 'labels' zarr group to write the raster data to. - name: str + name The name of the raster element. raster_format The format used to write the raster data. @@ -561,6 +565,10 @@ def _write_raster_datatree( Compression settings as a len-1 dictionary with a single key-value {compression: compression level} pair metadata Additional metadata for the raster element + + Returns + ------- + The zarr group the raster data was written to. """ write_multi_scale_ngff = write_multiscale_ngff if raster_type == "image" else write_multiscale_labels_ngff data = get_pyramid_levels(raster_data, attr="data") diff --git a/src/spatialdata/_io/io_shapes.py b/src/spatialdata/_io/io_shapes.py index 833406d39..69566ca49 100644 --- a/src/spatialdata/_io/io_shapes.py +++ b/src/spatialdata/_io/io_shapes.py @@ -104,7 +104,7 @@ def write_shapes( The format of the shapes element used to store it. geometry_encoding Whether to use the WKB or geoarrow encoding for GeoParquet. See :meth:`geopandas.GeoDataFrame.to_parquet` for - details. If None, uses the value from :attr:`spatialdata.settings.shapes_geometry_encoding`. + details. If None, uses the value from ``spatialdata.settings.shapes_geometry_encoding``. """ if element_format.zarr_format == 2: warnings.warn( @@ -146,6 +146,10 @@ def _write_shapes_v01(shapes: GeoDataFrame, group: zarr.Group, element_format: S The zarr group in the 'shapes' zarr group to write the shapes element to. element_format The format of the shapes element used to store it. + + Returns + ------- + The attributes (metadata) to write for the shapes element. """ # np.array() creates a writable copy, needed for pandas 3.0 CoW compatibility # https://github.com/geopandas/geopandas/issues/3697 @@ -186,6 +190,10 @@ def _write_shapes_v02_v03( geometry_encoding Whether to use the WKB or geoarrow encoding for GeoParquet. See :meth:`geopandas.GeoDataFrame.to_parquet` for details. + + Returns + ------- + The attributes (metadata) to write for the shapes element. """ from spatialdata.models._utils import TRANSFORM_KEY diff --git a/src/spatialdata/_io/io_zarr.py b/src/spatialdata/_io/io_zarr.py index 186d7c974..4b546dfc3 100644 --- a/src/spatialdata/_io/io_zarr.py +++ b/src/spatialdata/_io/io_zarr.py @@ -324,6 +324,8 @@ def _group_for_element_exists(zarr_path: Path, element_type: str, element_name: Parameters ---------- + zarr_path + Path to the Zarr store. element_type type of the element; must be in ["images", "labels", "points", "polygons", "shapes", "tables"]. element_name diff --git a/src/spatialdata/_utils.py b/src/spatialdata/_utils.py index a0086b7b2..d5b2aaa5b 100644 --- a/src/spatialdata/_utils.py +++ b/src/spatialdata/_utils.py @@ -6,7 +6,7 @@ from collections.abc import Callable, Generator from contextlib import contextmanager from itertools import islice -from typing import Any, TypeVar +from typing import Any, TypeVar, overload import numpy as np import pandas as pd @@ -161,6 +161,10 @@ def _compute_paddings(data: DataArray, axis: str) -> tuple[int, int]: return compute_coordinates(unpadded) +@overload +def get_pyramid_levels(image: DataTree, attr: str | None = None, n: None = None) -> list[Any]: ... +@overload +def get_pyramid_levels(image: DataTree, attr: str | None = None, *, n: int) -> Any: ... def get_pyramid_levels(image: DataTree, attr: str | None = None, n: int | None = None) -> list[Any] | Any: """ Access the data/attribute of the pyramid levels of a multiscale spatial image. @@ -200,9 +204,9 @@ def iterate_pyramid_levels( If `None`, return the data of the pyramid level as a `DataArray`, if not None, return the specified attribute within the `DataArray` data. - Returns - ------- - A generator to iterate over the pyramid levels. + Yields + ------ + The pyramid levels (or their attribute `attr`, if given). """ scale0 = data["scale0"] assert isinstance(scale0, DataTree) diff --git a/src/spatialdata/dataloader/datasets.py b/src/spatialdata/dataloader/datasets.py index b34ad5bf5..82037a2df 100644 --- a/src/spatialdata/dataloader/datasets.py +++ b/src/spatialdata/dataloader/datasets.py @@ -101,10 +101,6 @@ class ImageTilesDataset(Dataset[Any]): Keyword arguments passed to :func:`spatialdata.rasterize` if `rasterize` is `True`. This argument can be used in particular to choose the pixel dimension of the produced image tiles; please refer to the :func:`spatialdata.rasterize` documentation for this use case. - - Returns - ------- - :class:`torch.utils.data.Dataset` for loading tiles from a :class:`spatialdata.SpatialData`. """ INSTANCE_KEY = "instance_id" diff --git a/src/spatialdata/datasets.py b/src/spatialdata/datasets.py index fb57a28b1..299cb4d81 100644 --- a/src/spatialdata/datasets.py +++ b/src/spatialdata/datasets.py @@ -59,7 +59,8 @@ def blobs( Extra coordinate space on top of the standard global coordinate space. Will have only identity transform. n_channels Number of channels of the image - + c_coords + Channel names of the image. If given, overrides `n_channels`. Returns ------- @@ -189,6 +190,8 @@ def __init__( Extra coordinate space on top of the standard global coordinate space. Will have only identity transform. n_channels Number of channels of the image + c_coords + Channel names of the image. If given, overrides `n_channels`. """ self.length = length self.n_points = n_points diff --git a/src/spatialdata/datasets.yaml b/src/spatialdata/datasets.yaml index 62e151d45..fd057e978 100644 --- a/src/spatialdata/datasets.yaml +++ b/src/spatialdata/datasets.yaml @@ -11,17 +11,17 @@ # a ``license_url`` field. base_url: https://exampledata.scverse.org/spatialdata/ datasets: - cells: - type: spatialdata - doc_header: Cells dataset as a SpatialData object. - license: CC BY 4.0 - license_url: https://creativecommons.org/licenses/by/4.0/ - attribution: >- - Derived from the 10x Genomics Xenium Prime Cervical Cancer FFPE dataset - (https://www.10xgenomics.com/datasets/xenium-prime-ffpe-human-cervical-cancer), - subset to a small tissue region. Licensed under CC BY 4.0 - (https://creativecommons.org/licenses/by/4.0/). - files: - - name: cells.zip - s3_key: cells.zip - sha256: dc9613cb9e16fd2cd8d83f3a9586eeda4af5ba8ba366f1066efb51305820c5fb + cells: + type: spatialdata + doc_header: Cells dataset as a SpatialData object. + license: CC BY 4.0 + license_url: https://creativecommons.org/licenses/by/4.0/ + attribution: >- + Derived from the 10x Genomics Xenium Prime Cervical Cancer FFPE dataset + (https://www.10xgenomics.com/datasets/xenium-prime-ffpe-human-cervical-cancer), + subset to a small tissue region. Licensed under CC BY 4.0 + (https://creativecommons.org/licenses/by/4.0/). + files: + - name: cells.zip + s3_key: cells.zip + sha256: dc9613cb9e16fd2cd8d83f3a9586eeda4af5ba8ba366f1066efb51305820c5fb diff --git a/src/spatialdata/models/_utils.py b/src/spatialdata/models/_utils.py index 972e2d9be..36a33f60f 100644 --- a/src/spatialdata/models/_utils.py +++ b/src/spatialdata/models/_utils.py @@ -202,6 +202,8 @@ def points_dask_dataframe_to_geopandas(points: DaskDataFrame, suppress_z_warning points Dask DataFrame with columns "x" and "y". Eventually, it can contain a column "z" that will be not included in the geometry column. + suppress_z_warning + If `True`, do not warn that the "z" column is not included in the geometry. Returns ------- @@ -241,6 +243,8 @@ def points_geopandas_to_dask_dataframe(gdf: GeoDataFrame, suppress_z_warning: bo ---------- gdf GeoDataFrame with a geometry column that contains 2D or 3D points. + suppress_z_warning + If `True`, do not warn about the z coordinate being taken from a separate column. Returns ------- diff --git a/src/spatialdata/models/models.py b/src/spatialdata/models/models.py index b0a6c16f6..6d17c32e2 100644 --- a/src/spatialdata/models/models.py +++ b/src/spatialdata/models/models.py @@ -118,6 +118,20 @@ def parse( **kwargs: Any, ) -> DataTree: ... + @overload + @classmethod + def parse( + cls, + data: ArrayLike | DataArray | DaskArray, + dims: Sequence[str] | None = ..., + c_coords: str | list[str] | None = ..., + transformations: MappingToCoordinateSystem_t | None = ..., + scale_factors: ScaleFactors_t | None = ..., + method: Methods | None = ..., + chunks: Chunks_t | None = ..., + **kwargs: Any, + ) -> DataArray | DataTree: ... + @classmethod def parse( cls, @@ -143,7 +157,7 @@ def parse( Dimensions of the data (e.g. ['c', 'y', 'x'] for 2D image data). If the data is a :class:`xarray.DataArray`, the dimensions can also be inferred from the data. If the dimensions are not in the order (c)(z)yx, the data will be transposed to match the order. - c_coords : str | list[str] | None + c_coords Channel names of image data. Must be equal to the length of dimension 'c'. Only supported for `Image` models. transformations @@ -151,7 +165,7 @@ def parse( the value is the transformation to apply. By default, a single `Identity` transformation mapping to the `"global"` coordinate system is applied. scale_factors - Scale factors to apply to construct a multiscale image (:class:`datatree.DataTree`). + Scale factors to apply to construct a multiscale image (:class:`xarray.DataTree`). If `None`, a :class:`xarray.DataArray` is returned instead. Importantly, each scale factor is relative to the previous scale factor. For example, if the scale factors are `[2, 2, 2]`, the returned multiscale image will have 4 scales. The original image and then the 2x, 4x @@ -178,13 +192,13 @@ def parse( chunks Chunks to use for dask array. kwargs - Additional arguments for :func:`to_spatial_image`. In particular the `c_coords` kwargs argument (an - iterable) can be used to set the channel coordinates for image data. `c_coords` is not available for labels - data as labels do not have channels. + Additional arguments for ``spatial_image.to_spatial_image()``. In particular the `c_coords` kwargs argument + (an iterable) can be used to set the channel coordinates for image data. `c_coords` is not available for + labels data as labels do not have channels. Returns ------- - :class:`xarray.DataArray` or :class:`datatree.DataTree` + :class:`xarray.DataArray` or :class:`xarray.DataTree` Notes ----- @@ -194,8 +208,8 @@ def parse( the `c_coords` argument to specify the channel coordinates as `["r", "g", "b"]` or `["r", "g", "b", "a"]`. You can also pass the `rgb` argument to `kwargs` to automatically set the `c_coords` to `["r", "g", "b"]`. - Please refer to :func:`to_spatial_image` for more information. Note: if you set `rgb=None` in `kwargs`, 3-4 - channel images will be interpreted automatically as RGB(A) images. + Please refer to ``spatial_image.to_spatial_image()`` for more information. Note: if you set `rgb=None` in + `kwargs`, 3-4 channel images will be interpreted automatically as RGB(A) images. **Setting axes / dims** In case of the data being a numpy or dask array, there are no named axes yet. In this case, we first try to use the dimensions specified by the user in the `dims` argument of `.parse`. These @@ -707,7 +721,7 @@ def validate(cls, data: DaskDataFrame) -> None: Parameters ---------- data - :class:`dask.dataframe.core.DataFrame` to validate. + :class:`dask.dataframe.DataFrame` to validate. Returns ------- @@ -782,7 +796,7 @@ def parse(cls, data: Any, **kwargs: Any) -> DaskDataFrame: Returns ------- - :class:`dask.dataframe.core.DataFrame` + :class:`dask.dataframe.DataFrame` Notes ----- diff --git a/src/spatialdata/transformations/_utils.py b/src/spatialdata/transformations/_utils.py index 032c89c13..c0cf1484f 100644 --- a/src/spatialdata/transformations/_utils.py +++ b/src/spatialdata/transformations/_utils.py @@ -60,12 +60,13 @@ def _set_transformations_to_element(element: Any, transformations: MappingToCoor def _set_transformations(e: SpatialElement, transformations: MappingToCoordinateSystem_t) -> None: """ Set the transformation of a SpatialElement *only in memory*. + Parameters ---------- e SpatialElement - t - transformation + transformations + Mapping from coordinate system names to transformations. Notes ----- @@ -276,6 +277,8 @@ def convert_transformations_to_affine(sdata: SpatialData, coordinate_system: str Parameters ---------- + sdata + The SpatialData object whose elements' transformations are converted. coordinate_system The coordinate system to convert to. diff --git a/src/spatialdata/transformations/ngff/_utils.py b/src/spatialdata/transformations/ngff/_utils.py index 07dff152c..c3f0a795a 100644 --- a/src/spatialdata/transformations/ngff/_utils.py +++ b/src/spatialdata/transformations/ngff/_utils.py @@ -46,6 +46,9 @@ def get_default_coordinate_system(dims: tuple[str, ...]) -> NgffCoordinateSystem The dimension names to get the corresponding axes of the defeault coordinate system for. Names should be in ['x', 'y', 'z', 'c']. + Returns + ------- + The default coordinate system with the axes corresponding to `dims`. """ axes = [] for c in dims: diff --git a/src/spatialdata/transformations/ngff/ngff_coordinate_system.py b/src/spatialdata/transformations/ngff/ngff_coordinate_system.py index fb5a24882..56424d6e1 100644 --- a/src/spatialdata/transformations/ngff/ngff_coordinate_system.py +++ b/src/spatialdata/transformations/ngff/ngff_coordinate_system.py @@ -15,7 +15,7 @@ class NgffAxis: """ Representation of an axis, following the NGFF specification. - Attributes + Parameters ---------- name name of the axis. @@ -181,6 +181,10 @@ def has_axis(self, name: str) -> bool: ---------- name name of the axis. + + Returns + ------- + Whether the coordinate system has an axis with the given name. """ return any(axis.name == name for axis in self._axes) @@ -206,6 +210,10 @@ def merge( new_name name of the new coordinate system + + Returns + ------- + The merged coordinate system. """ # common axes need to be the identical otherwise no merge is made common_axes = set(coord_sys1.axes_names).intersection(coord_sys2.axes_names) diff --git a/src/spatialdata/transformations/ngff/ngff_transformations.py b/src/spatialdata/transformations/ngff/ngff_transformations.py index 1758159bf..f73744b59 100644 --- a/src/spatialdata/transformations/ngff/ngff_transformations.py +++ b/src/spatialdata/transformations/ngff/ngff_transformations.py @@ -85,6 +85,10 @@ def from_dict(cls, d: Transformation_t) -> NgffBaseTransformation: ---------- d the Python dict representing the transformation. + + Returns + ------- + The transformation. """ # d = MappingProxyType(d) type = d["type"] @@ -118,7 +122,7 @@ def _update_dict_with_input_output_cs(self, d: Transformation_t) -> None: The dictionary to be updated. Notes - ------- + ----- Use of this helper function. A transformation is saved to disk as a json string. When loaded this is represented by a dictionary. We allow transformations to be defined even when the input and output coordinate systems are not @@ -365,6 +369,10 @@ def _affine_matrix_from_input_and_output_axes( the input axes. output_axes the output axes. + + Returns + ------- + The affine matrix. """ from spatialdata.models import C, X, Y, Z diff --git a/src/spatialdata/transformations/operations.py b/src/spatialdata/transformations/operations.py index 9091cec38..c267e2e25 100644 --- a/src/spatialdata/transformations/operations.py +++ b/src/spatialdata/transformations/operations.py @@ -1,7 +1,7 @@ from __future__ import annotations import contextlib -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, Literal, overload import numpy as np from dask.dataframe import DataFrame as DaskDataFrame @@ -88,6 +88,30 @@ def set_transformation( write_to_sdata.write_transformations(element_name=element_name) +@overload +def get_transformation( + element: SpatialElement, to_coordinate_system: str | None = None, get_all: Literal[False] = False +) -> BaseTransformation: ... + + +@overload +def get_transformation( + element: SpatialElement, to_coordinate_system: None, get_all: Literal[True] +) -> dict[str, BaseTransformation]: ... + + +@overload +def get_transformation( + element: SpatialElement, to_coordinate_system: None = None, *, get_all: Literal[True] +) -> dict[str, BaseTransformation]: ... + + +@overload +def get_transformation( + element: SpatialElement, to_coordinate_system: str | None = None, get_all: bool = False +) -> BaseTransformation | dict[str, BaseTransformation]: ... + + def get_transformation( element: SpatialElement, to_coordinate_system: str | None = None, get_all: bool = False ) -> BaseTransformation | dict[str, BaseTransformation]: @@ -223,12 +247,17 @@ def get_transformation_between_coordinate_systems( Parameters ---------- + sdata + The SpatialData object containing the elements and their transformations. source_coordinate_system The source coordinate system. Can be a SpatialElement (intrinsic coordinate system) or a string (extrinsic coordinate system). target_coordinate_system The target coordinate system. Can be a SpatialElement (intrinsic coordinate system) or a string (extrinsic coordinate system). + intermediate_coordinate_systems + If multiple paths exist between source and target, only consider those passing through this coordinate system + (a SpatialElement for an intrinsic one, or a string for an extrinsic one). shortest_path Whether to return the shortest paths when multiple paths are found between the coordinate systems and a single shortest path is found. If `False`, an error is raised when multiple paths exist. diff --git a/tests/core/operations/test_aggregations.py b/tests/core/operations/test_aggregations.py index d471b79cc..7fadeb6ec 100644 --- a/tests/core/operations/test_aggregations.py +++ b/tests/core/operations/test_aggregations.py @@ -8,10 +8,12 @@ from anndata.tests.helpers import assert_equal from geopandas import GeoDataFrame from numpy.random import default_rng +from scipy.sparse import issparse from spatialdata import aggregate, to_polygons from spatialdata._core._deepcopy import deepcopy as _deepcopy from spatialdata._core.spatialdata import SpatialData +from spatialdata._types import ArrayLike from spatialdata.models import Image2DModel, Labels2DModel, PointsModel, TableModel from spatialdata.transformations import Affine, Identity, set_transformation @@ -359,6 +361,32 @@ def test_aggregate_image_by_labels(labels_blobs, image_schema, labels_schema) -> assert len(out) == 3 +@pytest.mark.parametrize("multiscale_values", [False, True]) +@pytest.mark.parametrize("multiscale_by", [False, True]) +def test_aggregate_image_by_labels_multiscale( + labels_blobs: ArrayLike, *, multiscale_values: bool, multiscale_by: bool +) -> None: + """Multiscale `values` and `by` aggregate like their single-scale counterparts.""" + image = RNG.normal(size=(3,) + labels_blobs.shape) + scale_factors = [2] + + single = aggregate( + values=Image2DModel.parse(image), + by=Labels2DModel.parse(labels_blobs), + agg_func="mean", + ).tables["table"] + out = aggregate( + values=Image2DModel.parse(image, scale_factors=scale_factors if multiscale_values else None), + by=Labels2DModel.parse(labels_blobs, scale_factors=scale_factors if multiscale_by else None), + agg_func="mean", + ).tables["table"] + + assert len(out) + 1 == len(np.unique(labels_blobs)) + np.testing.assert_array_equal(out.obs_names, single.obs_names) + x, x_single = (a.toarray() if issparse(a) else a for a in (out.X, single.X)) + np.testing.assert_allclose(x, x_single) + + @pytest.mark.parametrize("values", ["blobs_image", "blobs_points", "blobs_circles", "blobs_polygons"]) @pytest.mark.parametrize("by", ["blobs_labels", "blobs_circles", "blobs_polygons"]) def test_aggregate_requiring_alignment(sdata_blobs: SpatialData, values, by) -> None: diff --git a/tests/core/operations/test_rasterize.py b/tests/core/operations/test_rasterize.py index 53d362d15..56c314966 100644 --- a/tests/core/operations/test_rasterize.py +++ b/tests/core/operations/test_rasterize.py @@ -446,6 +446,79 @@ def _rasterize(element: DaskDataFrame, **kwargs) -> SpatialImage: assert d[res[1, 2]] == 4 +def test_rasterize_points_selects_label_dtype(): + n_points = np.iinfo(np.uint16).max + 1 + points = PointsModel.parse( + dd.from_pandas( + pd.DataFrame({"x": np.arange(n_points), "y": np.zeros(n_points)}), + npartitions=1, + ) + ) + + result = rasterize( + points, + axes=("x", "y"), + min_coordinate=[0, 0], + max_coordinate=[n_points, 1], + target_coordinate_system="global", + target_width=n_points, + return_regions_as_labels=True, + ) + + assert result.dtype == np.uint32 + assert result.max().compute() == n_points + + +def _rasterize_point_labels(x, labels, agg_func): + df = pd.DataFrame({"x": x, "y": [0.5] * len(x), "label": np.array(labels, dtype=np.uint64)}) + points = PointsModel.parse(dd.from_pandas(df, npartitions=1)) + return rasterize( + points, + axes=("x", "y"), + min_coordinate=[0, 0], + max_coordinate=[2, 1], + target_coordinate_system="global", + target_width=2, + value_key="label", + agg_func=agg_func, + return_regions_as_labels=True, + ) + + +# (x, labels, agg_func, expected maximum label) +_LARGE_LABEL_CASES = [ + ([0.5, 1.5], [1, 2**53], "first", 2**53), + ([0.5, 1.5], [1, 2**53 + 1], "first", 2**53 + 1), + # overlapping labels are summed: each label is below 2**53, the sum is not + ([0.5, 0.5], [2**53 - 1, 2], "sum", 2**53 + 1), +] + + +def test_rasterize_labels_below_float64_precision(): + result = _rasterize_point_labels([0.5, 1.5], [1, 2**53 - 1], "first") + assert result.dtype == np.uint64 + assert int(result.max().compute()) == 2**53 - 1 + + +@pytest.mark.parametrize(("x", "labels", "agg_func", "expected"), _LARGE_LABEL_CASES) +def test_rasterize_labels_above_float64_precision_raises(x, labels, agg_func, expected): + # until rasterization is exact for large labels, they must raise instead of being silently rounded + with pytest.raises(ValueError, match=r"2\*\*53"): + _rasterize_point_labels(x, labels, agg_func) + + +@pytest.mark.xfail( + reason="datashader aggregates in float64, so labels of 2**53 or higher cannot be rasterized exactly", + strict=False, # an unexpected pass (root cause fixed) should not fail CI; the ValueError test will flag the guard +) +@pytest.mark.parametrize(("x", "labels", "agg_func", "expected"), _LARGE_LABEL_CASES) +def test_rasterize_labels_above_float64_precision(x, labels, agg_func, expected): + # the desired behaviour once the root cause is fixed; the ValueError guard and its test should then be removed + result = _rasterize_point_labels(x, labels, agg_func) + assert result.dtype == np.uint64 + assert int(result.max().compute()) == expected + + def test_rasterize_spatialdata(full_sdata): sdata = full_sdata.subset( ["image2d", "image2d_multiscale", "labels2d", "labels2d_multiscale", "points_0", "circles"] diff --git a/tests/core/operations/test_transform.py b/tests/core/operations/test_transform.py index ef307ac7b..bf980fe26 100644 --- a/tests/core/operations/test_transform.py +++ b/tests/core/operations/test_transform.py @@ -16,7 +16,7 @@ from spatialdata._core.data_extent import are_extents_equal, get_extent from spatialdata._core.spatialdata import SpatialData from spatialdata._utils import disable_dask_tune_optimization, unpad_raster -from spatialdata.models import Image2DModel, PointsModel, ShapesModel, get_axes_names +from spatialdata.models import Image2DModel, Labels2DModel, Labels3DModel, PointsModel, ShapesModel, get_axes_names from spatialdata.transformations.operations import ( align_elements_using_landmarks, get_transformation, @@ -234,6 +234,58 @@ def test_transform_shapes(shapes: SpatialData): assert geom_almost_equals(p0["geometry"], p1["geometry"]) +def _label_ids_per_scale(labels: DataArray | DataTree) -> list[set[int]]: + levels = [labels] if isinstance(labels, DataArray) else [next(iter(scale.values())) for scale in labels.values()] + return [set(np.unique(np.asarray(level.data)).tolist()) for level in levels] + + +def _rotation_xy(degrees: float) -> Affine: + theta = np.deg2rad(degrees) + matrix = np.array([[np.cos(theta), -np.sin(theta), 0], [np.sin(theta), np.cos(theta), 0], [0, 0, 1]]) + return Affine(matrix, input_axes=("x", "y"), output_axes=("x", "y")) + + +@pytest.mark.parametrize("multiscale", [False, True]) +@pytest.mark.parametrize("via_spatialdata", [False, True]) +@pytest.mark.parametrize( + "transformation", + [_rotation_xy(30), Scale([1.5, 1.5], axes=("x", "y"))], + ids=["rotation", "scale"], +) +def test_transform_labels_preserves_label_ids(multiscale: bool, via_spatialdata: bool, transformation): + """Labels are resampled with nearest neighbour, so no label ids are invented (gh-1202).""" + arr = np.zeros((64, 64), dtype=np.uint16) + arr[:32, :] = 1 + arr[32:, :] = 50 + labels = Labels2DModel.parse(arr, scale_factors=[2] if multiscale else None) + set_transformation(labels, transformation, "transformed") + + if via_spatialdata: + transformed = transform(SpatialData(labels={"labels": labels}), to_coordinate_system="transformed")["labels"] + else: + transformed = transform(labels, to_coordinate_system="transformed") + + for ids in _label_ids_per_scale(transformed): + assert ids <= {0, 1, 50} + assert {1, 50} <= ids + + +@pytest.mark.parametrize("multiscale", [False, True]) +def test_transform_labels_3d_preserves_label_ids(multiscale: bool): + """Labels are resampled with nearest neighbour, so no label ids are invented (gh-1202).""" + arr = np.zeros((8, 32, 32), dtype=np.uint16) + arr[:, :16, :] = 1 + arr[:, 16:, :] = 50 + labels = Labels3DModel.parse(arr, scale_factors=[2] if multiscale else None) + set_transformation(labels, Scale([1.5, 1.5, 1.5], axes=("x", "y", "z")), "transformed") + + transformed = transform(labels, to_coordinate_system="transformed") + + for ids in _label_ids_per_scale(transformed): + assert ids <= {0, 1, 50} + assert {1, 50} <= ids + + def test_transform_datatree_scale_handling(): """ Test the cases in which the lowest and highest scale of the result of a diff --git a/tests/core/query/test_spatial_query.py b/tests/core/query/test_spatial_query.py index 3b6ff3581..724131c04 100644 --- a/tests/core/query/test_spatial_query.py +++ b/tests/core/query/test_spatial_query.py @@ -517,6 +517,31 @@ def test_query_spatial_data(full_sdata): assert_spatial_data_objects_are_identical(result0, result4, check_transformations=False) +@pytest.mark.parametrize("with_polygon_query", [True, False]) +def test_query_labels_without_annotated_instances(with_polygon_query: bool): + labels = np.zeros((10, 10), dtype=np.int32) + labels[6:9, 6:9] = 1 + table = AnnData(shape=(1, 0)) + table.obs["region"] = pd.Categorical(["labels"]) + table.obs["instance_id"] = [1] + table = TableModel.parse(table, region="labels", region_key="region", instance_key="instance_id") + sdata = SpatialData(labels={"labels": Labels2DModel.parse(labels)}, tables={"table": table}) + + if with_polygon_query: + polygon = Polygon([(0, 0), (0, 2), (2, 2), (2, 0)]) + queried = polygon_query(sdata, polygon=polygon, target_coordinate_system="global", filter_table=True) + else: + queried = sdata.query.bounding_box( + axes=("x", "y"), + min_coordinate=np.array([0, 0]), + max_coordinate=np.array([2, 2]), + filter_table=True, + target_coordinate_system="global", + ) + assert "labels" in queried.labels + assert len(queried.tables) == 0 + + @pytest.mark.parametrize("with_polygon_query", [True, False]) def test_query_filter_table(with_polygon_query: bool): coords0 = np.array([[10, 10], [20, 20]]) diff --git a/tests/datasets/test_datasets.py b/tests/datasets/test_datasets.py index 3fc66370c..d71afedd2 100644 --- a/tests/datasets/test_datasets.py +++ b/tests/datasets/test_datasets.py @@ -2,10 +2,11 @@ from pathlib import Path +import pandas as pd import pooch import pytest -from spatialdata import SpatialData +from spatialdata import SpatialData, read_zarr from spatialdata.datasets import _cache_dir, _shipped_registry, blobs, cells, raccoon @@ -70,3 +71,23 @@ def test_cells_download(tmp_path) -> None: assert len(sdata.shapes["nucleus_boundaries"]) == 94 assert len(sdata.points["transcripts"].compute()) == 19479 assert sdata.tables["table"].shape == (94, 5101) + + +@pytest.mark.network +def test_cells_string_instance_key_dtype(tmp_path) -> None: + # Regression: the `cell_boundaries` index is read as the pandas>=3 `str` dtype while the table's `cell_id` + # column is read as `object`; both hold string ids, so annotating by `cell_id` must validate and round-trip. + sdata = cells(path=str(tmp_path / "cache")) + table = sdata.tables["table"] + table.obs["region"] = pd.Categorical(["cell_boundaries"] * table.n_obs) + sdata.set_table_annotates_spatialelement("table", region="cell_boundaries", instance_key="cell_id") + sdata.validate_table_in_spatialdata(table) + + sdata.write(tmp_path / "data.zarr") + sdata_read = read_zarr(tmp_path / "data.zarr") + assert sdata_read.tables["table"].uns["spatialdata_attrs"]["instance_key"] == "cell_id" + + # a string vs integer mismatch is still an error + sdata.set_table_annotates_spatialelement("table", region="cell_boundaries", instance_key="cell_labels") + with pytest.raises(TypeError, match="does not match the dtype"): + sdata.validate_table_in_spatialdata(table) diff --git a/tests/io/test_readwrite.py b/tests/io/test_readwrite.py index c21d7a0d3..3875f4da8 100644 --- a/tests/io/test_readwrite.py +++ b/tests/io/test_readwrite.py @@ -474,7 +474,7 @@ def test_incremental_io_on_disk( new_name=new_name, sdata_container_format=sdata_container_format, ) - elif workaround == 2: + elif workaround == 2: # noqa: SIM102 # workaround 2, unsafe but sometimes acceptable depending on the user's workflow. # this works only if the data is not dask-backed, otherwise an exception will be raised because the code