Skip to content

(feat): read_lazy for whole AnnData lazy-loading + xarray reading + read_elem_as_dask -> read_elem_lazy - #1247

Merged
ilan-gold merged 480 commits into
mainfrom
ig/xarray_compat
Mar 13, 2025
Merged

ilan-gold merged 480 commits into
mainfrom
ig/xarray_compat

Conversation

@ilan-gold

@ilan-gold ilan-gold commented Nov 30, 2023 •

Copy link
Copy Markdown
Contributor

This PR is a lighter weight version of #947 that involves using the original AnnData object as the class to hold obs and var xr.Dataset.

@codecov

codecov Bot commented Dec 7, 2023 •

Copy link
Copy Markdown

Codecov Report

Attention: Patch coverage is 90.74803% with 47 lines in your changes missing coverage. Please review.

Project coverage is 84.36%. Comparing base (64707b2) to head (b8ea225).
Report is 50 commits behind head on main.

Files with missing lines Patch % Lines
src/anndata/tests/helpers.py 71.42% 10 Missing ⚠️
src/anndata/_core/merge.py 92.13% 7 Missing ⚠️
src/anndata/experimental/backed/_lazy_arrays.py 94.17% 6 Missing ⚠️
src/anndata/_core/storage.py 50.00% 5 Missing ⚠️
src/anndata/experimental/backed/_xarray.py 92.53% 5 Missing ⚠️
src/anndata/_io/specs/lazy_methods.py 93.93% 4 Missing ⚠️
src/anndata/_core/index.py 66.66% 3 Missing ⚠️
src/anndata/experimental/backed/_compat.py 84.21% 3 Missing ⚠️
src/anndata/_io/specs/registry.py 88.23% 2 Missing ⚠️
src/anndata/experimental/backed/_io.py 96.22% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1247      +/-   ##
==========================================
- Coverage   85.96%   84.36%   -1.61%     
==========================================
  Files          40       45       +5     
  Lines        6350     6774     +424     
==========================================
+ Hits         5459     5715     +256     
- Misses        891     1059     +168     
Files with missing lines Coverage Δ
src/anndata/_core/aligned_df.py 95.83% <100.00%> (+0.18%) ⬆️
src/anndata/_core/anndata.py 82.46% <100.00%> (+0.04%) ⬆️
src/anndata/_core/views.py 85.40% <100.00%> (-5.35%) ⬇️
src/anndata/_io/specs/__init__.py 100.00% <ø> (ø)
src/anndata/_io/specs/methods.py 89.21% <100.00%> (-0.37%) ⬇️
src/anndata/_io/zarr.py 83.14% <100.00%> (+0.58%) ⬆️
src/anndata/_types.py 86.11% <100.00%> (+0.81%) ⬆️
src/anndata/compat/__init__.py 83.18% <100.00%> (+2.83%) ⬆️
src/anndata/experimental/__init__.py 100.00% <100.00%> (ø)
src/anndata/experimental/backed/__init__.py 100.00% <100.00%> (ø)
... and 12 more

... and 2 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@ilan-gold ilan-gold added this to the 0.11.0 milestone Jul 2, 2024
@ilan-gold ilan-gold self-assigned this Jul 2, 2024
@ilan-gold
ilan-gold changed the base branch from main to ig/read_dask_elem July 9, 2024 15:44
@ilan-gold ilan-gold mentioned this pull request Jul 10, 2024
2 of 3 tasks
Base automatically changed from ig/read_dask_elem to main July 23, 2024 08:39
@ilan-gold

ilan-gold commented Jul 23, 2024 •

Copy link
Copy Markdown
Contributor Author

@ivirshup @flying-sheep Not really looking for a thorough code review at the moment, more of a look at the structure of what we are exporting. The big changes are

  1. read_elem_as_dask->read_elem_lazy becomes a more general method focused on supporting the reading of obs and var lazy as xarray objects (although now it can read categoricals, nullables, etc. as a side-effect)
  2. read_backed is exported as a one-stop-shop for reading everything at once backed, as possible

Do we want this way of doing things? Or is there some other route?

Separately, are the changes made to the core acceptable? After that, I think we can look into the specifics of the code I added. Or you can review that now, but I'd rather get big changes out of the way first.

@ilan-gold

Copy link
Copy Markdown
Contributor Author

I will continue to make little changes to clean things up (this is still a draft!) but I think this structure is the way I would go. But maybe you have different ideas!

@flying-sheep flying-sheep left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I really like the approach.

Would of course be better if that stuff got upstreamed, but with only the category and mask handling being done by us, this is feasible I think, but I don’t have a lot of xarray experience.

There’s one hack in there that I really don’t want us to leave in, otherwise already looks quite clean.

I’ll take a deeper look once you’re done.

Comment thread ci/scripts/min-deps.py Resolved
Comment thread pyproject.toml Resolved
Comment thread src/anndata/_core/anndata.py Resolved
Comment thread pyproject.toml Resolved
@ilan-gold

ilan-gold commented Aug 6, 2024 •

Copy link
Copy Markdown
Contributor Author

Would of course be better if that stuff got upstreamed, but with only the category and mask handling being done by us, this is feasible I think, but I don’t have a lot of xarray experience.

The ability to handle any extension arrays in-memory for this was upstreamed, but this specific part is really just i/o and I don't think we can expect the xarray folks to take our custom i/o formats. Would be nice though. Eventually, they will do i/o for extension arrays and hopefully we can use their i/o completely.

@flying-sheep flying-sheep linked an issue Aug 8, 2024 that may be closed by this pull request
@ilan-gold
ilan-gold requested a review from flying-sheep August 13, 2024 14:12
Comment thread pyproject.toml Outdated
"awkward>=2.3",
]
dev-doc = ["towncrier>=24.8.0"] # release notes tool
test-full = ["anndata[test,lazy]"]

@ilan-gold ilan-gold Feb 25, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe a different name? Not sure about test-full

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in scanpy we have

  • test-min which is used in the minimum deps job,
  • test which is a healthy subset of functionality, and
  • test-full, which is everything (except for external I think)

Comment thread src/anndata/_core/index.py Resolved
Comment thread src/anndata/_core/merge.py Resolved
@flying-sheep

flying-sheep commented Feb 25, 2025 •

Copy link
Copy Markdown
Member

OK, so I went through all open conversations and new commits, and there’s almost nothing left:

@ilan-gold

Copy link
Copy Markdown
Contributor Author

pytestmark should work and is less complex.

Putting at the top-level of the conftest didn't work so I could have added it to the files individually but this seems anti-scalable.

I’m also still not happy about the deps here, it‘s pretty unclear what causes them to be there. Maybe annotate non-obvious ones so we can check if we need them and remove them at some point instead of cargo-culting them into infinity?

That's fair - maybe let's wait until zarr v3. The reason is simply that "using remote data with zarr requires these, and otherwise you will get a RuntimeError"

I’d still like to see a more local/explicit version of the "experimental/backed" in str(request.node.path)

I can redo this

@flying-sheep flying-sheep left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks great! One last thing:

Comment thread src/testing/anndata/_pytest.py Resolved
@ilan-gold

Copy link
Copy Markdown
Contributor Author

I will open follow up PRs after this one to account for a few things, but, for now, I am going to leave this unmerged because the zarr v3 PR should go in first.

I am very happy with the state of things :)

ilan-gold and others added 3 commits March 5, 2025 15:44
* (wip): support for new zarr version

* (chore): create setting for write version

* (fix): pathing issue

* (chore): use `open_group`

* (fix): another `zarr.open`

* (fix): `zarr_write_version` -> `zarr_write_format`

* (feat): batched reading for sparse

* (fix): object codec

* (fix): revert compressed vectors

* (feat): scalar support

* (fix): `open_group` for v3

* (fix): backed sparse copy method

* (fix): add speed-up for zarr by batching indexing

* (fix): no `__len__` on new zarr arrays

* (fix): some v3 fixes

* Specify mode with kwarg

* chore: typing fixes

* (fix): more `create_dataset` args

* format->version

* clear properly

* dynamic format/version

* Centralize version comparison

* Fix most create_dataset errors

* unpin zarr everywhere

* Almost fix docs

* (fix): compression test

* (fix): tracking store

* (fix): `as_group` `mode` arg

* (fix): temporary fix for writing from zarr array

* (fix): more context issues

* (fix): no `chunks` `bool` arg

* (fix): return `item` for array

* (chore): add issue

* Bump scanpydoc version

* (chore): add zarr v2 test

* (chore): add warning for zarr v2

* (fix): fix tracking tests for zarr v2

* (chore): refactor a bit

* (fix): revert zarr v2 test

* (fix): setting on group test

* (fix): reopening issue

* (fix): using zip files for backwards compat

* (fix): temporary fix for `empty`

* (fix): io dispatched keys test

* (fix): sparse array access tracking

* (fix): more reopen zarr store

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* (fix): lazy reading

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* (fix): ensure v2 group is made

* (fix): add `visititems`

* (fix): point zarr at main

* (fix): don't provide `VLenUTF8Codec` for default string

* (fix): doctest

* (fix): move off the zarr main branch

* (fix): pin zarr in benchmarks

* (feat): zarr v2 handling in tests

* (fix): warning on `zarr.open`

* (fix): `create_array` instead of `create_dataset`

* (chore): remove whitespace

* (fix): bring back zip files after fixing zarr bug

* (chore): relnote

* (chore): clarify comment

* (fix): cleaner `X` check

* (fix): wrong operator

* (fix): read in `zarr` zip correctly

* (chore): relnote

* merge

* (fix): bound zarr

* (chore): unbound zarr

* (chore): update `zarr` dep

* (fix): del `append_data` after use

* (chore): revert h5 sparse_as_dense

* Update src/anndata/_core/sparse_dataset.py

Co-authored-by: Philipp A. <flying-sheep@web.de>

* (fix): cleaner `fitlers, dtype`

* (fix): type of `write_scalar_group`

* (chore): future warning -> deprecation warning

* Update src/anndata/_io/specs/methods.py

Co-authored-by: Philipp A. <flying-sheep@web.de>

* (chore): remove nested if-then

* (fix): scalar condition

* (chore): disallow zarr 3

* (chore): update message

* (fix): zarr v3 fixes

* (chore): comment

* (fix): docs

---------

Co-authored-by: Phil Schaf <flying-sheep@web.de>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
@ilan-gold

Copy link
Copy Markdown
Contributor Author

@flying-sheep Here is the diff for mergin the zarr v3 into this branch - it's non-trivial so I wanted to give you a chance to peak this before merging:

42264e4

@ilan-gold
ilan-gold enabled auto-merge (squash) March 13, 2025 10:42
@ilan-gold
ilan-gold merged commit 3a472c7 into main Mar 13, 2025
@ilan-gold
ilan-gold deleted the ig/xarray_compat branch March 13, 2025 11:01
barlowa124 pushed a commit to barlowa124/anndata that referenced this pull request Dec 4, 2026
…ng + `read_elem_as_dask` -> `read_elem_lazy` (scverse#1247)

* (fix): change unused category function from method to function

* (fix): actually track keys instead of relying on `deafultdict` behavior

* (chore): test unconsolidated warning

* Update pyproject.toml

Co-authored-by: Philipp A. <flying-sheep@web.de>

* (fix): use `test-full`/`test`

* (fix): typing for `_gen_dataframe`

* (chore): imrpoved comments for `Dataset2D`

* (fix): `iloc` is an `attr` not a `meth`

* (fix): release notes

* (fix): `zarr` doc in `read_backed`

* (fix): docs string

* (fix): wording in release note

* (chore): move `_remove_unused_categories` to static method

* (chore): use one `isinstance` call in `coerce_arrays`

* (chore): clean up `read_dataframe`

* (chore): handle case where `chunks` is not needed

* (chore): make reusable `LazyDataStructures`

* (chore): use `Path.suffix`

* (chore): `msg` for `warnings`

* (chore): remove erroneous `Union` in `TypeVar`

* (fix): use `cached_property` for accessing `dtype` + test

* (refactor): use `cached_property` for `categories`

* (refactor): use guard clause in `__getitem__` better

* (chore): type `get_index_dim`

* (fix): `shape` return type

* (refactor): `_subset` guard clause

* (fix): use `Counter`

* (refactor): `fix_known_differences` usage of `as_type`

* (chore): fragment

* (chore): fix the generic problem

* (chore): clean up tests

* Update tests/test_read_backed_experimental.py

Co-authored-by: Philipp A. <flying-sheep@web.de>

* (fix): should -> shall

* Apply suggestions from code review

Co-authored-by: Philipp A. <flying-sheep@web.de>

* (fix): `_gen_xarray_dict_iterator_from_elems` -> `_gen_xarray_dict_iterator_from_elems`

* (feat): indexing with `DataArray`

* (fix): check h5 store

* (fix):check `DataArray` closer

* (fix): clean up `api.md` from merge

* (fix): remove `read_elem_as_dask` docs reference

* (chore): add notebooks/read_backed_experimental

* (chore): update notebooks

* (refactor): set `pytestmark` at the top

* (chore): clarify comment

* (refactor): add `assert_access_count` method for `AccessTrackingStore`

* (refactor): `read_backed`->`read_lazy`

* (fix): actually `read_backed` -> `read_lazy`

* (chore): time to require `aiohttp` `fsspec` and `zarr` and `requests`

* Merge branch 'main' into ig/xarray_compat

* (chore): update notebook

* (fix): actually only read `index` once

* (chore): add `concat` test

* (feat): add `columns` compat

* (fix): type of subset

* (fix): `MaskedArray` `dtype

* (fix): add `index.setter`

* (chore): add `concat` compat for xarray

* (fix): refactor concat for in-memory

* (chore): add rest of test

* (feat): allow for concat with masked type using dask

* (refactor): own function for concat xarray

* (fix): add basic off-axis mapping without reading in i.e just an index

* (feat): add merge for alt annot

* (fix): notebook

* (fix): NaS in sparse dask

* (chore): add `X` tracker

* (chore): add more robust matrix type tests

* (fix): ok now notebooks?

* (feat): fix additional index load

* (feat): no-load index

* (fix): only use range indices for `{obs,var}`

* (chore): add range index testing

* (fix): ensure `{obs,var}_names` always exists on dataset

* (fix): only use `use_range_index` on `{obs,var}`

* (fix): don't check uniqueness to prevent index load + rename variable

* (fix): check for presence of indexing key

* always return `index` object

* (fix): remove unnecessary check?

* (chore): update notebook

* (fix): docstring class

* (fix): explicit 1d chunking for `concat`

* (chore): change `concat` test name

* (chore): rename test file

* (chore): rename notebook

* (chore): clarify `load_annotation_index`

* (fix): allow concatenation along arbitrary index + indexing test

* (fix): notebook path in docs

* (fix): don't copy column in dataset concat

* (fix): actually test h5

* (feat): add h5ad concat support

* (fix): add docsting example

* (fix): catch warnings

* (fix): format

* (fix): threaded tests annotation index

* (fix): remove xarray test from minimum deps

* (fix): skip experimental backed tests if xarray not installed

* (chore): remove todo

* (feat): add `uns` reading

* (feat): add `Raw` reading + tests

* (chore): make `test-full` shorter

* (fix): stricter type checking

* (fix): dtype casting for concat

* (chore): separate into two cleaner unit tests

* (fix): typing of `make_xarray_extension_dtypes_dask

* (chore): remove comment

* (fix): clean up compat

* (chore): xarray raises import error for `read_lazy`

* (fix) ignore some uncovered lines

* use existing warn import

* merge

* (chore): add awkward `nitpick_ignore` comment

* (refactor): use generator for new datasets

* (chore): docs + types in `merge.py`

* (recactor): use set for `index_name` in `merge.py`

* (refactor): comprehension for `{alt_}annotations_in_memory`

* (chore): types in `lazy_methods.py`

* (chore): `lazy_methods.py` index handling made clearer

* (chore): move comment

* (chore): dedupe `read_params` usage

* (chore): `**kwargs` usage doesn't affect call when empty

* (fix): clean up `_lazy_arrays.py` typing

* (fix): no assert, raise ValueError

* (fix): use `get` instead of membership check + no in-place

* (chore): pytest mark to beginning + `diskfmt` -> `diskfmt` + thread safety using `worker_id`

* (fix): remove resetting key trackers

* (fix): adata only has 4 cchunks in test, udpate comment

* (chore): better use arrange-act-assert

* (chore): ids for boolean params

* (chore): contextlib + better assert objects

* (chore): refactor concatenation for arrange-act-assert

* (fix): notebook submodule

* (fix): use `find_spec` pattern

* (chore): re-insert types for `AccessTrackingStore`

* (chore): dedent docstrings

* (chore): raise error if slots have changed on `ZarrOrHDF5Wrapper`

* (fix): add slots to please xarray

* (chore): remove redefinition

* (refactor): reuse join type

* (fix): mixed type dataframe merging

* (fix): condition for going to memory in mixed typing

* (refactor): mixed type helper function

* (fix): try linking to dask/awkward in docs build

* (fix): awkward array docs

* (chore): `ValueError` -> `AssertionError`

* (fix): clean up `_lazy_arrays.py`

* (fix): `ValueError`->`KeyError` for store

* (chore): add note about `unify_extension_dtypes`

* (chore): add ids

* Apply suggestions from code review

Co-authored-by: Philipp A. <flying-sheep@web.de>

* (fix): move all changes form anndata_elem

* (fix): `read_elem_as_dask`->`read_elem_lazy`

* (chore): refactor `test_read_lazy` fixtures

* Update tests/test_read_lazy.py

Co-authored-by: Philipp A. <flying-sheep@web.de>

* (chore): restore types

* (fix): do `randint`

* (chore): ermove slots check

* (fix): return read_lazy

* (fix): concating with hdf5 and cluster obviates need for locks works with normal pytest

* (fix): add warning catch

* (chore): good chunk size

* (chore): remove duplicated line

* (chore): use a simpler read mechanism for remote io

* (fix): docs

* (chore): docs note

* (fix): missing element shape

* (fix): correct shape for empty element in concat with dask

* (chore): add test

* (fix): handling of off axis size when no-dask array

* (fix): ruff

* (fix): add `dask` bound for sparse issue

* (chore): relnote

* (fix): undo scientific python changes

* (fix): no `mod` dask

* Apply suggestions from code review

Co-authored-by: Philipp A. <flying-sheep@web.de>

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* (chore): add comment about processes

* (feat): add `nullable-string` support

* (fix): test name

* (chore): add a doc string

* (fix): clarify `categories` read behavior

* (chore): doc

* (chore): ellipses for shortened docstring test

* Apply suggestions from code review

Co-authored-by: Philipp A. <flying-sheep@web.de>

* centralize dev setup

* "useEditorconfig": true

* (fix): dont coerce awkward

* (fix): materialize dask array

* (feat): finish handling of `nullable-string-array`

* (fix): silence warning by using `StringDtype` directly instead of `string`

* (refactor): simplify xarray `dim` -- pandas `index` interplay

* (chore): rename test files

* (refactor): clarify `test_concat_to_memory_var`

* (fix): throw away zeros for numpy-backed dask array

* (chore): loosen restriction on merged part

* (feat): drop requirement that indices must match

* (fix): mark tests properly

* (fix): string dtype issues

* (fix): ensure dummy indices are string typed instead of range for indexing ops

* (chore): raise `TypeError` not `ValueError`

* (chore): pyproject.toml comment

* (refactor): use `doctest_needs` marker

* (fix): remove runtime `pytest` dep

* skip conditionally

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* (fix): pytest skipping

* (chore): `zarr` v3 updates for `xarray` (scverse#1888)

* (wip): support for new zarr version

* (chore): create setting for write version

* (fix): pathing issue

* (chore): use `open_group`

* (fix): another `zarr.open`

* (fix): `zarr_write_version` -> `zarr_write_format`

* (feat): batched reading for sparse

* (fix): object codec

* (fix): revert compressed vectors

* (feat): scalar support

* (fix): `open_group` for v3

* (fix): backed sparse copy method

* (fix): add speed-up for zarr by batching indexing

* (fix): no `__len__` on new zarr arrays

* (fix): some v3 fixes

* Specify mode with kwarg

* chore: typing fixes

* (fix): more `create_dataset` args

* format->version

* clear properly

* dynamic format/version

* Centralize version comparison

* Fix most create_dataset errors

* unpin zarr everywhere

* Almost fix docs

* (fix): compression test

* (fix): tracking store

* (fix): `as_group` `mode` arg

* (fix): temporary fix for writing from zarr array

* (fix): more context issues

* (fix): no `chunks` `bool` arg

* (fix): return `item` for array

* (chore): add issue

* Bump scanpydoc version

* (chore): add zarr v2 test

* (chore): add warning for zarr v2

* (fix): fix tracking tests for zarr v2

* (chore): refactor a bit

* (fix): revert zarr v2 test

* (fix): setting on group test

* (fix): reopening issue

* (fix): using zip files for backwards compat

* (fix): temporary fix for `empty`

* (fix): io dispatched keys test

* (fix): sparse array access tracking

* (fix): more reopen zarr store

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* (fix): lazy reading

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* (fix): ensure v2 group is made

* (fix): add `visititems`

* (fix): point zarr at main

* (fix): don't provide `VLenUTF8Codec` for default string

* (fix): doctest

* (fix): move off the zarr main branch

* (fix): pin zarr in benchmarks

* (feat): zarr v2 handling in tests

* (fix): warning on `zarr.open`

* (fix): `create_array` instead of `create_dataset`

* (chore): remove whitespace

* (fix): bring back zip files after fixing zarr bug

* (chore): relnote

* (chore): clarify comment

* (fix): cleaner `X` check

* (fix): wrong operator

* (fix): read in `zarr` zip correctly

* (chore): relnote

* merge

* (fix): bound zarr

* (chore): unbound zarr

* (chore): update `zarr` dep

* (fix): del `append_data` after use

* (chore): revert h5 sparse_as_dense

* Update src/anndata/_core/sparse_dataset.py

Co-authored-by: Philipp A. <flying-sheep@web.de>

* (fix): cleaner `fitlers, dtype`

* (fix): type of `write_scalar_group`

* (chore): future warning -> deprecation warning

* Update src/anndata/_io/specs/methods.py

Co-authored-by: Philipp A. <flying-sheep@web.de>

* (chore): remove nested if-then

* (fix): scalar condition

* (chore): disallow zarr 3

* (chore): update message

* (fix): zarr v3 fixes

* (chore): comment

* (fix): docs

---------

Co-authored-by: Phil Schaf <flying-sheep@web.de>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* (chore): notebooks

* (fix): notebooks

* (chore): remove zarr import checks

* Merge branch 'main' into ig/xarray_compat

---------

Co-authored-by: Philipp A. <flying-sheep@web.de>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

5 participants