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/_ivcsc.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
"""Byte-packed delta encoding of VCS indices, for compact on-disk storage.
|
|
2
|
+
|
|
3
|
+
This backs the "IVCSC"/"IVCSR" file format (named after `IVSparse's IVCSC
|
|
4
|
+
<https://github.com/Seth-Wolfgang/IVSparse>`_, which inspired it): the same
|
|
5
|
+
VCSC/VCSR layout, but with the ``indices`` array replaced by a variable-
|
|
6
|
+
length-integer (LEB128), delta-encoded byte stream, which is typically much
|
|
7
|
+
smaller on disk than a plain int32/int64 array.
|
|
8
|
+
|
|
9
|
+
Indices within each (major-slice, value) group are unordered with respect to
|
|
10
|
+
the original layout -- decompression re-sorts them per major slice regardless
|
|
11
|
+
(see :mod:`vsparse._construct`) -- so packing is free to sort each group
|
|
12
|
+
ascending before delta-encoding it. That keeps every delta non-negative and
|
|
13
|
+
usually small, which is what makes the byte packing worth doing.
|
|
14
|
+
|
|
15
|
+
This module only implements the byte codec; :mod:`vsparse._io` uses it to decode
|
|
16
|
+
a packed group straight back into a plain VCSCArray/VCSRArray with an
|
|
17
|
+
ordinary ``indices`` array on read, so none of the compute paths in
|
|
18
|
+
:mod:`vsparse._ops` need to know this encoding exists.
|
|
19
|
+
|
|
20
|
+
Decoding is the expensive direction (see :func:`unpack_indices`): a serial
|
|
21
|
+
byte-at-a-time varint walk over the whole packed stream. For large arrays,
|
|
22
|
+
``unpack_indices`` instead uses a parallel decode that exploits two facts:
|
|
23
|
+
|
|
24
|
+
- LEB128 is self-synchronizing at the byte level -- a byte with the
|
|
25
|
+
continuation bit clear is *always* the last byte of some varint, and the
|
|
26
|
+
byte after it *always* starts the next one, no matter where in the stream
|
|
27
|
+
you started reading. So a handful of arbitrary byte offsets can each be
|
|
28
|
+
cheaply walked forward to a true varint boundary with no global context.
|
|
29
|
+
- ``value_ptr`` (which group each index belongs to) is plain, uncompressed,
|
|
30
|
+
and already fully known -- so once a chunk's byte boundary is realigned to
|
|
31
|
+
*some* varint boundary, snapping it onto the nearest *group* boundary is a
|
|
32
|
+
short bounded scan, not a rescan from byte 0.
|
|
33
|
+
|
|
34
|
+
That turns what looks like an inherently serial stream into: a cheap fully
|
|
35
|
+
parallel counting pass, a tiny (thread-count-sized) serial prefix sum, a
|
|
36
|
+
cheap bounded per-boundary snap, then a fully parallel real decode. See
|
|
37
|
+
:func:`_unpack_parallel`.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
from __future__ import annotations
|
|
41
|
+
|
|
42
|
+
import numba
|
|
43
|
+
import numpy as np
|
|
44
|
+
|
|
45
|
+
__all__ = ["pack_indices", "unpack_indices"]
|
|
46
|
+
|
|
47
|
+
# Below this many packed bytes, decode serially -- the fixed overhead of the
|
|
48
|
+
# counting pass plus a second (parallel) pass isn't worth it.
|
|
49
|
+
_PARALLEL_MIN_BYTES = 1 << 20 # 1 MiB
|
|
50
|
+
# Lower bound on how small a per-thread chunk is allowed to get, so we don't
|
|
51
|
+
# over-split modestly-sized arrays into slivers.
|
|
52
|
+
_MIN_CHUNK_BYTES = 1 << 16 # 64 KiB
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@numba.njit(cache=True)
|
|
56
|
+
def _pack(value_ptr: np.ndarray, indices: np.ndarray) -> np.ndarray:
|
|
57
|
+
n_groups = value_ptr.shape[0] - 1
|
|
58
|
+
nnz = indices.shape[0]
|
|
59
|
+
# Worst case (index deltas needing the full 10-byte varint width for a
|
|
60
|
+
# 64-bit value) plus one byte per empty group.
|
|
61
|
+
buf = np.empty(nnz * 10 + n_groups, dtype=np.uint8)
|
|
62
|
+
pos = 0
|
|
63
|
+
for g in range(n_groups):
|
|
64
|
+
start, end = value_ptr[g], value_ptr[g + 1]
|
|
65
|
+
seg = np.sort(indices[start:end])
|
|
66
|
+
prev = np.int64(-1)
|
|
67
|
+
for k in range(seg.shape[0]):
|
|
68
|
+
cur = np.int64(seg[k])
|
|
69
|
+
v = np.uint64(cur - prev - 1)
|
|
70
|
+
prev = cur
|
|
71
|
+
while v >= 0x80:
|
|
72
|
+
buf[pos] = np.uint8((v & 0x7F) | 0x80)
|
|
73
|
+
pos += 1
|
|
74
|
+
v >>= np.uint64(7)
|
|
75
|
+
buf[pos] = np.uint8(v)
|
|
76
|
+
pos += 1
|
|
77
|
+
return buf[:pos].copy()
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@numba.njit(cache=True)
|
|
81
|
+
def _unpack(value_ptr: np.ndarray, buf: np.ndarray, out: np.ndarray) -> None:
|
|
82
|
+
n_groups = value_ptr.shape[0] - 1
|
|
83
|
+
pos = 0
|
|
84
|
+
for g in range(n_groups):
|
|
85
|
+
start, end = value_ptr[g], value_ptr[g + 1]
|
|
86
|
+
prev = np.int64(-1)
|
|
87
|
+
for k in range(start, end):
|
|
88
|
+
shift = np.uint64(0)
|
|
89
|
+
result = np.uint64(0)
|
|
90
|
+
while True:
|
|
91
|
+
b = buf[pos]
|
|
92
|
+
pos += 1
|
|
93
|
+
result |= np.uint64(b & 0x7F) << shift
|
|
94
|
+
if b & 0x80 == 0:
|
|
95
|
+
break
|
|
96
|
+
shift += np.uint64(7)
|
|
97
|
+
prev = prev + 1 + np.int64(result)
|
|
98
|
+
out[k] = prev
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def pack_indices(value_ptr: np.ndarray, indices: np.ndarray) -> np.ndarray:
|
|
102
|
+
"""Delta+varint encode ``indices``, grouped by ``value_ptr``, into ``uint8`` bytes."""
|
|
103
|
+
value_ptr = np.ascontiguousarray(value_ptr, dtype=np.int64)
|
|
104
|
+
indices = np.ascontiguousarray(indices)
|
|
105
|
+
return _pack(value_ptr, indices)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
# -- parallel decode ----------------------------------------------------------
|
|
109
|
+
#
|
|
110
|
+
# See the module docstring for the overall strategy. Three passes:
|
|
111
|
+
#
|
|
112
|
+
# 1. _realign_forward / _count_all: for K guessed byte splits, walk forward
|
|
113
|
+
# to a true varint boundary (self-synchronizing, no context needed), then
|
|
114
|
+
# count (not decode) the varints in each resulting span. Fully parallel.
|
|
115
|
+
# 2. A serial prefix sum over just the K counts, then _advance_n_varints
|
|
116
|
+
# snaps each boundary from "some varint" onto "the start of a value_ptr
|
|
117
|
+
# group" with a short bounded scan (at most one group's worth of bytes).
|
|
118
|
+
# 3. _decode_chunks: the real decode, now with exact (start_group, end_group,
|
|
119
|
+
# start_byte) per chunk, so each chunk is fully independent. Parallel.
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
@numba.njit(cache=True)
|
|
123
|
+
def _realign_forward(buf: np.ndarray, guess: np.int64) -> np.int64:
|
|
124
|
+
"""Smallest byte offset >= guess that starts a fresh varint."""
|
|
125
|
+
if guess == 0:
|
|
126
|
+
return np.int64(0)
|
|
127
|
+
pos = guess
|
|
128
|
+
n = buf.shape[0]
|
|
129
|
+
while pos < n and (buf[pos - 1] & 0x80) != 0:
|
|
130
|
+
pos += 1
|
|
131
|
+
return pos
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
@numba.njit(cache=True)
|
|
135
|
+
def _count_varints_range(buf: np.ndarray, start: np.int64, end: np.int64) -> np.int64:
|
|
136
|
+
"""Count complete varints in buf[start:end); start/end must be true boundaries."""
|
|
137
|
+
pos = start
|
|
138
|
+
count = np.int64(0)
|
|
139
|
+
while pos < end:
|
|
140
|
+
while buf[pos] & 0x80:
|
|
141
|
+
pos += 1
|
|
142
|
+
pos += 1
|
|
143
|
+
count += 1
|
|
144
|
+
return count
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
@numba.njit(cache=True)
|
|
148
|
+
def _advance_n_varints(buf: np.ndarray, start_byte: np.int64, n: np.int64) -> np.int64:
|
|
149
|
+
"""Byte offset n complete varints after start_byte."""
|
|
150
|
+
pos = start_byte
|
|
151
|
+
for _ in range(n):
|
|
152
|
+
while buf[pos] & 0x80:
|
|
153
|
+
pos += 1
|
|
154
|
+
pos += 1
|
|
155
|
+
return pos
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
@numba.njit(cache=True, parallel=True)
|
|
159
|
+
def _count_all(buf: np.ndarray, real_starts: np.ndarray, out_counts: np.ndarray) -> None:
|
|
160
|
+
k = real_starts.shape[0] - 1
|
|
161
|
+
for t in numba.prange(k): # ty: ignore[not-iterable]
|
|
162
|
+
out_counts[t] = _count_varints_range(buf, real_starts[t], real_starts[t + 1])
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
@numba.njit(cache=True, parallel=True)
|
|
166
|
+
def _decode_chunks(
|
|
167
|
+
value_ptr: np.ndarray,
|
|
168
|
+
buf: np.ndarray,
|
|
169
|
+
out: np.ndarray,
|
|
170
|
+
chunk_group: np.ndarray,
|
|
171
|
+
chunk_byte: np.ndarray,
|
|
172
|
+
) -> None:
|
|
173
|
+
k = chunk_group.shape[0] - 1
|
|
174
|
+
for t in numba.prange(k): # ty: ignore[not-iterable]
|
|
175
|
+
pos = chunk_byte[t]
|
|
176
|
+
for g in range(chunk_group[t], chunk_group[t + 1]):
|
|
177
|
+
start, end = value_ptr[g], value_ptr[g + 1]
|
|
178
|
+
prev = np.int64(-1)
|
|
179
|
+
for kk in range(start, end):
|
|
180
|
+
shift = np.uint64(0)
|
|
181
|
+
result = np.uint64(0)
|
|
182
|
+
while True:
|
|
183
|
+
b = buf[pos]
|
|
184
|
+
pos += 1
|
|
185
|
+
result |= np.uint64(b & 0x7F) << shift
|
|
186
|
+
if b & 0x80 == 0:
|
|
187
|
+
break
|
|
188
|
+
shift += np.uint64(7)
|
|
189
|
+
prev = prev + 1 + np.int64(result)
|
|
190
|
+
out[kk] = prev
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _group_chunk_boundaries(
|
|
194
|
+
value_ptr: np.ndarray, buf: np.ndarray, n_chunks: int
|
|
195
|
+
) -> tuple[np.ndarray, np.ndarray]:
|
|
196
|
+
"""Split ``buf`` into ``n_chunks`` pieces landing on exact group boundaries.
|
|
197
|
+
|
|
198
|
+
Returns ``(chunk_group, chunk_byte)``, each of length ``n_chunks + 1``:
|
|
199
|
+
chunk ``t`` owns groups ``[chunk_group[t], chunk_group[t + 1])``, whose
|
|
200
|
+
packed bytes start at ``chunk_byte[t]``. Used by :func:`_unpack_parallel`
|
|
201
|
+
to parallelize decoding safely.
|
|
202
|
+
"""
|
|
203
|
+
n_bytes = buf.shape[0]
|
|
204
|
+
n_groups = value_ptr.shape[0] - 1
|
|
205
|
+
nnz = int(value_ptr[-1])
|
|
206
|
+
|
|
207
|
+
guesses = np.linspace(0, n_bytes, n_chunks + 1).astype(np.int64)
|
|
208
|
+
real_starts = np.empty(n_chunks + 1, dtype=np.int64)
|
|
209
|
+
real_starts[0] = 0
|
|
210
|
+
real_starts[n_chunks] = n_bytes
|
|
211
|
+
for t in range(1, n_chunks):
|
|
212
|
+
real_starts[t] = _realign_forward(buf, guesses[t])
|
|
213
|
+
|
|
214
|
+
counts = np.empty(n_chunks, dtype=np.int64)
|
|
215
|
+
_count_all(buf, real_starts, counts)
|
|
216
|
+
cum = np.empty(n_chunks + 1, dtype=np.int64)
|
|
217
|
+
cum[0] = 0
|
|
218
|
+
cum[1:] = np.cumsum(counts)
|
|
219
|
+
assert cum[n_chunks] == nnz
|
|
220
|
+
|
|
221
|
+
chunk_group = np.empty(n_chunks + 1, dtype=np.int64)
|
|
222
|
+
chunk_byte = np.empty(n_chunks + 1, dtype=np.int64)
|
|
223
|
+
chunk_group[0], chunk_byte[0] = 0, 0
|
|
224
|
+
chunk_group[n_chunks], chunk_byte[n_chunks] = n_groups, n_bytes
|
|
225
|
+
for t in range(1, n_chunks):
|
|
226
|
+
target = cum[t]
|
|
227
|
+
g = int(np.searchsorted(value_ptr, target, side="right") - 1)
|
|
228
|
+
if value_ptr[g] == target:
|
|
229
|
+
chunk_group[t] = g
|
|
230
|
+
chunk_byte[t] = real_starts[t]
|
|
231
|
+
else:
|
|
232
|
+
extra = np.int64(value_ptr[g + 1] - target)
|
|
233
|
+
chunk_group[t] = g + 1
|
|
234
|
+
chunk_byte[t] = _advance_n_varints(buf, real_starts[t], extra)
|
|
235
|
+
|
|
236
|
+
return chunk_group, chunk_byte
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _unpack_parallel(value_ptr: np.ndarray, buf: np.ndarray, out: np.ndarray, n_chunks: int) -> None:
|
|
240
|
+
chunk_group, chunk_byte = _group_chunk_boundaries(value_ptr, buf, n_chunks)
|
|
241
|
+
_decode_chunks(value_ptr, buf, out, chunk_group, chunk_byte)
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _num_chunks(n_bytes: int) -> int:
|
|
245
|
+
if n_bytes < _PARALLEL_MIN_BYTES:
|
|
246
|
+
return 1
|
|
247
|
+
return max(1, min(numba.get_num_threads(), n_bytes // _MIN_CHUNK_BYTES))
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def unpack_indices(value_ptr: np.ndarray, packed: np.ndarray, dtype: np.dtype) -> np.ndarray:
|
|
251
|
+
"""Invert :func:`pack_indices`, producing an ``indices`` array of the given dtype.
|
|
252
|
+
|
|
253
|
+
Decodes in parallel across ``packed``-sized chunks once the packed array
|
|
254
|
+
is large enough to be worth it (see :func:`_unpack_parallel`); small
|
|
255
|
+
arrays fall back to a plain serial decode.
|
|
256
|
+
"""
|
|
257
|
+
value_ptr = np.ascontiguousarray(value_ptr, dtype=np.int64)
|
|
258
|
+
packed = np.ascontiguousarray(packed, dtype=np.uint8)
|
|
259
|
+
out = np.empty(int(value_ptr[-1]), dtype=dtype)
|
|
260
|
+
n_chunks = _num_chunks(packed.shape[0])
|
|
261
|
+
if out.shape[0] == 0 or n_chunks <= 1:
|
|
262
|
+
_unpack(value_ptr, packed, out)
|
|
263
|
+
else:
|
|
264
|
+
_unpack_parallel(value_ptr, packed, out, n_chunks)
|
|
265
|
+
return out
|
vsparse/_norm_common.py
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
"""Shared statistics/materialization logic for normalized VCS views.
|
|
2
|
+
|
|
3
|
+
:mod:`vsparse._vcs_norm` (:class:`~vsparse.VCSCArrayNormalized`/:class:`~vsparse.
|
|
4
|
+
VCSRArrayNormalized`) wraps a raw VCS array and behaves like the
|
|
5
|
+
read-depth-normalized, log-transformed, mean-centered matrix that
|
|
6
|
+
:func:`vsparse._rapid_load.load_and_normalize` builds -- without ever
|
|
7
|
+
materializing it. Centering makes every implicit structural zero a nonzero
|
|
8
|
+
value, so a real materialization is an ``n_rows * n_cols`` dense array; the
|
|
9
|
+
whole point of a "view" here is to avoid paying for that until (and unless)
|
|
10
|
+
the caller actually asks for it.
|
|
11
|
+
|
|
12
|
+
What's precomputed, once, at construction:
|
|
13
|
+
|
|
14
|
+
- ``row_scale``: per-row (cell) total raw counts, scaled to a median of 1 --
|
|
15
|
+
the read-depth normalization factor.
|
|
16
|
+
- ``gene_scale``: per-column (gene) sum of read-depth-scaled raw counts --
|
|
17
|
+
the per-gene normalization factor used inside the log transform.
|
|
18
|
+
- ``col_mean``: the mean, over *all* rows (including implicit zeros, whose
|
|
19
|
+
transformed value is exactly ``log10(1) == 0``), of the transformed value
|
|
20
|
+
in that column -- the centering offset.
|
|
21
|
+
|
|
22
|
+
Given those three (all ``O(n_rows)``/``O(n_cols)``-sized, not ``O(nnz)``),
|
|
23
|
+
any entry's final value is ``log10(1 + 1000 * raw / row_scale / gene_scale)
|
|
24
|
+
- col_mean``, computable independently per entry. Computing the statistics
|
|
25
|
+
themselves still requires touching every nonzero (twice: once for
|
|
26
|
+
``gene_scale``, once more for ``col_mean``, since the transform needs
|
|
27
|
+
``gene_scale`` first) -- exactly like :mod:`vsparse._rapid_load`'s reference
|
|
28
|
+
implementation -- so that part is done with parallel numba kernels below,
|
|
29
|
+
specialized per storage format:
|
|
30
|
+
|
|
31
|
+
- major=columns (VCSC): both passes collapse into one, fully parallel
|
|
32
|
+
over columns with no cross-thread writes -- each column's own elements
|
|
33
|
+
carry everything needed to compute both its ``gene_scale`` and its
|
|
34
|
+
``col_mean`` (:func:`_column_stats_major_is_col`).
|
|
35
|
+
- major=rows (VCSR): each pass is a scatter-add across columns from
|
|
36
|
+
many rows, so it's parallelized like :mod:`vsparse._rapid_load`'s
|
|
37
|
+
``_scaled_col_sums`` -- row-chunked with thread-local partial column
|
|
38
|
+
arrays, reduced by summing across threads (:func:`_scaled_col_sums_vcs`,
|
|
39
|
+
:func:`_transformed_col_sums_vcs`).
|
|
40
|
+
|
|
41
|
+
These kernels only need ``major_ptr``/``values``/``value_ptr``/``indices``
|
|
42
|
+
arrays, from the plain (:mod:`vsparse._base`) array types. The matmul kernels
|
|
43
|
+
in :mod:`vsparse._vcs_matmul` walk that same already-materialized ``indices``
|
|
44
|
+
array directly. :class:`VCSCArrayNormalized`/:class:`VCSRArrayNormalized`
|
|
45
|
+
each supply their own ``__matmul__``/``__rmatmul__`` wired to those kernels.
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
from __future__ import annotations
|
|
49
|
+
|
|
50
|
+
from typing import Any
|
|
51
|
+
|
|
52
|
+
import numba
|
|
53
|
+
import numpy as np
|
|
54
|
+
|
|
55
|
+
__all__ = ["NormalizedViewBase"]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
# -- statistics: major=columns -- fused, no cross-thread writes -------------
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@numba.njit(cache=True, parallel=True)
|
|
62
|
+
def _column_stats_major_is_col(major_ptr, values, value_ptr, indices, row_scale, n_rows):
|
|
63
|
+
n_major = major_ptr.shape[0] - 1
|
|
64
|
+
gene_scale = np.zeros(n_major, dtype=np.float64)
|
|
65
|
+
col_mean = np.zeros(n_major, dtype=np.float64)
|
|
66
|
+
for j in numba.prange(n_major): # ty: ignore[not-iterable]
|
|
67
|
+
gs = 0.0
|
|
68
|
+
for u in range(major_ptr[j], major_ptr[j + 1]):
|
|
69
|
+
v = values[u]
|
|
70
|
+
for k in range(value_ptr[u], value_ptr[u + 1]):
|
|
71
|
+
gs += v / row_scale[indices[k]]
|
|
72
|
+
gene_scale[j] = gs
|
|
73
|
+
if gs > 0.0 and n_rows > 0:
|
|
74
|
+
cs = 0.0
|
|
75
|
+
for u in range(major_ptr[j], major_ptr[j + 1]):
|
|
76
|
+
v = values[u]
|
|
77
|
+
for k in range(value_ptr[u], value_ptr[u + 1]):
|
|
78
|
+
scaled = v / row_scale[indices[k]] / gs
|
|
79
|
+
cs += np.log10(1.0 + 1000.0 * scaled)
|
|
80
|
+
col_mean[j] = cs / n_rows
|
|
81
|
+
return gene_scale, col_mean
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
# -- statistics: major=rows -- scatter-add passes ----------------------------
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@numba.njit(cache=True, parallel=True)
|
|
88
|
+
def _scaled_col_sums_vcs(major_ptr, values, value_ptr, indices, row_scale, n_cols, nthreads):
|
|
89
|
+
n_major = major_ptr.shape[0] - 1
|
|
90
|
+
chunk = (n_major + nthreads - 1) // nthreads
|
|
91
|
+
partial = np.zeros((nthreads, n_cols), dtype=np.float64)
|
|
92
|
+
for t in numba.prange(nthreads): # ty: ignore[not-iterable]
|
|
93
|
+
start = t * chunk
|
|
94
|
+
end = min(n_major, start + chunk)
|
|
95
|
+
local = partial[t]
|
|
96
|
+
for i in range(start, end):
|
|
97
|
+
rs = row_scale[i]
|
|
98
|
+
for u in range(major_ptr[i], major_ptr[i + 1]):
|
|
99
|
+
v = values[u]
|
|
100
|
+
for k in range(value_ptr[u], value_ptr[u + 1]):
|
|
101
|
+
local[indices[k]] += v / rs
|
|
102
|
+
return partial.sum(axis=0)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@numba.njit(cache=True, parallel=True)
|
|
106
|
+
def _transformed_col_sums_vcs(
|
|
107
|
+
major_ptr, values, value_ptr, indices, row_scale, gene_scale, n_cols, nthreads
|
|
108
|
+
):
|
|
109
|
+
n_major = major_ptr.shape[0] - 1
|
|
110
|
+
chunk = (n_major + nthreads - 1) // nthreads
|
|
111
|
+
partial = np.zeros((nthreads, n_cols), dtype=np.float64)
|
|
112
|
+
for t in numba.prange(nthreads): # ty: ignore[not-iterable]
|
|
113
|
+
start = t * chunk
|
|
114
|
+
end = min(n_major, start + chunk)
|
|
115
|
+
local = partial[t]
|
|
116
|
+
for i in range(start, end):
|
|
117
|
+
rs = row_scale[i]
|
|
118
|
+
for u in range(major_ptr[i], major_ptr[i + 1]):
|
|
119
|
+
v = values[u]
|
|
120
|
+
for k in range(value_ptr[u], value_ptr[u + 1]):
|
|
121
|
+
c = indices[k]
|
|
122
|
+
gs = gene_scale[c]
|
|
123
|
+
if gs > 0.0:
|
|
124
|
+
scaled = v / rs / gs
|
|
125
|
+
local[c] += np.log10(1.0 + 1000.0 * scaled)
|
|
126
|
+
return partial.sum(axis=0)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
# -- full materialization -----------------------------------------------------
|
|
130
|
+
#
|
|
131
|
+
# Both kernels start from an ``out`` already filled with ``-col_mean``
|
|
132
|
+
# (the value every implicit structural zero takes) and only overwrite the
|
|
133
|
+
# entries that are actually stored -- each parallelized over the major axis,
|
|
134
|
+
# which owns disjoint rows (major=rows) or columns (major=columns) of
|
|
135
|
+
# ``out``, so there's no cross-thread write.
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
@numba.njit(cache=True, parallel=True)
|
|
139
|
+
def _fill_normalized_major_is_col(major_ptr, values, value_ptr, indices, row_scale, gene_scale, col_mean, out):
|
|
140
|
+
n_major = major_ptr.shape[0] - 1
|
|
141
|
+
for j in numba.prange(n_major): # ty: ignore[not-iterable]
|
|
142
|
+
gs = gene_scale[j]
|
|
143
|
+
if gs == 0.0:
|
|
144
|
+
continue
|
|
145
|
+
cm = col_mean[j]
|
|
146
|
+
for u in range(major_ptr[j], major_ptr[j + 1]):
|
|
147
|
+
v = values[u]
|
|
148
|
+
for k in range(value_ptr[u], value_ptr[u + 1]):
|
|
149
|
+
r = indices[k]
|
|
150
|
+
scaled = v / row_scale[r] / gs
|
|
151
|
+
out[r, j] = np.log10(1.0 + 1000.0 * scaled) - cm
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
@numba.njit(cache=True, parallel=True)
|
|
155
|
+
def _fill_normalized_major_is_row(major_ptr, values, value_ptr, indices, row_scale, gene_scale, col_mean, out):
|
|
156
|
+
n_major = major_ptr.shape[0] - 1
|
|
157
|
+
for i in numba.prange(n_major): # ty: ignore[not-iterable]
|
|
158
|
+
rs = row_scale[i]
|
|
159
|
+
for u in range(major_ptr[i], major_ptr[i + 1]):
|
|
160
|
+
v = values[u]
|
|
161
|
+
for k in range(value_ptr[u], value_ptr[u + 1]):
|
|
162
|
+
c = indices[k]
|
|
163
|
+
gs = gene_scale[c]
|
|
164
|
+
if gs == 0.0:
|
|
165
|
+
continue
|
|
166
|
+
scaled = v / rs / gs
|
|
167
|
+
out[i, c] = np.log10(1.0 + 1000.0 * scaled) - col_mean[c]
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _prep_key(key: Any) -> Any:
|
|
171
|
+
"""Turn a bare int into a length-1 list, so fancy indexing never drops that axis."""
|
|
172
|
+
if isinstance(key, int | np.integer):
|
|
173
|
+
return [int(key)]
|
|
174
|
+
return key
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
class NormalizedViewBase:
|
|
178
|
+
"""Shared implementation for the normalized VCSC/VCSR views.
|
|
179
|
+
|
|
180
|
+
Subclasses fix ``_format`` (``"csc"``/``"csr"``) and supply
|
|
181
|
+
``__matmul__``/``__rmatmul__`` wired to :mod:`vsparse._vcs_matmul`.
|
|
182
|
+
"""
|
|
183
|
+
|
|
184
|
+
_format: str
|
|
185
|
+
|
|
186
|
+
__array_ufunc__ = None
|
|
187
|
+
|
|
188
|
+
__slots__ = ("_arr", "col_mean", "gene_scale", "row_scale")
|
|
189
|
+
|
|
190
|
+
def __init__(self, arr: Any) -> None:
|
|
191
|
+
if arr._format != self._format:
|
|
192
|
+
raise ValueError(
|
|
193
|
+
f"{type(self).__name__} wraps a {self._format!r}-format array, "
|
|
194
|
+
f"got {type(arr).__name__}"
|
|
195
|
+
)
|
|
196
|
+
self._arr = arr
|
|
197
|
+
|
|
198
|
+
n_rows, n_cols = arr.shape
|
|
199
|
+
row_totals = np.asarray(arr.sum(axis=1), dtype=np.float64)
|
|
200
|
+
median = float(np.median(row_totals)) if row_totals.shape[0] else 0.0
|
|
201
|
+
if median > 0.0:
|
|
202
|
+
row_scale = row_totals / median
|
|
203
|
+
row_scale[row_scale == 0.0] = 1.0
|
|
204
|
+
else:
|
|
205
|
+
row_scale = np.ones(n_rows, dtype=np.float64)
|
|
206
|
+
self.row_scale = row_scale
|
|
207
|
+
|
|
208
|
+
indices = arr.indices # decode once; shared by both statistics passes below
|
|
209
|
+
if self._format == "csc":
|
|
210
|
+
gene_scale, col_mean = _column_stats_major_is_col(
|
|
211
|
+
arr.major_ptr, arr.values, arr.value_ptr, indices, row_scale, n_rows
|
|
212
|
+
)
|
|
213
|
+
else:
|
|
214
|
+
nthreads = numba.get_num_threads()
|
|
215
|
+
gene_scale = _scaled_col_sums_vcs(
|
|
216
|
+
arr.major_ptr, arr.values, arr.value_ptr, indices, row_scale, n_cols, nthreads
|
|
217
|
+
)
|
|
218
|
+
col_sum = _transformed_col_sums_vcs(
|
|
219
|
+
arr.major_ptr, arr.values, arr.value_ptr, indices, row_scale, gene_scale, n_cols, nthreads
|
|
220
|
+
)
|
|
221
|
+
col_mean = col_sum / n_rows if n_rows > 0 else np.zeros(n_cols, dtype=np.float64)
|
|
222
|
+
self.gene_scale = gene_scale
|
|
223
|
+
self.col_mean = col_mean
|
|
224
|
+
|
|
225
|
+
@property
|
|
226
|
+
def shape(self) -> tuple[int, int]:
|
|
227
|
+
return self._arr.shape
|
|
228
|
+
|
|
229
|
+
@property
|
|
230
|
+
def dtype(self) -> np.dtype:
|
|
231
|
+
return np.dtype(np.float64)
|
|
232
|
+
|
|
233
|
+
def __repr__(self) -> str: # pragma: no cover - cosmetic
|
|
234
|
+
return f"<{type(self).__name__} shape={self.shape} dtype={self.dtype}>"
|
|
235
|
+
|
|
236
|
+
# -- materialization ------------------------------------------------------
|
|
237
|
+
|
|
238
|
+
def toarray(self) -> np.ndarray:
|
|
239
|
+
"""The full normalized, log-transformed, mean-centered matrix, densely."""
|
|
240
|
+
n_rows, n_cols = self.shape
|
|
241
|
+
out = np.broadcast_to(-self.col_mean, (n_rows, n_cols)).copy()
|
|
242
|
+
arr = self._arr
|
|
243
|
+
if self._format == "csc":
|
|
244
|
+
_fill_normalized_major_is_col(
|
|
245
|
+
arr.major_ptr, arr.values, arr.value_ptr, arr.indices,
|
|
246
|
+
self.row_scale, self.gene_scale, self.col_mean, out,
|
|
247
|
+
)
|
|
248
|
+
else:
|
|
249
|
+
_fill_normalized_major_is_row(
|
|
250
|
+
arr.major_ptr, arr.values, arr.value_ptr, arr.indices,
|
|
251
|
+
self.row_scale, self.gene_scale, self.col_mean, out,
|
|
252
|
+
)
|
|
253
|
+
return out
|
|
254
|
+
|
|
255
|
+
# -- on-the-fly elementwise access ------------------------------------------
|
|
256
|
+
|
|
257
|
+
def __getitem__(self, key: Any) -> np.ndarray:
|
|
258
|
+
"""Compute just the requested sub-block, on the fly, from the raw data.
|
|
259
|
+
|
|
260
|
+
Only the raw counts for the requested rows/columns are ever
|
|
261
|
+
decompressed (via the underlying array's own indexing, which stays
|
|
262
|
+
compact for a major-axis-only slice); the transform/centering
|
|
263
|
+
formula is then applied to that small block directly, using the
|
|
264
|
+
precomputed per-row/per-column statistics -- never the full matrix.
|
|
265
|
+
"""
|
|
266
|
+
if isinstance(key, tuple):
|
|
267
|
+
if len(key) != 2:
|
|
268
|
+
raise IndexError(f"{type(self).__name__} arrays are 2-D")
|
|
269
|
+
row_key, col_key = key
|
|
270
|
+
else:
|
|
271
|
+
row_key, col_key = key, slice(None)
|
|
272
|
+
|
|
273
|
+
row_key = _prep_key(row_key)
|
|
274
|
+
col_key = _prep_key(col_key)
|
|
275
|
+
|
|
276
|
+
dense_raw = self._arr[row_key, col_key].toarray().astype(np.float64)
|
|
277
|
+
rs = np.asarray(self.row_scale)[row_key].reshape(-1, 1)
|
|
278
|
+
gs = np.asarray(self.gene_scale)[col_key].reshape(1, -1)
|
|
279
|
+
cm = np.asarray(self.col_mean)[col_key].reshape(1, -1)
|
|
280
|
+
|
|
281
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
282
|
+
scaled = np.where(gs > 0.0, dense_raw / rs / gs, 0.0)
|
|
283
|
+
return np.log10(1.0 + 1000.0 * scaled) - cm
|
|
284
|
+
|
|
285
|
+
# -- explicitly-unsupported operations ------------------------------------
|
|
286
|
+
|
|
287
|
+
def _unsupported(self, op: str) -> Any:
|
|
288
|
+
raise RuntimeError(
|
|
289
|
+
f"{op} is not supported on {type(self).__name__}. "
|
|
290
|
+
"Call .toarray() first if you need it."
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
def __add__(self, other: Any) -> Any:
|
|
294
|
+
return self._unsupported("addition")
|
|
295
|
+
|
|
296
|
+
__radd__ = __add__
|
|
297
|
+
|
|
298
|
+
def __sub__(self, other: Any) -> Any:
|
|
299
|
+
return self._unsupported("subtraction")
|
|
300
|
+
|
|
301
|
+
def __mul__(self, other: Any) -> Any:
|
|
302
|
+
return self._unsupported("multiplication")
|
|
303
|
+
|
|
304
|
+
__rmul__ = __mul__
|
vsparse/_ops.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""Numba-accelerated numerical kernels on the VCS layout."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import numba
|
|
6
|
+
import numpy as np
|
|
7
|
+
|
|
8
|
+
__all__ = ["major_matmat", "major_matvec", "minor_matmat", "minor_matvec"]
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@numba.njit(cache=True)
|
|
12
|
+
def _major_matvec(major_ptr, values, value_ptr, indices, x, n_major, n_minor):
|
|
13
|
+
"""y = A @ x where A's major axis (columns for VCSC) has length n_major.
|
|
14
|
+
|
|
15
|
+
x has length n_major, output y has length n_minor.
|
|
16
|
+
"""
|
|
17
|
+
y = np.zeros(n_minor, dtype=values.dtype)
|
|
18
|
+
for j in range(n_major):
|
|
19
|
+
xj = x[j]
|
|
20
|
+
if xj == 0:
|
|
21
|
+
continue
|
|
22
|
+
for u in range(major_ptr[j], major_ptr[j + 1]):
|
|
23
|
+
val = values[u] * xj
|
|
24
|
+
for k in range(value_ptr[u], value_ptr[u + 1]):
|
|
25
|
+
y[indices[k]] += val
|
|
26
|
+
return y
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@numba.njit(cache=True, parallel=True)
|
|
30
|
+
def _minor_matvec(major_ptr, values, value_ptr, indices, x, n_major):
|
|
31
|
+
"""y = x @ A, i.e. contract over the minor axis. x has length n_minor.
|
|
32
|
+
|
|
33
|
+
Output y has length n_major. Safe to parallelize over major slices since
|
|
34
|
+
each output element is written by exactly one iteration.
|
|
35
|
+
"""
|
|
36
|
+
y = np.zeros(n_major, dtype=values.dtype)
|
|
37
|
+
for j in numba.prange(n_major): # ty: ignore[not-iterable]
|
|
38
|
+
s = 0.0
|
|
39
|
+
for u in range(major_ptr[j], major_ptr[j + 1]):
|
|
40
|
+
acc = 0.0
|
|
41
|
+
for k in range(value_ptr[u], value_ptr[u + 1]):
|
|
42
|
+
acc += x[indices[k]]
|
|
43
|
+
s += values[u] * acc
|
|
44
|
+
y[j] = s
|
|
45
|
+
return y
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@numba.njit(cache=True)
|
|
49
|
+
def _major_matmat(major_ptr, values, value_ptr, indices, b, n_major, n_minor):
|
|
50
|
+
"""Y = A @ B where A's major axis has length n_major, B is (n_major, k)."""
|
|
51
|
+
k = b.shape[1]
|
|
52
|
+
y = np.zeros((n_minor, k), dtype=values.dtype)
|
|
53
|
+
for j in range(n_major):
|
|
54
|
+
for u in range(major_ptr[j], major_ptr[j + 1]):
|
|
55
|
+
val = values[u]
|
|
56
|
+
for idx in range(value_ptr[u], value_ptr[u + 1]):
|
|
57
|
+
row = indices[idx]
|
|
58
|
+
for c in range(k):
|
|
59
|
+
y[row, c] += val * b[j, c]
|
|
60
|
+
return y
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@numba.njit(cache=True, parallel=True)
|
|
64
|
+
def _minor_matmat(major_ptr, values, value_ptr, indices, b, n_major):
|
|
65
|
+
"""Y = B @ A, i.e. B is (k, n_minor), contracting over the minor axis."""
|
|
66
|
+
k = b.shape[0]
|
|
67
|
+
y = np.zeros((k, n_major), dtype=values.dtype)
|
|
68
|
+
for j in numba.prange(n_major): # ty: ignore[not-iterable]
|
|
69
|
+
for u in range(major_ptr[j], major_ptr[j + 1]):
|
|
70
|
+
val = values[u]
|
|
71
|
+
for idx in range(value_ptr[u], value_ptr[u + 1]):
|
|
72
|
+
col = indices[idx]
|
|
73
|
+
for c in range(k):
|
|
74
|
+
y[c, j] += val * b[c, col]
|
|
75
|
+
return y
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def major_matvec(major_ptr, values, value_ptr, indices, x, n_major, n_minor):
|
|
79
|
+
return _major_matvec(major_ptr, values, value_ptr, indices, np.asarray(x), n_major, n_minor)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def minor_matvec(major_ptr, values, value_ptr, indices, x, n_major):
|
|
83
|
+
return _minor_matvec(major_ptr, values, value_ptr, indices, np.asarray(x), n_major)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def major_matmat(major_ptr, values, value_ptr, indices, b, n_major, n_minor):
|
|
87
|
+
b = np.ascontiguousarray(b)
|
|
88
|
+
return _major_matmat(major_ptr, values, value_ptr, indices, b, n_major, n_minor)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def minor_matmat(major_ptr, values, value_ptr, indices, b, n_major):
|
|
92
|
+
b = np.ascontiguousarray(b)
|
|
93
|
+
return _minor_matmat(major_ptr, values, value_ptr, indices, b, n_major)
|