-
Notifications
You must be signed in to change notification settings - Fork 200
feat: AnnData.unwriteable based on AnnData._reduce + iter_outer + refactorings of other relevant functions
#2372
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 3 commits
Commits
Show all changes
39 commits
Select commit
Hold shift + click to select a range
b907554
feat: `AnnData.can_write` based on `AnnData.fold`
ilan-gold 19daed5
chore: docs
ilan-gold 4125375
refactor: use accessors
ilan-gold 8be5ba2
fix: DFS order + fixes
ilan-gold 0f4d1b0
chore: add test for `uns`
ilan-gold 9338baa
Merge branch 'main' into ig/fold_can_write
ilan-gold 69daf90
feat: `raw` + `uns` traversal
ilan-gold 932d766
fix: `fold` -> `reduce`
ilan-gold e0f3ee2
chore: docs
ilan-gold 436fc68
Merge branch 'main' into ig/fold_can_write
ilan-gold ee04741
fix: `meth` not `func`
ilan-gold 6d6f454
fix: `fold` not `reduce` in relnote
ilan-gold 1f77a4c
fix: nested
ilan-gold 91adffe
chore: more `func` clarification
ilan-gold 928b72a
fix: link
ilan-gold 19a915d
fix: link
ilan-gold c0886fe
refactor: simpler
ilan-gold 6cffc05
fix: relnote number
ilan-gold 44890eb
Merge branch 'main' into ig/fold_can_write
ilan-gold 39800aa
refactor: use `iter`
ilan-gold 6cb401b
fix: oops
ilan-gold 1dfdd96
fix: why was this deleted?
ilan-gold 9ad937f
fix: doc string
ilan-gold 0c03ffb
fix: docs
ilan-gold f00db89
fix: remove `parent_type`
ilan-gold cabc914
Merge branch 'main' into ig/fold_can_write
ilan-gold 9fa978a
fix: writing none
ilan-gold e7b201f
fix: API changes
ilan-gold 95136a2
fix use `set`
ilan-gold 4eba690
fix: docs
ilan-gold fdd6b7c
fix: remove unused docs / private type
ilan-gold 5760cb2
fix: nexting
ilan-gold 7382b67
fix: ok
ilan-gold 3c747e1
fix: handle bad categoricals
ilan-gold 371d535
fix: handle index / awkward
ilan-gold d8f66c3
Merge branch 'main' into ig/fold_can_write
ilan-gold 5a0fded
refactor: `can_write` -> `unwriteable`
ilan-gold a6374ce
Merge branch 'ig/fold_can_write' of github.com:scverse/anndata into i…
ilan-gold 1ad82f4
Merge branch 'main' into ig/fold_can_write
ilan-gold File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| New {meth}`AnnData.fold` for crawling the "elems" and accumulating a value over these, and then {meth}`AnnData.can_write` built on top {user}`ilan-gold` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4,7 +4,7 @@ | |
|
|
||
| from __future__ import annotations | ||
|
|
||
| from collections import OrderedDict | ||
| from collections import OrderedDict, defaultdict | ||
| from collections.abc import Mapping, MutableMapping, Sequence | ||
| from copy import copy, deepcopy | ||
| from functools import partial, singledispatchmethod | ||
|
|
@@ -22,6 +22,7 @@ | |
| from scipy.sparse import issparse | ||
|
|
||
| from anndata._warnings import ImplicitModificationWarning | ||
| from anndata.acc import A, AdRef, GraphAcc, LayerAcc, MultiAcc | ||
|
|
||
| from .. import utils | ||
| from .._settings import settings | ||
|
|
@@ -63,7 +64,10 @@ | |
|
|
||
| from zarr.storage import StoreLike | ||
|
|
||
| from ..acc import AdRef, Array, MapAcc, RefAcc | ||
| from anndata.types import FoldFunc | ||
| from anndata.typing import RWAble | ||
|
|
||
| from ..acc import Array, MapAcc, RefAcc | ||
| from ..compat import XDataset | ||
| from ..typing import Index, Index1D, _Index1DNorm, _XDataType | ||
| from .aligned_mapping import AxisArraysView, LayersView, PairwiseArraysView | ||
|
|
@@ -513,36 +517,39 @@ def _init_as_actual( # noqa: PLR0912, PLR0913, PLR0915 | |
| def __sizeof__( | ||
| self, *, show_stratified: bool = False, with_disk: bool = False | ||
| ) -> int: | ||
| def get_size(X) -> int: | ||
| def get_size[R: dict[RefAcc | None, int]]( | ||
| X: RWAble, | ||
| *, | ||
| accumulate: R, | ||
| ref_acc: RefAcc | AdRef | None, | ||
| ) -> R: | ||
| def cs_to_bytes(X) -> int: | ||
| return int(X.data.nbytes + X.indptr.nbytes + X.indices.nbytes) | ||
|
|
||
| if isinstance(X, h5py.Dataset) and with_disk: | ||
| return int(np.array(X.shape).prod() * X.dtype.itemsize) | ||
| elif isinstance(X, BaseCompressedSparseDataset) and with_disk: | ||
| return cs_to_bytes(X._to_backed()) | ||
| elif issparse(X): | ||
| return cs_to_bytes(X) | ||
| else: | ||
| return X.__sizeof__() | ||
|
|
||
| sizes = {} | ||
| attrs = ["X", "_obs", "_var"] | ||
| attrs_multi = ["_uns", "_obsm", "_varm", "varp", "_obsp", "_layers"] | ||
| for attr in attrs + attrs_multi: | ||
| if attr in attrs_multi: | ||
| keys = getattr(self, attr).keys() | ||
| s = sum(get_size(getattr(self, attr)[k]) for k in keys) | ||
| else: | ||
| s = get_size(getattr(self, attr)) | ||
| if s > 0 and show_stratified: | ||
| from tqdm import tqdm | ||
| if is_elem := ( | ||
| (is_ad_ref := isinstance(ref_acc, AdRef)) | ||
| or isinstance(ref_acc, LayerAcc | MultiAcc | GraphAcc) | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. so I wonder if this use case would be better handled with a control flow API. See main review comment. |
||
| ) or (ref_acc is None and X is not self.uns): | ||
| key = ref_acc.acc if is_ad_ref else ref_acc | ||
| if isinstance(X, h5py.Dataset) and with_disk: | ||
| accumulate[key] += int(np.array(X.shape).prod() * X.dtype.itemsize) | ||
| elif isinstance(X, BaseCompressedSparseDataset) and with_disk: | ||
| accumulate[key] += cs_to_bytes(X._to_backed()) | ||
| elif issparse(X): | ||
| accumulate[key] += cs_to_bytes(X) | ||
| else: | ||
| accumulate[key] += X.__sizeof__() | ||
| if not is_elem or ref_acc is A.X: | ||
| s = accumulate[ref_acc] | ||
| if s > 0 and show_stratified: | ||
| from tqdm import tqdm | ||
|
|
||
| print( | ||
| f"Size of {repr(ref_acc).replace('A.', '') if ref_acc is not None else 'uns'}: {tqdm.format_sizeof(s, 'B')}" | ||
| ) | ||
| return accumulate | ||
|
|
||
| print( | ||
| f"Size of {attr.replace('_', '.'):<7}: {tqdm.format_sizeof(s, 'B')}" | ||
| ) | ||
| sizes[attr] = s | ||
| return sum(sizes.values()) | ||
| return sum(self.fold(get_size, init=defaultdict(int)).values()) | ||
|
|
||
| def _gen_repr(self, n_obs, n_vars) -> str: | ||
| backed_at = f" backed at {str(self.filename)!r}" if self.isbacked else "" | ||
|
|
@@ -1446,6 +1453,75 @@ def copy(self, filename: PathLike[str] | str | None = None) -> AnnData: | |
| write_h5ad(filename, self) | ||
| return read_h5ad(filename, backed=mode) | ||
|
|
||
| def fold[T](self, func: FoldFunc[T], *, init: T) -> T: | ||
| """Accumulate a value starting from init by iterating over the "elems"/leaf nodes of the AnnData object in DFS order. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| func | ||
| The function that performs the accumulation | ||
| init | ||
| The starting value | ||
|
|
||
|
|
||
| Returns | ||
| ------- | ||
| An accumulated value | ||
| """ | ||
| accumulate = init | ||
| for attr_name in [ | ||
| "X", | ||
| "obs", | ||
| "var", | ||
| "obsm", | ||
| "varm", | ||
| "obsp", | ||
| "varp", | ||
| "layers", | ||
| ]: | ||
| attr = getattr(self, attr_name) | ||
| acc = getattr(A, attr_name) | ||
| if attr_name != "X": | ||
| for elem_name in attr: | ||
| ref = acc[elem_name] | ||
| accumulate = func( | ||
| attr[elem_name], accumulate=accumulate, ref_acc=ref | ||
| ) | ||
| accumulate = func(attr, accumulate=accumulate, ref_acc=acc) | ||
|
ilan-gold marked this conversation as resolved.
Outdated
|
||
| for elem in self.uns: | ||
| accumulate = func(elem, accumulate=accumulate, ref_acc=None) | ||
| return accumulate | ||
|
|
||
| def can_write(self, *, store_type: Literal["h5", "zarr"] | None) -> bool: | ||
| """Whether or not an `AnnData` object can be written to disk for a given store type. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| store_type | ||
| Which backing store - `None` indicates that it can be writeable to either. | ||
|
|
||
| Returns | ||
| ------- | ||
| Whether or not this object is writable. | ||
| """ | ||
| from anndata._io.specs.registry import _REGISTRY | ||
|
|
||
| writeable_elems = { | ||
| src_type | ||
| for (dest_type, src_type, __) in _REGISTRY.write | ||
| if store_type is None or store_type in dest_type.__module__ | ||
| } | ||
|
|
||
| def predicate(x: RWAble, *, accumulate: bool, ref_acc: AdRef | RefAcc | None): | ||
| if isinstance(ref_acc, AdRef) or ref_acc is None: | ||
|
ilan-gold marked this conversation as resolved.
Outdated
|
||
| if isinstance(x, pd.Series): | ||
| # matches behavior in methods.py | ||
| x = x._values | ||
| return accumulate and type(x) in writeable_elems | ||
| return accumulate | ||
|
|
||
| return self.fold(predicate, init=True) | ||
|
|
||
| @deprecated( | ||
| deprecation_msg( | ||
| *("AnnData.concatenate", "anndata.concat"), | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
FWIW this never handled
rawanyway