vsparse 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.
- vsparse/__init__.py +27 -0
- vsparse/_anndata.py +68 -0
- vsparse/_anndata_class.py +346 -0
- vsparse/_base.py +589 -0
- vsparse/_compression.py +162 -0
- vsparse/_construct.py +194 -0
- vsparse/_indexutils.py +36 -0
- vsparse/_io.py +139 -0
- vsparse/_ivcsc.py +265 -0
- vsparse/_norm_common.py +304 -0
- vsparse/_ops.py +93 -0
- vsparse/_rapid_load.py +552 -0
- vsparse/_vcs_matmul.py +168 -0
- vsparse/_vcs_norm.py +62 -0
- vsparse/py.typed +0 -0
- vsparse-0.1.0.dist-info/METADATA +175 -0
- vsparse-0.1.0.dist-info/RECORD +18 -0
- vsparse-0.1.0.dist-info/WHEEL +4 -0
vsparse/_vcs_matmul.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"""Parallel numba kernels for ``VCSCArrayNormalized``/``VCSRArrayNormalized`` @ dense.
|
|
2
|
+
|
|
3
|
+
For row-scale ``r``, gene-scale ``g``, and centering ``c = col_mean``,
|
|
4
|
+
|
|
5
|
+
A_norm = broadcast_rows(-c) + Delta, Delta[i, j] = log10(1 + 1000 * raw[i, j] / r[i] / g[j])
|
|
6
|
+
|
|
7
|
+
with ``Delta`` exactly zero off the structural nonzeros, so
|
|
8
|
+
``A_norm @ B = ones(n_rows) (x) (-c @ B) + Delta @ B`` and ``B @ A_norm =
|
|
9
|
+
(B.sum(axis=1)) (x) (-c) + B @ Delta``, with only the genuinely ``O(nnz)``
|
|
10
|
+
``Delta @ B`` / ``B @ Delta`` needing a kernel.
|
|
11
|
+
|
|
12
|
+
Both ``self @ B`` and ``B @ self`` need a kernel that's *major-aligned*:
|
|
13
|
+
parallelizing safely over the major axis requires the major axis to be
|
|
14
|
+
exactly the output's disjoint axis (:class:`~vsparse.VCSRArray` for
|
|
15
|
+
``self @ B``, :class:`~vsparse.VCSCArray` for ``B @ self`` -- see
|
|
16
|
+
:func:`_vcsr_matmul_delta`/:func:`_vcsc_rmatmul_delta`). The other direction
|
|
17
|
+
on a given array (:class:`~vsparse.VCSCArray` for ``self @ B``,
|
|
18
|
+
:class:`~vsparse.VCSRArray` for ``B @ self``) doesn't have that alignment --
|
|
19
|
+
rather than run a scatter kernel there (thread-local output-shaped
|
|
20
|
+
accumulators, reduced across threads: cache-unfriendly, and memory-hungry
|
|
21
|
+
enough for wide ``B`` to need throttling), :func:`_get_dual` builds and
|
|
22
|
+
caches the *other* VCS format's storage for the same underlying array, once,
|
|
23
|
+
via :meth:`~vsparse._base._VCSBase._transpose_major` -- a single global sort
|
|
24
|
+
(see :func:`vsparse._construct.transpose_major`), not a per-call cost -- and
|
|
25
|
+
every subsequent call in the misaligned direction runs the same
|
|
26
|
+
major-aligned kernel against that cached dual instead. ``row_scale``/
|
|
27
|
+
``gene_scale``/``col_mean`` are per-row/per-column statistics, so they carry
|
|
28
|
+
over unchanged regardless of which physical layout is used to compute
|
|
29
|
+
against.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
from __future__ import annotations
|
|
33
|
+
|
|
34
|
+
from typing import TYPE_CHECKING, Any
|
|
35
|
+
|
|
36
|
+
import numba
|
|
37
|
+
import numpy as np
|
|
38
|
+
|
|
39
|
+
if TYPE_CHECKING:
|
|
40
|
+
from vsparse._vcs_norm import _VCSNormalizedBase
|
|
41
|
+
|
|
42
|
+
__all__ = ["dense_at_normalized", "normalized_at_dense"]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
# -- major-aligned: VCSR, self @ B (out rows == major slices) ---------------
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@numba.njit(cache=True, parallel=True)
|
|
49
|
+
def _vcsr_matmul_delta(major_ptr, values, value_ptr, indices, row_scale, gene_scale, B, out):
|
|
50
|
+
n_major = major_ptr.shape[0] - 1
|
|
51
|
+
k = B.shape[1]
|
|
52
|
+
for i in numba.prange(n_major): # ty: ignore[not-iterable]
|
|
53
|
+
rs = row_scale[i]
|
|
54
|
+
for u in range(major_ptr[i], major_ptr[i + 1]):
|
|
55
|
+
v = values[u]
|
|
56
|
+
for kk in range(value_ptr[u], value_ptr[u + 1]):
|
|
57
|
+
col = indices[kk]
|
|
58
|
+
gs = gene_scale[col]
|
|
59
|
+
if gs > 0.0:
|
|
60
|
+
delta = np.log10(1.0 + 1000.0 * (v / rs / gs))
|
|
61
|
+
for c in range(k):
|
|
62
|
+
out[i, c] += delta * B[col, c]
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _matmul_vcsr(arr, row_scale, gene_scale, B: np.ndarray) -> np.ndarray:
|
|
66
|
+
n_rows = arr.n_major
|
|
67
|
+
k = B.shape[1]
|
|
68
|
+
out = np.zeros((n_rows, k), dtype=np.float64)
|
|
69
|
+
_vcsr_matmul_delta(arr.major_ptr, arr.values, arr.value_ptr, arr.indices, row_scale, gene_scale, B, out)
|
|
70
|
+
return out
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
# -- major-aligned: VCSC, B @ self (out cols == major slices) ---------------
|
|
74
|
+
#
|
|
75
|
+
# ``B`` arrives as (p, n_rows) and the natural output is (p, n_cols) -- but
|
|
76
|
+
# with ``out``/``B`` in that shape, the innermost loop over ``c`` (0..p) hits
|
|
77
|
+
# out[c, j] and B[c, row], both strided by the *other* array's full width
|
|
78
|
+
# (n_cols/n_rows elements between consecutive c), not the unit stride a
|
|
79
|
+
# C-contiguous inner loop needs. Every one of the up to nnz*p inner-loop
|
|
80
|
+
# steps is a separate cache line, so this is a per-nonzero cost, not a
|
|
81
|
+
# one-off. Transposing both to (n_rows, p)/(n_cols, p) first makes the
|
|
82
|
+
# inner loop over ``c`` walk one contiguous row of each -- the transposes
|
|
83
|
+
# themselves are O(p * (n_rows + n_cols)), negligible next to the O(nnz * p)
|
|
84
|
+
# kernel they speed up.
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@numba.njit(cache=True, parallel=True)
|
|
88
|
+
def _vcsc_rmatmul_delta(major_ptr, values, value_ptr, indices, row_scale, gene_scale, Bt, out_t):
|
|
89
|
+
n_major = major_ptr.shape[0] - 1
|
|
90
|
+
p = Bt.shape[1]
|
|
91
|
+
for j in numba.prange(n_major): # ty: ignore[not-iterable]
|
|
92
|
+
gs = gene_scale[j]
|
|
93
|
+
if gs == 0.0:
|
|
94
|
+
continue
|
|
95
|
+
acc = out_t[j]
|
|
96
|
+
for u in range(major_ptr[j], major_ptr[j + 1]):
|
|
97
|
+
v = values[u]
|
|
98
|
+
for kk in range(value_ptr[u], value_ptr[u + 1]):
|
|
99
|
+
row = indices[kk]
|
|
100
|
+
delta = np.log10(1.0 + 1000.0 * (v / row_scale[row] / gs))
|
|
101
|
+
brow = Bt[row]
|
|
102
|
+
for c in range(p):
|
|
103
|
+
acc[c] += delta * brow[c]
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _rmatmul_vcsc(arr, row_scale, gene_scale, B: np.ndarray) -> np.ndarray:
|
|
107
|
+
n_cols = arr.n_major
|
|
108
|
+
p = B.shape[0]
|
|
109
|
+
Bt = np.ascontiguousarray(B.T) # (n_rows, p)
|
|
110
|
+
out_t = np.zeros((n_cols, p), dtype=np.float64)
|
|
111
|
+
_vcsc_rmatmul_delta(arr.major_ptr, arr.values, arr.value_ptr, arr.indices, row_scale, gene_scale, Bt, out_t)
|
|
112
|
+
return np.ascontiguousarray(out_t.T)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
# -- dual-format cache: gives every call a major-aligned array to run against
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _get_dual(nview: _VCSNormalizedBase):
|
|
119
|
+
"""The opposite-format raw array for ``nview``'s wrapped array, built once and cached."""
|
|
120
|
+
if nview._dual_arr is None:
|
|
121
|
+
nview._dual_arr = nview._arr._transpose_major()
|
|
122
|
+
return nview._dual_arr
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
# -- public entry points: dense correction + sparse delta -------------------
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _prep_dense(other: Any, expect_rows: int) -> tuple[np.ndarray, bool]:
|
|
129
|
+
B = np.asarray(other, dtype=np.float64)
|
|
130
|
+
squeeze = B.ndim == 1
|
|
131
|
+
if squeeze:
|
|
132
|
+
B = B.reshape(-1, 1)
|
|
133
|
+
if B.ndim != 2 or B.shape[0] != expect_rows:
|
|
134
|
+
raise ValueError(f"shape mismatch: expected first dimension {expect_rows}, got {B.shape}")
|
|
135
|
+
return np.ascontiguousarray(B), squeeze
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def normalized_at_dense(nview: _VCSNormalizedBase, other: Any) -> np.ndarray:
|
|
139
|
+
"""``nview @ other`` -- normalized-view-on-the-left sparse-dense product."""
|
|
140
|
+
arr = nview._arr
|
|
141
|
+
n_cols = arr.shape[1]
|
|
142
|
+
B, squeeze = _prep_dense(other, n_cols)
|
|
143
|
+
|
|
144
|
+
# self @ B is major-aligned for VCSR; VCSC needs its VCSR dual.
|
|
145
|
+
src = arr if arr._format == "csr" else _get_dual(nview)
|
|
146
|
+
out = _matmul_vcsr(src, nview.row_scale, nview.gene_scale, B)
|
|
147
|
+
baseline = (-nview.col_mean) @ B # (k,): every row's implicit-zero contribution
|
|
148
|
+
out += baseline[None, :]
|
|
149
|
+
return out[:, 0] if squeeze else out
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def dense_at_normalized(nview: _VCSNormalizedBase, other: Any) -> np.ndarray:
|
|
153
|
+
"""``other @ nview`` -- normalized-view-on-the-right dense-sparse product."""
|
|
154
|
+
arr = nview._arr
|
|
155
|
+
n_rows = arr.shape[0]
|
|
156
|
+
other_arr = np.asarray(other, dtype=np.float64)
|
|
157
|
+
squeeze = other_arr.ndim == 1
|
|
158
|
+
B2 = other_arr.reshape(1, -1) if squeeze else other_arr
|
|
159
|
+
if B2.ndim != 2 or B2.shape[1] != n_rows:
|
|
160
|
+
raise ValueError(f"shape mismatch: expected last dimension {n_rows}, got {B2.shape}")
|
|
161
|
+
B2 = np.ascontiguousarray(B2)
|
|
162
|
+
|
|
163
|
+
# B @ self is major-aligned for VCSC; VCSR needs its VCSC dual.
|
|
164
|
+
src = arr if arr._format == "csc" else _get_dual(nview)
|
|
165
|
+
out = _rmatmul_vcsc(src, nview.row_scale, nview.gene_scale, B2)
|
|
166
|
+
baseline = B2.sum(axis=1)[:, None] * (-nview.col_mean)[None, :] # (m, n_cols)
|
|
167
|
+
out += baseline
|
|
168
|
+
return out[0, :] if squeeze else out
|
vsparse/_vcs_norm.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Normalized, mean-centered *views* of :class:`~vsparse.VCSCArray`/:class:`~vsparse.VCSRArray`.
|
|
2
|
+
|
|
3
|
+
:class:`VCSCArrayNormalized`/:class:`VCSRArrayNormalized` wrap a plain
|
|
4
|
+
(unpacked) VCSC/VCSR array and behave like the read-depth-normalized,
|
|
5
|
+
log-transformed, mean-centered matrix that :func:`vsparse._rapid_load.
|
|
6
|
+
load_and_normalize` builds -- without ever materializing it. See
|
|
7
|
+
:mod:`vsparse._norm_common` for the shared statistics/materialization logic
|
|
8
|
+
(:class:`~vsparse._norm_common.NormalizedViewBase`) and :mod:`vsparse._vcs_matmul`
|
|
9
|
+
for the matmul kernels these use (a direct per-nonzero walk over the
|
|
10
|
+
already-decoded ``indices`` array).
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from typing import TYPE_CHECKING, Any
|
|
16
|
+
|
|
17
|
+
from vsparse._norm_common import NormalizedViewBase
|
|
18
|
+
|
|
19
|
+
if TYPE_CHECKING:
|
|
20
|
+
from vsparse._base import _VCSBase
|
|
21
|
+
|
|
22
|
+
__all__ = ["VCSCArrayNormalized", "VCSRArrayNormalized"]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class _VCSNormalizedBase(NormalizedViewBase):
|
|
26
|
+
"""Shared implementation for :class:`VCSCArrayNormalized`/:class:`VCSRArrayNormalized`."""
|
|
27
|
+
|
|
28
|
+
__slots__ = ("_dual_arr",)
|
|
29
|
+
|
|
30
|
+
def __init__(self, arr: _VCSBase) -> None:
|
|
31
|
+
super().__init__(arr)
|
|
32
|
+
# Lazily built, cached opposite-format copy of `arr` -- see
|
|
33
|
+
# vsparse._vcs_matmul._get_dual. Built at most once per view, the
|
|
34
|
+
# first time a matmul needs it in the direction `arr` isn't
|
|
35
|
+
# major-aligned for.
|
|
36
|
+
self._dual_arr: _VCSBase | None = None
|
|
37
|
+
|
|
38
|
+
def __matmul__(self, other: Any) -> Any:
|
|
39
|
+
"""``self @ other`` for a dense ``other`` -- see :mod:`vsparse._vcs_matmul`."""
|
|
40
|
+
from vsparse._vcs_matmul import normalized_at_dense
|
|
41
|
+
|
|
42
|
+
return normalized_at_dense(self, other)
|
|
43
|
+
|
|
44
|
+
def __rmatmul__(self, other: Any) -> Any:
|
|
45
|
+
"""``other @ self`` for a dense ``other`` -- see :mod:`vsparse._vcs_matmul`."""
|
|
46
|
+
from vsparse._vcs_matmul import dense_at_normalized
|
|
47
|
+
|
|
48
|
+
return dense_at_normalized(self, other)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class VCSCArrayNormalized(_VCSNormalizedBase):
|
|
52
|
+
"""Read-depth-normalized, log-transformed, mean-centered view of a :class:`~vsparse.VCSCArray`."""
|
|
53
|
+
|
|
54
|
+
__slots__ = ()
|
|
55
|
+
_format = "csc"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class VCSRArrayNormalized(_VCSNormalizedBase):
|
|
59
|
+
"""Read-depth-normalized, log-transformed, mean-centered view of a :class:`~vsparse.VCSRArray`."""
|
|
60
|
+
|
|
61
|
+
__slots__ = ()
|
|
62
|
+
_format = "csr"
|
vsparse/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: vsparse
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Value-Compressed Sparse Column/Row (VCSC/VCSR) arrays, with optional AnnData integration
|
|
5
|
+
Keywords: anndata,single-cell,sparse,compression
|
|
6
|
+
Author: Aaron Meyer
|
|
7
|
+
Author-email: Aaron Meyer <git@ameyer.me>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Intended Audience :: Science/Research
|
|
11
|
+
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
14
|
+
Requires-Dist: numpy>=2.0
|
|
15
|
+
Requires-Dist: scipy>=1.12
|
|
16
|
+
Requires-Dist: numba>=0.60
|
|
17
|
+
Requires-Dist: anndata>=0.13
|
|
18
|
+
Requires-Dist: hdf5plugin>=4.0
|
|
19
|
+
Requires-Dist: sphinx>=7.0 ; extra == 'docs'
|
|
20
|
+
Requires-Dist: furo>=2024.1.29 ; extra == 'docs'
|
|
21
|
+
Requires-Dist: myst-parser>=3.0 ; extra == 'docs'
|
|
22
|
+
Requires-Dist: sphinx-autodoc-typehints>=2.0 ; extra == 'docs'
|
|
23
|
+
Requires-Python: >=3.12
|
|
24
|
+
Project-URL: Homepage, https://meyer-lab.github.io/vsparse/
|
|
25
|
+
Project-URL: Repository, https://github.com/meyer-lab/vsparse
|
|
26
|
+
Project-URL: Documentation, https://meyer-lab.github.io/vsparse/
|
|
27
|
+
Project-URL: Issues, https://github.com/meyer-lab/vsparse/issues
|
|
28
|
+
Provides-Extra: docs
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
|
|
31
|
+
# vsparse
|
|
32
|
+
|
|
33
|
+
`vsparse` provides `VCSCArray`/`VCSRArray`: Value-Compressed Sparse Column/Row (VCSC/VCSR)
|
|
34
|
+
array types, implemented in NumPy and accelerated with [Numba](https://numba.pydata.org/). The
|
|
35
|
+
array types are standalone -- they can be built from and converted to SciPy sparse arrays and
|
|
36
|
+
used entirely without [AnnData](https://anndata.readthedocs.io). `vsparse` also ships an
|
|
37
|
+
optional AnnData integration (`from_anndata`, `to_layer`, and the `VCSCAnnData` subclass) for
|
|
38
|
+
projects that want compressed arrays backed directly into an `AnnData` object.
|
|
39
|
+
|
|
40
|
+
VCSC/VCSR are compressed-sparse layouts inspired by
|
|
41
|
+
[IVSparse's VCSC](https://github.com/Seth-Wolfgang/IVSparse). In addition to the usual
|
|
42
|
+
compressed-sparse pointer/index arrays, nonzero values within each major-axis slice
|
|
43
|
+
(columns for VCSC, rows for VCSR) are deduplicated: each unique value is stored once,
|
|
44
|
+
alongside the list of minor-axis positions that share it. This is a strict memory win
|
|
45
|
+
whenever values repeat heavily within a slice — as is typical for integer count
|
|
46
|
+
matrices, e.g. single-cell RNA-seq counts.
|
|
47
|
+
|
|
48
|
+
## Install
|
|
49
|
+
|
|
50
|
+
Install from source or via package manager:
|
|
51
|
+
|
|
52
|
+
```sh
|
|
53
|
+
pip install git+https://github.com/meyer-lab/vsparse.git
|
|
54
|
+
# or with uv
|
|
55
|
+
uv add git+https://github.com/meyer-lab/vsparse.git
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
For local development:
|
|
59
|
+
|
|
60
|
+
```sh
|
|
61
|
+
git clone https://github.com/meyer-lab/vsparse.git
|
|
62
|
+
cd vsparse
|
|
63
|
+
uv sync --all-extras --dev
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## Quickstart
|
|
67
|
+
|
|
68
|
+
### Working with VCSC / VCSR arrays
|
|
69
|
+
|
|
70
|
+
`VCSCArray`/`VCSRArray` are standalone array types -- they only need a SciPy sparse array
|
|
71
|
+
(or an AnnData object, if you have one) to be built, and none of the operations below require
|
|
72
|
+
AnnData at all:
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
import vsparse
|
|
76
|
+
import scipy.sparse as sp
|
|
77
|
+
|
|
78
|
+
# Build directly from a SciPy sparse array -- no AnnData involved
|
|
79
|
+
csc = sp.random(1000, 500, density=0.1, format="csc")
|
|
80
|
+
v = vsparse.VCSCArray.from_scipy(csc)
|
|
81
|
+
|
|
82
|
+
# Or build from an AnnData object or SciPy sparse array
|
|
83
|
+
adata = ... # an AnnData object
|
|
84
|
+
v = vsparse.from_anndata(adata) # VCSCArray (column-compressed) from adata.X
|
|
85
|
+
vr = vsparse.from_anndata(adata, format="csr") # VCSRArray (row-compressed)
|
|
86
|
+
|
|
87
|
+
# Transposition is zero-copy (swaps major/minor axes and shares buffers)
|
|
88
|
+
vr = v.T # VCSRArray
|
|
89
|
+
|
|
90
|
+
# Scalar arithmetic & math
|
|
91
|
+
v2 = v * 2.0 # Scalar multiplication
|
|
92
|
+
v_div = v / 2.0 # Scalar division
|
|
93
|
+
v_neg = -v # Negation
|
|
94
|
+
v_log = v.log1p() # Elementwise log1p
|
|
95
|
+
|
|
96
|
+
# Matrix & vector products (Numba-parallelized)
|
|
97
|
+
y = v @ x # Matrix-vector: (n_rows, n_cols) @ (n_cols,) -> (n_rows,)
|
|
98
|
+
y_left = x @ v # Vector-matrix: (n_rows,) @ (n_rows, n_cols) -> (n_cols,)
|
|
99
|
+
Y = v @ B # Matrix-matrix: (n_rows, n_cols) @ (n_cols, k) -> (n_rows, k)
|
|
100
|
+
Y_left = B @ v # Matrix-matrix: (k, n_rows) @ (n_rows, n_cols) -> (k, n_cols)
|
|
101
|
+
|
|
102
|
+
# Slicing
|
|
103
|
+
col_slice = v[:, [1, 3, 5]] # Fast major-axis slicing (returns VCSCArray)
|
|
104
|
+
sub = v[0:10, 0:10] # 2D slicing (falls back to scipy)
|
|
105
|
+
|
|
106
|
+
# Conversion & layers
|
|
107
|
+
sp_csc = v.to_scipy() # -> scipy.sparse.csc_array (or to_csr())
|
|
108
|
+
dense = v.toarray() # -> numpy.ndarray
|
|
109
|
+
vsparse.to_layer(adata, v, key="counts_vcsc") # Attach to AnnData layer
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
### `VCSCAnnData`: AnnData with direct VCSC/VCSR backing
|
|
113
|
+
|
|
114
|
+
For projects that want the compressed array wired directly into AnnData, `vsparse.VCSCAnnData`
|
|
115
|
+
is an `AnnData` subclass whose `X` (and optionally `raw_X`) is backed directly by a
|
|
116
|
+
`VCSCArray` or `VCSRArray`:
|
|
117
|
+
|
|
118
|
+
```python
|
|
119
|
+
import vsparse
|
|
120
|
+
|
|
121
|
+
va = vsparse.VCSCAnnData.from_anndata(adata) # Compresses X and raw.X
|
|
122
|
+
va.X # VCSCArray
|
|
123
|
+
va.raw_X # VCSCArray (separate from anndata's .raw)
|
|
124
|
+
|
|
125
|
+
# Persist to HDF5 (.h5ad) or Zarr with default Blosc2+LZ4 compression
|
|
126
|
+
va.write_h5ad("compressed.h5ad") # Read back with VCSCAnnData.read_h5ad
|
|
127
|
+
va2 = vsparse.VCSCAnnData.read_h5ad("compressed.h5ad")
|
|
128
|
+
|
|
129
|
+
va.write_zarr("compressed.zarr") # Read back with VCSCAnnData.read_zarr
|
|
130
|
+
va3 = vsparse.VCSCAnnData.read_zarr("compressed.zarr")
|
|
131
|
+
|
|
132
|
+
# Escape hatch back to standard AnnData
|
|
133
|
+
plain = va.to_anndata()
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
### Byte-Packed On-Disk Format (IVCSC / IVCSR)
|
|
137
|
+
|
|
138
|
+
For smaller files, pass `format="ivcsc"` (or `"ivcsr"`) on write. This byte-packs the minor-axis indices with delta + varint encoding (inspired by [IVSparse's IVCSC](https://github.com/Seth-Wolfgang/IVSparse)).
|
|
139
|
+
|
|
140
|
+
It is purely an archival storage format: `read_h5ad` / `read_zarr` decompress the indices on load and return a standard `VCSCArray`/`VCSRArray`.
|
|
141
|
+
|
|
142
|
+
```python
|
|
143
|
+
# Write delta+varint byte-packed indices
|
|
144
|
+
va.write_h5ad("archived.h5ad", format="ivcsc")
|
|
145
|
+
|
|
146
|
+
# Reads back directly as an ordinary VCSCAnnData
|
|
147
|
+
va_loaded = vsparse.VCSCAnnData.read_h5ad("archived.h5ad")
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
### Fast Filtering & Depth Normalization (`load_and_normalize`)
|
|
151
|
+
|
|
152
|
+
For IVCSR-backed datasets, `vsparse.load_and_normalize` bypasses full array decompression for rapid preprocessing, reproducing the filtering and depth normalization from `parafac2.normalize.prepare_dataset`:
|
|
153
|
+
|
|
154
|
+
- **Cell filtering without decoding**: Computes cell totals in $O(n_{\text{unique}})$ time directly from group sizes without unpacking varint indices.
|
|
155
|
+
- **Fused filter & normalization**: Performs gene filtering, cell/gene depth-scaling, and $\log_{10}(1000x + 1)$ transform in parallel passes over the compact CSR representation.
|
|
156
|
+
|
|
157
|
+
```python
|
|
158
|
+
adata_norm = vsparse.load_and_normalize(
|
|
159
|
+
"archived.h5ad",
|
|
160
|
+
min_cell_counts=10.0, # Filter cells with counts <= 10
|
|
161
|
+
gene_threshold=0.05, # Filter genes with counts <= 0.05 * n_cells
|
|
162
|
+
)
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
See `docs/` for full usage guides and API documentation.
|
|
166
|
+
|
|
167
|
+
## Development
|
|
168
|
+
|
|
169
|
+
```sh
|
|
170
|
+
uv sync --all-extras --dev
|
|
171
|
+
uv run pytest
|
|
172
|
+
uv run ruff check .
|
|
173
|
+
uv run ty check
|
|
174
|
+
uv run sphinx-build -b html docs docs/_build/html
|
|
175
|
+
```
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
vsparse/__init__.py,sha256=YgtjEbhHFz3TbHQXmkGgt5AGpQQdVE6gUEeOL8HUYog,890
|
|
2
|
+
vsparse/_anndata.py,sha256=5xSTYa6oGASDxensvH_iQA-UmN-93n7G3Mo18Dq9NVY,2117
|
|
3
|
+
vsparse/_anndata_class.py,sha256=vrfzPKR3KiBhRtJoKqXDFX1Ytcx7spvfYZoR-IuIdKI,14509
|
|
4
|
+
vsparse/_base.py,sha256=iCQUZlyfqOrDAj0RxG4WM-3PwkW5wl_88-IQyRPuR6w,24093
|
|
5
|
+
vsparse/_compression.py,sha256=p0YCkHTUG22fwQgQGWf1yrwUWC-UNNzeaLfm9opu8CI,5677
|
|
6
|
+
vsparse/_construct.py,sha256=K-91WlOSjMUv87Nlx0itBHNCxp30SA4Sg1e_EKyL5U0,7361
|
|
7
|
+
vsparse/_indexutils.py,sha256=raCFQrlSNdK2IYCrqMh6r6cqg_8a72B8NJFew6lv0TI,1260
|
|
8
|
+
vsparse/_io.py,sha256=4AQQZdt65x0vY4xAQkN4LQ6sEy07GCIxxEaFssJT05A,5328
|
|
9
|
+
vsparse/_ivcsc.py,sha256=i42lTtYmO6YjD_i4LInyLbMBDsxCvrq-koF8Hz4px_A,10445
|
|
10
|
+
vsparse/_norm_common.py,sha256=tMt-Vuqex2tpiRc8egWVmHylU0B4t4B0QZZWmcKCZ04,12400
|
|
11
|
+
vsparse/_ops.py,sha256=xqetVL6iQ9XoGAXKfkSJYPwdRy51AIO7arfQBu5I9Y8,3353
|
|
12
|
+
vsparse/_rapid_load.py,sha256=GCpamz1bBh79DE6ytLUlHkQBT5eDXdjcxzwgQEap3ls,21571
|
|
13
|
+
vsparse/_vcs_matmul.py,sha256=kJ2hvCn3A2xILR4BY6uojQniGibIAOWjmBlPMVxKV4I,7185
|
|
14
|
+
vsparse/_vcs_norm.py,sha256=oIT4xwnqE8Nit-HYOVLehhG4XQ69sZgJPktHCmH0aVI,2297
|
|
15
|
+
vsparse/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
16
|
+
vsparse-0.1.0.dist-info/WHEEL,sha256=y6e-a5KI2W-qDAJKfh9Xr81bin8NgUdfWgz3VSXXpe4,80
|
|
17
|
+
vsparse-0.1.0.dist-info/METADATA,sha256=7B9U84KAhmmzhxXz7oMWLythDbTOFEe4JsnPjI29DX4,7279
|
|
18
|
+
vsparse-0.1.0.dist-info/RECORD,,
|