vsparse 0.2.0__tar.gz → 0.4.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: vsparse
3
- Version: 0.2.0
3
+ Version: 0.4.0
4
4
  Summary: Value-Compressed Sparse Column/Row (VCSC/VCSR) arrays, with optional AnnData integration
5
5
  Keywords: anndata,single-cell,sparse,compression
6
6
  Author: Aaron Meyer
@@ -89,31 +89,31 @@ v = vsparse.VCSCArray.from_scipy(csc)
89
89
 
90
90
  # Or build from an AnnData object or SciPy sparse array
91
91
  adata = ... # an AnnData object
92
- v = vsparse.from_anndata(adata) # VCSCArray (column-compressed) from adata.X
93
- vr = vsparse.from_anndata(adata, format="csr") # VCSRArray (row-compressed)
92
+ v = vsparse.from_anndata(adata) # VCSCArray (column-compressed) from adata.X
93
+ vr = vsparse.from_anndata(adata, format="csr") # VCSRArray (row-compressed)
94
94
 
95
95
  # Transposition is zero-copy (swaps major/minor axes and shares buffers)
96
- vr = v.T # VCSRArray
96
+ vr = v.T # VCSRArray
97
97
 
98
98
  # Scalar arithmetic & math
99
- v2 = v * 2.0 # Scalar multiplication
100
- v_div = v / 2.0 # Scalar division
101
- v_neg = -v # Negation
102
- v_log = v.log1p() # Elementwise log1p
99
+ v2 = v * 2.0 # Scalar multiplication
100
+ v_div = v / 2.0 # Scalar division
101
+ v_neg = -v # Negation
102
+ v_log = v.log1p() # Elementwise log1p
103
103
 
104
104
  # Matrix & vector products (Numba-parallelized)
105
- y = v @ x # Matrix-vector: (n_rows, n_cols) @ (n_cols,) -> (n_rows,)
106
- y_left = x @ v # Vector-matrix: (n_rows,) @ (n_rows, n_cols) -> (n_cols,)
107
- Y = v @ B # Matrix-matrix: (n_rows, n_cols) @ (n_cols, k) -> (n_rows, k)
108
- Y_left = B @ v # Matrix-matrix: (k, n_rows) @ (n_rows, n_cols) -> (k, n_cols)
105
+ y = v @ x # Matrix-vector: (n_rows, n_cols) @ (n_cols,) -> (n_rows,)
106
+ y_left = x @ v # Vector-matrix: (n_rows,) @ (n_rows, n_cols) -> (n_cols,)
107
+ Y = v @ B # Matrix-matrix: (n_rows, n_cols) @ (n_cols, k) -> (n_rows, k)
108
+ Y_left = B @ v # Matrix-matrix: (k, n_rows) @ (n_rows, n_cols) -> (k, n_cols)
109
109
 
110
110
  # Slicing
111
- col_slice = v[:, [1, 3, 5]] # Fast major-axis slicing (returns VCSCArray)
112
- sub = v[0:10, 0:10] # 2D slicing (falls back to scipy)
111
+ col_slice = v[:, [1, 3, 5]] # Fast major-axis slicing (returns VCSCArray)
112
+ sub = v[0:10, 0:10] # 2D slicing (falls back to scipy)
113
113
 
114
114
  # Conversion & layers
115
- sp_csc = v.to_scipy() # -> scipy.sparse.csc_array (or to_csr())
116
- dense = v.toarray() # -> numpy.ndarray
115
+ sp_csc = v.to_scipy() # -> scipy.sparse.csc_array (or to_csr())
116
+ dense = v.toarray() # -> numpy.ndarray
117
117
  vsparse.to_layer(adata, v, key="counts_vcsc") # Attach to AnnData layer
118
118
  ```
119
119
 
@@ -126,15 +126,15 @@ is an `AnnData` subclass whose `X` (and optionally `raw_X`) is backed directly b
126
126
  ```python
127
127
  import vsparse
128
128
 
129
- va = vsparse.VCSCAnnData.from_anndata(adata) # Compresses X and raw.X
130
- va.X # VCSCArray
131
- va.raw_X # VCSCArray (separate from anndata's .raw)
129
+ va = vsparse.VCSCAnnData.from_anndata(adata) # Compresses X and raw.X
130
+ va.X # VCSCArray
131
+ va.raw_X # VCSCArray (separate from anndata's .raw)
132
132
 
133
133
  # Persist to HDF5 (.h5ad) or Zarr with default Blosc2+LZ4 compression
134
- va.write_h5ad("compressed.h5ad") # Read back with VCSCAnnData.read_h5ad
134
+ va.write_h5ad("compressed.h5ad") # Read back with VCSCAnnData.read_h5ad
135
135
  va2 = vsparse.VCSCAnnData.read_h5ad("compressed.h5ad")
136
136
 
137
- va.write_zarr("compressed.zarr") # Read back with VCSCAnnData.read_zarr
137
+ va.write_zarr("compressed.zarr") # Read back with VCSCAnnData.read_zarr
138
138
  va3 = vsparse.VCSCAnnData.read_zarr("compressed.zarr")
139
139
 
140
140
  # Escape hatch back to standard AnnData
@@ -165,8 +165,8 @@ For IVCSR-backed datasets, `vsparse.load_and_normalize` bypasses full array deco
165
165
  ```python
166
166
  adata_norm = vsparse.load_and_normalize(
167
167
  "archived.h5ad",
168
- min_cell_counts=10.0, # Filter cells with counts <= 10
169
- gene_threshold=0.05, # Filter genes with counts <= 0.05 * n_cells
168
+ min_cell_counts=10.0, # Filter cells with counts <= 10
169
+ gene_threshold=0.05, # Filter genes with counts <= 0.05 * n_cells
170
170
  )
171
171
  ```
172
172
 
@@ -59,31 +59,31 @@ v = vsparse.VCSCArray.from_scipy(csc)
59
59
 
60
60
  # Or build from an AnnData object or SciPy sparse array
61
61
  adata = ... # an AnnData object
62
- v = vsparse.from_anndata(adata) # VCSCArray (column-compressed) from adata.X
63
- vr = vsparse.from_anndata(adata, format="csr") # VCSRArray (row-compressed)
62
+ v = vsparse.from_anndata(adata) # VCSCArray (column-compressed) from adata.X
63
+ vr = vsparse.from_anndata(adata, format="csr") # VCSRArray (row-compressed)
64
64
 
65
65
  # Transposition is zero-copy (swaps major/minor axes and shares buffers)
66
- vr = v.T # VCSRArray
66
+ vr = v.T # VCSRArray
67
67
 
68
68
  # Scalar arithmetic & math
69
- v2 = v * 2.0 # Scalar multiplication
70
- v_div = v / 2.0 # Scalar division
71
- v_neg = -v # Negation
72
- v_log = v.log1p() # Elementwise log1p
69
+ v2 = v * 2.0 # Scalar multiplication
70
+ v_div = v / 2.0 # Scalar division
71
+ v_neg = -v # Negation
72
+ v_log = v.log1p() # Elementwise log1p
73
73
 
74
74
  # Matrix & vector products (Numba-parallelized)
75
- y = v @ x # Matrix-vector: (n_rows, n_cols) @ (n_cols,) -> (n_rows,)
76
- y_left = x @ v # Vector-matrix: (n_rows,) @ (n_rows, n_cols) -> (n_cols,)
77
- Y = v @ B # Matrix-matrix: (n_rows, n_cols) @ (n_cols, k) -> (n_rows, k)
78
- Y_left = B @ v # Matrix-matrix: (k, n_rows) @ (n_rows, n_cols) -> (k, n_cols)
75
+ y = v @ x # Matrix-vector: (n_rows, n_cols) @ (n_cols,) -> (n_rows,)
76
+ y_left = x @ v # Vector-matrix: (n_rows,) @ (n_rows, n_cols) -> (n_cols,)
77
+ Y = v @ B # Matrix-matrix: (n_rows, n_cols) @ (n_cols, k) -> (n_rows, k)
78
+ Y_left = B @ v # Matrix-matrix: (k, n_rows) @ (n_rows, n_cols) -> (k, n_cols)
79
79
 
80
80
  # Slicing
81
- col_slice = v[:, [1, 3, 5]] # Fast major-axis slicing (returns VCSCArray)
82
- sub = v[0:10, 0:10] # 2D slicing (falls back to scipy)
81
+ col_slice = v[:, [1, 3, 5]] # Fast major-axis slicing (returns VCSCArray)
82
+ sub = v[0:10, 0:10] # 2D slicing (falls back to scipy)
83
83
 
84
84
  # Conversion & layers
85
- sp_csc = v.to_scipy() # -> scipy.sparse.csc_array (or to_csr())
86
- dense = v.toarray() # -> numpy.ndarray
85
+ sp_csc = v.to_scipy() # -> scipy.sparse.csc_array (or to_csr())
86
+ dense = v.toarray() # -> numpy.ndarray
87
87
  vsparse.to_layer(adata, v, key="counts_vcsc") # Attach to AnnData layer
88
88
  ```
89
89
 
@@ -96,15 +96,15 @@ is an `AnnData` subclass whose `X` (and optionally `raw_X`) is backed directly b
96
96
  ```python
97
97
  import vsparse
98
98
 
99
- va = vsparse.VCSCAnnData.from_anndata(adata) # Compresses X and raw.X
100
- va.X # VCSCArray
101
- va.raw_X # VCSCArray (separate from anndata's .raw)
99
+ va = vsparse.VCSCAnnData.from_anndata(adata) # Compresses X and raw.X
100
+ va.X # VCSCArray
101
+ va.raw_X # VCSCArray (separate from anndata's .raw)
102
102
 
103
103
  # Persist to HDF5 (.h5ad) or Zarr with default Blosc2+LZ4 compression
104
- va.write_h5ad("compressed.h5ad") # Read back with VCSCAnnData.read_h5ad
104
+ va.write_h5ad("compressed.h5ad") # Read back with VCSCAnnData.read_h5ad
105
105
  va2 = vsparse.VCSCAnnData.read_h5ad("compressed.h5ad")
106
106
 
107
- va.write_zarr("compressed.zarr") # Read back with VCSCAnnData.read_zarr
107
+ va.write_zarr("compressed.zarr") # Read back with VCSCAnnData.read_zarr
108
108
  va3 = vsparse.VCSCAnnData.read_zarr("compressed.zarr")
109
109
 
110
110
  # Escape hatch back to standard AnnData
@@ -135,8 +135,8 @@ For IVCSR-backed datasets, `vsparse.load_and_normalize` bypasses full array deco
135
135
  ```python
136
136
  adata_norm = vsparse.load_and_normalize(
137
137
  "archived.h5ad",
138
- min_cell_counts=10.0, # Filter cells with counts <= 10
139
- gene_threshold=0.05, # Filter genes with counts <= 0.05 * n_cells
138
+ min_cell_counts=10.0, # Filter cells with counts <= 10
139
+ gene_threshold=0.05, # Filter genes with counts <= 0.05 * n_cells
140
140
  )
141
141
  ```
142
142
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "vsparse"
3
- version = "0.2.0"
3
+ version = "0.4.0"
4
4
  description = "Value-Compressed Sparse Column/Row (VCSC/VCSR) arrays, with optional AnnData integration"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.12"
@@ -50,6 +50,8 @@ dev = [
50
50
  "pytest-cov>=5.0",
51
51
  "ruff>=0.6",
52
52
  "ty>=0.0.1a1",
53
+ "hypothesis>=6.100",
54
+ "codespell>=2.3",
53
55
  ]
54
56
 
55
57
  [build-system]
@@ -64,10 +66,16 @@ target-version = "py312"
64
66
  select = [
65
67
  "E",
66
68
  "F",
67
- "I",
68
- "UP",
69
69
  "B",
70
70
  "NPY",
71
+ "PD",
72
+ "SIM",
73
+ "RET",
74
+ "PIE",
75
+ "ERA",
76
+ "PERF",
77
+ "UP",
78
+ "C4",
71
79
  "RUF",
72
80
  ]
73
81
  ignore = ["E501"]
@@ -75,6 +83,10 @@ ignore = ["E501"]
75
83
  [tool.ruff.lint.isort]
76
84
  known-first-party = ["vsparse"]
77
85
 
86
+ [tool.codespell]
87
+ skip = "*.lock,uv.lock,.venv,docs/_build,benchmarks/baselines.json"
88
+ ignore-words-list = "coo"
89
+
78
90
  [tool.ty.environment]
79
91
  python-version = "3.12"
80
92
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "vsparse"
3
- version = "0.2.0"
3
+ version = "0.4.0"
4
4
  description = "Value-Compressed Sparse Column/Row (VCSC/VCSR) arrays, with optional AnnData integration"
5
5
  readme = "README.md"
6
6
  authors = [
@@ -44,6 +44,8 @@ dev = [
44
44
  "pytest-cov>=5.0",
45
45
  "ruff>=0.6",
46
46
  "ty>=0.0.1a1",
47
+ "hypothesis>=6.100",
48
+ "codespell>=2.3",
47
49
  ]
48
50
 
49
51
  [build-system]
@@ -55,12 +57,16 @@ line-length = 100
55
57
  target-version = "py312"
56
58
 
57
59
  [tool.ruff.lint]
58
- select = ["E", "F", "I", "UP", "B", "NPY", "RUF"]
60
+ select = ["E", "F", "B", "NPY", "PD", "SIM", "RET", "PIE", "ERA", "PERF", "UP", "C4", "RUF"]
59
61
  ignore = ["E501"]
60
62
 
61
63
  [tool.ruff.lint.isort]
62
64
  known-first-party = ["vsparse"]
63
65
 
66
+ [tool.codespell]
67
+ skip = "*.lock,uv.lock,.venv,docs/_build,benchmarks/baselines.json"
68
+ ignore-words-list = "coo"
69
+
64
70
  [tool.ty.environment]
65
71
  python-version = "3.12"
66
72
 
@@ -9,10 +9,13 @@ AnnData subclass that holds a VCSC/VCSR array as ``X`` directly.
9
9
  from vsparse._anndata import from_anndata, to_layer
10
10
  from vsparse._anndata_class import VCSCAnnData
11
11
  from vsparse._base import VCSCArray, VCSRArray
12
+ from vsparse._norm_common import RECIPES, Recipe
12
13
  from vsparse._rapid_load import load_and_normalize, load_packed
13
14
  from vsparse._vcs_norm import VCSCArrayNormalized, VCSRArrayNormalized
14
15
 
15
16
  __all__ = [
17
+ "RECIPES",
18
+ "Recipe",
16
19
  "VCSCAnnData",
17
20
  "VCSCArray",
18
21
  "VCSCArrayNormalized",
@@ -24,4 +27,4 @@ __all__ = [
24
27
  "to_layer",
25
28
  ]
26
29
 
27
- __version__ = "0.1.0"
30
+ __version__ = "0.4.0"
@@ -2,6 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import copy as _copy
5
6
  from types import MappingProxyType
6
7
  from typing import TYPE_CHECKING, Any, cast
7
8
 
@@ -12,6 +13,8 @@ import scipy.sparse as sp
12
13
 
13
14
  from vsparse import _compression, _io
14
15
  from vsparse._base import VCSCArray, VCSRArray, _VCSBase
16
+ from vsparse._norm_common import DEFAULT_RECIPE, Recipe, _NormCache, resolve_recipe
17
+ from vsparse._vcs_norm import VCSCArrayNormalized, VCSRArrayNormalized
15
18
 
16
19
  if TYPE_CHECKING:
17
20
  from collections.abc import Mapping
@@ -26,6 +29,13 @@ _MAPPING_KEYS = ("obsm", "varm", "obsp", "varp", "layers", "uns")
26
29
  _FIELD_KEYS = (*_DF_KEYS, *_MAPPING_KEYS)
27
30
  _STORE_FORMATS = ("vcsc", "ivcsc")
28
31
 
32
+ # Names statistics are recorded under in .obs/.varm/.uns -- see .normalized().
33
+ _VSPARSE_UNS_KEY = "vsparse"
34
+ _VSPARSE_OBS_A = "vsparse_a"
35
+ _VSPARSE_VARM_B = "vsparse_b"
36
+ _VSPARSE_VARM_C = "vsparse_c"
37
+ _VSPARSE_VARM_S = "vsparse_s"
38
+
29
39
 
30
40
  def _as_slice_index(idx: Any, n: int) -> Any:
31
41
  """Turn a bare int index into a length-1 slice, matching anndata's own convention."""
@@ -60,6 +70,16 @@ def _subset_2d(v: Any, oidx: Any, vidx: Any) -> Any:
60
70
  return np.asarray(v)[oidx][:, vidx]
61
71
 
62
72
 
73
+ def _copy_value(v: Any) -> Any:
74
+ """A deep-enough copy of one obs/var/obsm/varm/obsp/varp/layers value.
75
+
76
+ Every value anndata can hold there -- a DataFrame, ndarray, scipy sparse
77
+ array, or a :class:`~vsparse.VCSCArray`/:class:`~vsparse.VCSRArray` --
78
+ implements its own ``.copy()``.
79
+ """
80
+ return None if v is None else v.copy()
81
+
82
+
63
83
  def _check_vcs_type(value: Any, name: str) -> None:
64
84
  if value is not None and not isinstance(value, _VCS_TYPES):
65
85
  raise TypeError(
@@ -108,6 +128,7 @@ class VCSCAnnData(ad.AnnData):
108
128
  )
109
129
  self._vcs_X: _AnyVCS | None = None
110
130
  self._vcs_raw_X: _AnyVCS | None = None
131
+ self._vcs_norm_cache = _NormCache()
111
132
  shape = kwargs.pop("shape", None)
112
133
  if shape is None and X is None and "obs" not in kwargs:
113
134
  shape = (0, 0)
@@ -131,7 +152,12 @@ class VCSCAnnData(ad.AnnData):
131
152
  value = vcls.from_scipy(value)
132
153
  else:
133
154
  _check_vcs_type(value, "X")
134
- if value is not None and hasattr(self, "_obs") and hasattr(self, "_var") and value.shape != self.shape:
155
+ if (
156
+ value is not None
157
+ and hasattr(self, "_obs")
158
+ and hasattr(self, "_var")
159
+ and value.shape != self.shape
160
+ ):
135
161
  raise ValueError(f"X shape {value.shape} does not match adata shape {self.shape}")
136
162
  self._vcs_X = value
137
163
 
@@ -161,6 +187,11 @@ class VCSCAnnData(ad.AnnData):
161
187
  this class doesn't use (see the class docstring), so it can't be
162
188
  reused here. ``X``/``raw_X`` stay VCSC/VCSR-backed either way, via
163
189
  that array type's own indexing.
190
+
191
+ Returns ``type(self)``, not a bare ``VCSCAnnData``, so a subclass
192
+ overriding ``X`` (e.g. one that always hands back a normalized view
193
+ computed fresh from ``_vcs_X``, as with :meth:`copy`/:meth:`to_memory`)
194
+ keeps that behavior after slicing.
164
195
  """
165
196
  oidx, vidx = self._normalize_indices(index)
166
197
  oidx = _as_slice_index(oidx, self.n_obs)
@@ -169,12 +200,25 @@ class VCSCAnnData(ad.AnnData):
169
200
  obs = cast(pd.DataFrame, self.obs).iloc[oidx].copy()
170
201
  var = cast(pd.DataFrame, self.var).iloc[vidx].copy()
171
202
 
172
- return VCSCAnnData(
203
+ # obs["vsparse_a"]/varm["vsparse_b"/"c"/"s"] get windowed along with
204
+ # obs/varm below, same as any other per-cell/per-gene column -- each
205
+ # kept cell/gene keeps its own precomputed factor. But population-level
206
+ # aspects of those statistics (e.g. the median depth or per-gene mean
207
+ # baked into them) were derived from the *pre-subset* population, so
208
+ # they no longer reflect this narrower one -- mark them stale rather
209
+ # than silently pretending they were computed fresh. Call
210
+ # .normalized(recalculate=True) to recompute for this subset, or
211
+ # recalculate=False to keep using these (stale) values.
212
+ uns = self.uns
213
+ if _VSPARSE_UNS_KEY in uns:
214
+ uns = {**uns, _VSPARSE_UNS_KEY: {**uns[_VSPARSE_UNS_KEY], "stale": True}}
215
+
216
+ return type(self)(
173
217
  X=_subset_2d(self._vcs_X, oidx, vidx),
174
218
  raw_X=_subset_2d(self._vcs_raw_X, oidx, vidx),
175
219
  obs=obs,
176
220
  var=var,
177
- uns=self.uns,
221
+ uns=uns,
178
222
  obsm={k: _subset_1d(v, oidx) for k, v in self.obsm.items() if k is not None},
179
223
  varm={k: _subset_1d(v, vidx) for k, v in self.varm.items() if k is not None},
180
224
  obsp={k: _subset_2d(v, oidx, oidx) for k, v in self.obsp.items() if k is not None},
@@ -182,6 +226,116 @@ class VCSCAnnData(ad.AnnData):
182
226
  layers={k: _subset_2d(v, oidx, vidx) for k, v in self.layers.items() if k is not None},
183
227
  )
184
228
 
229
+ def copy(self) -> VCSCAnnData: # ty: ignore[invalid-method-override]
230
+ """A deep copy, preserving the VCSC/VCSR-backed ``X``/``raw_X``.
231
+
232
+ The inherited :meth:`anndata.AnnData.copy` only knows how to copy the
233
+ standard private ``_X`` attribute, which this class never sets (see
234
+ the class docstring: ``X``/``raw_X`` live in ``_vcs_X``/``_vcs_raw_X``
235
+ instead) -- so it silently drops them (``X`` comes back ``None``) and
236
+ returns a plain ``AnnData`` rather than this class. This copies every
237
+ field explicitly instead, including a real ``VCSCArray``/
238
+ ``VCSRArray`` copy of ``X``/``raw_X``, and returns ``type(self)`` so a
239
+ subclass (e.g. one overriding the ``X`` property) round-trips too.
240
+ """
241
+ return type(self)(
242
+ X=_copy_value(self._vcs_X),
243
+ raw_X=_copy_value(self._vcs_raw_X),
244
+ obs=cast(pd.DataFrame, self.obs).copy(),
245
+ var=cast(pd.DataFrame, self.var).copy(),
246
+ uns=_copy.deepcopy(dict(self.uns)),
247
+ obsm={k: _copy_value(v) for k, v in self.obsm.items() if k is not None},
248
+ varm={k: _copy_value(v) for k, v in self.varm.items() if k is not None},
249
+ obsp={k: _copy_value(v) for k, v in self.obsp.items() if k is not None},
250
+ varp={k: _copy_value(v) for k, v in self.varp.items() if k is not None},
251
+ layers={k: _copy_value(v) for k, v in self.layers.items() if k is not None},
252
+ )
253
+
254
+ def to_memory(self, *, copy: bool = False) -> VCSCAnnData:
255
+ """Return this object with its data loaded into memory.
256
+
257
+ The inherited :meth:`anndata.AnnData.to_memory` has the same problem
258
+ as the inherited ``copy()`` (see above): it iterates the object's
259
+ *standard* attributes, which never includes this class's ``X``/
260
+ ``raw_X`` (held in ``_vcs_X``/``_vcs_raw_X`` instead), and reconstructs
261
+ a plain ``AnnData`` -- so ``X`` silently comes back ``None``.
262
+
263
+ This class never actually supports a lazily backed ``X``/``raw_X``
264
+ (they're always eagerly-held ``VCSCArray``/``VCSRArray`` instances),
265
+ so there is never anything to load -- this always returns a full
266
+ :meth:`copy` instead, regardless of ``copy`` (unlike plain
267
+ ``AnnData``, where ``copy=False`` can skip copying arrays already in
268
+ memory; here everything already is, so the distinction doesn't apply).
269
+ """
270
+ return self.copy()
271
+
272
+ # -- normalization ----------------------------------------------------------
273
+
274
+ def normalized(self, view: str | Recipe = DEFAULT_RECIPE, *, recalculate: bool = True) -> Any:
275
+ """A normalized view of ``X`` -- see :meth:`vsparse._base._VCSBase.normalized`.
276
+
277
+ Also records the recipe's statistics -- per-cell ``a`` in
278
+ ``obs["vsparse_a"]``, per-gene ``b``/``c``/``s`` in
279
+ ``varm["vsparse_b"]``/``["vsparse_c"]``/``["vsparse_s"]``, and the
280
+ active recipe name plus a ``stale`` flag in ``uns["vsparse"]`` -- so
281
+ they persist across :meth:`write_h5ad`/:meth:`write_zarr` and can be
282
+ reused instead of recomputed.
283
+
284
+ ``recalculate=False`` reuses whatever is already recorded for
285
+ ``view``: first an in-memory view already built this session (however
286
+ it was built), else what's stored in ``obs``/``varm``/``uns`` (built
287
+ fresh, but skipping the ``O(nnz)`` statistics passes) if it matches
288
+ ``view`` and the current shape. ``uns["vsparse"]["stale"]`` is set to
289
+ ``True`` after indexing (see :meth:`__getitem__`), since population
290
+ statistics like a depth median or a per-gene mean no longer reflect
291
+ the subset -- ``recalculate=False`` reuses them anyway; the default
292
+ ``recalculate=True`` always recomputes fresh (and clears ``stale``).
293
+ """
294
+ if self._vcs_X is None:
295
+ raise ValueError("normalized() requires X to be set")
296
+ recipe = resolve_recipe(view)
297
+ cache = self._vcs_norm_cache
298
+ if not recalculate:
299
+ cached = cache.get(recipe, self._vcs_X)
300
+ if cached is not None:
301
+ return cached
302
+ stored = self.uns.get(_VSPARSE_UNS_KEY)
303
+ if (
304
+ stored is not None
305
+ and stored.get("recipe") == recipe.name
306
+ and _VSPARSE_OBS_A in self.obs
307
+ and len(self.obs[_VSPARSE_OBS_A]) == self.n_obs
308
+ and _VSPARSE_VARM_B in self.varm
309
+ and _VSPARSE_VARM_C in self.varm
310
+ and _VSPARSE_VARM_S in self.varm
311
+ and len(self.varm[_VSPARSE_VARM_B]) == self.n_vars
312
+ ):
313
+ nview_cls = (
314
+ VCSCArrayNormalized
315
+ if isinstance(self._vcs_X, VCSCArray)
316
+ else VCSRArrayNormalized
317
+ )
318
+ nview = nview_cls.from_stats(
319
+ self._vcs_X,
320
+ recipe,
321
+ a=np.asarray(self.obs[_VSPARSE_OBS_A], dtype=np.float64),
322
+ b=np.asarray(self.varm[_VSPARSE_VARM_B], dtype=np.float64).reshape(-1),
323
+ c=np.asarray(self.varm[_VSPARSE_VARM_C], dtype=np.float64).reshape(-1),
324
+ s=np.asarray(self.varm[_VSPARSE_VARM_S], dtype=np.float64).reshape(-1),
325
+ stale=bool(stored.get("stale", False)),
326
+ )
327
+ cache.put(recipe, nview)
328
+ return nview
329
+
330
+ nview = self._vcs_X.normalized(recipe, recalculate=True)
331
+ cache.put(recipe, nview)
332
+ self.obs[_VSPARSE_OBS_A] = nview.a
333
+ self.varm[_VSPARSE_VARM_B] = nview.b
334
+ self.varm[_VSPARSE_VARM_C] = nview.c
335
+ self.varm[_VSPARSE_VARM_S] = nview.s
336
+ self.uns[_VSPARSE_UNS_KEY] = {"recipe": recipe.name, "stale": False}
337
+ return nview
338
+
185
339
  # -- conversion -------------------------------------------------------------
186
340
 
187
341
  @classmethod