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/_compression.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
"""Default on-disk compression for arrays written via anndata's IO registry.
|
|
2
|
+
|
|
3
|
+
Blosc2+LZ4 gives a good default speed/ratio tradeoff and, unlike gzip, is
|
|
4
|
+
fast enough to leave on by default. It requires the ``hdf5plugin`` filter to
|
|
5
|
+
be registered for HDF5; zarr already ships blosc support via ``numcodecs``.
|
|
6
|
+
|
|
7
|
+
Blosc is only ever applied to *numeric* arrays. anndata applies whatever
|
|
8
|
+
``dataset_kwargs`` it's given uniformly to every array it writes, including
|
|
9
|
+
the small variable-length string arrays nested inside dataframes and
|
|
10
|
+
categoricals (category labels, ``obs``/``var`` string columns, the
|
|
11
|
+
``_index``). At least some HDF5 filter-plugin builds (seen in this
|
|
12
|
+
environment: h5py 3.16 / HDF5 2.0.0 / hdf5plugin's Blosc2) segfault
|
|
13
|
+
(``SIGFPE``) when the Blosc2 filter is applied to a variable-length-string
|
|
14
|
+
dataset -- and there's no benefit to compressing already-tiny label arrays
|
|
15
|
+
anyway. :func:`numeric_only_compression` patches the relevant
|
|
16
|
+
``create_dataset``/``create_array`` calls for the duration of a write so
|
|
17
|
+
string/object arrays always land uncompressed, regardless of what
|
|
18
|
+
``dataset_kwargs`` was passed in -- callers don't have to know about this.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import contextlib
|
|
24
|
+
from typing import TYPE_CHECKING, Any, cast
|
|
25
|
+
|
|
26
|
+
import numpy as np
|
|
27
|
+
|
|
28
|
+
if TYPE_CHECKING:
|
|
29
|
+
from collections.abc import Iterator
|
|
30
|
+
|
|
31
|
+
__all__ = ["h5_dataset_kwargs", "numeric_only_compression", "zarr_dataset_kwargs"]
|
|
32
|
+
|
|
33
|
+
_H5_COMPRESSION_KEYS = ("compression", "compression_opts")
|
|
34
|
+
_ZARR_V2_COMPRESSION_KEYS = ("compressor",)
|
|
35
|
+
_ZARR_V3_COMPRESSION_KEYS = ("compressors", "compressor")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def h5_dataset_kwargs() -> dict[str, Any]:
|
|
39
|
+
"""``h5py.Group.create_dataset`` kwargs for Blosc2+LZ4 compression."""
|
|
40
|
+
import hdf5plugin
|
|
41
|
+
|
|
42
|
+
return dict(hdf5plugin.Blosc2(cname="lz4"))
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _is_zarr_v2() -> bool:
|
|
46
|
+
try:
|
|
47
|
+
import zarr
|
|
48
|
+
|
|
49
|
+
return getattr(zarr, "__version__", "").startswith("2.")
|
|
50
|
+
except Exception:
|
|
51
|
+
return False
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def zarr_dataset_kwargs() -> dict[str, Any]:
|
|
55
|
+
"""``dataset_kwargs`` for Blosc+LZ4 compression, understood by anndata's zarr writers."""
|
|
56
|
+
if _is_zarr_v2():
|
|
57
|
+
import numcodecs
|
|
58
|
+
|
|
59
|
+
return {"compressor": numcodecs.Blosc(cname="lz4")}
|
|
60
|
+
|
|
61
|
+
import zarr.codecs
|
|
62
|
+
|
|
63
|
+
return {"compressor": zarr.codecs.BloscCodec(cname="lz4")}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _is_string_like(dtype: Any, data: Any) -> bool:
|
|
67
|
+
"""True if a dataset write looks like a variable-length/string/object array."""
|
|
68
|
+
for candidate in (dtype, getattr(data, "dtype", None)):
|
|
69
|
+
if candidate is None:
|
|
70
|
+
continue
|
|
71
|
+
try:
|
|
72
|
+
import h5py
|
|
73
|
+
|
|
74
|
+
if h5py.check_string_dtype(candidate) is not None:
|
|
75
|
+
return True
|
|
76
|
+
except Exception:
|
|
77
|
+
# h5py's check only understands its own/numpy dtypes -- anything
|
|
78
|
+
# else (e.g. zarr's own dtype objects) falls through to the
|
|
79
|
+
# numpy-dtype and class-name checks below.
|
|
80
|
+
pass
|
|
81
|
+
try:
|
|
82
|
+
if np.dtype(candidate).kind in ("O", "U", "S"):
|
|
83
|
+
return True
|
|
84
|
+
except TypeError:
|
|
85
|
+
# Not numpy-dtype-like, e.g. zarr v3's VariableLengthUTF8() dtype object.
|
|
86
|
+
if any(tag in type(candidate).__name__ for tag in ("UTF8", "String")):
|
|
87
|
+
return True
|
|
88
|
+
return False
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@contextlib.contextmanager
|
|
92
|
+
def _numeric_only_h5() -> Iterator[None]:
|
|
93
|
+
import h5py
|
|
94
|
+
|
|
95
|
+
original = h5py.Group.create_dataset
|
|
96
|
+
|
|
97
|
+
def patched(self: h5py.Group, name: str, *args: Any, **kwargs: Any) -> h5py.Dataset:
|
|
98
|
+
data = kwargs.get("data", args[0] if args else None)
|
|
99
|
+
if _is_string_like(kwargs.get("dtype"), data):
|
|
100
|
+
for key in _H5_COMPRESSION_KEYS:
|
|
101
|
+
kwargs.pop(key, None)
|
|
102
|
+
return original(self, name, *args, **kwargs)
|
|
103
|
+
|
|
104
|
+
h5py.Group.create_dataset = patched
|
|
105
|
+
try:
|
|
106
|
+
yield
|
|
107
|
+
finally:
|
|
108
|
+
h5py.Group.create_dataset = original
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
@contextlib.contextmanager
|
|
112
|
+
def _numeric_only_zarr() -> Iterator[None]:
|
|
113
|
+
import zarr
|
|
114
|
+
|
|
115
|
+
if _is_zarr_v2():
|
|
116
|
+
zarr_group = cast(Any, zarr.Group)
|
|
117
|
+
original_ds = getattr(zarr_group, "create_dataset", None)
|
|
118
|
+
if original_ds is not None:
|
|
119
|
+
keys = _ZARR_V2_COMPRESSION_KEYS
|
|
120
|
+
|
|
121
|
+
def patched_ds(self: Any, name: str, **kwargs: Any) -> Any:
|
|
122
|
+
if _is_string_like(kwargs.get("dtype"), kwargs.get("data")):
|
|
123
|
+
for key in keys:
|
|
124
|
+
kwargs[key] = None
|
|
125
|
+
return original_ds(self, name, **kwargs)
|
|
126
|
+
|
|
127
|
+
zarr_group.create_dataset = patched_ds
|
|
128
|
+
try:
|
|
129
|
+
yield
|
|
130
|
+
finally:
|
|
131
|
+
zarr_group.create_dataset = original_ds
|
|
132
|
+
return
|
|
133
|
+
|
|
134
|
+
original = zarr.Group.create_array
|
|
135
|
+
keys = _ZARR_V3_COMPRESSION_KEYS
|
|
136
|
+
|
|
137
|
+
def patched(self: zarr.Group, name: str, **kwargs: Any) -> Any:
|
|
138
|
+
if _is_string_like(kwargs.get("dtype"), kwargs.get("data")):
|
|
139
|
+
for key in keys:
|
|
140
|
+
if key in kwargs:
|
|
141
|
+
kwargs[key] = None if key == "compressor" else ()
|
|
142
|
+
return original(self, name, **kwargs)
|
|
143
|
+
|
|
144
|
+
zarr.Group.create_array = patched
|
|
145
|
+
try:
|
|
146
|
+
yield
|
|
147
|
+
finally:
|
|
148
|
+
zarr.Group.create_array = original
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def numeric_only_compression(store_kind: str) -> contextlib.AbstractContextManager[None]:
|
|
152
|
+
"""Scoped patch making Blosc compression apply to numeric arrays only.
|
|
153
|
+
|
|
154
|
+
``store_kind`` is ``"h5"`` or ``"zarr"``. See the module docstring for why
|
|
155
|
+
this is needed. Use as ``with numeric_only_compression("h5"): ...`` around
|
|
156
|
+
the write.
|
|
157
|
+
"""
|
|
158
|
+
if store_kind == "h5":
|
|
159
|
+
return _numeric_only_h5()
|
|
160
|
+
if store_kind == "zarr":
|
|
161
|
+
return _numeric_only_zarr()
|
|
162
|
+
raise ValueError(f"store_kind must be 'h5' or 'zarr', got {store_kind!r}")
|
vsparse/_construct.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"""Numba-accelerated construction and decompression of the VCS layout.
|
|
2
|
+
|
|
3
|
+
The value-compressed sparse (VCS) layout groups the nonzero entries of each
|
|
4
|
+
major-axis slice (columns for VCSC, rows for VCSR) by their *value* rather
|
|
5
|
+
than storing one value per nonzero. For data with heavy value repetition
|
|
6
|
+
(e.g. integer count matrices) this makes the value array much smaller than
|
|
7
|
+
the number of nonzeros.
|
|
8
|
+
|
|
9
|
+
Arrays (major axis of size ``n_major``, ``nnz`` total stored nonzeros,
|
|
10
|
+
``n_unique`` total unique (major, value) groups):
|
|
11
|
+
|
|
12
|
+
``major_ptr``
|
|
13
|
+
``int64[n_major + 1]``. ``major_ptr[i]:major_ptr[i + 1]`` indexes into
|
|
14
|
+
``values``/``value_ptr`` for the unique values of major-slice ``i``.
|
|
15
|
+
``values``
|
|
16
|
+
``dtype[n_unique]``. The unique nonzero values, grouped by major slice.
|
|
17
|
+
``value_ptr``
|
|
18
|
+
``int64[n_unique + 1]``. ``value_ptr[k]:value_ptr[k + 1]`` indexes into
|
|
19
|
+
``indices`` for the minor indices sharing ``values[k]``.
|
|
20
|
+
``indices``
|
|
21
|
+
``int32/int64[nnz]``. Minor-axis indices (rows for VCSC, columns for
|
|
22
|
+
VCSR), grouped by the unique value they belong to.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import numba
|
|
28
|
+
import numpy as np
|
|
29
|
+
|
|
30
|
+
__all__ = ["compress", "decompress", "transpose_major"]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@numba.njit(cache=True)
|
|
34
|
+
def _compress(major_ptr_in, minor_indices, data, n_major):
|
|
35
|
+
nnz = minor_indices.shape[0]
|
|
36
|
+
out_indices = np.empty(nnz, dtype=minor_indices.dtype)
|
|
37
|
+
out_values = np.empty(nnz, dtype=data.dtype)
|
|
38
|
+
out_value_ptr = np.empty(nnz + 1, dtype=np.int64)
|
|
39
|
+
out_major_ptr = np.empty(n_major + 1, dtype=np.int64)
|
|
40
|
+
|
|
41
|
+
value_count = 0
|
|
42
|
+
pos = 0
|
|
43
|
+
out_major_ptr[0] = 0
|
|
44
|
+
|
|
45
|
+
for j in range(n_major):
|
|
46
|
+
start, end = major_ptr_in[j], major_ptr_in[j + 1]
|
|
47
|
+
seg_len = end - start
|
|
48
|
+
if seg_len == 0:
|
|
49
|
+
out_major_ptr[j + 1] = value_count
|
|
50
|
+
continue
|
|
51
|
+
|
|
52
|
+
seg_vals = data[start:end]
|
|
53
|
+
seg_minor = minor_indices[start:end]
|
|
54
|
+
order = np.argsort(seg_vals)
|
|
55
|
+
sorted_vals = seg_vals[order]
|
|
56
|
+
sorted_minor = seg_minor[order]
|
|
57
|
+
|
|
58
|
+
out_indices[pos : pos + seg_len] = sorted_minor
|
|
59
|
+
|
|
60
|
+
out_values[value_count] = sorted_vals[0]
|
|
61
|
+
out_value_ptr[value_count] = pos
|
|
62
|
+
for k in range(1, seg_len):
|
|
63
|
+
if sorted_vals[k] != sorted_vals[k - 1]:
|
|
64
|
+
value_count += 1
|
|
65
|
+
out_values[value_count] = sorted_vals[k]
|
|
66
|
+
out_value_ptr[value_count] = pos + k
|
|
67
|
+
value_count += 1
|
|
68
|
+
pos += seg_len
|
|
69
|
+
out_major_ptr[j + 1] = value_count
|
|
70
|
+
|
|
71
|
+
out_value_ptr[value_count] = pos
|
|
72
|
+
return (
|
|
73
|
+
out_major_ptr,
|
|
74
|
+
out_values[:value_count].copy(),
|
|
75
|
+
out_value_ptr[: value_count + 1].copy(),
|
|
76
|
+
out_indices,
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@numba.njit(cache=True)
|
|
81
|
+
def _decompress(major_ptr, values, value_ptr, indices, n_major, nnz):
|
|
82
|
+
out_indices = np.empty(nnz, dtype=indices.dtype)
|
|
83
|
+
out_data = np.empty(nnz, dtype=values.dtype)
|
|
84
|
+
out_major_ptr = np.empty(n_major + 1, dtype=np.int64)
|
|
85
|
+
|
|
86
|
+
pos = 0
|
|
87
|
+
out_major_ptr[0] = 0
|
|
88
|
+
for j in range(n_major):
|
|
89
|
+
u_start, u_end = major_ptr[j], major_ptr[j + 1]
|
|
90
|
+
col_start = pos
|
|
91
|
+
for u in range(u_start, u_end):
|
|
92
|
+
v = values[u]
|
|
93
|
+
i_start, i_end = value_ptr[u], value_ptr[u + 1]
|
|
94
|
+
cnt = i_end - i_start
|
|
95
|
+
out_indices[pos : pos + cnt] = indices[i_start:i_end]
|
|
96
|
+
out_data[pos : pos + cnt] = v
|
|
97
|
+
pos += cnt
|
|
98
|
+
order = np.argsort(out_indices[col_start:pos])
|
|
99
|
+
out_indices[col_start:pos] = out_indices[col_start:pos][order]
|
|
100
|
+
out_data[col_start:pos] = out_data[col_start:pos][order]
|
|
101
|
+
out_major_ptr[j + 1] = pos
|
|
102
|
+
|
|
103
|
+
return out_major_ptr, out_indices, out_data
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def compress(
|
|
107
|
+
major_ptr: np.ndarray,
|
|
108
|
+
minor_indices: np.ndarray,
|
|
109
|
+
data: np.ndarray,
|
|
110
|
+
n_major: int,
|
|
111
|
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
|
|
112
|
+
"""Build the VCS layout from a standard compressed-sparse layout.
|
|
113
|
+
|
|
114
|
+
Parameters mirror scipy's ``indptr``/``indices``/``data`` for either a
|
|
115
|
+
CSC (major axis = columns) or CSR (major axis = rows) matrix.
|
|
116
|
+
"""
|
|
117
|
+
major_ptr = np.ascontiguousarray(major_ptr, dtype=np.int64)
|
|
118
|
+
minor_indices = np.ascontiguousarray(minor_indices)
|
|
119
|
+
data = np.ascontiguousarray(data)
|
|
120
|
+
return _compress(major_ptr, minor_indices, data, n_major)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def decompress(
|
|
124
|
+
major_ptr: np.ndarray,
|
|
125
|
+
values: np.ndarray,
|
|
126
|
+
value_ptr: np.ndarray,
|
|
127
|
+
indices: np.ndarray,
|
|
128
|
+
n_major: int,
|
|
129
|
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
|
130
|
+
"""Invert :func:`compress`, producing standard ``indptr``/``indices``/``data``."""
|
|
131
|
+
nnz = indices.shape[0]
|
|
132
|
+
return _decompress(major_ptr, values, value_ptr, indices, n_major, nnz)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def transpose_major(
|
|
136
|
+
major_ptr: np.ndarray,
|
|
137
|
+
values: np.ndarray,
|
|
138
|
+
value_ptr: np.ndarray,
|
|
139
|
+
indices: np.ndarray,
|
|
140
|
+
n_minor: int,
|
|
141
|
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
|
|
142
|
+
"""Re-group the VCS layout by the *other* axis (VCSC indices <-> VCSR indices).
|
|
143
|
+
|
|
144
|
+
This is a storage-layout conversion, not a mathematical transpose: shape
|
|
145
|
+
is unchanged, only which axis is deduplicated-by-value changes. Every
|
|
146
|
+
stored ``(old_major, value, old_minor)`` triple becomes a
|
|
147
|
+
``(new_major=old_minor, value, new_minor=old_major)`` triple in the
|
|
148
|
+
output.
|
|
149
|
+
|
|
150
|
+
Unlike going through :func:`decompress` (expand to plain nonzeros,
|
|
151
|
+
sorting *within each major slice* to restore minor-index order) followed
|
|
152
|
+
by re-:func:`compress` (sorting *within each major slice* again to
|
|
153
|
+
re-dedupe), this does the whole regrouping as a single global
|
|
154
|
+
``np.lexsort`` by ``(new_major, value)`` -- one vectorized C sort over
|
|
155
|
+
all ``nnz`` entries, rather than one Python-level call into a per-slice
|
|
156
|
+
sort for every one of the (potentially many thousands of) major slices
|
|
157
|
+
in each direction. That per-slice-call overhead, not the sorting itself,
|
|
158
|
+
is what makes the decompress-then-recompress route slow at scale.
|
|
159
|
+
"""
|
|
160
|
+
n_major = major_ptr.shape[0] - 1
|
|
161
|
+
nnz = indices.shape[0]
|
|
162
|
+
|
|
163
|
+
if nnz == 0:
|
|
164
|
+
return (
|
|
165
|
+
np.zeros(n_minor + 1, dtype=np.int64),
|
|
166
|
+
values[:0].copy(),
|
|
167
|
+
np.zeros(1, dtype=np.int64),
|
|
168
|
+
np.empty(0, dtype=indices.dtype),
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
group_sizes = np.diff(value_ptr) # nnz-count per unique (major, value) group
|
|
172
|
+
value_of_entry = np.repeat(values, group_sizes)
|
|
173
|
+
major_of_group = np.repeat(np.arange(n_major, dtype=np.int64), np.diff(major_ptr))
|
|
174
|
+
old_major_of_entry = np.repeat(major_of_group, group_sizes) # -> new minor index
|
|
175
|
+
new_major_of_entry = np.asarray(indices) # old minor index IS the new major
|
|
176
|
+
|
|
177
|
+
order = np.lexsort((value_of_entry, new_major_of_entry))
|
|
178
|
+
sorted_major = new_major_of_entry[order]
|
|
179
|
+
sorted_value = value_of_entry[order]
|
|
180
|
+
sorted_minor = old_major_of_entry[order]
|
|
181
|
+
|
|
182
|
+
change = np.empty(nnz, dtype=bool)
|
|
183
|
+
change[0] = True
|
|
184
|
+
change[1:] = (sorted_major[1:] != sorted_major[:-1]) | (sorted_value[1:] != sorted_value[:-1])
|
|
185
|
+
group_starts = np.flatnonzero(change)
|
|
186
|
+
|
|
187
|
+
values_out = sorted_value[group_starts]
|
|
188
|
+
value_ptr_out = np.concatenate([group_starts, [nnz]]).astype(np.int64)
|
|
189
|
+
major_ptr_out = np.searchsorted(sorted_major[group_starts], np.arange(n_minor + 1)).astype(np.int64)
|
|
190
|
+
|
|
191
|
+
minor_dtype = np.int32 if n_major <= np.iinfo(np.int32).max else np.int64
|
|
192
|
+
indices_out = sorted_minor.astype(minor_dtype, copy=False)
|
|
193
|
+
|
|
194
|
+
return major_ptr_out, values_out, value_ptr_out, indices_out
|
vsparse/_indexutils.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Tiny indexing helpers shared by the VCS and IVCS array types."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
|
|
9
|
+
__all__ = ["is_full_slice", "normalize_major_idx"]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def is_full_slice(key: Any) -> bool:
|
|
13
|
+
return isinstance(key, slice) and key.start is None and key.stop is None and key.step is None
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def normalize_major_idx(key: Any, n_major: int) -> np.ndarray:
|
|
17
|
+
"""Turn a major-axis index (slice/int/bool mask/int array) into a plain int array."""
|
|
18
|
+
if isinstance(key, slice):
|
|
19
|
+
return np.arange(*key.indices(n_major))
|
|
20
|
+
if isinstance(key, int | np.integer):
|
|
21
|
+
idx = int(key)
|
|
22
|
+
if idx < 0:
|
|
23
|
+
idx += n_major
|
|
24
|
+
if not (0 <= idx < n_major):
|
|
25
|
+
raise IndexError(f"index {key} out of bounds for axis of size {n_major}")
|
|
26
|
+
return np.array([idx])
|
|
27
|
+
arr = np.asarray(key)
|
|
28
|
+
if arr.dtype == bool:
|
|
29
|
+
if arr.shape[0] != n_major:
|
|
30
|
+
raise IndexError("boolean index does not match major axis length")
|
|
31
|
+
return np.nonzero(arr)[0]
|
|
32
|
+
arr = arr.astype(np.int64)
|
|
33
|
+
arr = np.where(arr < 0, arr + n_major, arr)
|
|
34
|
+
if arr.size and ((arr < 0).any() or (arr >= n_major).any()):
|
|
35
|
+
raise IndexError("index out of bounds for major axis")
|
|
36
|
+
return arr
|
vsparse/_io.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"""Registers VCSCArray/VCSRArray with anndata's on-disk IO registry.
|
|
2
|
+
|
|
3
|
+
This lets a VCSCArray/VCSRArray be written/read anywhere anndata's generic
|
|
4
|
+
element writer (``anndata.io.write_elem``/``read_elem``) is used -- e.g.
|
|
5
|
+
nested inside ``adata.uns``, or as ``X``/a custom top-level key on a
|
|
6
|
+
:class:`~vsparse.VCSCAnnData` -- and survive a round trip through HDF5 or zarr
|
|
7
|
+
without any manual (de)serialization.
|
|
8
|
+
|
|
9
|
+
This relies on ``anndata._io.specs.registry``, an internal (not yet public)
|
|
10
|
+
extension mechanism -- the same one anndata itself uses to support
|
|
11
|
+
dask/awkward/cupy arrays. It is not guaranteed stable across anndata
|
|
12
|
+
versions; if this module fails to import, it means anndata's registry
|
|
13
|
+
internals changed shape.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from types import MappingProxyType
|
|
19
|
+
from typing import TYPE_CHECKING, Any, cast
|
|
20
|
+
|
|
21
|
+
import anndata as ad
|
|
22
|
+
import h5py
|
|
23
|
+
import numpy as np
|
|
24
|
+
import zarr
|
|
25
|
+
|
|
26
|
+
from vsparse import _ivcsc
|
|
27
|
+
from vsparse._base import VCSCArray, VCSRArray, _VCSBase
|
|
28
|
+
|
|
29
|
+
if TYPE_CHECKING:
|
|
30
|
+
from collections.abc import Mapping
|
|
31
|
+
|
|
32
|
+
from anndata._io.specs.registry import Reader, Writer
|
|
33
|
+
|
|
34
|
+
GroupStorageType = h5py.Group | zarr.Group
|
|
35
|
+
|
|
36
|
+
__all__ = ["write_ivcs_elem"]
|
|
37
|
+
|
|
38
|
+
_ARRAY_KEYS = ("major_ptr", "values", "value_ptr", "indices")
|
|
39
|
+
_SPEC_VERSION = "0.1.0"
|
|
40
|
+
_IVCS_SPEC_VERSION = "0.1.0"
|
|
41
|
+
_IVCS_SPEC_NAMES: dict[type[_VCSBase], str] = {VCSCArray: "ivcsc", VCSRArray: "ivcsr"}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _write_vcs(
|
|
45
|
+
f: GroupStorageType,
|
|
46
|
+
k: str,
|
|
47
|
+
v: _VCSBase,
|
|
48
|
+
*,
|
|
49
|
+
_writer: Writer,
|
|
50
|
+
dataset_kwargs: Mapping[str, Any] = MappingProxyType({}),
|
|
51
|
+
) -> None:
|
|
52
|
+
g = f.require_group(k)
|
|
53
|
+
g.attrs["shape"] = v.shape
|
|
54
|
+
for name in _ARRAY_KEYS:
|
|
55
|
+
_writer.write_elem(g, name, getattr(v, name), dataset_kwargs=dataset_kwargs)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _make_read_vcs(cls: type[_VCSBase]):
|
|
59
|
+
def _read(elem: GroupStorageType, *, _reader: Reader) -> _VCSBase:
|
|
60
|
+
shape_vals = [int(s) for s in np.asarray(elem.attrs["shape"]).tolist()]
|
|
61
|
+
shape = (shape_vals[0], shape_vals[1])
|
|
62
|
+
arrays = {
|
|
63
|
+
name: cast(np.ndarray, _reader.read_elem(elem[name])) for name in _ARRAY_KEYS
|
|
64
|
+
}
|
|
65
|
+
return cls(
|
|
66
|
+
shape,
|
|
67
|
+
arrays["major_ptr"],
|
|
68
|
+
arrays["values"],
|
|
69
|
+
arrays["value_ptr"],
|
|
70
|
+
arrays["indices"],
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
return _read
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def write_ivcs_elem(
|
|
77
|
+
f: GroupStorageType,
|
|
78
|
+
k: str,
|
|
79
|
+
v: _VCSBase,
|
|
80
|
+
*,
|
|
81
|
+
dataset_kwargs: Mapping[str, Any] = MappingProxyType({}),
|
|
82
|
+
) -> None:
|
|
83
|
+
"""Write ``v`` in the byte-packed IVCSC/IVCSR on-disk format.
|
|
84
|
+
|
|
85
|
+
This trades write/read cost for a smaller file: ``indices`` is delta+
|
|
86
|
+
varint packed via :mod:`vsparse._ivcsc` instead of stored as a plain int
|
|
87
|
+
array. It is meant for archival storage only -- reading it back (through
|
|
88
|
+
the registry, e.g. via ``anndata.io.read_elem``) always reconstructs a
|
|
89
|
+
normal VCSCArray/VCSRArray with a plain ``indices`` array.
|
|
90
|
+
|
|
91
|
+
Unlike the VCSC/VCSR codec registered below, this is not reachable
|
|
92
|
+
through anndata's generic ``write_elem`` type dispatch (which can only
|
|
93
|
+
route by the Python type of ``v``, and both formats share the same
|
|
94
|
+
VCSCArray/VCSRArray types) -- call it directly, e.g. from
|
|
95
|
+
:meth:`~vsparse.VCSCAnnData.write_h5ad`.
|
|
96
|
+
"""
|
|
97
|
+
g = f.require_group(k)
|
|
98
|
+
g.attrs["shape"] = v.shape
|
|
99
|
+
g.attrs["indices_dtype"] = np.dtype(v.indices.dtype).name
|
|
100
|
+
for name in ("major_ptr", "values", "value_ptr"):
|
|
101
|
+
ad.io.write_elem(g, name, getattr(v, name), dataset_kwargs=dataset_kwargs)
|
|
102
|
+
packed = _ivcsc.pack_indices(v.value_ptr, v.indices)
|
|
103
|
+
ad.io.write_elem(g, "packed_indices", packed, dataset_kwargs=dataset_kwargs)
|
|
104
|
+
g.attrs["encoding-type"] = "ivcsc" if v._format == "csc" else "ivcsr"
|
|
105
|
+
g.attrs["encoding-version"] = _IVCS_SPEC_VERSION
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _make_read_ivcs(cls: type[_VCSBase]):
|
|
109
|
+
def _read(elem: GroupStorageType, *, _reader: Reader) -> _VCSBase:
|
|
110
|
+
shape_vals = [int(s) for s in np.asarray(elem.attrs["shape"]).tolist()]
|
|
111
|
+
shape = (shape_vals[0], shape_vals[1])
|
|
112
|
+
major_ptr = cast(np.ndarray, _reader.read_elem(elem["major_ptr"]))
|
|
113
|
+
values = cast(np.ndarray, _reader.read_elem(elem["values"]))
|
|
114
|
+
value_ptr = cast(np.ndarray, _reader.read_elem(elem["value_ptr"]))
|
|
115
|
+
packed = cast(np.ndarray, _reader.read_elem(elem["packed_indices"]))
|
|
116
|
+
dtype = np.dtype(elem.attrs["indices_dtype"])
|
|
117
|
+
indices = _ivcsc.unpack_indices(value_ptr, packed, dtype)
|
|
118
|
+
return cls(shape, major_ptr, values, value_ptr, indices)
|
|
119
|
+
|
|
120
|
+
return _read
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _register() -> None:
|
|
124
|
+
from anndata._io.specs.registry import _REGISTRY, IOSpec
|
|
125
|
+
|
|
126
|
+
for store_type in (h5py.Group, zarr.Group):
|
|
127
|
+
for cls, spec_name in ((VCSCArray, "vcsc"), (VCSRArray, "vcsr")):
|
|
128
|
+
spec = IOSpec(spec_name, _SPEC_VERSION)
|
|
129
|
+
if not _REGISTRY.has_write(store_type, cls, frozenset()):
|
|
130
|
+
_REGISTRY.register_write(store_type, cls, spec)(_write_vcs)
|
|
131
|
+
if not _REGISTRY.has_read(store_type, spec, frozenset()):
|
|
132
|
+
_REGISTRY.register_read(store_type, spec, frozenset())(_make_read_vcs(cls))
|
|
133
|
+
for cls, spec_name in _IVCS_SPEC_NAMES.items():
|
|
134
|
+
spec = IOSpec(spec_name, _IVCS_SPEC_VERSION)
|
|
135
|
+
if not _REGISTRY.has_read(store_type, spec, frozenset()):
|
|
136
|
+
_REGISTRY.register_read(store_type, spec, frozenset())(_make_read_ivcs(cls))
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
_register()
|