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/_rapid_load.py
ADDED
|
@@ -0,0 +1,552 @@
|
|
|
1
|
+
"""Fast filter/normalize loader for IVCSR-stored ``.h5ad`` files.
|
|
2
|
+
|
|
3
|
+
Mirrors the preprocessing in `parafac2.normalize.prepare_dataset
|
|
4
|
+
<https://github.com/meyer-lab/parafac2/blob/main/parafac2/normalize.py>`_
|
|
5
|
+
(minimum-count cell filtering, minimum-expression gene filtering, per-cell
|
|
6
|
+
read-depth normalization, and a log10 transform) but is written directly
|
|
7
|
+
against the on-disk VCSR/IVCSR layout instead of going through
|
|
8
|
+
:meth:`~vsparse.VCSCAnnData.read_h5ad` + generic ``AnnData`` indexing.
|
|
9
|
+
|
|
10
|
+
Why this needs its own code path
|
|
11
|
+
---------------------------------
|
|
12
|
+
A VCSR major (row/cell) slice stores each *unique* value once, alongside the
|
|
13
|
+
list of minor-axis (gene) indices that share it -- ``values``/``value_ptr``
|
|
14
|
+
are indexed per unique-value group, not per nonzero. Two consequences drive
|
|
15
|
+
the design here:
|
|
16
|
+
|
|
17
|
+
- **Cell filtering is (almost) free.** A cell's total count is
|
|
18
|
+
``sum(value * group_size for each unique-value group in that row)``, a sum
|
|
19
|
+
over ``n_unique`` (~46x fewer entries than ``nnz`` on the bundled example
|
|
20
|
+
dataset) that touches only ``major_ptr``/``values``/``value_ptr``. It needs
|
|
21
|
+
none of the (compressed, delta+varint-packed) ``indices`` array, so the
|
|
22
|
+
cell mask can be computed without ever decoding it.
|
|
23
|
+
- **Gene filtering and normalization must touch every retained nonzero.** A
|
|
24
|
+
gene's total count is a scatter-add keyed by minor-axis index, so there is
|
|
25
|
+
no shortcut analogous to the cell case. Without an ``obs_filter``, every
|
|
26
|
+
index is decoded. With an ``obs_filter``, the packed stream must still be
|
|
27
|
+
scanned because row byte offsets are not stored, but indices and values
|
|
28
|
+
are materialized only for selected rows. Once decoded, the per-cell scale
|
|
29
|
+
factor differs per row while the per-gene scale factor differs per column,
|
|
30
|
+
so after both are applied a row's values are no longer mostly-repeated --
|
|
31
|
+
the whole point of VCSC/VCSR's deduplication is gone. Normalization is
|
|
32
|
+
therefore done on a plain CSR array, built once, right after the two masks
|
|
33
|
+
are known -- via a fused numba pass rather than scipy's generic per-step
|
|
34
|
+
(row sum, row scale, column sum, column scale, multiply, add, log10)
|
|
35
|
+
elementwise pipeline, each step of which is another single-threaded
|
|
36
|
+
full-``nnz`` pass with its own temporary.
|
|
37
|
+
|
|
38
|
+
The one thing this implementation does *not* do is what
|
|
39
|
+
:func:`parafac2.normalize.prepare_dataset` calls "indexing for subsetting the
|
|
40
|
+
data": ``X[cell_mask, gene_mask]``. That line re-derives a filtered matrix via
|
|
41
|
+
scipy's generic fancy indexing (row selection, then a column selection that
|
|
42
|
+
internally goes through a CSC conversion). Here, row/gene filtering,
|
|
43
|
+
compaction, and column-index remapping happen in one fused parallel pass
|
|
44
|
+
(:func:`_count_kept`/:func:`_fill_kept`) directly on the decoded arrays, so
|
|
45
|
+
the filtered CSR is built once instead of assembled and then re-sliced.
|
|
46
|
+
Gene means (``X.var["means"]``) aren't computed either -- nothing here needs
|
|
47
|
+
them, and computing them is a simple ``X.mean(axis=0)`` for callers that do.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
from __future__ import annotations
|
|
51
|
+
|
|
52
|
+
from collections.abc import Callable
|
|
53
|
+
from pathlib import Path
|
|
54
|
+
from typing import TYPE_CHECKING
|
|
55
|
+
|
|
56
|
+
import anndata as ad
|
|
57
|
+
import numba
|
|
58
|
+
import numpy as np
|
|
59
|
+
import pandas as pd
|
|
60
|
+
from scipy.sparse import csr_array
|
|
61
|
+
|
|
62
|
+
from vsparse import _ivcsc
|
|
63
|
+
from vsparse._anndata_class import VCSCAnnData
|
|
64
|
+
|
|
65
|
+
if TYPE_CHECKING:
|
|
66
|
+
from os import PathLike
|
|
67
|
+
|
|
68
|
+
__all__ = ["load_and_normalize", "load_packed"]
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
# -- group-level (no-decode) cell totals -------------------------------------
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _cell_totals(major_ptr: np.ndarray, values: np.ndarray, value_ptr: np.ndarray) -> np.ndarray:
|
|
75
|
+
"""Per-row total counts, computed without touching ``indices``.
|
|
76
|
+
|
|
77
|
+
Each unique-value group of size ``value_ptr[k + 1] - value_ptr[k]``
|
|
78
|
+
contributes ``values[k] * group_size`` to its row's total -- so this
|
|
79
|
+
only costs ``O(n_unique)``, not ``O(nnz)``.
|
|
80
|
+
"""
|
|
81
|
+
n_major = major_ptr.shape[0] - 1
|
|
82
|
+
group_sizes = np.diff(value_ptr)
|
|
83
|
+
weighted = values.astype(np.float64) * group_sizes
|
|
84
|
+
row_of_group = np.repeat(np.arange(n_major, dtype=np.int64), np.diff(major_ptr))
|
|
85
|
+
return np.bincount(row_of_group, weights=weighted, minlength=n_major)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
# -- parallel value expansion (values/value_ptr -> per-nonzero data) --------
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@numba.njit(cache=True, parallel=True)
|
|
92
|
+
def _expand_values(values: np.ndarray, value_ptr: np.ndarray, out: np.ndarray) -> None:
|
|
93
|
+
n_unique = values.shape[0]
|
|
94
|
+
for k in numba.prange(n_unique): # ty: ignore[not-iterable]
|
|
95
|
+
v = values[k]
|
|
96
|
+
for p in range(value_ptr[k], value_ptr[k + 1]):
|
|
97
|
+
out[p] = v
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _build_data(values: np.ndarray, value_ptr: np.ndarray, nnz: int) -> np.ndarray:
|
|
101
|
+
out = np.empty(nnz, dtype=values.dtype)
|
|
102
|
+
_expand_values(values, value_ptr, out)
|
|
103
|
+
return out
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
# -- selective packed decode (obs-filtered IVCSR rows only) -----------------
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
@numba.njit(cache=True)
|
|
110
|
+
def _decode_selected_rows(
|
|
111
|
+
major_ptr: np.ndarray,
|
|
112
|
+
values: np.ndarray,
|
|
113
|
+
value_ptr: np.ndarray,
|
|
114
|
+
packed: np.ndarray,
|
|
115
|
+
row_mask: np.ndarray,
|
|
116
|
+
out_indices: np.ndarray,
|
|
117
|
+
out_data: np.ndarray,
|
|
118
|
+
) -> None:
|
|
119
|
+
"""Decode only selected IVCSR rows while scanning past excluded rows."""
|
|
120
|
+
pos = 0
|
|
121
|
+
out_pos = 0
|
|
122
|
+
n_rows = major_ptr.shape[0] - 1
|
|
123
|
+
|
|
124
|
+
for r in range(n_rows):
|
|
125
|
+
keep = row_mask[r]
|
|
126
|
+
for g in range(major_ptr[r], major_ptr[r + 1]):
|
|
127
|
+
if keep:
|
|
128
|
+
prev = np.int64(-1)
|
|
129
|
+
value = values[g]
|
|
130
|
+
for _ in range(value_ptr[g], value_ptr[g + 1]):
|
|
131
|
+
shift = np.uint64(0)
|
|
132
|
+
result = np.uint64(0)
|
|
133
|
+
while True:
|
|
134
|
+
b = packed[pos]
|
|
135
|
+
pos += 1
|
|
136
|
+
result |= np.uint64(b & 0x7F) << shift
|
|
137
|
+
if b & 0x80 == 0:
|
|
138
|
+
break
|
|
139
|
+
shift += np.uint64(7)
|
|
140
|
+
prev = prev + 1 + np.int64(result)
|
|
141
|
+
out_indices[out_pos] = prev
|
|
142
|
+
out_data[out_pos] = value
|
|
143
|
+
out_pos += 1
|
|
144
|
+
else:
|
|
145
|
+
for _ in range(value_ptr[g], value_ptr[g + 1]):
|
|
146
|
+
while packed[pos] & 0x80:
|
|
147
|
+
pos += 1
|
|
148
|
+
pos += 1
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _build_selected_rows(
|
|
152
|
+
major_ptr: np.ndarray,
|
|
153
|
+
values: np.ndarray,
|
|
154
|
+
value_ptr: np.ndarray,
|
|
155
|
+
packed: np.ndarray,
|
|
156
|
+
indices_dtype: np.dtype,
|
|
157
|
+
row_mask: np.ndarray,
|
|
158
|
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
|
159
|
+
full_indptr = value_ptr[major_ptr]
|
|
160
|
+
row_nnz = np.diff(full_indptr)[row_mask]
|
|
161
|
+
nnz = int(row_nnz.sum())
|
|
162
|
+
ptr_dtype = np.int64 if nnz > np.iinfo(np.int32).max else np.int32
|
|
163
|
+
|
|
164
|
+
indptr = np.zeros(row_nnz.shape[0] + 1, dtype=ptr_dtype)
|
|
165
|
+
np.cumsum(row_nnz, out=indptr[1:])
|
|
166
|
+
indices = np.empty(nnz, dtype=indices_dtype)
|
|
167
|
+
data = np.empty(nnz, dtype=values.dtype)
|
|
168
|
+
_decode_selected_rows(major_ptr, values, value_ptr, packed, row_mask, indices, data)
|
|
169
|
+
return indptr, indices, data
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
# -- parallel weighted bincount (raw per-gene totals, for gene_mask) --------
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
@numba.njit(cache=True, parallel=True)
|
|
176
|
+
def _weighted_bincount(
|
|
177
|
+
indices: np.ndarray, data: np.ndarray, n_bins: int, nthreads: int
|
|
178
|
+
) -> np.ndarray:
|
|
179
|
+
n = indices.shape[0]
|
|
180
|
+
chunk = (n + nthreads - 1) // nthreads
|
|
181
|
+
partial = np.zeros((nthreads, n_bins), dtype=np.float64)
|
|
182
|
+
for t in numba.prange(nthreads): # ty: ignore[not-iterable]
|
|
183
|
+
start = t * chunk
|
|
184
|
+
end = min(n, start + chunk)
|
|
185
|
+
local = partial[t]
|
|
186
|
+
for k in range(start, end):
|
|
187
|
+
local[indices[k]] += data[k]
|
|
188
|
+
return partial.sum(axis=0)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
@numba.njit(cache=True, parallel=True)
|
|
192
|
+
def _gene_detection_counts(
|
|
193
|
+
indices: np.ndarray, data: np.ndarray, n_genes: int, nthreads: int
|
|
194
|
+
) -> np.ndarray:
|
|
195
|
+
"""Number of cells with positive expression for each gene."""
|
|
196
|
+
n = indices.shape[0]
|
|
197
|
+
chunk = (n + nthreads - 1) // nthreads
|
|
198
|
+
partial = np.zeros((nthreads, n_genes), dtype=np.int64)
|
|
199
|
+
for t in numba.prange(nthreads): # ty: ignore[not-iterable]
|
|
200
|
+
start = t * chunk
|
|
201
|
+
end = min(n, start + chunk)
|
|
202
|
+
local = partial[t]
|
|
203
|
+
for k in range(start, end):
|
|
204
|
+
if data[k] > 0:
|
|
205
|
+
local[indices[k]] += 1
|
|
206
|
+
return partial.sum(axis=0)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
# -- fused row+column filter/compaction --------------------------------------
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
@numba.njit(cache=True, parallel=True)
|
|
213
|
+
def _count_kept(
|
|
214
|
+
row_indptr: np.ndarray,
|
|
215
|
+
indices: np.ndarray,
|
|
216
|
+
gene_mask: np.ndarray,
|
|
217
|
+
kept_rows: np.ndarray,
|
|
218
|
+
out_counts: np.ndarray,
|
|
219
|
+
) -> None:
|
|
220
|
+
for j in numba.prange(kept_rows.shape[0]): # ty: ignore[not-iterable]
|
|
221
|
+
r = kept_rows[j]
|
|
222
|
+
c = 0
|
|
223
|
+
for k in range(row_indptr[r], row_indptr[r + 1]):
|
|
224
|
+
if gene_mask[indices[k]]:
|
|
225
|
+
c += 1
|
|
226
|
+
out_counts[j] = c
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
@numba.njit(cache=True, parallel=True)
|
|
230
|
+
def _fill_kept(
|
|
231
|
+
row_indptr: np.ndarray,
|
|
232
|
+
indices: np.ndarray,
|
|
233
|
+
data: np.ndarray,
|
|
234
|
+
gene_remap: np.ndarray,
|
|
235
|
+
kept_rows: np.ndarray,
|
|
236
|
+
new_indptr: np.ndarray,
|
|
237
|
+
out_indices: np.ndarray,
|
|
238
|
+
out_data: np.ndarray,
|
|
239
|
+
) -> None:
|
|
240
|
+
for j in numba.prange(kept_rows.shape[0]): # ty: ignore[not-iterable]
|
|
241
|
+
r = kept_rows[j]
|
|
242
|
+
pos = new_indptr[j]
|
|
243
|
+
for k in range(row_indptr[r], row_indptr[r + 1]):
|
|
244
|
+
g = gene_remap[indices[k]]
|
|
245
|
+
if g >= 0:
|
|
246
|
+
out_indices[pos] = g
|
|
247
|
+
out_data[pos] = data[k]
|
|
248
|
+
pos += 1
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _filter_and_compact(
|
|
252
|
+
row_indptr: np.ndarray,
|
|
253
|
+
indices: np.ndarray,
|
|
254
|
+
data: np.ndarray,
|
|
255
|
+
cell_mask: np.ndarray,
|
|
256
|
+
gene_mask: np.ndarray,
|
|
257
|
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, int]:
|
|
258
|
+
kept_rows = np.nonzero(cell_mask)[0]
|
|
259
|
+
gene_remap = (np.cumsum(gene_mask) - 1).astype(np.int32)
|
|
260
|
+
gene_remap[~gene_mask] = -1
|
|
261
|
+
n_kept_genes = int(gene_mask.sum())
|
|
262
|
+
|
|
263
|
+
idx_dtype = np.int64 if indices.shape[0] > np.iinfo(np.int32).max else np.int32
|
|
264
|
+
counts = np.empty(kept_rows.shape[0], dtype=idx_dtype)
|
|
265
|
+
_count_kept(row_indptr, indices, gene_mask, kept_rows, counts)
|
|
266
|
+
new_indptr = np.zeros(kept_rows.shape[0] + 1, dtype=idx_dtype)
|
|
267
|
+
np.cumsum(counts, out=new_indptr[1:])
|
|
268
|
+
|
|
269
|
+
nnz_filtered = int(new_indptr[-1])
|
|
270
|
+
out_indices = np.empty(nnz_filtered, dtype=idx_dtype)
|
|
271
|
+
out_data = np.empty(nnz_filtered, dtype=np.float32)
|
|
272
|
+
_fill_kept(row_indptr, indices, data, gene_remap, kept_rows, new_indptr, out_indices, out_data)
|
|
273
|
+
|
|
274
|
+
return new_indptr, out_indices, out_data, kept_rows, n_kept_genes
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
# -- fused row-scale / gene-scale / log10 transform --------------------------
|
|
278
|
+
#
|
|
279
|
+
# scipy's route to the same result -- X.sum(axis=1), a np.repeat of the
|
|
280
|
+
# per-row scale over nnz, an in-place divide, X.sum(axis=0), a fancy-index
|
|
281
|
+
# gather of the per-column scale over nnz, another in-place divide, then
|
|
282
|
+
# three more elementwise passes (*1000, +1, log10) -- is ~9 passes over the
|
|
283
|
+
# (still nnz-scale, filtering rarely drops much on real data) array plus two
|
|
284
|
+
# extra full-nnz temporaries (the repeat and the gather). Every one of those
|
|
285
|
+
# passes and temporaries is single-threaded generic numpy code. Fusing the
|
|
286
|
+
# whole tail into three parallel passes over the already-filtered CSR (row
|
|
287
|
+
# sums -> per-column sums of the row-scaled data -> the final transform,
|
|
288
|
+
# each row-parallel with no nnz-sized temporary beyond the output) removes
|
|
289
|
+
# both the redundant passes and the memory pressure from those temporaries.
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
@numba.njit(cache=True, parallel=True)
|
|
293
|
+
def _row_sums(indptr: np.ndarray, data: np.ndarray, out: np.ndarray) -> None:
|
|
294
|
+
for r in numba.prange(out.shape[0]): # ty: ignore[not-iterable]
|
|
295
|
+
s = 0.0
|
|
296
|
+
for k in range(indptr[r], indptr[r + 1]):
|
|
297
|
+
s += data[k]
|
|
298
|
+
out[r] = s
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
@numba.njit(cache=True, parallel=True)
|
|
302
|
+
def _scaled_col_sums(
|
|
303
|
+
indptr: np.ndarray,
|
|
304
|
+
indices: np.ndarray,
|
|
305
|
+
data: np.ndarray,
|
|
306
|
+
row_scale: np.ndarray,
|
|
307
|
+
n_bins: int,
|
|
308
|
+
nthreads: int,
|
|
309
|
+
) -> np.ndarray:
|
|
310
|
+
n_rows = indptr.shape[0] - 1
|
|
311
|
+
chunk = (n_rows + nthreads - 1) // nthreads
|
|
312
|
+
partial = np.zeros((nthreads, n_bins), dtype=np.float64)
|
|
313
|
+
for t in numba.prange(nthreads): # ty: ignore[not-iterable]
|
|
314
|
+
start = t * chunk
|
|
315
|
+
end = min(n_rows, start + chunk)
|
|
316
|
+
local = partial[t]
|
|
317
|
+
for r in range(start, end):
|
|
318
|
+
sc = row_scale[r]
|
|
319
|
+
for k in range(indptr[r], indptr[r + 1]):
|
|
320
|
+
local[indices[k]] += data[k] / sc
|
|
321
|
+
return partial.sum(axis=0)
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
@numba.njit(cache=True, parallel=True)
|
|
325
|
+
def _fused_normalize_transform(
|
|
326
|
+
indptr: np.ndarray,
|
|
327
|
+
indices: np.ndarray,
|
|
328
|
+
data: np.ndarray,
|
|
329
|
+
row_scale: np.ndarray,
|
|
330
|
+
gene_sums: np.ndarray,
|
|
331
|
+
) -> None:
|
|
332
|
+
"""Overwrites ``data`` in place -- each output only depends on its own input."""
|
|
333
|
+
n_rows = indptr.shape[0] - 1
|
|
334
|
+
for r in numba.prange(n_rows): # ty: ignore[not-iterable]
|
|
335
|
+
sc = row_scale[r]
|
|
336
|
+
for k in range(indptr[r], indptr[r + 1]):
|
|
337
|
+
v = (data[k] / sc) / gene_sums[indices[k]]
|
|
338
|
+
data[k] = np.log10(np.float32(1.0) + np.float32(1000.0) * v)
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def _normalize_and_transform(
|
|
342
|
+
indptr: np.ndarray, indices: np.ndarray, data: np.ndarray, n_genes: int
|
|
343
|
+
) -> np.ndarray:
|
|
344
|
+
"""Depth normalization + log10(1000x + 1), fused, overwriting ``data`` in place."""
|
|
345
|
+
n_rows = indptr.shape[0] - 1
|
|
346
|
+
nthreads = numba.get_num_threads()
|
|
347
|
+
|
|
348
|
+
counts_per_cell = np.empty(n_rows, dtype=np.float64)
|
|
349
|
+
_row_sums(indptr, data, counts_per_cell)
|
|
350
|
+
counts_per_cell /= np.median(counts_per_cell)
|
|
351
|
+
|
|
352
|
+
gene_sums = _scaled_col_sums(indptr, indices, data, counts_per_cell, n_genes, nthreads)
|
|
353
|
+
|
|
354
|
+
_fused_normalize_transform(indptr, indices, data, counts_per_cell, gene_sums)
|
|
355
|
+
return data
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
# -- top-level entry point ---------------------------------------------------
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
_FIELD_KEYS = ("obs", "var", "obsm", "varm", "obsp", "varp", "layers", "uns")
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def load_and_normalize(
|
|
365
|
+
path: str | PathLike[str],
|
|
366
|
+
*,
|
|
367
|
+
min_cell_counts: float = 10.0,
|
|
368
|
+
gene_threshold: float = 0.0,
|
|
369
|
+
min_cells: int | None = None,
|
|
370
|
+
obs_filter: Callable[[pd.DataFrame], object] | None = None,
|
|
371
|
+
x_key: str = "X",
|
|
372
|
+
) -> ad.AnnData:
|
|
373
|
+
"""Load, filter, and depth-normalize a VCSR/IVCSR-backed ``.h5ad`` file.
|
|
374
|
+
|
|
375
|
+
Reproduces ``parafac2.normalize.prepare_dataset``: cells with total
|
|
376
|
+
counts <= ``min_cell_counts`` and genes with total counts <=
|
|
377
|
+
``gene_threshold * n_cells`` are dropped. When ``min_cells`` is given,
|
|
378
|
+
genes expressed in fewer than ``min_cells`` cells are also dropped. Gene
|
|
379
|
+
filters are measured on the raw counts after any ``obs_filter``.
|
|
380
|
+
The remaining matrix is row-normalized to the median per-cell depth, then
|
|
381
|
+
column-normalized by gene sum, then transformed as ``log10(1000x + 1)``.
|
|
382
|
+
Surrounding metadata (``obs``, ``var``, ``obsm``, etc.) is sliced to
|
|
383
|
+
match the retained cells and genes.
|
|
384
|
+
|
|
385
|
+
Parameters
|
|
386
|
+
----------
|
|
387
|
+
path
|
|
388
|
+
Path to an ``.h5ad`` file whose ``X`` (or ``layers[x_key]``) was
|
|
389
|
+
written with ``format="ivcsc"``/``"ivcsr"`` (see
|
|
390
|
+
:meth:`~vsparse.VCSCAnnData.write_h5ad`).
|
|
391
|
+
min_cell_counts
|
|
392
|
+
Cells with total raw counts <= this are dropped.
|
|
393
|
+
gene_threshold
|
|
394
|
+
Minimum threshold fraction for gene inclusion, as in
|
|
395
|
+
``parafac2.normalize.prepare_dataset``: genes with total raw counts
|
|
396
|
+
<= ``gene_threshold * n_cells`` are dropped.
|
|
397
|
+
min_cells
|
|
398
|
+
Optional gene filter. Genes expressed in fewer than this
|
|
399
|
+
many cells are dropped. Expression is defined as a raw count > 0.
|
|
400
|
+
obs_filter
|
|
401
|
+
Optional callable receiving ``obs`` and returning a one-dimensional
|
|
402
|
+
boolean mask. When provided, rows are subset before cell filtering,
|
|
403
|
+
gene filtering, and normalization, so gene totals and
|
|
404
|
+
``gene_threshold`` are computed using only the selected cells. The
|
|
405
|
+
packed IVCSR stream is still read in full, but indices and values are
|
|
406
|
+
materialized only for selected rows.
|
|
407
|
+
x_key
|
|
408
|
+
Top-level h5ad group holding the IVCSR array (``"X"`` by default).
|
|
409
|
+
|
|
410
|
+
Returns
|
|
411
|
+
-------
|
|
412
|
+
ad.AnnData
|
|
413
|
+
Filtered, depth-normalized AnnData object with ``X`` as a CSR array
|
|
414
|
+
and sliced metadata.
|
|
415
|
+
|
|
416
|
+
Examples
|
|
417
|
+
--------
|
|
418
|
+
Select cells using multiple ``obs`` columns and multiple accepted values::
|
|
419
|
+
|
|
420
|
+
load_and_normalize(
|
|
421
|
+
path,
|
|
422
|
+
obs_filter=lambda obs: (
|
|
423
|
+
obs["condition"].isin(["control", "vehicle"])
|
|
424
|
+
& (obs["timepoint"] == "T3")
|
|
425
|
+
),
|
|
426
|
+
)
|
|
427
|
+
"""
|
|
428
|
+
import h5py
|
|
429
|
+
import hdf5plugin # noqa: F401 -- registers the Blosc2 HDF5 filter
|
|
430
|
+
|
|
431
|
+
if min_cells is not None:
|
|
432
|
+
if isinstance(min_cells, bool) or not isinstance(min_cells, int):
|
|
433
|
+
raise TypeError("min_cells must be an integer or None")
|
|
434
|
+
if min_cells < 0:
|
|
435
|
+
raise ValueError("min_cells must be non-negative")
|
|
436
|
+
|
|
437
|
+
with h5py.File(Path(path), "r") as f:
|
|
438
|
+
g = f[x_key]
|
|
439
|
+
shape = (int(g.attrs["shape"][0]), int(g.attrs["shape"][1]))
|
|
440
|
+
indices_dtype = np.dtype(g.attrs["indices_dtype"])
|
|
441
|
+
major_ptr = g["major_ptr"][...]
|
|
442
|
+
values = g["values"][...]
|
|
443
|
+
value_ptr = g["value_ptr"][...]
|
|
444
|
+
packed = g["packed_indices"][...]
|
|
445
|
+
|
|
446
|
+
kwargs = {k: ad.io.read_elem(f[k]) for k in _FIELD_KEYS if k in f}
|
|
447
|
+
if "raw" in f:
|
|
448
|
+
kwargs["raw"] = ad.io.read_elem(f["raw"])
|
|
449
|
+
|
|
450
|
+
n_cells, n_genes = shape
|
|
451
|
+
|
|
452
|
+
# Cell mask: no decode needed.
|
|
453
|
+
cell_totals = _cell_totals(major_ptr, values, value_ptr)
|
|
454
|
+
|
|
455
|
+
if obs_filter is None:
|
|
456
|
+
cell_mask = cell_totals > min_cell_counts
|
|
457
|
+
|
|
458
|
+
# Everything past this point needs every nonzero visited at least once.
|
|
459
|
+
# Each array below is only kept alive as long as something still needs
|
|
460
|
+
# it -- at nnz-billions scale, an un-`del`ed stale reference is a real
|
|
461
|
+
# multi-GB cost, not housekeeping.
|
|
462
|
+
indices = _ivcsc.unpack_indices(value_ptr, packed, indices_dtype)
|
|
463
|
+
del packed
|
|
464
|
+
data = _build_data(values, value_ptr, indices.shape[0])
|
|
465
|
+
row_indptr = value_ptr[major_ptr]
|
|
466
|
+
|
|
467
|
+
gene_totals_raw = _weighted_bincount(indices, data, n_genes, numba.get_num_threads())
|
|
468
|
+
gene_mask = gene_totals_raw > (gene_threshold * n_cells)
|
|
469
|
+
if min_cells is not None:
|
|
470
|
+
gene_detection_counts = _gene_detection_counts(
|
|
471
|
+
indices, data, n_genes, numba.get_num_threads()
|
|
472
|
+
)
|
|
473
|
+
gene_mask &= gene_detection_counts >= min_cells
|
|
474
|
+
metadata_cell_mask = cell_mask
|
|
475
|
+
else:
|
|
476
|
+
obs = kwargs.get("obs")
|
|
477
|
+
if not isinstance(obs, pd.DataFrame):
|
|
478
|
+
raise ValueError("obs_filter requires an obs table in the h5ad file")
|
|
479
|
+
if not callable(obs_filter):
|
|
480
|
+
raise TypeError("obs_filter must be callable or None")
|
|
481
|
+
|
|
482
|
+
obs_mask = np.asarray(obs_filter(obs))
|
|
483
|
+
if obs_mask.ndim != 1 or obs_mask.shape[0] != n_cells:
|
|
484
|
+
raise ValueError(f"obs_filter must return a one-dimensional mask of length {n_cells}")
|
|
485
|
+
if obs_mask.dtype != np.bool_:
|
|
486
|
+
raise ValueError("obs_filter must return a boolean mask")
|
|
487
|
+
if not np.any(obs_mask):
|
|
488
|
+
raise ValueError("obs_filter selected no cells")
|
|
489
|
+
obs_mask = np.ascontiguousarray(obs_mask)
|
|
490
|
+
|
|
491
|
+
selected_rows = np.nonzero(obs_mask)[0]
|
|
492
|
+
cell_mask = cell_totals[obs_mask] > min_cell_counts
|
|
493
|
+
row_indptr, indices, data = _build_selected_rows(
|
|
494
|
+
major_ptr, values, value_ptr, packed, indices_dtype, obs_mask
|
|
495
|
+
)
|
|
496
|
+
del packed
|
|
497
|
+
|
|
498
|
+
gene_totals_raw = _weighted_bincount(indices, data, n_genes, numba.get_num_threads())
|
|
499
|
+
gene_mask = gene_totals_raw > (gene_threshold * selected_rows.shape[0])
|
|
500
|
+
if min_cells is not None:
|
|
501
|
+
gene_detection_counts = _gene_detection_counts(
|
|
502
|
+
indices, data, n_genes, numba.get_num_threads()
|
|
503
|
+
)
|
|
504
|
+
gene_mask &= gene_detection_counts >= min_cells
|
|
505
|
+
|
|
506
|
+
metadata_cell_mask = np.zeros(n_cells, dtype=np.bool_)
|
|
507
|
+
metadata_cell_mask[selected_rows[cell_mask]] = True
|
|
508
|
+
|
|
509
|
+
new_indptr, out_indices, out_data, kept_rows, n_kept_genes = _filter_and_compact(
|
|
510
|
+
row_indptr, indices, data, cell_mask, gene_mask
|
|
511
|
+
)
|
|
512
|
+
del indices, data, row_indptr
|
|
513
|
+
|
|
514
|
+
normalized = _normalize_and_transform(new_indptr, out_indices, out_data, n_kept_genes)
|
|
515
|
+
X = csr_array(
|
|
516
|
+
(normalized, out_indices, new_indptr), shape=(kept_rows.shape[0], n_kept_genes)
|
|
517
|
+
)
|
|
518
|
+
|
|
519
|
+
if "obs" in kwargs and "var" in kwargs:
|
|
520
|
+
adata = ad.AnnData(**kwargs) # ty: ignore[invalid-argument-type]
|
|
521
|
+
else:
|
|
522
|
+
adata = ad.AnnData(shape=shape, **kwargs) # ty: ignore[invalid-argument-type]
|
|
523
|
+
adata = adata[metadata_cell_mask, gene_mask].copy()
|
|
524
|
+
adata.X = X
|
|
525
|
+
|
|
526
|
+
return adata
|
|
527
|
+
|
|
528
|
+
|
|
529
|
+
def load_packed(path: str | PathLike[str], *, x_key: str = "X") -> VCSCAnnData:
|
|
530
|
+
"""Load an IVCSR/IVCSC-backed ``.h5ad`` file, decoding ``X`` immediately.
|
|
531
|
+
|
|
532
|
+
Unlike :func:`load_and_normalize`, this does no filtering or
|
|
533
|
+
normalization -- ``X`` comes back as an ordinary VCSCArray/VCSRArray with
|
|
534
|
+
plain ``indices``, decoded from the packed bytes read from disk.
|
|
535
|
+
|
|
536
|
+
Parameters
|
|
537
|
+
----------
|
|
538
|
+
path
|
|
539
|
+
Path to an ``.h5ad`` file whose ``X`` (or a top-level group named
|
|
540
|
+
``x_key``) was written with ``format="ivcsc"``/``"ivcsr"`` (see
|
|
541
|
+
:meth:`~vsparse.VCSCAnnData.write_h5ad`).
|
|
542
|
+
x_key
|
|
543
|
+
Top-level h5ad group holding the IVCSR/IVCSC array (``"X"`` by default).
|
|
544
|
+
"""
|
|
545
|
+
import h5py
|
|
546
|
+
import hdf5plugin # noqa: F401 -- registers the Blosc2 HDF5 filter
|
|
547
|
+
|
|
548
|
+
with h5py.File(Path(path), "r") as f:
|
|
549
|
+
X = ad.io.read_elem(f[x_key])
|
|
550
|
+
kwargs = {k: ad.io.read_elem(f[k]) for k in _FIELD_KEYS if k in f}
|
|
551
|
+
|
|
552
|
+
return VCSCAnnData(X=X, **kwargs) # ty: ignore[invalid-argument-type]
|