vsparse 0.2.0__tar.gz → 0.3.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.3.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
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "vsparse"
3
- version = "0.2.0"
3
+ version = "0.3.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"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "vsparse"
3
- version = "0.2.0"
3
+ version = "0.3.0"
4
4
  description = "Value-Compressed Sparse Column/Row (VCSC/VCSR) arrays, with optional AnnData integration"
5
5
  readme = "README.md"
6
6
  authors = [
@@ -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",
@@ -12,6 +12,8 @@ import scipy.sparse as sp
12
12
 
13
13
  from vsparse import _compression, _io
14
14
  from vsparse._base import VCSCArray, VCSRArray, _VCSBase
15
+ from vsparse._norm_common import DEFAULT_RECIPE, Recipe, _NormCache, resolve_recipe
16
+ from vsparse._vcs_norm import VCSCArrayNormalized, VCSRArrayNormalized
15
17
 
16
18
  if TYPE_CHECKING:
17
19
  from collections.abc import Mapping
@@ -26,6 +28,13 @@ _MAPPING_KEYS = ("obsm", "varm", "obsp", "varp", "layers", "uns")
26
28
  _FIELD_KEYS = (*_DF_KEYS, *_MAPPING_KEYS)
27
29
  _STORE_FORMATS = ("vcsc", "ivcsc")
28
30
 
31
+ # Names statistics are recorded under in .obs/.varm/.uns -- see .normalized().
32
+ _VSPARSE_UNS_KEY = "vsparse"
33
+ _VSPARSE_OBS_A = "vsparse_a"
34
+ _VSPARSE_VARM_B = "vsparse_b"
35
+ _VSPARSE_VARM_C = "vsparse_c"
36
+ _VSPARSE_VARM_S = "vsparse_s"
37
+
29
38
 
30
39
  def _as_slice_index(idx: Any, n: int) -> Any:
31
40
  """Turn a bare int index into a length-1 slice, matching anndata's own convention."""
@@ -108,6 +117,7 @@ class VCSCAnnData(ad.AnnData):
108
117
  )
109
118
  self._vcs_X: _AnyVCS | None = None
110
119
  self._vcs_raw_X: _AnyVCS | None = None
120
+ self._vcs_norm_cache = _NormCache()
111
121
  shape = kwargs.pop("shape", None)
112
122
  if shape is None and X is None and "obs" not in kwargs:
113
123
  shape = (0, 0)
@@ -131,7 +141,12 @@ class VCSCAnnData(ad.AnnData):
131
141
  value = vcls.from_scipy(value)
132
142
  else:
133
143
  _check_vcs_type(value, "X")
134
- if value is not None and hasattr(self, "_obs") and hasattr(self, "_var") and value.shape != self.shape:
144
+ if (
145
+ value is not None
146
+ and hasattr(self, "_obs")
147
+ and hasattr(self, "_var")
148
+ and value.shape != self.shape
149
+ ):
135
150
  raise ValueError(f"X shape {value.shape} does not match adata shape {self.shape}")
136
151
  self._vcs_X = value
137
152
 
@@ -169,12 +184,25 @@ class VCSCAnnData(ad.AnnData):
169
184
  obs = cast(pd.DataFrame, self.obs).iloc[oidx].copy()
170
185
  var = cast(pd.DataFrame, self.var).iloc[vidx].copy()
171
186
 
187
+ # obs["vsparse_a"]/varm["vsparse_b"/"c"/"s"] get windowed along with
188
+ # obs/varm below, same as any other per-cell/per-gene column -- each
189
+ # kept cell/gene keeps its own precomputed factor. But population-level
190
+ # aspects of those statistics (e.g. the median depth or per-gene mean
191
+ # baked into them) were derived from the *pre-subset* population, so
192
+ # they no longer reflect this narrower one -- mark them stale rather
193
+ # than silently pretending they were computed fresh. Call
194
+ # .normalized(recalculate=True) to recompute for this subset, or
195
+ # recalculate=False to keep using these (stale) values.
196
+ uns = self.uns
197
+ if _VSPARSE_UNS_KEY in uns:
198
+ uns = {**uns, _VSPARSE_UNS_KEY: {**uns[_VSPARSE_UNS_KEY], "stale": True}}
199
+
172
200
  return VCSCAnnData(
173
201
  X=_subset_2d(self._vcs_X, oidx, vidx),
174
202
  raw_X=_subset_2d(self._vcs_raw_X, oidx, vidx),
175
203
  obs=obs,
176
204
  var=var,
177
- uns=self.uns,
205
+ uns=uns,
178
206
  obsm={k: _subset_1d(v, oidx) for k, v in self.obsm.items() if k is not None},
179
207
  varm={k: _subset_1d(v, vidx) for k, v in self.varm.items() if k is not None},
180
208
  obsp={k: _subset_2d(v, oidx, oidx) for k, v in self.obsp.items() if k is not None},
@@ -182,6 +210,73 @@ class VCSCAnnData(ad.AnnData):
182
210
  layers={k: _subset_2d(v, oidx, vidx) for k, v in self.layers.items() if k is not None},
183
211
  )
184
212
 
213
+ # -- normalization ----------------------------------------------------------
214
+
215
+ def normalized(self, view: str | Recipe = DEFAULT_RECIPE, *, recalculate: bool = True) -> Any:
216
+ """A normalized view of ``X`` -- see :meth:`vsparse._base._VCSBase.normalized`.
217
+
218
+ Also records the recipe's statistics -- per-cell ``a`` in
219
+ ``obs["vsparse_a"]``, per-gene ``b``/``c``/``s`` in
220
+ ``varm["vsparse_b"]``/``["vsparse_c"]``/``["vsparse_s"]``, and the
221
+ active recipe name plus a ``stale`` flag in ``uns["vsparse"]`` -- so
222
+ they persist across :meth:`write_h5ad`/:meth:`write_zarr` and can be
223
+ reused instead of recomputed.
224
+
225
+ ``recalculate=False`` reuses whatever is already recorded for
226
+ ``view``: first an in-memory view already built this session (however
227
+ it was built), else what's stored in ``obs``/``varm``/``uns`` (built
228
+ fresh, but skipping the ``O(nnz)`` statistics passes) if it matches
229
+ ``view`` and the current shape. ``uns["vsparse"]["stale"]`` is set to
230
+ ``True`` after indexing (see :meth:`__getitem__`), since population
231
+ statistics like a depth median or a per-gene mean no longer reflect
232
+ the subset -- ``recalculate=False`` reuses them anyway; the default
233
+ ``recalculate=True`` always recomputes fresh (and clears ``stale``).
234
+ """
235
+ if self._vcs_X is None:
236
+ raise ValueError("normalized() requires X to be set")
237
+ recipe = resolve_recipe(view)
238
+ cache = self._vcs_norm_cache
239
+ if not recalculate:
240
+ cached = cache.get(recipe, self._vcs_X)
241
+ if cached is not None:
242
+ return cached
243
+ stored = self.uns.get(_VSPARSE_UNS_KEY)
244
+ if (
245
+ stored is not None
246
+ and stored.get("recipe") == recipe.name
247
+ and _VSPARSE_OBS_A in self.obs
248
+ and len(self.obs[_VSPARSE_OBS_A]) == self.n_obs
249
+ and _VSPARSE_VARM_B in self.varm
250
+ and _VSPARSE_VARM_C in self.varm
251
+ and _VSPARSE_VARM_S in self.varm
252
+ and len(self.varm[_VSPARSE_VARM_B]) == self.n_vars
253
+ ):
254
+ nview_cls = (
255
+ VCSCArrayNormalized
256
+ if isinstance(self._vcs_X, VCSCArray)
257
+ else VCSRArrayNormalized
258
+ )
259
+ nview = nview_cls.from_stats(
260
+ self._vcs_X,
261
+ recipe,
262
+ a=np.asarray(self.obs[_VSPARSE_OBS_A], dtype=np.float64),
263
+ b=np.asarray(self.varm[_VSPARSE_VARM_B], dtype=np.float64).reshape(-1),
264
+ c=np.asarray(self.varm[_VSPARSE_VARM_C], dtype=np.float64).reshape(-1),
265
+ s=np.asarray(self.varm[_VSPARSE_VARM_S], dtype=np.float64).reshape(-1),
266
+ stale=bool(stored.get("stale", False)),
267
+ )
268
+ cache.put(recipe, nview)
269
+ return nview
270
+
271
+ nview = self._vcs_X.normalized(recipe, recalculate=True)
272
+ cache.put(recipe, nview)
273
+ self.obs[_VSPARSE_OBS_A] = nview.a
274
+ self.varm[_VSPARSE_VARM_B] = nview.b
275
+ self.varm[_VSPARSE_VARM_C] = nview.c
276
+ self.varm[_VSPARSE_VARM_S] = nview.s
277
+ self.uns[_VSPARSE_UNS_KEY] = {"recipe": recipe.name, "stale": False}
278
+ return nview
279
+
185
280
  # -- conversion -------------------------------------------------------------
186
281
 
187
282
  @classmethod
@@ -21,6 +21,9 @@ from vsparse import _construct, _ops
21
21
  from vsparse._indexutils import is_full_slice as _is_full_slice
22
22
  from vsparse._indexutils import normalize_major_idx as _normalize_major_idx
23
23
  from vsparse._indexutils import smallest_index_dtype as _smallest_index_dtype
24
+ from vsparse._norm_common import DEFAULT_RECIPE as _DEFAULT_RECIPE
25
+ from vsparse._norm_common import Recipe as _Recipe
26
+ from vsparse._norm_common import _NormCache
24
27
 
25
28
  __all__ = ["VCSCArray", "VCSRArray"]
26
29
 
@@ -39,7 +42,7 @@ class _VCSBase:
39
42
  # __rmatmul__/__rmul__ instead of trying to broadcast us as an ndarray.
40
43
  __array_ufunc__ = None
41
44
 
42
- __slots__ = ("indices", "major_ptr", "shape", "value_ptr", "values")
45
+ __slots__ = ("_norm_cache", "indices", "major_ptr", "shape", "value_ptr", "values")
43
46
 
44
47
  def __init__(
45
48
  self,
@@ -56,9 +59,7 @@ class _VCSBase:
56
59
  indices = np.asarray(indices)
57
60
 
58
61
  if major_ptr.shape[0] != n_major + 1:
59
- raise ValueError(
60
- f"major_ptr has length {major_ptr.shape[0]}, expected {n_major + 1}"
61
- )
62
+ raise ValueError(f"major_ptr has length {major_ptr.shape[0]}, expected {n_major + 1}")
62
63
  if value_ptr.shape[0] != values.shape[0] + 1:
63
64
  raise ValueError("value_ptr must have length len(values) + 1")
64
65
  if major_ptr[-1] != values.shape[0]:
@@ -79,6 +80,7 @@ class _VCSBase:
79
80
  self.values = values
80
81
  self.value_ptr = value_ptr
81
82
  self.indices = indices
83
+ self._norm_cache = _NormCache()
82
84
 
83
85
  # -- axis bookkeeping ------------------------------------------------
84
86
 
@@ -112,8 +114,7 @@ class _VCSBase:
112
114
  def __repr__(self) -> str: # pragma: no cover - cosmetic
113
115
  cls = type(self).__name__
114
116
  return (
115
- f"<{cls} shape={self.shape} dtype={self.dtype} "
116
- f"nnz={self.nnz} n_unique={self.n_unique}>"
117
+ f"<{cls} shape={self.shape} dtype={self.dtype} nnz={self.nnz} n_unique={self.n_unique}>"
117
118
  )
118
119
 
119
120
  def copy(self):
@@ -200,12 +201,42 @@ class _VCSBase:
200
201
  )
201
202
  return other_cls(self.shape, major_ptr, values, value_ptr, indices)
202
203
 
203
- def normalized(self) -> Any:
204
- """A read-depth-normalized, log-transformed, mean-centered *view* -- see :mod:`vsparse._vcs_norm`."""
204
+ def normalized(self, view: str | _Recipe = _DEFAULT_RECIPE, *, recalculate: bool = True) -> Any:
205
+ """A normalized *view* of this array -- see :mod:`vsparse._vcs_norm`/:mod:`vsparse._norm_common`.
206
+
207
+ Parameters
208
+ ----------
209
+ view
210
+ Which normalization recipe to apply: the name of one of
211
+ :data:`vsparse._norm_common.RECIPES` (``"raw"``, ``"cp10k_log1p"``,
212
+ ``"parafac2"`` (the default), ``"scanpy"``, ``"pearson"``), or a
213
+ :class:`~vsparse._norm_common.Recipe` built by the caller.
214
+ recalculate
215
+ If ``True`` (the default), (re)compute the recipe's statistics
216
+ fresh from this array. If ``False``, reuse a previously computed
217
+ view for ``view`` on this same array, if one exists (from an
218
+ earlier ``.normalized(view, ...)`` call, with any value of
219
+ ``recalculate``) -- this is how switching between recipes avoids
220
+ recomputing each one every time. If no such view has been
221
+ computed yet, one is still computed (there is nothing to reuse).
222
+ The cache holds at most
223
+ :data:`~vsparse._norm_common.NORM_CACHE_MAXSIZE` recipes, and holds
224
+ each view weakly -- see :class:`~vsparse._norm_common._NormCache`.
225
+ """
226
+ from vsparse._norm_common import resolve_recipe
205
227
  from vsparse._vcs_norm import VCSCArrayNormalized, VCSRArrayNormalized
206
228
 
229
+ recipe = resolve_recipe(view)
230
+ cache = self._norm_cache
231
+ if not recalculate:
232
+ cached = cache.get(recipe, self)
233
+ if cached is not None:
234
+ return cached
235
+
207
236
  cls = VCSCArrayNormalized if self._format == "csc" else VCSRArrayNormalized
208
- return cls(self)
237
+ result = cls(self, recipe)
238
+ cache.put(recipe, result)
239
+ return result
209
240
 
210
241
  def log1p(self) -> _VCSBase:
211
242
  """Elementwise ``log1p``. Structural zeros stay zero implicitly."""
@@ -229,7 +260,10 @@ class _VCSBase:
229
260
  def _minor_sums(self) -> np.ndarray:
230
261
  """A parallel scatter-add over every nonzero to get per-minor-index totals."""
231
262
  return _ops.minor_sums(
232
- self.values, self.value_ptr, self.indices, self.n_minor,
263
+ self.values,
264
+ self.value_ptr,
265
+ self.indices,
266
+ self.n_minor,
233
267
  _ops.accumulator_threads(self.n_minor),
234
268
  )
235
269
 
@@ -255,7 +289,9 @@ class _VCSBase:
255
289
  def _minor_nnz(self) -> np.ndarray:
256
290
  """A parallel scatter over every nonzero to get per-minor-index counts."""
257
291
  return _ops.minor_counts(
258
- self.value_ptr, self.indices, self.n_minor,
292
+ self.value_ptr,
293
+ self.indices,
294
+ self.n_minor,
259
295
  _ops.accumulator_threads(self.n_minor),
260
296
  )
261
297
 
@@ -355,9 +391,7 @@ class _VCSBase:
355
391
  if np.isscalar(other):
356
392
  if other == 0:
357
393
  return self.copy()
358
- raise NotImplementedError(
359
- "adding a nonzero scalar to a sparse array is not supported"
360
- )
394
+ raise NotImplementedError("adding a nonzero scalar to a sparse array is not supported")
361
395
  return self._elementwise(other, "__add__")
362
396
 
363
397
  __radd__ = __add__
@@ -465,15 +499,11 @@ class _VCSBase:
465
499
  other_arr = np.asarray(other)
466
500
  if other_arr.ndim == 1:
467
501
  if other_arr.shape[0] != self.shape[1]:
468
- raise ValueError(
469
- f"shapes {self.shape} and {other_arr.shape} not aligned"
470
- )
502
+ raise ValueError(f"shapes {self.shape} and {other_arr.shape} not aligned")
471
503
  return self._dot_right(other_arr)
472
504
  if other_arr.ndim == 2:
473
505
  if other_arr.shape[0] != self.shape[1]:
474
- raise ValueError(
475
- f"shapes {self.shape} and {other_arr.shape} not aligned"
476
- )
506
+ raise ValueError(f"shapes {self.shape} and {other_arr.shape} not aligned")
477
507
  return self._dot_right_mat(other_arr)
478
508
  return NotImplemented
479
509
 
@@ -481,15 +511,11 @@ class _VCSBase:
481
511
  other_arr = np.asarray(other)
482
512
  if other_arr.ndim == 1:
483
513
  if other_arr.shape[0] != self.shape[0]:
484
- raise ValueError(
485
- f"shapes {other_arr.shape} and {self.shape} not aligned"
486
- )
514
+ raise ValueError(f"shapes {other_arr.shape} and {self.shape} not aligned")
487
515
  return self._dot_left(other_arr)
488
516
  if other_arr.ndim == 2:
489
517
  if other_arr.shape[1] != self.shape[0]:
490
- raise ValueError(
491
- f"shapes {other_arr.shape} and {self.shape} not aligned"
492
- )
518
+ raise ValueError(f"shapes {other_arr.shape} and {self.shape} not aligned")
493
519
  return self._dot_left_mat(other_arr)
494
520
  return NotImplemented
495
521
 
@@ -503,9 +529,11 @@ class _VCSBase:
503
529
  new_major_ptr = np.zeros(idx.shape[0] + 1, dtype=np.int64)
504
530
  np.cumsum(counts, out=new_major_ptr[1:])
505
531
 
506
- value_slots = np.concatenate(
507
- [np.arange(s, e) for s, e in zip(starts, ends, strict=True)]
508
- ) if idx.shape[0] else np.empty(0, dtype=np.int64)
532
+ value_slots = (
533
+ np.concatenate([np.arange(s, e) for s, e in zip(starts, ends, strict=True)])
534
+ if idx.shape[0]
535
+ else np.empty(0, dtype=np.int64)
536
+ )
509
537
  new_values = self.values[value_slots]
510
538
 
511
539
  v_starts = self.value_ptr[value_slots]
@@ -513,14 +541,14 @@ class _VCSBase:
513
541
  idx_counts = v_ends - v_starts
514
542
  new_value_ptr = np.zeros(value_slots.shape[0] + 1, dtype=np.int64)
515
543
  np.cumsum(idx_counts, out=new_value_ptr[1:])
516
- new_indices = np.concatenate(
517
- [self.indices[s:e] for s, e in zip(v_starts, v_ends, strict=True)]
518
- ) if value_slots.shape[0] else np.empty(0, dtype=self.indices.dtype)
544
+ new_indices = (
545
+ np.concatenate([self.indices[s:e] for s, e in zip(v_starts, v_ends, strict=True)])
546
+ if value_slots.shape[0]
547
+ else np.empty(0, dtype=self.indices.dtype)
548
+ )
519
549
 
520
550
  n_minor = self.n_minor
521
- new_shape = (
522
- (n_minor, idx.shape[0]) if self._format == "csc" else (idx.shape[0], n_minor)
523
- )
551
+ new_shape = (n_minor, idx.shape[0]) if self._format == "csc" else (idx.shape[0], n_minor)
524
552
  return type(self)(new_shape, new_major_ptr, new_values, new_value_ptr, new_indices)
525
553
 
526
554
  def _major_range(self, start: int, stop: int) -> _VCSBase:
@@ -532,9 +560,7 @@ class _VCSBase:
532
560
  u0, u1 = int(self.major_ptr[start]), int(self.major_ptr[stop])
533
561
  k0, k1 = int(self.value_ptr[u0]), int(self.value_ptr[u1])
534
562
  n_sel = stop - start
535
- new_shape = (
536
- (self.n_minor, n_sel) if self._format == "csc" else (n_sel, self.n_minor)
537
- )
563
+ new_shape = (self.n_minor, n_sel) if self._format == "csc" else (n_sel, self.n_minor)
538
564
  return type(self)(
539
565
  new_shape,
540
566
  self.major_ptr[start : stop + 1] - u0,
@@ -569,8 +595,13 @@ class _VCSBase:
569
595
  # Keep the parent's index dtype, as every other structural op does.
570
596
  new_indices = np.empty(int(new_value_ptr[-1]), dtype=self.indices.dtype)
571
597
  _ops.minor_select_fill(
572
- self.value_ptr, self.indices, offsets, positions,
573
- kept_slots, new_value_ptr, new_indices,
598
+ self.value_ptr,
599
+ self.indices,
600
+ offsets,
601
+ positions,
602
+ kept_slots,
603
+ new_value_ptr,
604
+ new_indices,
574
605
  )
575
606
 
576
607
  # Slots keep their original order, so each major slice owns a
@@ -598,9 +629,7 @@ class _VCSBase:
598
629
  if isinstance(row_key, int | np.integer) and isinstance(col_key, int | np.integer):
599
630
  return self.to_scipy()[row_key, col_key]
600
631
 
601
- major_key, minor_key = (
602
- (col_key, row_key) if self._format == "csc" else (row_key, col_key)
603
- )
632
+ major_key, minor_key = (col_key, row_key) if self._format == "csc" else (row_key, col_key)
604
633
  if _is_full_slice(major_key) and _is_full_slice(minor_key):
605
634
  return self.copy()
606
635
 
@@ -195,7 +195,9 @@ def transpose_major(
195
195
 
196
196
  values_out = sorted_value[group_starts]
197
197
  value_ptr_out = np.concatenate([group_starts, [nnz]]).astype(np.int64)
198
- major_ptr_out = np.searchsorted(sorted_major[group_starts], np.arange(n_minor + 1)).astype(np.int64)
198
+ major_ptr_out = np.searchsorted(sorted_major[group_starts], np.arange(n_minor + 1)).astype(
199
+ np.int64
200
+ )
199
201
 
200
202
  # The output's minor axis is the input's major axis, so that's the bound.
201
203
  indices_out = sorted_minor.astype(smallest_index_dtype(n_major), copy=False)
@@ -60,9 +60,7 @@ def _make_read_vcs(cls: type[_VCSBase]):
60
60
  def _read(elem: GroupStorageType, *, _reader: Reader) -> _VCSBase:
61
61
  shape_vals = [int(s) for s in np.asarray(elem.attrs["shape"]).tolist()]
62
62
  shape = (shape_vals[0], shape_vals[1])
63
- arrays = {
64
- name: cast(np.ndarray, _reader.read_elem(elem[name])) for name in _ARRAY_KEYS
65
- }
63
+ arrays = {name: cast(np.ndarray, _reader.read_elem(elem[name])) for name in _ARRAY_KEYS}
66
64
  return cls(
67
65
  shape,
68
66
  arrays["major_ptr"],
@@ -236,7 +236,9 @@ def _group_chunk_boundaries(
236
236
  return chunk_group, chunk_byte
237
237
 
238
238
 
239
- def _unpack_parallel(value_ptr: np.ndarray, buf: np.ndarray, out: np.ndarray, n_chunks: int) -> None:
239
+ def _unpack_parallel(
240
+ value_ptr: np.ndarray, buf: np.ndarray, out: np.ndarray, n_chunks: int
241
+ ) -> None:
240
242
  chunk_group, chunk_byte = _group_chunk_boundaries(value_ptr, buf, n_chunks)
241
243
  _decode_chunks(value_ptr, buf, out, chunk_group, chunk_byte)
242
244