boundannbatch 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,22 @@
1
+ """Declarative, index-free class-mapping data loading over annbatch.
2
+
3
+ Everything is a :class:`Stream` — one streamed population over a source. :class:`Loader` yields stochastic
4
+ matched batches for training and :class:`EvalLoader` a deterministic full-coverage pass; both key their
5
+ output by stream name, then by the stream's :mod:`anndata.acc` references (``A.X``, ``A.layers[k]``,
6
+ ``A.obsm[k]``).
7
+ """
8
+
9
+ from boundannbatch._eval import EvalLoader
10
+ from boundannbatch._io import obs_columns, open_adata, open_source
11
+ from boundannbatch._loader import Loader
12
+ from boundannbatch._schema import SamplerParams, Stream
13
+
14
+ __all__ = [
15
+ "EvalLoader",
16
+ "Loader",
17
+ "SamplerParams",
18
+ "Stream",
19
+ "obs_columns",
20
+ "open_adata",
21
+ "open_source",
22
+ ]
@@ -0,0 +1,108 @@
1
+ """``BoundClassSampler``: a link's sampler, drawing each batch from the class the primary drew for it."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import itertools
6
+ from typing import TYPE_CHECKING
7
+
8
+ import numpy as np
9
+ from annbatch.samplers import ClassSampler
10
+ from annbatch.utils import split_given_size
11
+
12
+ if TYPE_CHECKING:
13
+ from collections.abc import Iterator, Mapping
14
+
15
+ import pandas as pd
16
+ from annbatch.types import LoadRequest
17
+
18
+ __all__ = ["BoundClassSampler"]
19
+
20
+
21
+ class BoundClassSampler(ClassSampler):
22
+ """Replays ``inner``'s per-batch class schedule onto another obs table.
23
+
24
+ For every batch ``inner`` yields, this sampler yields one batch of its own ``batch_size`` observations,
25
+ read as whole chunks of a single class of ``classes``: one whose labels agree with the inner batch's on
26
+ the ``on`` positions (``{inner tuple position: own tuple position}``), drawn ∝ ``class_weights`` among
27
+ those (a non-positive weight excludes a class). Both samplers see the same batches, so iterate a
28
+ ``deepcopy`` of the sampler ``inner`` was copied from to stay in lockstep with it.
29
+
30
+ Parameters
31
+ ----------
32
+ inner
33
+ The class sampler whose schedule is replayed.
34
+ chunk_size, preload_nchunks, batch_size
35
+ Sizing for this sampler; ``batch_size`` must be a multiple of ``chunk_size``.
36
+ inner_classes
37
+ ``inner``'s per-observation classes, whose categories are tuples.
38
+ classes
39
+ This sampler's per-observation classes, whose categories are tuples.
40
+ on
41
+ ``{inner tuple position: own tuple position}`` for the label positions that must agree.
42
+ class_weights
43
+ One weight per category of ``classes``; ``None`` is uniform.
44
+ rng
45
+ Random number generator for the within-context draws and the chunk starts.
46
+ """
47
+
48
+ def __init__(
49
+ self,
50
+ inner: ClassSampler,
51
+ chunk_size: int,
52
+ preload_nchunks: int,
53
+ batch_size: int,
54
+ *,
55
+ inner_classes: pd.Categorical,
56
+ classes: pd.Categorical,
57
+ on: Mapping[int, int],
58
+ class_weights: np.ndarray | None = None,
59
+ rng: np.random.Generator | None = None,
60
+ ) -> None:
61
+ if batch_size % chunk_size:
62
+ raise ValueError(f"batch_size ({batch_size}) must be a multiple of chunk_size ({chunk_size}).")
63
+ super().__init__(
64
+ chunk_size,
65
+ preload_nchunks,
66
+ batch_size,
67
+ classes=classes,
68
+ num_samples=inner.n_batches(len(inner_classes)) * batch_size,
69
+ class_weights=class_weights,
70
+ drop_last=True,
71
+ rng=rng,
72
+ )
73
+ self._inner = inner
74
+ self._inner_classes = inner_classes
75
+ self._inner_chunk_size = inner._chunk_size
76
+
77
+ # Own drawable classes per shared key, with their probabilities renormalized within the key.
78
+ def key(label: tuple, positions: Mapping[int, int] | list[int]) -> tuple:
79
+ return tuple(label[p] for p in positions)
80
+
81
+ own_codes, own_probs = self._rle_manager.codes, self._rle_manager.weights
82
+ by_key: dict[tuple, list[int]] = {}
83
+ for i, code in enumerate(own_codes):
84
+ by_key.setdefault(key(classes.categories[code], list(on.values())), []).append(i)
85
+ self._choices = {k: (own_codes[ix], own_probs[ix] / own_probs[ix].sum()) for k, ix in by_key.items()}
86
+ # Per inner class code: the key it binds on. Every class inner can draw must be drawable here.
87
+ self._inner_key = [key(label, list(on)) for label in inner_classes.categories]
88
+ missing = {self._inner_key[c] for c in inner._rle_manager.codes} - self._choices.keys()
89
+ if missing:
90
+ raise ValueError(f"The inner sampler can draw classes {sorted(missing)} with no positive-weight match.")
91
+
92
+ def _iter_requests(self) -> Iterator[LoadRequest]:
93
+ inner_codes = self._inner_classes.codes
94
+ batch_codes = []
95
+ for request in self._inner.sample(len(self._inner_classes)):
96
+ starts = [s.start for s in request["requests"]]
97
+ for split in request["splits"]:
98
+ pos = int(split[0]) # every row of an inner batch is of the same class
99
+ row = starts[pos // self._inner_chunk_size] + pos % self._inner_chunk_size
100
+ codes, probs = self._choices[self._inner_key[inner_codes[row]]]
101
+ batch_codes.append(self._rng.choice(codes, p=probs))
102
+ per_batch = self._batch_size // self._chunk_size
103
+ slices = self._rle_manager.slices_from_classes(np.repeat(np.asarray(batch_codes), per_batch), self._rng)
104
+ for window in itertools.batched(slices, self._preload_nchunks):
105
+ splits = split_given_size(np.arange(len(window) * self._chunk_size), self._batch_size)
106
+ for batch in splits:
107
+ self._rng.shuffle(batch)
108
+ yield {"requests": list(window), "splits": splits}
boundannbatch/_eval.py ADDED
@@ -0,0 +1,142 @@
1
+ """``EvalLoader`` — the deterministic, full-coverage counterpart to :class:`~boundannbatch.Loader`.
2
+
3
+ It reuses :class:`Loader`'s :class:`~boundannbatch.Stream` + :class:`~boundannbatch._source.Source` machinery;
4
+ only the sampler becomes an ordered leaf walk, so matching, unified sources and reps behave identically.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Callable, Iterator, Mapping
10
+
11
+ import anndata as ad
12
+ import numpy as np
13
+
14
+ from boundannbatch._io import _read_rows
15
+ from boundannbatch._schema import _LEAF, _PRIMARY, _ROWS, Rep, Stream, Weights, validate_links
16
+ from boundannbatch._source import Source, build_sources, resolve_source
17
+
18
+ __all__ = ["EvalLoader"]
19
+
20
+
21
+ def _positive(weights: Weights | None) -> set[tuple] | None:
22
+ """The positive-weight leaves as a set — ``None`` when unweighted (keep every leaf)."""
23
+ return None if weights is None else {tuple(k) for k, w in weights.items() if w > 0}
24
+
25
+
26
+ class EvalLoader:
27
+ """Deterministic full-coverage (or deduplicated) matched pass over grouped data.
28
+
29
+ Where :class:`~boundannbatch.Loader` draws a stochastic per-batch schedule for training, this walks every
30
+ primary **leaf once** in factorization order, yielding all its cells, each matched to its linked source
31
+ by ``match_on``. Every group is covered and surfaced as ``batch["leaf"]`` — what shape inference and
32
+ metrics want.
33
+
34
+ Parameters
35
+ ----------
36
+ max_per_group
37
+ Per-group cap that doubles as a dedup knob. :obj:`None` — every cell of every group (full eval
38
+ against real target cells); ``N`` — at most ``N`` per group (all of them when fewer); ``1`` — one
39
+ representative per group, i.e. the unique ``group_by`` combinations (a deduplicated dataset).
40
+ subsample
41
+ Which ``N``: ``"head"`` (first ``N`` in row order), ``"random"`` (a ``seed``-ed, per-seed
42
+ reproducible draw), or a callable ``(rows, n, rng) -> rows``.
43
+ """
44
+
45
+ def __init__(
46
+ self,
47
+ sources: Mapping[str, ad.AnnData | list[ad.AnnData]],
48
+ *,
49
+ primary: Stream,
50
+ links: Mapping[str, Stream] | None = None,
51
+ to: str | None = None,
52
+ max_per_group: int | None = None,
53
+ subsample: str | Callable[[np.ndarray, int, np.random.Generator], np.ndarray] = "head",
54
+ seed: int = 0,
55
+ ) -> None:
56
+ self._to = to
57
+ self._max = max_per_group
58
+ self._subsample = subsample
59
+ self._seed = seed
60
+ self._primary = primary
61
+ self._links = dict(links or {})
62
+ validate_links(primary, self._links)
63
+ self._sources = build_sources(sources)
64
+ self._union_cache: dict[tuple[str, ...], Source] = {}
65
+
66
+ # Primary: factorize once -> per-cell codes + the ordered leaves (== unique group_by combinations).
67
+ self._psrc = resolve_source(self._sources, primary, self._union_cache)
68
+ self._pf = self._psrc.factorize(tuple(primary.group_by))
69
+ # Optional selection: a primary weight of 0 (or an absent leaf) excludes that group, as for Loader.
70
+ self._wanted = _positive(primary.weights)
71
+
72
+ # Each link: bucket its (positive-weight) cells by ``match_on`` value, so a primary leaf resolves its
73
+ # matched rows in O(1); ``match_on=()`` buckets everything under one unconditional key.
74
+ self._lsrc: dict[str, Source] = {}
75
+ self._lrows: dict[str, dict[tuple, np.ndarray]] = {}
76
+ for name, link in self._links.items():
77
+ src = resolve_source(self._sources, link, self._union_cache)
78
+ self._lsrc[name] = src
79
+ lf = src.factorize(tuple(link.group_by))
80
+ keep = _positive(link.weights)
81
+ match_pos = [link.group_by.index(c) for c in link.match_on]
82
+ buckets: dict[tuple, list[np.ndarray]] = {}
83
+ for code, leaf in enumerate(lf.leaves):
84
+ if keep is not None and leaf not in keep:
85
+ continue
86
+ key = tuple(leaf[p] for p in match_pos)
87
+ buckets.setdefault(key, []).append(np.flatnonzero(lf.codes == code))
88
+ self._lrows[name] = {key: np.sort(np.concatenate(rows)) for key, rows in buckets.items()}
89
+
90
+ def _cap(self, rows: np.ndarray, rng: np.random.Generator) -> np.ndarray:
91
+ """Subsample ``rows`` to at most ``max_per_group`` per group, per the ``subsample`` strategy."""
92
+ if self._max is None or len(rows) <= self._max:
93
+ return rows
94
+ if self._subsample == "head":
95
+ return rows[: self._max]
96
+ if self._subsample == "random":
97
+ return np.sort(rng.choice(rows, size=self._max, replace=False))
98
+ return self._subsample(rows, self._max, rng) # custom callable
99
+
100
+ def _read(self, src: Source, reps: tuple[Rep, ...], rows: np.ndarray) -> dict[Rep, object]:
101
+ """Read the given global ``rows`` for each rep of a stream (optionally as torch tensors).
102
+
103
+ ``reps=()`` reads nothing and returns ``{}`` — a metadata-only stream, contributing just its leaf.
104
+ On the primary that is a prediction pass with no known target state: every covariate combination
105
+ enumerated, with linked streams still supplying real cells (e.g. matched controls) as model input.
106
+ """
107
+ arrays: dict[Rep, object] = {ref: _read_rows(src.adatas, ref, rows) for ref in reps}
108
+ if self._to == "torch":
109
+ import torch
110
+
111
+ arrays = {ref: torch.as_tensor(np.asarray(a)) for ref, a in arrays.items()}
112
+ return arrays
113
+
114
+ # ── iteration ──────────────────────────────────────────────────────────
115
+ def __iter__(self) -> Iterator[dict]:
116
+ """Yield one batch per primary leaf: ``{"primary": {rep: rows}, <link>: {...}, "leaf": <tuple>, "rows": {...}}``.
117
+
118
+ Reps are keyed by the stream's :mod:`anndata.acc` references, as for :class:`~boundannbatch.Loader`.
119
+
120
+ ``rows`` maps each stream to the int64 global rows it read (its source's files concatenated in order).
121
+ """
122
+ p_pos = {c: i for i, c in enumerate(self._primary.group_by)}
123
+ rng = np.random.default_rng(self._seed) # reset each pass -> reproducible subsamples for a fixed seed
124
+ for code, leaf in enumerate(self._pf.leaves):
125
+ if self._wanted is not None and leaf not in self._wanted:
126
+ continue
127
+ rows = self._cap(np.flatnonzero(self._pf.codes == code), rng)
128
+ out: dict[str, object] = {_PRIMARY: self._read(self._psrc, self._primary.reps, rows), _LEAF: leaf}
129
+ out_rows = {_PRIMARY: rows}
130
+ for name, link in self._links.items():
131
+ match_vals = tuple(leaf[p_pos[c]] for c in link.match_on) # primary leaf's match_on values
132
+ lrows = self._cap(self._lrows[name].get(match_vals, np.empty(0, dtype=int)), rng)
133
+ out[name] = self._read(self._lsrc[name], link.reps, lrows)
134
+ out_rows[name] = lrows
135
+ out[_ROWS] = out_rows # the global rows each stream read, as for Loader
136
+ yield out
137
+
138
+ def __len__(self) -> int:
139
+ """Number of batches == number of selected primary groups."""
140
+ if self._wanted is None:
141
+ return len(self._pf.leaves)
142
+ return sum(1 for leaf in self._pf.leaves if leaf in self._wanted)
boundannbatch/_io.py ADDED
@@ -0,0 +1,355 @@
1
+ """Container-agnostic data access for the loader: obs columns, leaf codes, and rep backings.
2
+
3
+ Every helper works uniformly over an in-memory ``AnnData``, an out-of-core annbatch
4
+ ``DatasetCollection``, and reps given as :mod:`anndata.acc` references (``A.X``, ``A.layers[k]``,
5
+ ``A.obsm[k]``), so the loader never branches on the source kind. No cell matrices are touched for
6
+ grouping — obs only.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ from collections.abc import Sequence
13
+ from typing import TYPE_CHECKING, Literal
14
+
15
+ import anndata as ad
16
+ import numpy as np
17
+ import pandas as pd
18
+ import zarr
19
+ from anndata.acc import AdRef, LayerAcc, MetaAcc
20
+
21
+ from boundannbatch._schema import Container, Rep, _slot, weight_vector
22
+
23
+ if TYPE_CHECKING:
24
+ from boundannbatch._schema import Stream
25
+
26
+ __all__ = [
27
+ "get_from_container",
28
+ "leaf_codes",
29
+ "materialize_node",
30
+ "obs_columns",
31
+ "open_adata",
32
+ "open_source",
33
+ "is_backed_array",
34
+ ]
35
+
36
+
37
+ def read_backing(x: zarr.Array | zarr.Group) -> zarr.Array | ad.abc.CSRDataset:
38
+ if hasattr(x, "shape"):
39
+ return x
40
+ from anndata.io import sparse_dataset
41
+
42
+ return sparse_dataset(x)
43
+
44
+
45
+ def get_from_container(source: ad.AnnData | list[ad.AnnData], ref: Rep) -> list[zarr.Array | ad.abc.CSRDataset]:
46
+ """The array(s) backing rep ``ref`` (``A.X`` | ``A.layers[k]`` | ``A.obsm[k]``) — one per adata for a list."""
47
+ if isinstance(source, list):
48
+ return [b for a in source for b in get_from_container(a, ref)]
49
+ return [ref.get(source)]
50
+
51
+
52
+ def _put(adata: ad.AnnData, ref: Rep, value) -> None:
53
+ """Place ``value`` at rep ``ref``'s slot of ``adata``, so :func:`get_from_container` finds it again."""
54
+ field, k = _slot(ref)
55
+ if k is None:
56
+ adata.X = value
57
+ else:
58
+ getattr(adata, field)[k] = value
59
+
60
+
61
+ def _path(ref: Rep) -> str:
62
+ """Rep ``ref``'s path inside a zarr / h5ad store (``"X"``, ``"layers/<k>"``, ``"obsm/<k>"``)."""
63
+ field, k = _slot(ref)
64
+ return field if k is None else f"{field}/{k}"
65
+
66
+
67
+ def _read_rows(source: Container, ref: Rep, row_idx: np.ndarray) -> np.ndarray:
68
+ r"""Densely read the global rows ``row_idx`` (ascending, unique) of rep ``ref`` from a source's backings.
69
+
70
+ Each maximal run of *consecutive* rows is read as one contiguous slice (``b[start:stop]``), not a
71
+ scattered fancy-index gather — so a leaf-contiguous layout collapses to a few big reads, and fully
72
+ scattered rows degrade to one slice per row (still correct). Slicing reads uniformly across dense zarr,
73
+ backed ``CSRDataset``\\s and in-memory arrays, so no per-backend indexing branch is needed.
74
+ """
75
+ backings = get_from_container(source, ref) # each has ``.shape`` (sparse groups already wrapped by read_backing)
76
+ offs = np.concatenate([[0], np.cumsum([b.shape[0] for b in backings])]).astype(np.int64)
77
+ parts = []
78
+ for d, b in enumerate(backings):
79
+ lb = row_idx[(row_idx >= offs[d]) & (row_idx < offs[d + 1])] - offs[d] # ascending within this dataset
80
+ runs = np.split(lb, np.flatnonzero(np.diff(lb) != 1) + 1) if lb.size else () # maximal consecutive runs
81
+ for run in runs:
82
+ sub = b[int(run[0]) : int(run[-1]) + 1] # contiguous slice read
83
+ dense = getattr(sub, "todense", None)
84
+ parts.append(np.asarray(dense()) if dense is not None else np.asarray(sub))
85
+ return np.concatenate(parts, axis=0) if parts else np.empty((0, int(backings[0].shape[1])), dtype=np.float32)
86
+
87
+
88
+ def materialize_node(
89
+ source: Container, stream: Stream, factorization: tuple[np.ndarray, list[tuple]] | None = None
90
+ ) -> tuple[ad.AnnData, np.ndarray, list[tuple]]:
91
+ """Materialize a stream's selected (positive-weight) cells into an in-memory (dense) ``AnnData``.
92
+
93
+ Behind :attr:`~boundannbatch.Stream.in_memory`: reads only the positive-weight rows (for each rep) and
94
+ sorts them by ``group_by`` so ``chunk_size > 1`` still reads contiguous runs. Dense and sparse (CSR
95
+ group) alike. Cells must fit host RAM (intended for a small, frequently re-drawn population, e.g.
96
+ matched controls).
97
+
98
+ Also returns the subset's ``(codes, leaves)`` — the caller's sampler needs the subset categorical, and
99
+ it's derived from ``factorization`` (the source's cached ``leaf_codes`` over ``group_by``) when given,
100
+ avoiding a re-factorize; omit it for standalone use.
101
+ """
102
+ cols = stream.group_by
103
+ obs = obs_columns(source, cols)
104
+ codes, leaves = factorization if factorization is not None else leaf_codes(obs, cols)
105
+ selected = np.flatnonzero(weight_vector(stream.weights, leaves) > 0) # leaf codes with positive weight
106
+ row_idx = np.flatnonzero(np.isin(codes, selected)) # ascending global rows of the selected leaves
107
+ reps = {ref: _read_rows(source, ref, row_idx) for ref in stream.reps} # keyed by reference
108
+ sub_obs = obs.iloc[row_idx].reset_index(drop=True)
109
+ # contiguous runs for chunk>1; with no grouping every row is already in the one run
110
+ order = sub_obs.sort_values(list(cols), kind="stable").index.to_numpy() if cols else np.arange(len(sub_obs))
111
+ sub_obs, reps = sub_obs.iloc[order].reset_index(drop=True), {k: v[order] for k, v in reps.items()}
112
+ sub_obs.index = sub_obs.index.astype(str)
113
+ n_vars = next((v.shape[1] for r, v in reps.items() if isinstance(r, LayerAcc)), 0) # X / layer width
114
+ adata = ad.AnnData(obs=sub_obs, var=pd.DataFrame(index=pd.RangeIndex(n_vars).astype(str)))
115
+ for ref, v in reps.items():
116
+ _put(adata, ref, v)
117
+ # Subset (codes, leaves) derived from the parent factorization — no re-factorize. Parent ``leaves`` are
118
+ # string-sorted, so the distinct parent codes present (ascending) are already the subset's leaves in that
119
+ # order, and searchsorted compacts parent → subset codes. Byte-identical to leaf_codes(sub_obs, cols).
120
+ sel = codes[row_idx][order] # parent leaf code per subset row, in the materialized (sorted) order
121
+ present = np.unique(sel) # ascending == string-sorted order of the parent leaves
122
+ sub_leaves = [leaves[c] for c in present]
123
+ sub_codes = np.searchsorted(present, sel)
124
+ return adata, sub_codes, sub_leaves
125
+
126
+
127
+ def leaf_codes(obs: pd.DataFrame, cols: Sequence[str]) -> tuple[np.ndarray, list[tuple]]:
128
+ """Per-cell leaf code + the ordered leaf combinations (the grouping over ``cols``).
129
+
130
+ ``leaves`` are the unique ``cols`` combinations as ``.to_numpy()``-typed tuples — the same construction
131
+ the ``{combo: weight}`` mappings use, so a leaf hash-equals its weight key — ordered by per-element
132
+ string key; ``codes[i]`` indexes ``leaves``.
133
+
134
+ Vectorized: rows are factorized once at C level and remapped onto the string-sorted leaf order. Grouping
135
+ columns are cast to ``category`` first (a pure speed lever — the returned ``(codes, leaves)`` are
136
+ identical either way).
137
+ """
138
+ cols = list(cols)
139
+ if not cols: # no grouping: every cell is in the one leaf ()
140
+ return np.zeros(len(obs), dtype=np.int64), [()] if len(obs) else []
141
+ sub = obs[cols]
142
+ # leaves keep the source dtypes' `.to_numpy()` element types (loop over the FEW unique rows only).
143
+ leaves = sorted((tuple(r) for r in sub.drop_duplicates().to_numpy()), key=lambda t: tuple(map(str, t)))
144
+ if len(sub) == 0:
145
+ return np.zeros(0, dtype=np.int64), leaves
146
+ # Per-column categorical codes + mixed-radix combine → a raw per-cell group code without materializing
147
+ # ~N object tuples. Cast only non-categorical cols (keeps existing category orders); a column's NaN is
148
+ # code -1, shifted to slot 0 so it owns a distinct combination.
149
+ cats = [sub[c] if isinstance(sub[c].dtype, pd.CategoricalDtype) else sub[c].astype("category") for c in cols]
150
+ ncards = [len(c.cat.categories) + 1 for c in cats]
151
+ prod = 1
152
+ for n in ncards:
153
+ prod *= n
154
+ if prod < (1 << 62): # O(N) integer combine (no object tuples); guard against int64 overflow
155
+ combined = np.zeros(len(sub), dtype=np.int64)
156
+ mult = 1
157
+ for cat, n in zip(cats, ncards, strict=True):
158
+ combined += (cat.cat.codes.to_numpy().astype(np.int64) + 1) * mult
159
+ mult *= n
160
+ raw = pd.factorize(combined, use_na_sentinel=False)[0]
161
+ else: # rare: cardinality product overflows int64 → fall back to the object-tuple path
162
+ raw = pd.factorize(
163
+ pd.MultiIndex.from_frame(pd.DataFrame({c: cats[i] for i, c in enumerate(cols)})), use_na_sentinel=False
164
+ )[0]
165
+ # Remap raw group codes → string-sorted leaf codes, keying off each group's representative row read back
166
+ # through `.to_numpy()` (like `leaves`) — so both share the same dtype promotion and NaN→"nan"
167
+ # normalization that the raw factorize `uniques` (keeping per-column dtypes) would not.
168
+ _, first_idx = np.unique(raw, return_index=True) # first row of each group code g = 0..G-1
169
+ reps = sub.iloc[first_idx].to_numpy()
170
+ key_to_code = {tuple(map(str, lf)): i for i, lf in enumerate(leaves)}
171
+ remap = np.fromiter((key_to_code[tuple(map(str, r))] for r in reps), dtype=np.int64, count=len(reps))
172
+ return remap[raw], leaves
173
+
174
+
175
+ def obs_columns(source: Container, cols: Sequence[str]) -> pd.DataFrame:
176
+ """The ``cols`` of ``source``'s obs, without touching any cell matrix.
177
+
178
+ A list of AnnData is read as one dataset: their columns are stacked in list order with a fresh positional
179
+ index, and a column categorical in every file gets the union of their categories, so its codes compare
180
+ across files.
181
+ """
182
+ if isinstance(source, list): # list of AnnData: concatenate obs in list order (= key_backings order)
183
+ frames = [obs_columns(a, cols) for a in source]
184
+ _align_categoricals(frames)
185
+ return pd.concat(frames, ignore_index=True)
186
+ if isinstance(source, ad.AnnData):
187
+ return source.obs[list(cols)]
188
+ return source.obs(columns=list(cols)) # DatasetCollection
189
+
190
+
191
+ def _align_categoricals(frames: list[pd.DataFrame]) -> None:
192
+ """Align each column that is categorical in *every* frame to the union of its categories, in place.
193
+
194
+ ``pd.concat`` upcasts categoricals with mismatched categories to ``object``, so per-source obs with
195
+ differing category sets would turn grouping columns into strings and force a re-factorize downstream.
196
+ Setting the union categories first keeps integer codes (faster, lower-memory). No-op for <2 frames or
197
+ columns not categorical everywhere.
198
+ """
199
+ from pandas.api.types import union_categoricals
200
+
201
+ if len(frames) < 2:
202
+ return
203
+ for col in frames[0].columns:
204
+ series = [f[col] for f in frames]
205
+ if not all(isinstance(s.dtype, pd.CategoricalDtype) for s in series):
206
+ continue
207
+ union = union_categoricals(series, ignore_order=True).categories
208
+ for f in frames:
209
+ f[col] = f[col].cat.set_categories(union) # replace the column; `.loc` cannot change a dtype
210
+
211
+
212
+ def _keys(group) -> list[str]:
213
+ return sorted(group.keys()) if group is not None else []
214
+
215
+
216
+ def _has(g, ref: Rep) -> bool:
217
+ field, k = _slot(ref)
218
+ return "X" in g if k is None else k in _keys(g.get(field))
219
+
220
+
221
+ def _obs_cols(g) -> list[str]:
222
+ return list(g["obs"].attrs["column-order"]) # the on-disk dataframe spec lists its columns
223
+
224
+
225
+ def _present(where, g, arrays: Sequence[Rep], cols: Sequence[str], uns: Sequence[str], *, skip: bool):
226
+ """The ``(arrays, cols, uns)`` the store has. Unless ``skip``, one :class:`KeyError` names every absent part."""
227
+ has_cols, has_uns = set(_obs_cols(g)), set(_keys(g.get("uns")))
228
+ lacks = [r for r in arrays if not _has(g, r)]
229
+ if not skip:
230
+ missing = []
231
+ for ref in lacks:
232
+ field, k = _slot(ref)
233
+ missing.append("X" if k is None else f"{field}[{k!r}] (has {field}: {_keys(g.get(field))})")
234
+ if absent := sorted(set(cols) - has_cols):
235
+ missing.append(f"obs {absent} (has {sorted(has_cols)})")
236
+ if absent := sorted(set(uns) - has_uns):
237
+ missing.append(f"uns {absent} (has {sorted(has_uns)})")
238
+ if missing:
239
+ raise KeyError(f"{where} lacks " + "; ".join(missing))
240
+ return [r for r in arrays if r not in lacks], [c for c in cols if c in has_cols], [k for k in uns if k in has_uns]
241
+
242
+
243
+ def _assemble(g, obs: pd.DataFrame, arrays: dict, uns: Sequence[str]) -> ad.AnnData:
244
+ """An AnnData of ``obs``, ``var``'s index, the opened ``arrays`` (``{ref: array}``) and the ``uns`` keys."""
245
+ var = g["var"]
246
+ adata = ad.AnnData(obs=obs, var=pd.DataFrame(index=pd.Index(ad.io.read_elem(var[var.attrs["_index"]])).astype(str)))
247
+ for ref, array in arrays.items():
248
+ _put(adata, ref, array)
249
+ for key in uns:
250
+ adata.uns[key] = ad.io.read_elem(g["uns"][key])
251
+ return adata
252
+
253
+
254
+ def _split_refs(refs) -> tuple[list[Rep], list[str], bool]:
255
+ """``(arrays, obs columns, whether the obs index is asked for)`` from :mod:`anndata.acc` references.
256
+
257
+ A reference into an array (``A.obsm["pca"][:, 0]``) stands for the whole array.
258
+ """
259
+ arrays, cols, index = [], [], False
260
+ for ref in refs:
261
+ if isinstance(ref, AdRef) and isinstance(ref.acc, MetaAcc):
262
+ if ref.acc.dim != "obs":
263
+ raise ValueError(f"{ref!r}: only obs columns and the obs index can be opened, not var.")
264
+ if ref.idx is None:
265
+ index = True
266
+ else:
267
+ cols.append(ref.idx)
268
+ else:
269
+ arr = ref.acc if isinstance(ref, AdRef) else ref
270
+ _slot(arr) # X, a layer or an obsm entry
271
+ arrays.append(arr)
272
+ return list(dict.fromkeys(arrays)), list(dict.fromkeys(cols)), index
273
+
274
+
275
+ def _is_h5ad(path) -> bool:
276
+ return os.path.splitext(os.fspath(path))[1].lower() == ".h5ad"
277
+
278
+
279
+ def _open_store(path):
280
+ """A zarr group, or an h5py file for a ``.h5ad`` path. An annbatch collection root is refused."""
281
+ if _is_h5ad(path):
282
+ import h5py
283
+
284
+ return h5py.File(path, "r")
285
+ g = zarr.open_group(path, mode="r")
286
+ if g.attrs.get("encoding-type") == "annbatch-preshuffled":
287
+ raise NotImplementedError(
288
+ f"{path} is an annbatch DatasetCollection root, which open_adata does not support yet."
289
+ )
290
+ return g
291
+
292
+
293
+ def open_adata(
294
+ path: str | os.PathLike, *refs, uns_keys: Sequence[str] = (), missing: Literal["raise", "skip"] = "raise"
295
+ ) -> ad.AnnData:
296
+ """Open ``path`` with exactly the parts the :mod:`anndata.acc` references name.
297
+
298
+ ``A.X``, ``A.layers[k]`` and ``A.obsm[k]`` open arrays; a reference into one, such as
299
+ ``A.obsm["pca"][:, 0]``, opens the whole array. ``A.obs[col]`` reads a column and ``A.obs.index`` the obs
300
+ names; without it the frame gets a ``RangeIndex``. ``uns_keys`` are read into memory.
301
+
302
+ The arrays of a zarr store stay on disk, wrapped by :func:`read_backing` (a dense array passes through,
303
+ a sparse group becomes a ``CSRDataset``), so the loader streams them and a caller reads only the rows it
304
+ indexes. ``var`` is reduced to its index. A ``.h5ad`` file is read the same way, but its
305
+ arrays are loaded into memory and the file is closed: the loader streams only zarr and backed sparse
306
+ arrays, and an open h5py handle blocks writes to the file and does not survive a forked worker.
307
+ A reference the store lacks raises a :class:`KeyError` naming what it has, or with ``missing="skip"`` is left
308
+ out, for a dataset whose files each hold some of the parts.
309
+ """
310
+ if missing not in ("raise", "skip"):
311
+ raise ValueError(f'missing must be "raise" or "skip", not {missing!r}.')
312
+ arrays, cols, index = _split_refs(refs)
313
+ g = _open_store(path)
314
+ h5ad = not isinstance(g, zarr.Group)
315
+ try:
316
+ arrays, cols, uns_keys = _present(path, g, arrays, cols, uns_keys, skip=missing == "skip")
317
+ # zarr: on disk, wrapped for streaming; h5ad: into memory (dense or sparse) before the file closes
318
+ read = ad.io.read_elem if h5ad else read_backing
319
+ opened = {ref: read(g[_path(ref)]) for ref in arrays}
320
+ obs_group = g["obs"]
321
+ obs = pd.DataFrame({c: ad.io.read_elem(obs_group[c]) for c in cols})
322
+ if index or not (opened or cols): # nothing else gives the number of cells
323
+ obs.index = pd.Index(ad.io.read_elem(obs_group[obs_group.attrs["_index"]])).astype(str)
324
+ else:
325
+ obs.index = pd.RangeIndex(next(iter(opened.values())).shape[0] if opened else len(obs)).astype(str)
326
+ return _assemble(g, obs, opened, uns_keys)
327
+ finally:
328
+ if h5ad:
329
+ g.close()
330
+
331
+
332
+ def open_source(src, *refs, uns_keys: Sequence[str] = ()) -> Container:
333
+ """Resolve one :class:`~boundannbatch.Stream` source value to a :data:`~boundannbatch.Container`.
334
+
335
+ An in-memory ``AnnData`` or ``DatasetCollection`` passes through unchanged. A path (zarr or ``.h5ad``) is
336
+ opened with :func:`open_adata`, reading only the parts the :mod:`anndata.acc` ``refs`` name and the
337
+ ``uns_keys``; a zarr annbatch collection root (``encoding-type`` ``"annbatch-preshuffled"``) is not yet
338
+ supported. A list of paths becomes a list of AnnData (the loader feeds one backing per adata to
339
+ ``add_datasets``).
340
+ """
341
+ from annbatch import DatasetCollection
342
+
343
+ if isinstance(src, ad.AnnData | DatasetCollection):
344
+ return src
345
+ if isinstance(src, str | os.PathLike):
346
+ return open_adata(src, *refs, uns_keys=uns_keys)
347
+ return [a if isinstance(a, ad.AnnData) else open_adata(a, *refs, uns_keys=uns_keys) for a in src]
348
+
349
+
350
+ def is_backed_array(arr) -> bool:
351
+ """True if ``arr`` is an on-disk backing (dense zarr array / backed ``CSRDataset``), not in-memory."""
352
+ import zarr
353
+ from anndata.abc import CSRDataset
354
+
355
+ return isinstance(arr, zarr.Array | CSRDataset)