vsparse 0.5.0__tar.gz → 0.6.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.5.0
3
+ Version: 0.6.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
@@ -177,6 +177,25 @@ va = vsparse.load_packed("archived.h5ad")
177
177
  norm = va.X.normalized("parafac2") # lazy view; norm @ B works without densifying
178
178
  ```
179
179
 
180
+ `load_packed` can also subset as it decodes: `obs_idx`/`var_idx` take a boolean mask, an array of integer positions, or a slice, and give the same result as indexing a full load, without ever building the full matrix. With IVCSR, only the selected cells are decoded and unselected genes are dropped in the same pass (IVCSC is the same with the axes swapped). Every packed byte is still read, so reading the stream sets the floor: on a 1.26M-cell file, a 1% cell subset decodes `X` in 0.21 s against 0.50 s for all of it.
181
+
182
+ ```python
183
+ import anndata, h5py
184
+
185
+ with h5py.File("archived.h5ad") as f: # read only obs to build the mask
186
+ obs = anndata.io.read_elem(f["obs"])
187
+ va_blood = vsparse.load_packed("archived.h5ad", obs_idx=obs["tissue"] == "blood")
188
+ ```
189
+
190
+ ### Statistics sidecar
191
+
192
+ Every `VCSCArray`/`VCSRArray` carries per-row and per-column summary statistics as `arr.stats` (a `vsparse.VCSStats`): `row_sums`/`col_sums` (total counts), `row_nnz`/`col_nnz` (n-genes/n-cells by counts), and `col_depth_sums` (per-gene sums of depth-normalized counts). They are computed on first access and written next to `X`/`raw_X` by `write_h5ad`/`write_zarr` whether or not they were ever computed or a normalized view was ever made, so a file read back has them without touching the data. Every recipe's per-cell and per-gene scales (`a`/`b`) are derived from them, so only centering/scaling recipes still need a pass over the data. Files without a usable sidecar (older versions, other tools) load as before, and the statistics are recomputed when first needed.
193
+
194
+ ```python
195
+ va = vsparse.VCSCAnnData.read_h5ad("archived.h5ad")
196
+ keep = va.X.stats.row_sums >= 500 # QC filter from the sidecar alone
197
+ ```
198
+
180
199
  ### CUDA (`to_gpu`)
181
200
 
182
201
  A normalized view moves onto an NVIDIA GPU with `.to_gpu()`, keeping its value-compressed layout there rather than expanding to one float per nonzero — so a matrix that only fits in device memory compressed still fits. Everything floating-point on the device is float32.
@@ -143,6 +143,25 @@ va = vsparse.load_packed("archived.h5ad")
143
143
  norm = va.X.normalized("parafac2") # lazy view; norm @ B works without densifying
144
144
  ```
145
145
 
146
+ `load_packed` can also subset as it decodes: `obs_idx`/`var_idx` take a boolean mask, an array of integer positions, or a slice, and give the same result as indexing a full load, without ever building the full matrix. With IVCSR, only the selected cells are decoded and unselected genes are dropped in the same pass (IVCSC is the same with the axes swapped). Every packed byte is still read, so reading the stream sets the floor: on a 1.26M-cell file, a 1% cell subset decodes `X` in 0.21 s against 0.50 s for all of it.
147
+
148
+ ```python
149
+ import anndata, h5py
150
+
151
+ with h5py.File("archived.h5ad") as f: # read only obs to build the mask
152
+ obs = anndata.io.read_elem(f["obs"])
153
+ va_blood = vsparse.load_packed("archived.h5ad", obs_idx=obs["tissue"] == "blood")
154
+ ```
155
+
156
+ ### Statistics sidecar
157
+
158
+ Every `VCSCArray`/`VCSRArray` carries per-row and per-column summary statistics as `arr.stats` (a `vsparse.VCSStats`): `row_sums`/`col_sums` (total counts), `row_nnz`/`col_nnz` (n-genes/n-cells by counts), and `col_depth_sums` (per-gene sums of depth-normalized counts). They are computed on first access and written next to `X`/`raw_X` by `write_h5ad`/`write_zarr` whether or not they were ever computed or a normalized view was ever made, so a file read back has them without touching the data. Every recipe's per-cell and per-gene scales (`a`/`b`) are derived from them, so only centering/scaling recipes still need a pass over the data. Files without a usable sidecar (older versions, other tools) load as before, and the statistics are recomputed when first needed.
159
+
160
+ ```python
161
+ va = vsparse.VCSCAnnData.read_h5ad("archived.h5ad")
162
+ keep = va.X.stats.row_sums >= 500 # QC filter from the sidecar alone
163
+ ```
164
+
146
165
  ### CUDA (`to_gpu`)
147
166
 
148
167
  A normalized view moves onto an NVIDIA GPU with `.to_gpu()`, keeping its value-compressed layout there rather than expanding to one float per nonzero — so a matrix that only fits in device memory compressed still fits. Everything floating-point on the device is float32.
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "vsparse"
3
- version = "0.5.0"
3
+ version = "0.6.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.5.0"
3
+ version = "0.6.0"
4
4
  description = "Value-Compressed Sparse Column/Row (VCSC/VCSR) arrays, with optional AnnData integration"
5
5
  readme = "README.md"
6
6
  authors = [
@@ -12,6 +12,7 @@ from vsparse._base import VCSCArray, VCSRArray
12
12
  from vsparse._cuda import CudaNormalizedView, cuda_is_available
13
13
  from vsparse._norm_common import RECIPES, Recipe
14
14
  from vsparse._rapid_load import load_packed
15
+ from vsparse._stats import VCSStats
15
16
  from vsparse._vcs_norm import VCSCArrayNormalized, VCSRArrayNormalized
16
17
 
17
18
  __all__ = [
@@ -23,10 +24,11 @@ __all__ = [
23
24
  "VCSCArrayNormalized",
24
25
  "VCSRArray",
25
26
  "VCSRArrayNormalized",
27
+ "VCSStats",
26
28
  "cuda_is_available",
27
29
  "from_anndata",
28
30
  "load_packed",
29
31
  "to_layer",
30
32
  ]
31
33
 
32
- __version__ = "0.5.0"
34
+ __version__ = "0.6.0"
@@ -212,7 +212,18 @@ class VCSCAnnData(ad.AnnData):
212
212
  oidx, vidx = self._normalize_indices(index)
213
213
  oidx = _as_slice_index(oidx, self.n_obs)
214
214
  vidx = _as_slice_index(vidx, self.n_vars)
215
+ return type(self)(
216
+ X=_subset_2d(self._vcs_X, oidx, vidx),
217
+ raw_X=_subset_2d(self._vcs_raw_X, oidx, vidx),
218
+ **self._subset_fields(oidx, vidx),
219
+ )
220
+
221
+ def _subset_fields(self, oidx: Any, vidx: Any) -> dict[str, Any]:
222
+ """Every field but ``X``/``raw_X``, subset to positions ``oidx``/``vidx``.
215
223
 
224
+ Shared by :meth:`__getitem__` and :func:`~vsparse.load_packed`'s
225
+ ``obs_idx``/``var_idx``, which decodes ``X`` already subset.
226
+ """
216
227
  obs = cast(pd.DataFrame, self.obs).iloc[oidx].copy()
217
228
  var = cast(pd.DataFrame, self.var).iloc[vidx].copy()
218
229
 
@@ -229,18 +240,16 @@ class VCSCAnnData(ad.AnnData):
229
240
  if _VSPARSE_UNS_KEY in uns:
230
241
  uns = {**uns, _VSPARSE_UNS_KEY: {**uns[_VSPARSE_UNS_KEY], "stale": True}}
231
242
 
232
- return type(self)(
233
- X=_subset_2d(self._vcs_X, oidx, vidx),
234
- raw_X=_subset_2d(self._vcs_raw_X, oidx, vidx),
235
- obs=obs,
236
- var=var,
237
- uns=uns,
238
- obsm=_map_subset_1d(self.obsm, oidx),
239
- varm=_map_subset_1d(self.varm, vidx),
240
- obsp=_map_subset_2d(self.obsp, oidx, oidx),
241
- varp=_map_subset_2d(self.varp, vidx, vidx),
242
- layers=_map_subset_2d(self.layers, oidx, vidx),
243
- )
243
+ return {
244
+ "obs": obs,
245
+ "var": var,
246
+ "uns": uns,
247
+ "obsm": _map_subset_1d(self.obsm, oidx),
248
+ "varm": _map_subset_1d(self.varm, vidx),
249
+ "obsp": _map_subset_2d(self.obsp, oidx, oidx),
250
+ "varp": _map_subset_2d(self.varp, vidx, vidx),
251
+ "layers": _map_subset_2d(self.layers, oidx, vidx),
252
+ }
244
253
 
245
254
  def copy(self) -> VCSCAnnData: # ty: ignore[invalid-method-override]
246
255
  """A deep copy, preserving the VCSC/VCSR-backed ``X``/``raw_X``.
@@ -17,7 +17,7 @@ from typing import Any
17
17
  import numpy as np
18
18
  import scipy.sparse as sp
19
19
 
20
- from vsparse import _construct, _ops
20
+ from vsparse import _construct, _ops, _stats
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
@@ -42,7 +42,7 @@ class _VCSBase:
42
42
  # __rmatmul__/__rmul__ instead of trying to broadcast us as an ndarray.
43
43
  __array_ufunc__ = None
44
44
 
45
- __slots__ = ("_norm_cache", "indices", "major_ptr", "shape", "value_ptr", "values")
45
+ __slots__ = ("_norm_cache", "_stats", "indices", "major_ptr", "shape", "value_ptr", "values")
46
46
 
47
47
  def __init__(
48
48
  self,
@@ -81,6 +81,7 @@ class _VCSBase:
81
81
  self.value_ptr = value_ptr
82
82
  self.indices = indices
83
83
  self._norm_cache = _NormCache()
84
+ self._stats: _stats.VCSStats | None = None
84
85
 
85
86
  # -- axis bookkeeping ------------------------------------------------
86
87
 
@@ -117,14 +118,29 @@ class _VCSBase:
117
118
  f"<{cls} shape={self.shape} dtype={self.dtype} nnz={self.nnz} n_unique={self.n_unique}>"
118
119
  )
119
120
 
121
+ @property
122
+ def stats(self) -> _stats.VCSStats:
123
+ """Per-row/per-column totals and nonzero counts -- see :mod:`vsparse._stats`.
124
+
125
+ Computed on first access (``O(nnz)``) and kept, or restored from the
126
+ sidecar of a file written by :meth:`~vsparse.VCSCAnnData.write_h5ad`/
127
+ :meth:`~vsparse.VCSCAnnData.write_zarr`. Normalization reads its
128
+ per-cell/per-gene scales (``a``/``b``) from here.
129
+ """
130
+ if self._stats is None:
131
+ self._stats = _stats.compute_stats(self)
132
+ return self._stats
133
+
120
134
  def copy(self):
121
- return type(self)(
135
+ out = type(self)(
122
136
  self.shape,
123
137
  self.major_ptr.copy(),
124
138
  self.values.copy(),
125
139
  self.value_ptr.copy(),
126
140
  self.indices.copy(),
127
141
  )
142
+ out._stats = self._stats # same data, so the same (read-only) statistics
143
+ return out
128
144
 
129
145
  # -- construction / conversion ---------------------------------------
130
146
 
@@ -53,7 +53,9 @@ def _compress(major_ptr_in, minor_indices, data, n_major):
53
53
 
54
54
  seg_vals = data[start:end]
55
55
  seg_minor = minor_indices[start:end]
56
- order = np.argsort(seg_vals)
56
+ # Stable, so each value group keeps its minor indices in input order
57
+ # (sorted, for canonical scipy input) -- see vsparse._stats.
58
+ order = np.argsort(seg_vals, kind="mergesort")
57
59
  sorted_vals = seg_vals[order]
58
60
  sorted_minor = seg_minor[order]
59
61