vsparse 0.1.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.
- {vsparse-0.1.0 → vsparse-0.3.0}/PKG-INFO +10 -2
- {vsparse-0.1.0 → vsparse-0.3.0}/README.md +9 -1
- {vsparse-0.1.0 → vsparse-0.3.0}/pyproject.toml +1 -1
- {vsparse-0.1.0 → vsparse-0.3.0}/pyproject.toml.orig +1 -1
- {vsparse-0.1.0 → vsparse-0.3.0}/src/vsparse/__init__.py +3 -0
- {vsparse-0.1.0 → vsparse-0.3.0}/src/vsparse/_anndata_class.py +123 -7
- {vsparse-0.1.0 → vsparse-0.3.0}/src/vsparse/_base.py +132 -66
- {vsparse-0.1.0 → vsparse-0.3.0}/src/vsparse/_compression.py +8 -2
- {vsparse-0.1.0 → vsparse-0.3.0}/src/vsparse/_construct.py +15 -4
- {vsparse-0.1.0 → vsparse-0.3.0}/src/vsparse/_indexutils.py +8 -1
- {vsparse-0.1.0 → vsparse-0.3.0}/src/vsparse/_io.py +8 -4
- {vsparse-0.1.0 → vsparse-0.3.0}/src/vsparse/_ivcsc.py +3 -1
- vsparse-0.3.0/src/vsparse/_norm_common.py +729 -0
- vsparse-0.3.0/src/vsparse/_ops.py +230 -0
- {vsparse-0.1.0 → vsparse-0.3.0}/src/vsparse/_rapid_load.py +18 -14
- vsparse-0.3.0/src/vsparse/_vcs_matmul.py +277 -0
- {vsparse-0.1.0 → vsparse-0.3.0}/src/vsparse/_vcs_norm.py +22 -16
- vsparse-0.1.0/src/vsparse/_norm_common.py +0 -304
- vsparse-0.1.0/src/vsparse/_ops.py +0 -93
- vsparse-0.1.0/src/vsparse/_vcs_matmul.py +0 -168
- {vsparse-0.1.0 → vsparse-0.3.0}/src/vsparse/_anndata.py +0 -0
- {vsparse-0.1.0 → vsparse-0.3.0}/src/vsparse/py.typed +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: vsparse
|
|
3
|
-
Version: 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
|
|
@@ -47,7 +47,15 @@ matrices, e.g. single-cell RNA-seq counts.
|
|
|
47
47
|
|
|
48
48
|
## Install
|
|
49
49
|
|
|
50
|
-
Install from
|
|
50
|
+
Install from PyPI:
|
|
51
|
+
|
|
52
|
+
```sh
|
|
53
|
+
pip install vsparse
|
|
54
|
+
# or with uv
|
|
55
|
+
uv add vsparse
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
From source:
|
|
51
59
|
|
|
52
60
|
```sh
|
|
53
61
|
pip install git+https://github.com/meyer-lab/vsparse.git
|
|
@@ -17,7 +17,15 @@ matrices, e.g. single-cell RNA-seq counts.
|
|
|
17
17
|
|
|
18
18
|
## Install
|
|
19
19
|
|
|
20
|
-
Install from
|
|
20
|
+
Install from PyPI:
|
|
21
|
+
|
|
22
|
+
```sh
|
|
23
|
+
pip install vsparse
|
|
24
|
+
# or with uv
|
|
25
|
+
uv add vsparse
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
From source:
|
|
21
29
|
|
|
22
30
|
```sh
|
|
23
31
|
pip install git+https://github.com/meyer-lab/vsparse.git
|
|
@@ -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
|
|
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=
|
|
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
|
|
@@ -245,10 +340,15 @@ class VCSCAnnData(ad.AnnData):
|
|
|
245
340
|
g: Any,
|
|
246
341
|
*,
|
|
247
342
|
format: str = "vcsc",
|
|
343
|
+
convert_strings_to_categoricals: bool = True,
|
|
248
344
|
dataset_kwargs: Mapping[str, Any] = MappingProxyType({}),
|
|
249
345
|
) -> None:
|
|
250
346
|
if format not in _STORE_FORMATS:
|
|
251
347
|
raise ValueError(f"format must be one of {_STORE_FORMATS}, got {format!r}")
|
|
348
|
+
if convert_strings_to_categoricals:
|
|
349
|
+
# Writing field-by-field skips what anndata's own writers do here,
|
|
350
|
+
# leaving low-cardinality columns as one string per row.
|
|
351
|
+
self.strings_to_categoricals()
|
|
252
352
|
write_array = ad.io.write_elem if format == "vcsc" else _io.write_ivcs_elem
|
|
253
353
|
if self._vcs_X is not None:
|
|
254
354
|
write_array(g, "X", self._vcs_X, dataset_kwargs=dataset_kwargs)
|
|
@@ -277,6 +377,7 @@ class VCSCAnnData(ad.AnnData):
|
|
|
277
377
|
filename: str | PathLike[str],
|
|
278
378
|
*,
|
|
279
379
|
format: str = "vcsc",
|
|
380
|
+
convert_strings_to_categoricals: bool = True,
|
|
280
381
|
dataset_kwargs: Mapping[str, Any] | None = None,
|
|
281
382
|
**_kwargs: Any,
|
|
282
383
|
) -> None:
|
|
@@ -291,6 +392,10 @@ class VCSCAnnData(ad.AnnData):
|
|
|
291
392
|
the cost of extra work on write/read. Either way, ``X``/``raw_X``
|
|
292
393
|
come back from :meth:`read_h5ad` as ordinary VCSCArray/VCSRArray
|
|
293
394
|
objects -- ``"ivcsc"`` is purely an on-disk storage format.
|
|
395
|
+
convert_strings_to_categoricals
|
|
396
|
+
Convert ``obs``/``var`` string columns to categorical in place
|
|
397
|
+
before writing, as ``anndata``'s own writers do. Only columns
|
|
398
|
+
with fewer categories than rows are converted.
|
|
294
399
|
dataset_kwargs
|
|
295
400
|
Passed to ``h5py.Group.create_dataset`` for every array written.
|
|
296
401
|
Defaults to Blosc2+LZ4 compression; pass ``{}`` to store
|
|
@@ -305,7 +410,12 @@ class VCSCAnnData(ad.AnnData):
|
|
|
305
410
|
_compression.numeric_only_compression("h5"),
|
|
306
411
|
h5py.File(filename, "w") as f,
|
|
307
412
|
):
|
|
308
|
-
self._write_group(
|
|
413
|
+
self._write_group(
|
|
414
|
+
f,
|
|
415
|
+
format=format,
|
|
416
|
+
convert_strings_to_categoricals=convert_strings_to_categoricals,
|
|
417
|
+
dataset_kwargs=dataset_kwargs,
|
|
418
|
+
)
|
|
309
419
|
|
|
310
420
|
@classmethod
|
|
311
421
|
def read_h5ad(cls, filename: str | PathLike[str]) -> VCSCAnnData:
|
|
@@ -320,14 +430,15 @@ class VCSCAnnData(ad.AnnData):
|
|
|
320
430
|
store: Any,
|
|
321
431
|
*,
|
|
322
432
|
format: str = "vcsc",
|
|
433
|
+
convert_strings_to_categoricals: bool = True,
|
|
323
434
|
dataset_kwargs: Mapping[str, Any] | None = None,
|
|
324
435
|
**_kwargs: Any,
|
|
325
436
|
) -> None:
|
|
326
437
|
"""Write to a zarr store. Read back with :meth:`read_zarr`.
|
|
327
438
|
|
|
328
|
-
See :meth:`write_h5ad` for ``format``/``
|
|
329
|
-
numeric-only compression behavior);
|
|
330
|
-
Blosc+LZ4 via ``numcodecs``.
|
|
439
|
+
See :meth:`write_h5ad` for ``format``/``convert_strings_to_categoricals``/
|
|
440
|
+
``dataset_kwargs`` (including the numeric-only compression behavior);
|
|
441
|
+
the default compression here is Blosc+LZ4 via ``numcodecs``.
|
|
331
442
|
"""
|
|
332
443
|
import zarr
|
|
333
444
|
|
|
@@ -335,7 +446,12 @@ class VCSCAnnData(ad.AnnData):
|
|
|
335
446
|
dataset_kwargs = _compression.zarr_dataset_kwargs()
|
|
336
447
|
with _compression.numeric_only_compression("zarr"):
|
|
337
448
|
f = zarr.open_group(store, mode="w")
|
|
338
|
-
self._write_group(
|
|
449
|
+
self._write_group(
|
|
450
|
+
f,
|
|
451
|
+
format=format,
|
|
452
|
+
convert_strings_to_categoricals=convert_strings_to_categoricals,
|
|
453
|
+
dataset_kwargs=dataset_kwargs,
|
|
454
|
+
)
|
|
339
455
|
|
|
340
456
|
@classmethod
|
|
341
457
|
def read_zarr(cls, store: Any) -> VCSCAnnData:
|
|
@@ -20,6 +20,10 @@ import scipy.sparse as sp
|
|
|
20
20
|
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
|
+
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
|
|
23
27
|
|
|
24
28
|
__all__ = ["VCSCArray", "VCSRArray"]
|
|
25
29
|
|
|
@@ -38,7 +42,7 @@ class _VCSBase:
|
|
|
38
42
|
# __rmatmul__/__rmul__ instead of trying to broadcast us as an ndarray.
|
|
39
43
|
__array_ufunc__ = None
|
|
40
44
|
|
|
41
|
-
__slots__ = ("indices", "major_ptr", "shape", "value_ptr", "values")
|
|
45
|
+
__slots__ = ("_norm_cache", "indices", "major_ptr", "shape", "value_ptr", "values")
|
|
42
46
|
|
|
43
47
|
def __init__(
|
|
44
48
|
self,
|
|
@@ -55,9 +59,7 @@ class _VCSBase:
|
|
|
55
59
|
indices = np.asarray(indices)
|
|
56
60
|
|
|
57
61
|
if major_ptr.shape[0] != n_major + 1:
|
|
58
|
-
raise ValueError(
|
|
59
|
-
f"major_ptr has length {major_ptr.shape[0]}, expected {n_major + 1}"
|
|
60
|
-
)
|
|
62
|
+
raise ValueError(f"major_ptr has length {major_ptr.shape[0]}, expected {n_major + 1}")
|
|
61
63
|
if value_ptr.shape[0] != values.shape[0] + 1:
|
|
62
64
|
raise ValueError("value_ptr must have length len(values) + 1")
|
|
63
65
|
if major_ptr[-1] != values.shape[0]:
|
|
@@ -67,11 +69,18 @@ class _VCSBase:
|
|
|
67
69
|
if indices.shape[0] and (indices.min() < 0 or indices.max() >= n_minor):
|
|
68
70
|
raise ValueError("indices out of bounds for the given shape")
|
|
69
71
|
|
|
72
|
+
# Narrow after the bounds check above, so an out-of-range index is
|
|
73
|
+
# rejected rather than silently truncated by the cast.
|
|
74
|
+
idx_dtype = _smallest_index_dtype(n_minor)
|
|
75
|
+
if idx_dtype.itemsize < indices.dtype.itemsize:
|
|
76
|
+
indices = indices.astype(idx_dtype, copy=False)
|
|
77
|
+
|
|
70
78
|
self.shape = (int(shape[0]), int(shape[1]))
|
|
71
79
|
self.major_ptr = major_ptr
|
|
72
80
|
self.values = values
|
|
73
81
|
self.value_ptr = value_ptr
|
|
74
82
|
self.indices = indices
|
|
83
|
+
self._norm_cache = _NormCache()
|
|
75
84
|
|
|
76
85
|
# -- axis bookkeeping ------------------------------------------------
|
|
77
86
|
|
|
@@ -105,8 +114,7 @@ class _VCSBase:
|
|
|
105
114
|
def __repr__(self) -> str: # pragma: no cover - cosmetic
|
|
106
115
|
cls = type(self).__name__
|
|
107
116
|
return (
|
|
108
|
-
f"<{cls} shape={self.shape} dtype={self.dtype} "
|
|
109
|
-
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}>"
|
|
110
118
|
)
|
|
111
119
|
|
|
112
120
|
def copy(self):
|
|
@@ -124,9 +132,9 @@ class _VCSBase:
|
|
|
124
132
|
def from_scipy(cls, mat) -> _VCSBase:
|
|
125
133
|
"""Build from any scipy sparse array/matrix (converted internally)."""
|
|
126
134
|
mat = mat.tocsc() if cls._format == "csc" else mat.tocsr()
|
|
127
|
-
n_major,
|
|
135
|
+
n_major, n_minor = cls._swap(mat.shape)
|
|
128
136
|
major_ptr, values, value_ptr, indices = _construct.compress(
|
|
129
|
-
mat.indptr, mat.indices, mat.data, n_major
|
|
137
|
+
mat.indptr, mat.indices, mat.data, n_major, n_minor
|
|
130
138
|
)
|
|
131
139
|
return cls(mat.shape, major_ptr, values, value_ptr, indices)
|
|
132
140
|
|
|
@@ -193,12 +201,42 @@ class _VCSBase:
|
|
|
193
201
|
)
|
|
194
202
|
return other_cls(self.shape, major_ptr, values, value_ptr, indices)
|
|
195
203
|
|
|
196
|
-
def normalized(self) -> Any:
|
|
197
|
-
"""A
|
|
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
|
|
198
227
|
from vsparse._vcs_norm import VCSCArrayNormalized, VCSRArrayNormalized
|
|
199
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
|
+
|
|
200
236
|
cls = VCSCArrayNormalized if self._format == "csc" else VCSRArrayNormalized
|
|
201
|
-
|
|
237
|
+
result = cls(self, recipe)
|
|
238
|
+
cache.put(recipe, result)
|
|
239
|
+
return result
|
|
202
240
|
|
|
203
241
|
def log1p(self) -> _VCSBase:
|
|
204
242
|
"""Elementwise ``log1p``. Structural zeros stay zero implicitly."""
|
|
@@ -220,10 +258,14 @@ class _VCSBase:
|
|
|
220
258
|
return np.bincount(group_of_major, weights=weighted, minlength=self.n_major)
|
|
221
259
|
|
|
222
260
|
def _minor_sums(self) -> np.ndarray:
|
|
223
|
-
"""
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
261
|
+
"""A parallel scatter-add over every nonzero to get per-minor-index totals."""
|
|
262
|
+
return _ops.minor_sums(
|
|
263
|
+
self.values,
|
|
264
|
+
self.value_ptr,
|
|
265
|
+
self.indices,
|
|
266
|
+
self.n_minor,
|
|
267
|
+
_ops.accumulator_threads(self.n_minor),
|
|
268
|
+
)
|
|
227
269
|
|
|
228
270
|
def sum(self, axis: int | None = None) -> np.ndarray | float:
|
|
229
271
|
"""Sum of (structural) values along ``axis`` (0=rows, 1=columns), or overall if ``None``."""
|
|
@@ -245,8 +287,13 @@ class _VCSBase:
|
|
|
245
287
|
)
|
|
246
288
|
|
|
247
289
|
def _minor_nnz(self) -> np.ndarray:
|
|
248
|
-
"""
|
|
249
|
-
return
|
|
290
|
+
"""A parallel scatter over every nonzero to get per-minor-index counts."""
|
|
291
|
+
return _ops.minor_counts(
|
|
292
|
+
self.value_ptr,
|
|
293
|
+
self.indices,
|
|
294
|
+
self.n_minor,
|
|
295
|
+
_ops.accumulator_threads(self.n_minor),
|
|
296
|
+
)
|
|
250
297
|
|
|
251
298
|
def getnnz(self, axis: int | None = None) -> np.ndarray | int:
|
|
252
299
|
"""Count of stored elements along ``axis``, or overall if ``None``."""
|
|
@@ -291,11 +338,11 @@ class _VCSBase:
|
|
|
291
338
|
|
|
292
339
|
def _minor_reduce(self, ufunc: np.ufunc, initial: Any) -> np.ndarray:
|
|
293
340
|
"""Per-minor-index max/min, accounting for implicit zeros in sparse slices."""
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
341
|
+
out, counts = _ops.minor_extrema(
|
|
342
|
+
self.values, self.value_ptr, self.indices, self.n_minor, initial, ufunc is np.maximum
|
|
343
|
+
)
|
|
344
|
+
# A minor index missing from some major slice has a structural zero
|
|
345
|
+
# competing in the reduction.
|
|
299
346
|
not_dense = counts < self.n_major
|
|
300
347
|
out[not_dense] = ufunc(out[not_dense], 0)
|
|
301
348
|
return out
|
|
@@ -344,9 +391,7 @@ class _VCSBase:
|
|
|
344
391
|
if np.isscalar(other):
|
|
345
392
|
if other == 0:
|
|
346
393
|
return self.copy()
|
|
347
|
-
raise NotImplementedError(
|
|
348
|
-
"adding a nonzero scalar to a sparse array is not supported"
|
|
349
|
-
)
|
|
394
|
+
raise NotImplementedError("adding a nonzero scalar to a sparse array is not supported")
|
|
350
395
|
return self._elementwise(other, "__add__")
|
|
351
396
|
|
|
352
397
|
__radd__ = __add__
|
|
@@ -454,15 +499,11 @@ class _VCSBase:
|
|
|
454
499
|
other_arr = np.asarray(other)
|
|
455
500
|
if other_arr.ndim == 1:
|
|
456
501
|
if other_arr.shape[0] != self.shape[1]:
|
|
457
|
-
raise ValueError(
|
|
458
|
-
f"shapes {self.shape} and {other_arr.shape} not aligned"
|
|
459
|
-
)
|
|
502
|
+
raise ValueError(f"shapes {self.shape} and {other_arr.shape} not aligned")
|
|
460
503
|
return self._dot_right(other_arr)
|
|
461
504
|
if other_arr.ndim == 2:
|
|
462
505
|
if other_arr.shape[0] != self.shape[1]:
|
|
463
|
-
raise ValueError(
|
|
464
|
-
f"shapes {self.shape} and {other_arr.shape} not aligned"
|
|
465
|
-
)
|
|
506
|
+
raise ValueError(f"shapes {self.shape} and {other_arr.shape} not aligned")
|
|
466
507
|
return self._dot_right_mat(other_arr)
|
|
467
508
|
return NotImplemented
|
|
468
509
|
|
|
@@ -470,15 +511,11 @@ class _VCSBase:
|
|
|
470
511
|
other_arr = np.asarray(other)
|
|
471
512
|
if other_arr.ndim == 1:
|
|
472
513
|
if other_arr.shape[0] != self.shape[0]:
|
|
473
|
-
raise ValueError(
|
|
474
|
-
f"shapes {other_arr.shape} and {self.shape} not aligned"
|
|
475
|
-
)
|
|
514
|
+
raise ValueError(f"shapes {other_arr.shape} and {self.shape} not aligned")
|
|
476
515
|
return self._dot_left(other_arr)
|
|
477
516
|
if other_arr.ndim == 2:
|
|
478
517
|
if other_arr.shape[1] != self.shape[0]:
|
|
479
|
-
raise ValueError(
|
|
480
|
-
f"shapes {other_arr.shape} and {self.shape} not aligned"
|
|
481
|
-
)
|
|
518
|
+
raise ValueError(f"shapes {other_arr.shape} and {self.shape} not aligned")
|
|
482
519
|
return self._dot_left_mat(other_arr)
|
|
483
520
|
return NotImplemented
|
|
484
521
|
|
|
@@ -492,9 +529,11 @@ class _VCSBase:
|
|
|
492
529
|
new_major_ptr = np.zeros(idx.shape[0] + 1, dtype=np.int64)
|
|
493
530
|
np.cumsum(counts, out=new_major_ptr[1:])
|
|
494
531
|
|
|
495
|
-
value_slots =
|
|
496
|
-
[np.arange(s, e) for s, e in zip(starts, ends, strict=True)]
|
|
497
|
-
|
|
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
|
+
)
|
|
498
537
|
new_values = self.values[value_slots]
|
|
499
538
|
|
|
500
539
|
v_starts = self.value_ptr[value_slots]
|
|
@@ -502,44 +541,73 @@ class _VCSBase:
|
|
|
502
541
|
idx_counts = v_ends - v_starts
|
|
503
542
|
new_value_ptr = np.zeros(value_slots.shape[0] + 1, dtype=np.int64)
|
|
504
543
|
np.cumsum(idx_counts, out=new_value_ptr[1:])
|
|
505
|
-
new_indices =
|
|
506
|
-
[self.indices[s:e] for s, e in zip(v_starts, v_ends, strict=True)]
|
|
507
|
-
|
|
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
|
+
)
|
|
508
549
|
|
|
509
550
|
n_minor = self.n_minor
|
|
510
|
-
new_shape = (
|
|
511
|
-
(n_minor, idx.shape[0]) if self._format == "csc" else (idx.shape[0], n_minor)
|
|
512
|
-
)
|
|
551
|
+
new_shape = (n_minor, idx.shape[0]) if self._format == "csc" else (idx.shape[0], n_minor)
|
|
513
552
|
return type(self)(new_shape, new_major_ptr, new_values, new_value_ptr, new_indices)
|
|
514
553
|
|
|
554
|
+
def _major_range(self, start: int, stop: int) -> _VCSBase:
|
|
555
|
+
"""The contiguous major-slice range ``[start, stop)``, without copying values.
|
|
556
|
+
|
|
557
|
+
``values``/``indices`` come back as views; only the two pointer
|
|
558
|
+
arrays are rebuilt, rebased to the new start.
|
|
559
|
+
"""
|
|
560
|
+
u0, u1 = int(self.major_ptr[start]), int(self.major_ptr[stop])
|
|
561
|
+
k0, k1 = int(self.value_ptr[u0]), int(self.value_ptr[u1])
|
|
562
|
+
n_sel = stop - start
|
|
563
|
+
new_shape = (self.n_minor, n_sel) if self._format == "csc" else (n_sel, self.n_minor)
|
|
564
|
+
return type(self)(
|
|
565
|
+
new_shape,
|
|
566
|
+
self.major_ptr[start : stop + 1] - u0,
|
|
567
|
+
self.values[u0:u1],
|
|
568
|
+
self.value_ptr[u0 : u1 + 1] - k0,
|
|
569
|
+
self.indices[k0:k1],
|
|
570
|
+
)
|
|
571
|
+
|
|
515
572
|
def _select_minor(self, key: Any) -> _VCSBase:
|
|
516
573
|
"""Select along the minor axis (rows for VCSC, columns for VCSR).
|
|
517
574
|
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
index, shrinking ``major_ptr``/``value_ptr`` accordingly.
|
|
575
|
+
A key may name the same index more than once, so this is a fan-out
|
|
576
|
+
rather than a remap and one stored element can appear in several
|
|
577
|
+
output positions.
|
|
522
578
|
"""
|
|
523
579
|
idx = _normalize_major_idx(key, self.n_minor)
|
|
524
580
|
n_minor_new = idx.shape[0]
|
|
525
581
|
|
|
526
|
-
|
|
527
|
-
|
|
582
|
+
# Output positions grouped by the original index they came from.
|
|
583
|
+
fanout = np.bincount(idx, minlength=self.n_minor)
|
|
584
|
+
offsets = np.zeros(self.n_minor + 1, dtype=np.int64)
|
|
585
|
+
np.cumsum(fanout, out=offsets[1:])
|
|
586
|
+
positions = np.argsort(idx, kind="stable").astype(np.int64, copy=False)
|
|
528
587
|
|
|
529
|
-
|
|
530
|
-
|
|
588
|
+
slot_counts = _ops.minor_select_counts(self.value_ptr, self.indices, fanout)
|
|
589
|
+
kept_slots = np.flatnonzero(slot_counts)
|
|
531
590
|
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
surviving = kept_per_slot > 0
|
|
591
|
+
new_values = self.values[kept_slots]
|
|
592
|
+
new_value_ptr = np.zeros(kept_slots.shape[0] + 1, dtype=np.int64)
|
|
593
|
+
np.cumsum(slot_counts[kept_slots], out=new_value_ptr[1:])
|
|
536
594
|
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
595
|
+
# Keep the parent's index dtype, as every other structural op does.
|
|
596
|
+
new_indices = np.empty(int(new_value_ptr[-1]), dtype=self.indices.dtype)
|
|
597
|
+
_ops.minor_select_fill(
|
|
598
|
+
self.value_ptr,
|
|
599
|
+
self.indices,
|
|
600
|
+
offsets,
|
|
601
|
+
positions,
|
|
602
|
+
kept_slots,
|
|
603
|
+
new_value_ptr,
|
|
604
|
+
new_indices,
|
|
605
|
+
)
|
|
540
606
|
|
|
541
|
-
|
|
542
|
-
|
|
607
|
+
# Slots keep their original order, so each major slice owns a
|
|
608
|
+
# contiguous run of them.
|
|
609
|
+
major_of_slot = np.searchsorted(self.major_ptr, kept_slots, side="right") - 1
|
|
610
|
+
major_counts = np.bincount(major_of_slot, minlength=self.n_major)
|
|
543
611
|
new_major_ptr = np.zeros(self.n_major + 1, dtype=np.int64)
|
|
544
612
|
np.cumsum(major_counts, out=new_major_ptr[1:])
|
|
545
613
|
|
|
@@ -561,9 +629,7 @@ class _VCSBase:
|
|
|
561
629
|
if isinstance(row_key, int | np.integer) and isinstance(col_key, int | np.integer):
|
|
562
630
|
return self.to_scipy()[row_key, col_key]
|
|
563
631
|
|
|
564
|
-
major_key, minor_key = (
|
|
565
|
-
(col_key, row_key) if self._format == "csc" else (row_key, col_key)
|
|
566
|
-
)
|
|
632
|
+
major_key, minor_key = (col_key, row_key) if self._format == "csc" else (row_key, col_key)
|
|
567
633
|
if _is_full_slice(major_key) and _is_full_slice(minor_key):
|
|
568
634
|
return self.copy()
|
|
569
635
|
|
|
@@ -11,11 +11,17 @@ categoricals (category labels, ``obs``/``var`` string columns, the
|
|
|
11
11
|
``_index``). At least some HDF5 filter-plugin builds (seen in this
|
|
12
12
|
environment: h5py 3.16 / HDF5 2.0.0 / hdf5plugin's Blosc2) segfault
|
|
13
13
|
(``SIGFPE``) when the Blosc2 filter is applied to a variable-length-string
|
|
14
|
-
dataset
|
|
15
|
-
anyway. :func:`numeric_only_compression` patches the relevant
|
|
14
|
+
dataset. :func:`numeric_only_compression` patches the relevant
|
|
16
15
|
``create_dataset``/``create_array`` calls for the duration of a write so
|
|
17
16
|
string/object arrays always land uncompressed, regardless of what
|
|
18
17
|
``dataset_kwargs`` was passed in -- callers don't have to know about this.
|
|
18
|
+
|
|
19
|
+
Strings are left uncompressed rather than given a different codec: gzip and
|
|
20
|
+
lzf are safe on variable-length strings here, but the size problem is the
|
|
21
|
+
per-row string itself, not its compression. Encoding low-cardinality
|
|
22
|
+
columns as categoricals turns the per-row data numeric, which the existing
|
|
23
|
+
Blosc2 path then compresses -- see
|
|
24
|
+
:meth:`vsparse.VCSCAnnData.write_h5ad`'s ``convert_strings_to_categoricals``.
|
|
19
25
|
"""
|
|
20
26
|
|
|
21
27
|
from __future__ import annotations
|