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/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""vsparse: Value-Compressed Sparse Column/Row (VCSC/VCSR) arrays, with optional AnnData integration.
|
|
2
|
+
|
|
3
|
+
See :class:`~vsparse.VCSCArray` and :class:`~vsparse.VCSRArray` for the array
|
|
4
|
+
types, :func:`~vsparse.from_anndata` to build one from an
|
|
5
|
+
:class:`anndata.AnnData` object, and :class:`~vsparse.VCSCAnnData` for an
|
|
6
|
+
AnnData subclass that holds a VCSC/VCSR array as ``X`` directly.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from vsparse._anndata import from_anndata, to_layer
|
|
10
|
+
from vsparse._anndata_class import VCSCAnnData
|
|
11
|
+
from vsparse._base import VCSCArray, VCSRArray
|
|
12
|
+
from vsparse._rapid_load import load_and_normalize, load_packed
|
|
13
|
+
from vsparse._vcs_norm import VCSCArrayNormalized, VCSRArrayNormalized
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"VCSCAnnData",
|
|
17
|
+
"VCSCArray",
|
|
18
|
+
"VCSCArrayNormalized",
|
|
19
|
+
"VCSRArray",
|
|
20
|
+
"VCSRArrayNormalized",
|
|
21
|
+
"from_anndata",
|
|
22
|
+
"load_and_normalize",
|
|
23
|
+
"load_packed",
|
|
24
|
+
"to_layer",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
__version__ = "0.1.0"
|
vsparse/_anndata.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Read/write helpers bridging :mod:`anndata` and the VCSC/VCSR layout."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import anndata as ad
|
|
6
|
+
import scipy.sparse as sp
|
|
7
|
+
|
|
8
|
+
from vsparse._base import VCSCArray, VCSRArray, _VCSBase
|
|
9
|
+
|
|
10
|
+
__all__ = ["from_anndata", "to_layer"]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _get_matrix(adata: ad.AnnData, layer: str | None, use_raw: bool):
|
|
14
|
+
if use_raw:
|
|
15
|
+
if adata.raw is None:
|
|
16
|
+
raise ValueError("adata.raw is None; cannot use_raw=True")
|
|
17
|
+
return adata.raw.X
|
|
18
|
+
if layer is not None:
|
|
19
|
+
return adata.layers[layer]
|
|
20
|
+
return adata.X
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def from_anndata(
|
|
24
|
+
adata: ad.AnnData,
|
|
25
|
+
layer: str | None = None,
|
|
26
|
+
use_raw: bool = False,
|
|
27
|
+
format: str = "csc",
|
|
28
|
+
) -> _VCSBase:
|
|
29
|
+
"""Convert ``adata.X`` (or a layer / ``raw.X``) into a VCSC/VCSR array.
|
|
30
|
+
|
|
31
|
+
Parameters
|
|
32
|
+
----------
|
|
33
|
+
adata
|
|
34
|
+
Source :class:`anndata.AnnData` object.
|
|
35
|
+
layer
|
|
36
|
+
If given, read ``adata.layers[layer]`` instead of ``adata.X``.
|
|
37
|
+
use_raw
|
|
38
|
+
If ``True``, read ``adata.raw.X`` instead of ``adata.X``.
|
|
39
|
+
format
|
|
40
|
+
Either ``"csc"`` (default) or ``"csr"``, selecting the returned type.
|
|
41
|
+
|
|
42
|
+
Returns
|
|
43
|
+
-------
|
|
44
|
+
A :class:`~vsparse.VCSCArray` or :class:`~vsparse.VCSRArray`. The source
|
|
45
|
+
matrix may already be CSC, CSR, or dense; it is converted as needed.
|
|
46
|
+
"""
|
|
47
|
+
if layer is not None and use_raw:
|
|
48
|
+
raise ValueError("pass only one of layer= or use_raw=")
|
|
49
|
+
if format not in ("csc", "csr"):
|
|
50
|
+
raise ValueError(f"format must be 'csc' or 'csr', got {format!r}")
|
|
51
|
+
|
|
52
|
+
mat = _get_matrix(adata, layer, use_raw)
|
|
53
|
+
if not sp.issparse(mat):
|
|
54
|
+
mat = sp.csr_array(mat)
|
|
55
|
+
|
|
56
|
+
cls = VCSCArray if format == "csc" else VCSRArray
|
|
57
|
+
return cls.from_scipy(mat)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def to_layer(adata: ad.AnnData, arr: _VCSBase, key: str) -> None:
|
|
61
|
+
"""Decompress ``arr`` and store it as ``adata.layers[key]``.
|
|
62
|
+
|
|
63
|
+
AnnData does not natively understand the VCSC/VCSR layout, so this
|
|
64
|
+
stores the equivalent scipy sparse array.
|
|
65
|
+
"""
|
|
66
|
+
if arr.shape != adata.shape:
|
|
67
|
+
raise ValueError(f"shape mismatch: array is {arr.shape}, adata is {adata.shape}")
|
|
68
|
+
adata.layers[key] = arr.to_scipy()
|
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
"""An AnnData subclass whose X (and optionally raw X) is VCSC/VCSR-backed."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from types import MappingProxyType
|
|
6
|
+
from typing import TYPE_CHECKING, Any, cast
|
|
7
|
+
|
|
8
|
+
import anndata as ad
|
|
9
|
+
import numpy as np
|
|
10
|
+
import pandas as pd
|
|
11
|
+
import scipy.sparse as sp
|
|
12
|
+
|
|
13
|
+
from vsparse import _compression, _io
|
|
14
|
+
from vsparse._base import VCSCArray, VCSRArray, _VCSBase
|
|
15
|
+
|
|
16
|
+
if TYPE_CHECKING:
|
|
17
|
+
from collections.abc import Mapping
|
|
18
|
+
from os import PathLike
|
|
19
|
+
|
|
20
|
+
__all__ = ["VCSCAnnData"]
|
|
21
|
+
|
|
22
|
+
_VCS_TYPES = (VCSCArray, VCSRArray)
|
|
23
|
+
_AnyVCS = _VCSBase
|
|
24
|
+
_DF_KEYS = ("obs", "var")
|
|
25
|
+
_MAPPING_KEYS = ("obsm", "varm", "obsp", "varp", "layers", "uns")
|
|
26
|
+
_FIELD_KEYS = (*_DF_KEYS, *_MAPPING_KEYS)
|
|
27
|
+
_STORE_FORMATS = ("vcsc", "ivcsc")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _as_slice_index(idx: Any, n: int) -> Any:
|
|
31
|
+
"""Turn a bare int index into a length-1 slice, matching anndata's own convention."""
|
|
32
|
+
if isinstance(idx, int | np.integer):
|
|
33
|
+
i = int(idx)
|
|
34
|
+
if i < 0:
|
|
35
|
+
i += n
|
|
36
|
+
return slice(i, i + 1, 1)
|
|
37
|
+
return idx
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _subset_1d(v: Any, idx: Any) -> Any:
|
|
41
|
+
if isinstance(v, pd.DataFrame):
|
|
42
|
+
return v.iloc[idx]
|
|
43
|
+
return v[idx]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _subset_2d(v: Any, oidx: Any, vidx: Any) -> Any:
|
|
47
|
+
if v is None:
|
|
48
|
+
return None
|
|
49
|
+
if isinstance(v, _VCS_TYPES):
|
|
50
|
+
result = v[oidx, vidx]
|
|
51
|
+
# VCSCArray/VCSRArray.__getitem__ only converts to a plain scipy
|
|
52
|
+
# array when both axes collapse to a scalar (oidx/vidx are always
|
|
53
|
+
# slices/arrays here, never bare ints -- see _as_slice_index above),
|
|
54
|
+
# but re-wrap defensively so X/raw_X always stay VCS-backed.
|
|
55
|
+
if not isinstance(result, _VCS_TYPES):
|
|
56
|
+
result = type(v).from_scipy(result)
|
|
57
|
+
return result
|
|
58
|
+
if sp.issparse(v):
|
|
59
|
+
return v[oidx, :][:, vidx]
|
|
60
|
+
return np.asarray(v)[oidx][:, vidx]
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _check_vcs_type(value: Any, name: str) -> None:
|
|
64
|
+
if value is not None and not isinstance(value, _VCS_TYPES):
|
|
65
|
+
raise TypeError(
|
|
66
|
+
f"{name} must be a VCSCArray or VCSRArray, got {type(value).__name__}. "
|
|
67
|
+
f"Build one with VCSCArray.from_scipy(...) or vsparse.from_anndata(...)."
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class VCSCAnnData(ad.AnnData):
|
|
72
|
+
"""An :class:`~anndata.AnnData` whose ``X`` is a VCSCArray/VCSRArray.
|
|
73
|
+
|
|
74
|
+
Standard :class:`~anndata.AnnData` validates every array assigned to
|
|
75
|
+
``X``/``layers``/etc. against a fixed allowlist of types (dense/sparse/
|
|
76
|
+
dask), so a plain ``AnnData`` cannot hold a :class:`~vsparse.VCSCArray`
|
|
77
|
+
directly. This subclass overrides the ``X`` property to store one
|
|
78
|
+
without going through that validation. A "raw" VCSC/VCSR matrix, if any,
|
|
79
|
+
is kept as ``.raw_X`` -- a plain attribute, *not* wired into anndata's own
|
|
80
|
+
``.raw``/``Raw`` machinery, which has the same restriction.
|
|
81
|
+
|
|
82
|
+
Because of this, most operations that need anndata's normal per-element
|
|
83
|
+
type dispatch on ``X`` -- concatenation, most of scanpy/anndata's
|
|
84
|
+
ecosystem -- are **not** supported while ``X`` is VCSC/VCSR-backed. Call
|
|
85
|
+
:meth:`to_anndata` first to get a fully-featured, ordinary
|
|
86
|
+
``AnnData``. Indexing (``adata[obs_idx, var_idx]``) *is* supported (see
|
|
87
|
+
:meth:`__getitem__`), but always as an eager copy, not a lazy view --
|
|
88
|
+
anndata's view machinery bypasses the ``X``/``raw_X`` overrides here.
|
|
89
|
+
|
|
90
|
+
Persist with :meth:`write_h5ad`/:meth:`write_zarr` and
|
|
91
|
+
:meth:`read_h5ad`/:meth:`read_zarr` (not the top-level
|
|
92
|
+
``anndata.read_h5ad``/``read_zarr``, which always reconstruct a plain
|
|
93
|
+
``AnnData`` and would fail validating a VCSC-typed ``X``).
|
|
94
|
+
"""
|
|
95
|
+
|
|
96
|
+
def __init__(
|
|
97
|
+
self,
|
|
98
|
+
X: _AnyVCS | None = None,
|
|
99
|
+
*,
|
|
100
|
+
raw_X: _AnyVCS | None = None,
|
|
101
|
+
**kwargs: Any,
|
|
102
|
+
) -> None:
|
|
103
|
+
_check_vcs_type(X, "X")
|
|
104
|
+
_check_vcs_type(raw_X, "raw_X")
|
|
105
|
+
if "raw" in kwargs:
|
|
106
|
+
raise TypeError(
|
|
107
|
+
"VCSCAnnData does not support the standard `raw=` argument; pass `raw_X=` instead."
|
|
108
|
+
)
|
|
109
|
+
self._vcs_X: _AnyVCS | None = None
|
|
110
|
+
self._vcs_raw_X: _AnyVCS | None = None
|
|
111
|
+
shape = kwargs.pop("shape", None)
|
|
112
|
+
if shape is None and X is None and "obs" not in kwargs:
|
|
113
|
+
shape = (0, 0)
|
|
114
|
+
elif X is not None or ("obs" in kwargs and "var" in kwargs):
|
|
115
|
+
shape = None
|
|
116
|
+
super().__init__(X=None, shape=shape, **kwargs)
|
|
117
|
+
self._vcs_X = X
|
|
118
|
+
self._vcs_raw_X = raw_X
|
|
119
|
+
|
|
120
|
+
# -- X / raw_X ------------------------------------------------------------
|
|
121
|
+
|
|
122
|
+
@property
|
|
123
|
+
def X(self) -> _AnyVCS | None:
|
|
124
|
+
return self._vcs_X
|
|
125
|
+
|
|
126
|
+
@X.setter
|
|
127
|
+
def X(self, value: Any) -> None:
|
|
128
|
+
if value is not None and not isinstance(value, _VCS_TYPES):
|
|
129
|
+
if sp.issparse(value) or isinstance(value, np.ndarray):
|
|
130
|
+
vcls = VCSCArray if isinstance(value, sp.csc_array | sp.csc_matrix) else VCSRArray
|
|
131
|
+
value = vcls.from_scipy(value)
|
|
132
|
+
else:
|
|
133
|
+
_check_vcs_type(value, "X")
|
|
134
|
+
if value is not None and hasattr(self, "_obs") and hasattr(self, "_var") and value.shape != self.shape:
|
|
135
|
+
raise ValueError(f"X shape {value.shape} does not match adata shape {self.shape}")
|
|
136
|
+
self._vcs_X = value
|
|
137
|
+
|
|
138
|
+
@property
|
|
139
|
+
def raw_X(self) -> _AnyVCS | None:
|
|
140
|
+
"""The raw/X matrix, as a VCSCArray/VCSRArray (see class docstring)."""
|
|
141
|
+
return self._vcs_raw_X
|
|
142
|
+
|
|
143
|
+
@raw_X.setter
|
|
144
|
+
def raw_X(self, value: Any) -> None:
|
|
145
|
+
if value is not None and not isinstance(value, _VCS_TYPES):
|
|
146
|
+
if sp.issparse(value) or isinstance(value, np.ndarray):
|
|
147
|
+
vcls = VCSCArray if isinstance(value, sp.csc_array | sp.csc_matrix) else VCSRArray
|
|
148
|
+
value = vcls.from_scipy(value)
|
|
149
|
+
else:
|
|
150
|
+
_check_vcs_type(value, "raw_X")
|
|
151
|
+
self._vcs_raw_X = value
|
|
152
|
+
|
|
153
|
+
# -- indexing / view creation ---------------------------------------------
|
|
154
|
+
|
|
155
|
+
def __getitem__(self, index: Any) -> VCSCAnnData: # ty: ignore[invalid-method-override]
|
|
156
|
+
"""Subset by obs/var index (labels, ints, slices, boolean masks), as with plain AnnData.
|
|
157
|
+
|
|
158
|
+
Unlike plain AnnData, this always returns a new, eagerly-copied
|
|
159
|
+
object rather than a lazy, memory-sharing view -- anndata's built-in
|
|
160
|
+
view machinery slices the private ``_X`` attribute directly, which
|
|
161
|
+
this class doesn't use (see the class docstring), so it can't be
|
|
162
|
+
reused here. ``X``/``raw_X`` stay VCSC/VCSR-backed either way, via
|
|
163
|
+
that array type's own indexing.
|
|
164
|
+
"""
|
|
165
|
+
oidx, vidx = self._normalize_indices(index)
|
|
166
|
+
oidx = _as_slice_index(oidx, self.n_obs)
|
|
167
|
+
vidx = _as_slice_index(vidx, self.n_vars)
|
|
168
|
+
|
|
169
|
+
obs = cast(pd.DataFrame, self.obs).iloc[oidx].copy()
|
|
170
|
+
var = cast(pd.DataFrame, self.var).iloc[vidx].copy()
|
|
171
|
+
|
|
172
|
+
return VCSCAnnData(
|
|
173
|
+
X=_subset_2d(self._vcs_X, oidx, vidx),
|
|
174
|
+
raw_X=_subset_2d(self._vcs_raw_X, oidx, vidx),
|
|
175
|
+
obs=obs,
|
|
176
|
+
var=var,
|
|
177
|
+
uns=self.uns,
|
|
178
|
+
obsm={k: _subset_1d(v, oidx) for k, v in self.obsm.items() if k is not None},
|
|
179
|
+
varm={k: _subset_1d(v, vidx) for k, v in self.varm.items() if k is not None},
|
|
180
|
+
obsp={k: _subset_2d(v, oidx, oidx) for k, v in self.obsp.items() if k is not None},
|
|
181
|
+
varp={k: _subset_2d(v, vidx, vidx) for k, v in self.varp.items() if k is not None},
|
|
182
|
+
layers={k: _subset_2d(v, oidx, vidx) for k, v in self.layers.items() if k is not None},
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
# -- conversion -------------------------------------------------------------
|
|
186
|
+
|
|
187
|
+
@classmethod
|
|
188
|
+
def from_anndata(
|
|
189
|
+
cls,
|
|
190
|
+
adata: ad.AnnData,
|
|
191
|
+
format: str = "csc",
|
|
192
|
+
raw_format: str | None = None,
|
|
193
|
+
*,
|
|
194
|
+
include_raw: bool = True,
|
|
195
|
+
) -> VCSCAnnData:
|
|
196
|
+
"""Build from a regular :class:`~anndata.AnnData`, compressing X (and raw.X)."""
|
|
197
|
+
vcls = VCSCArray if format == "csc" else VCSRArray
|
|
198
|
+
X = vcls.from_scipy(adata.X) if adata.X is not None else None
|
|
199
|
+
raw_X = None
|
|
200
|
+
if include_raw and adata.raw is not None:
|
|
201
|
+
rcls = VCSCArray if (raw_format or format) == "csc" else VCSRArray
|
|
202
|
+
raw_X = rcls.from_scipy(adata.raw.X)
|
|
203
|
+
return cls(
|
|
204
|
+
X=X,
|
|
205
|
+
raw_X=raw_X,
|
|
206
|
+
obs=cast(pd.DataFrame, adata.obs).copy(),
|
|
207
|
+
var=cast(pd.DataFrame, adata.var).copy(),
|
|
208
|
+
uns=adata.uns,
|
|
209
|
+
obsm={k: v for k, v in adata.obsm.items() if k is not None},
|
|
210
|
+
varm={k: v for k, v in adata.varm.items() if k is not None},
|
|
211
|
+
obsp={k: v for k, v in adata.obsp.items() if k is not None},
|
|
212
|
+
varp={k: v for k, v in adata.varp.items() if k is not None},
|
|
213
|
+
layers={k: v for k, v in adata.layers.items() if k is not None},
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
def to_anndata(self) -> ad.AnnData:
|
|
217
|
+
"""Decompress to a regular, fully-featured :class:`~anndata.AnnData`."""
|
|
218
|
+
obs = cast(pd.DataFrame, self.obs)
|
|
219
|
+
var = cast(pd.DataFrame, self.var)
|
|
220
|
+
out = ad.AnnData(
|
|
221
|
+
X=self._vcs_X.to_scipy() if self._vcs_X is not None else None,
|
|
222
|
+
obs=obs.copy(),
|
|
223
|
+
var=var.copy(),
|
|
224
|
+
uns=self.uns,
|
|
225
|
+
obsm=cast(Any, {k: v for k, v in self.obsm.items() if k is not None}),
|
|
226
|
+
varm=cast(Any, {k: v for k, v in self.varm.items() if k is not None}),
|
|
227
|
+
obsp=cast(Any, {k: v for k, v in self.obsp.items() if k is not None}),
|
|
228
|
+
varp=cast(Any, {k: v for k, v in self.varp.items() if k is not None}),
|
|
229
|
+
layers=cast(Any, {k: v for k, v in self.layers.items() if k is not None}),
|
|
230
|
+
)
|
|
231
|
+
if self._vcs_raw_X is not None:
|
|
232
|
+
out.raw = ad.AnnData(X=self._vcs_raw_X.to_scipy(), obs=obs.copy(), var=var.copy())
|
|
233
|
+
return out
|
|
234
|
+
|
|
235
|
+
# -- persistence --------------------------------------------------------------
|
|
236
|
+
#
|
|
237
|
+
# Implemented by hand (field-by-field, via anndata.io.write_elem/read_elem)
|
|
238
|
+
# rather than delegating to anndata.write_h5ad/write_zarr/read_h5ad/read_zarr:
|
|
239
|
+
# those either construct a plain AnnData (crashes coerce_array on a VCSC-typed
|
|
240
|
+
# X) or dispatch on the exact Python type of `self` (VCSCAnnData isn't
|
|
241
|
+
# registered as an "anndata"-encoded type, only AnnData is).
|
|
242
|
+
|
|
243
|
+
def _write_group(
|
|
244
|
+
self,
|
|
245
|
+
g: Any,
|
|
246
|
+
*,
|
|
247
|
+
format: str = "vcsc",
|
|
248
|
+
dataset_kwargs: Mapping[str, Any] = MappingProxyType({}),
|
|
249
|
+
) -> None:
|
|
250
|
+
if format not in _STORE_FORMATS:
|
|
251
|
+
raise ValueError(f"format must be one of {_STORE_FORMATS}, got {format!r}")
|
|
252
|
+
write_array = ad.io.write_elem if format == "vcsc" else _io.write_ivcs_elem
|
|
253
|
+
if self._vcs_X is not None:
|
|
254
|
+
write_array(g, "X", self._vcs_X, dataset_kwargs=dataset_kwargs)
|
|
255
|
+
if self._vcs_raw_X is not None:
|
|
256
|
+
write_array(g, "raw_X", self._vcs_raw_X, dataset_kwargs=dataset_kwargs)
|
|
257
|
+
for key in _DF_KEYS:
|
|
258
|
+
ad.io.write_elem(g, key, getattr(self, key), dataset_kwargs=dataset_kwargs)
|
|
259
|
+
for key in _MAPPING_KEYS:
|
|
260
|
+
mapping = {k: v for k, v in getattr(self, key).items() if k is not None}
|
|
261
|
+
ad.io.write_elem(g, key, mapping, dataset_kwargs=dataset_kwargs)
|
|
262
|
+
g.attrs["encoding-type"] = "anndata"
|
|
263
|
+
g.attrs["encoding-version"] = "0.1.0"
|
|
264
|
+
|
|
265
|
+
@classmethod
|
|
266
|
+
def _read_group(cls, g: Any) -> VCSCAnnData:
|
|
267
|
+
# X/raw_X read back as plain VCSCArray/VCSRArray regardless of whether
|
|
268
|
+
# they were stored "vcsc" or "ivcsc" -- the registry dispatches on the
|
|
269
|
+
# encoding-type attr each group was written with, not on how it's read.
|
|
270
|
+
kwargs = {k: ad.io.read_elem(g[k]) for k in _FIELD_KEYS if k in g}
|
|
271
|
+
X = cast("_AnyVCS | None", ad.io.read_elem(g["X"]) if "X" in g else None)
|
|
272
|
+
raw_X = cast("_AnyVCS | None", ad.io.read_elem(g["raw_X"]) if "raw_X" in g else None)
|
|
273
|
+
return cls(X=X, raw_X=raw_X, **kwargs)
|
|
274
|
+
|
|
275
|
+
def write_h5ad( # ty: ignore[invalid-method-override]
|
|
276
|
+
self,
|
|
277
|
+
filename: str | PathLike[str],
|
|
278
|
+
*,
|
|
279
|
+
format: str = "vcsc",
|
|
280
|
+
dataset_kwargs: Mapping[str, Any] | None = None,
|
|
281
|
+
**_kwargs: Any,
|
|
282
|
+
) -> None:
|
|
283
|
+
"""Write to ``.h5ad``. Read back with :meth:`read_h5ad`.
|
|
284
|
+
|
|
285
|
+
Parameters
|
|
286
|
+
----------
|
|
287
|
+
format
|
|
288
|
+
``"vcsc"`` (default) stores ``X``/``raw_X`` with plain int arrays
|
|
289
|
+
for the minor-axis indices. ``"ivcsc"`` (IVCSC/IVCSR) instead
|
|
290
|
+
byte-packs them (delta + varint encoding) for a smaller file, at
|
|
291
|
+
the cost of extra work on write/read. Either way, ``X``/``raw_X``
|
|
292
|
+
come back from :meth:`read_h5ad` as ordinary VCSCArray/VCSRArray
|
|
293
|
+
objects -- ``"ivcsc"`` is purely an on-disk storage format.
|
|
294
|
+
dataset_kwargs
|
|
295
|
+
Passed to ``h5py.Group.create_dataset`` for every array written.
|
|
296
|
+
Defaults to Blosc2+LZ4 compression; pass ``{}`` to store
|
|
297
|
+
uncompressed. Either way, compression is only ever applied to
|
|
298
|
+
numeric arrays -- see :func:`vsparse._compression.numeric_only_compression`.
|
|
299
|
+
"""
|
|
300
|
+
import h5py
|
|
301
|
+
|
|
302
|
+
if dataset_kwargs is None:
|
|
303
|
+
dataset_kwargs = _compression.h5_dataset_kwargs()
|
|
304
|
+
with (
|
|
305
|
+
_compression.numeric_only_compression("h5"),
|
|
306
|
+
h5py.File(filename, "w") as f,
|
|
307
|
+
):
|
|
308
|
+
self._write_group(f, format=format, dataset_kwargs=dataset_kwargs)
|
|
309
|
+
|
|
310
|
+
@classmethod
|
|
311
|
+
def read_h5ad(cls, filename: str | PathLike[str]) -> VCSCAnnData:
|
|
312
|
+
"""Read a file written by :meth:`write_h5ad`."""
|
|
313
|
+
import h5py
|
|
314
|
+
|
|
315
|
+
with h5py.File(filename, "r") as f:
|
|
316
|
+
return cls._read_group(f)
|
|
317
|
+
|
|
318
|
+
def write_zarr(
|
|
319
|
+
self,
|
|
320
|
+
store: Any,
|
|
321
|
+
*,
|
|
322
|
+
format: str = "vcsc",
|
|
323
|
+
dataset_kwargs: Mapping[str, Any] | None = None,
|
|
324
|
+
**_kwargs: Any,
|
|
325
|
+
) -> None:
|
|
326
|
+
"""Write to a zarr store. Read back with :meth:`read_zarr`.
|
|
327
|
+
|
|
328
|
+
See :meth:`write_h5ad` for ``format``/``dataset_kwargs`` (including the
|
|
329
|
+
numeric-only compression behavior); the default compression here is
|
|
330
|
+
Blosc+LZ4 via ``numcodecs``.
|
|
331
|
+
"""
|
|
332
|
+
import zarr
|
|
333
|
+
|
|
334
|
+
if dataset_kwargs is None:
|
|
335
|
+
dataset_kwargs = _compression.zarr_dataset_kwargs()
|
|
336
|
+
with _compression.numeric_only_compression("zarr"):
|
|
337
|
+
f = zarr.open_group(store, mode="w")
|
|
338
|
+
self._write_group(f, format=format, dataset_kwargs=dataset_kwargs)
|
|
339
|
+
|
|
340
|
+
@classmethod
|
|
341
|
+
def read_zarr(cls, store: Any) -> VCSCAnnData:
|
|
342
|
+
"""Read a store written by :meth:`write_zarr`."""
|
|
343
|
+
import zarr
|
|
344
|
+
|
|
345
|
+
f = zarr.open_group(store, mode="r")
|
|
346
|
+
return cls._read_group(f)
|