vsparse 0.1.0__tar.gz

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-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,175 @@
1
+ Metadata-Version: 2.4
2
+ Name: vsparse
3
+ Version: 0.1.0
4
+ Summary: Value-Compressed Sparse Column/Row (VCSC/VCSR) arrays, with optional AnnData integration
5
+ Keywords: anndata,single-cell,sparse,compression
6
+ Author: Aaron Meyer
7
+ Author-email: Aaron Meyer <git@ameyer.me>
8
+ License-Expression: MIT
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Requires-Dist: numpy>=2.0
15
+ Requires-Dist: scipy>=1.12
16
+ Requires-Dist: numba>=0.60
17
+ Requires-Dist: anndata>=0.13
18
+ Requires-Dist: hdf5plugin>=4.0
19
+ Requires-Dist: sphinx>=7.0 ; extra == 'docs'
20
+ Requires-Dist: furo>=2024.1.29 ; extra == 'docs'
21
+ Requires-Dist: myst-parser>=3.0 ; extra == 'docs'
22
+ Requires-Dist: sphinx-autodoc-typehints>=2.0 ; extra == 'docs'
23
+ Requires-Python: >=3.12
24
+ Project-URL: Homepage, https://meyer-lab.github.io/vsparse/
25
+ Project-URL: Repository, https://github.com/meyer-lab/vsparse
26
+ Project-URL: Documentation, https://meyer-lab.github.io/vsparse/
27
+ Project-URL: Issues, https://github.com/meyer-lab/vsparse/issues
28
+ Provides-Extra: docs
29
+ Description-Content-Type: text/markdown
30
+
31
+ # vsparse
32
+
33
+ `vsparse` provides `VCSCArray`/`VCSRArray`: Value-Compressed Sparse Column/Row (VCSC/VCSR)
34
+ array types, implemented in NumPy and accelerated with [Numba](https://numba.pydata.org/). The
35
+ array types are standalone -- they can be built from and converted to SciPy sparse arrays and
36
+ used entirely without [AnnData](https://anndata.readthedocs.io). `vsparse` also ships an
37
+ optional AnnData integration (`from_anndata`, `to_layer`, and the `VCSCAnnData` subclass) for
38
+ projects that want compressed arrays backed directly into an `AnnData` object.
39
+
40
+ VCSC/VCSR are compressed-sparse layouts inspired by
41
+ [IVSparse's VCSC](https://github.com/Seth-Wolfgang/IVSparse). In addition to the usual
42
+ compressed-sparse pointer/index arrays, nonzero values within each major-axis slice
43
+ (columns for VCSC, rows for VCSR) are deduplicated: each unique value is stored once,
44
+ alongside the list of minor-axis positions that share it. This is a strict memory win
45
+ whenever values repeat heavily within a slice — as is typical for integer count
46
+ matrices, e.g. single-cell RNA-seq counts.
47
+
48
+ ## Install
49
+
50
+ Install from source or via package manager:
51
+
52
+ ```sh
53
+ pip install git+https://github.com/meyer-lab/vsparse.git
54
+ # or with uv
55
+ uv add git+https://github.com/meyer-lab/vsparse.git
56
+ ```
57
+
58
+ For local development:
59
+
60
+ ```sh
61
+ git clone https://github.com/meyer-lab/vsparse.git
62
+ cd vsparse
63
+ uv sync --all-extras --dev
64
+ ```
65
+
66
+ ## Quickstart
67
+
68
+ ### Working with VCSC / VCSR arrays
69
+
70
+ `VCSCArray`/`VCSRArray` are standalone array types -- they only need a SciPy sparse array
71
+ (or an AnnData object, if you have one) to be built, and none of the operations below require
72
+ AnnData at all:
73
+
74
+ ```python
75
+ import vsparse
76
+ import scipy.sparse as sp
77
+
78
+ # Build directly from a SciPy sparse array -- no AnnData involved
79
+ csc = sp.random(1000, 500, density=0.1, format="csc")
80
+ v = vsparse.VCSCArray.from_scipy(csc)
81
+
82
+ # Or build from an AnnData object or SciPy sparse array
83
+ adata = ... # an AnnData object
84
+ v = vsparse.from_anndata(adata) # VCSCArray (column-compressed) from adata.X
85
+ vr = vsparse.from_anndata(adata, format="csr") # VCSRArray (row-compressed)
86
+
87
+ # Transposition is zero-copy (swaps major/minor axes and shares buffers)
88
+ vr = v.T # VCSRArray
89
+
90
+ # Scalar arithmetic & math
91
+ v2 = v * 2.0 # Scalar multiplication
92
+ v_div = v / 2.0 # Scalar division
93
+ v_neg = -v # Negation
94
+ v_log = v.log1p() # Elementwise log1p
95
+
96
+ # Matrix & vector products (Numba-parallelized)
97
+ y = v @ x # Matrix-vector: (n_rows, n_cols) @ (n_cols,) -> (n_rows,)
98
+ y_left = x @ v # Vector-matrix: (n_rows,) @ (n_rows, n_cols) -> (n_cols,)
99
+ Y = v @ B # Matrix-matrix: (n_rows, n_cols) @ (n_cols, k) -> (n_rows, k)
100
+ Y_left = B @ v # Matrix-matrix: (k, n_rows) @ (n_rows, n_cols) -> (k, n_cols)
101
+
102
+ # Slicing
103
+ col_slice = v[:, [1, 3, 5]] # Fast major-axis slicing (returns VCSCArray)
104
+ sub = v[0:10, 0:10] # 2D slicing (falls back to scipy)
105
+
106
+ # Conversion & layers
107
+ sp_csc = v.to_scipy() # -> scipy.sparse.csc_array (or to_csr())
108
+ dense = v.toarray() # -> numpy.ndarray
109
+ vsparse.to_layer(adata, v, key="counts_vcsc") # Attach to AnnData layer
110
+ ```
111
+
112
+ ### `VCSCAnnData`: AnnData with direct VCSC/VCSR backing
113
+
114
+ For projects that want the compressed array wired directly into AnnData, `vsparse.VCSCAnnData`
115
+ is an `AnnData` subclass whose `X` (and optionally `raw_X`) is backed directly by a
116
+ `VCSCArray` or `VCSRArray`:
117
+
118
+ ```python
119
+ import vsparse
120
+
121
+ va = vsparse.VCSCAnnData.from_anndata(adata) # Compresses X and raw.X
122
+ va.X # VCSCArray
123
+ va.raw_X # VCSCArray (separate from anndata's .raw)
124
+
125
+ # Persist to HDF5 (.h5ad) or Zarr with default Blosc2+LZ4 compression
126
+ va.write_h5ad("compressed.h5ad") # Read back with VCSCAnnData.read_h5ad
127
+ va2 = vsparse.VCSCAnnData.read_h5ad("compressed.h5ad")
128
+
129
+ va.write_zarr("compressed.zarr") # Read back with VCSCAnnData.read_zarr
130
+ va3 = vsparse.VCSCAnnData.read_zarr("compressed.zarr")
131
+
132
+ # Escape hatch back to standard AnnData
133
+ plain = va.to_anndata()
134
+ ```
135
+
136
+ ### Byte-Packed On-Disk Format (IVCSC / IVCSR)
137
+
138
+ For smaller files, pass `format="ivcsc"` (or `"ivcsr"`) on write. This byte-packs the minor-axis indices with delta + varint encoding (inspired by [IVSparse's IVCSC](https://github.com/Seth-Wolfgang/IVSparse)).
139
+
140
+ It is purely an archival storage format: `read_h5ad` / `read_zarr` decompress the indices on load and return a standard `VCSCArray`/`VCSRArray`.
141
+
142
+ ```python
143
+ # Write delta+varint byte-packed indices
144
+ va.write_h5ad("archived.h5ad", format="ivcsc")
145
+
146
+ # Reads back directly as an ordinary VCSCAnnData
147
+ va_loaded = vsparse.VCSCAnnData.read_h5ad("archived.h5ad")
148
+ ```
149
+
150
+ ### Fast Filtering & Depth Normalization (`load_and_normalize`)
151
+
152
+ For IVCSR-backed datasets, `vsparse.load_and_normalize` bypasses full array decompression for rapid preprocessing, reproducing the filtering and depth normalization from `parafac2.normalize.prepare_dataset`:
153
+
154
+ - **Cell filtering without decoding**: Computes cell totals in $O(n_{\text{unique}})$ time directly from group sizes without unpacking varint indices.
155
+ - **Fused filter & normalization**: Performs gene filtering, cell/gene depth-scaling, and $\log_{10}(1000x + 1)$ transform in parallel passes over the compact CSR representation.
156
+
157
+ ```python
158
+ adata_norm = vsparse.load_and_normalize(
159
+ "archived.h5ad",
160
+ min_cell_counts=10.0, # Filter cells with counts <= 10
161
+ gene_threshold=0.05, # Filter genes with counts <= 0.05 * n_cells
162
+ )
163
+ ```
164
+
165
+ See `docs/` for full usage guides and API documentation.
166
+
167
+ ## Development
168
+
169
+ ```sh
170
+ uv sync --all-extras --dev
171
+ uv run pytest
172
+ uv run ruff check .
173
+ uv run ty check
174
+ uv run sphinx-build -b html docs docs/_build/html
175
+ ```
@@ -0,0 +1,145 @@
1
+ # vsparse
2
+
3
+ `vsparse` provides `VCSCArray`/`VCSRArray`: Value-Compressed Sparse Column/Row (VCSC/VCSR)
4
+ array types, implemented in NumPy and accelerated with [Numba](https://numba.pydata.org/). The
5
+ array types are standalone -- they can be built from and converted to SciPy sparse arrays and
6
+ used entirely without [AnnData](https://anndata.readthedocs.io). `vsparse` also ships an
7
+ optional AnnData integration (`from_anndata`, `to_layer`, and the `VCSCAnnData` subclass) for
8
+ projects that want compressed arrays backed directly into an `AnnData` object.
9
+
10
+ VCSC/VCSR are compressed-sparse layouts inspired by
11
+ [IVSparse's VCSC](https://github.com/Seth-Wolfgang/IVSparse). In addition to the usual
12
+ compressed-sparse pointer/index arrays, nonzero values within each major-axis slice
13
+ (columns for VCSC, rows for VCSR) are deduplicated: each unique value is stored once,
14
+ alongside the list of minor-axis positions that share it. This is a strict memory win
15
+ whenever values repeat heavily within a slice — as is typical for integer count
16
+ matrices, e.g. single-cell RNA-seq counts.
17
+
18
+ ## Install
19
+
20
+ Install from source or via package manager:
21
+
22
+ ```sh
23
+ pip install git+https://github.com/meyer-lab/vsparse.git
24
+ # or with uv
25
+ uv add git+https://github.com/meyer-lab/vsparse.git
26
+ ```
27
+
28
+ For local development:
29
+
30
+ ```sh
31
+ git clone https://github.com/meyer-lab/vsparse.git
32
+ cd vsparse
33
+ uv sync --all-extras --dev
34
+ ```
35
+
36
+ ## Quickstart
37
+
38
+ ### Working with VCSC / VCSR arrays
39
+
40
+ `VCSCArray`/`VCSRArray` are standalone array types -- they only need a SciPy sparse array
41
+ (or an AnnData object, if you have one) to be built, and none of the operations below require
42
+ AnnData at all:
43
+
44
+ ```python
45
+ import vsparse
46
+ import scipy.sparse as sp
47
+
48
+ # Build directly from a SciPy sparse array -- no AnnData involved
49
+ csc = sp.random(1000, 500, density=0.1, format="csc")
50
+ v = vsparse.VCSCArray.from_scipy(csc)
51
+
52
+ # Or build from an AnnData object or SciPy sparse array
53
+ adata = ... # an AnnData object
54
+ v = vsparse.from_anndata(adata) # VCSCArray (column-compressed) from adata.X
55
+ vr = vsparse.from_anndata(adata, format="csr") # VCSRArray (row-compressed)
56
+
57
+ # Transposition is zero-copy (swaps major/minor axes and shares buffers)
58
+ vr = v.T # VCSRArray
59
+
60
+ # Scalar arithmetic & math
61
+ v2 = v * 2.0 # Scalar multiplication
62
+ v_div = v / 2.0 # Scalar division
63
+ v_neg = -v # Negation
64
+ v_log = v.log1p() # Elementwise log1p
65
+
66
+ # Matrix & vector products (Numba-parallelized)
67
+ y = v @ x # Matrix-vector: (n_rows, n_cols) @ (n_cols,) -> (n_rows,)
68
+ y_left = x @ v # Vector-matrix: (n_rows,) @ (n_rows, n_cols) -> (n_cols,)
69
+ Y = v @ B # Matrix-matrix: (n_rows, n_cols) @ (n_cols, k) -> (n_rows, k)
70
+ Y_left = B @ v # Matrix-matrix: (k, n_rows) @ (n_rows, n_cols) -> (k, n_cols)
71
+
72
+ # Slicing
73
+ col_slice = v[:, [1, 3, 5]] # Fast major-axis slicing (returns VCSCArray)
74
+ sub = v[0:10, 0:10] # 2D slicing (falls back to scipy)
75
+
76
+ # Conversion & layers
77
+ sp_csc = v.to_scipy() # -> scipy.sparse.csc_array (or to_csr())
78
+ dense = v.toarray() # -> numpy.ndarray
79
+ vsparse.to_layer(adata, v, key="counts_vcsc") # Attach to AnnData layer
80
+ ```
81
+
82
+ ### `VCSCAnnData`: AnnData with direct VCSC/VCSR backing
83
+
84
+ For projects that want the compressed array wired directly into AnnData, `vsparse.VCSCAnnData`
85
+ is an `AnnData` subclass whose `X` (and optionally `raw_X`) is backed directly by a
86
+ `VCSCArray` or `VCSRArray`:
87
+
88
+ ```python
89
+ import vsparse
90
+
91
+ va = vsparse.VCSCAnnData.from_anndata(adata) # Compresses X and raw.X
92
+ va.X # VCSCArray
93
+ va.raw_X # VCSCArray (separate from anndata's .raw)
94
+
95
+ # Persist to HDF5 (.h5ad) or Zarr with default Blosc2+LZ4 compression
96
+ va.write_h5ad("compressed.h5ad") # Read back with VCSCAnnData.read_h5ad
97
+ va2 = vsparse.VCSCAnnData.read_h5ad("compressed.h5ad")
98
+
99
+ va.write_zarr("compressed.zarr") # Read back with VCSCAnnData.read_zarr
100
+ va3 = vsparse.VCSCAnnData.read_zarr("compressed.zarr")
101
+
102
+ # Escape hatch back to standard AnnData
103
+ plain = va.to_anndata()
104
+ ```
105
+
106
+ ### Byte-Packed On-Disk Format (IVCSC / IVCSR)
107
+
108
+ For smaller files, pass `format="ivcsc"` (or `"ivcsr"`) on write. This byte-packs the minor-axis indices with delta + varint encoding (inspired by [IVSparse's IVCSC](https://github.com/Seth-Wolfgang/IVSparse)).
109
+
110
+ It is purely an archival storage format: `read_h5ad` / `read_zarr` decompress the indices on load and return a standard `VCSCArray`/`VCSRArray`.
111
+
112
+ ```python
113
+ # Write delta+varint byte-packed indices
114
+ va.write_h5ad("archived.h5ad", format="ivcsc")
115
+
116
+ # Reads back directly as an ordinary VCSCAnnData
117
+ va_loaded = vsparse.VCSCAnnData.read_h5ad("archived.h5ad")
118
+ ```
119
+
120
+ ### Fast Filtering & Depth Normalization (`load_and_normalize`)
121
+
122
+ For IVCSR-backed datasets, `vsparse.load_and_normalize` bypasses full array decompression for rapid preprocessing, reproducing the filtering and depth normalization from `parafac2.normalize.prepare_dataset`:
123
+
124
+ - **Cell filtering without decoding**: Computes cell totals in $O(n_{\text{unique}})$ time directly from group sizes without unpacking varint indices.
125
+ - **Fused filter & normalization**: Performs gene filtering, cell/gene depth-scaling, and $\log_{10}(1000x + 1)$ transform in parallel passes over the compact CSR representation.
126
+
127
+ ```python
128
+ adata_norm = vsparse.load_and_normalize(
129
+ "archived.h5ad",
130
+ min_cell_counts=10.0, # Filter cells with counts <= 10
131
+ gene_threshold=0.05, # Filter genes with counts <= 0.05 * n_cells
132
+ )
133
+ ```
134
+
135
+ See `docs/` for full usage guides and API documentation.
136
+
137
+ ## Development
138
+
139
+ ```sh
140
+ uv sync --all-extras --dev
141
+ uv run pytest
142
+ uv run ruff check .
143
+ uv run ty check
144
+ uv run sphinx-build -b html docs docs/_build/html
145
+ ```
@@ -0,0 +1,86 @@
1
+ [project]
2
+ name = "vsparse"
3
+ version = "0.1.0"
4
+ description = "Value-Compressed Sparse Column/Row (VCSC/VCSR) arrays, with optional AnnData integration"
5
+ readme = "README.md"
6
+ requires-python = ">=3.12"
7
+ license = "MIT"
8
+ keywords = [
9
+ "anndata",
10
+ "single-cell",
11
+ "sparse",
12
+ "compression",
13
+ ]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Intended Audience :: Science/Research",
17
+ "Topic :: Scientific/Engineering :: Bio-Informatics",
18
+ "Programming Language :: Python :: 3.12",
19
+ "Programming Language :: Python :: 3.13",
20
+ ]
21
+ dependencies = [
22
+ "numpy>=2.0",
23
+ "scipy>=1.12",
24
+ "numba>=0.60",
25
+ "anndata>=0.13",
26
+ "hdf5plugin>=4.0",
27
+ ]
28
+
29
+ [[project.authors]]
30
+ name = "Aaron Meyer"
31
+ email = "git@ameyer.me"
32
+
33
+ [project.urls]
34
+ Homepage = "https://meyer-lab.github.io/vsparse/"
35
+ Repository = "https://github.com/meyer-lab/vsparse"
36
+ Documentation = "https://meyer-lab.github.io/vsparse/"
37
+ Issues = "https://github.com/meyer-lab/vsparse/issues"
38
+
39
+ [project.optional-dependencies]
40
+ docs = [
41
+ "sphinx>=7.0",
42
+ "furo>=2024.1.29",
43
+ "myst-parser>=3.0",
44
+ "sphinx-autodoc-typehints>=2.0",
45
+ ]
46
+
47
+ [dependency-groups]
48
+ dev = [
49
+ "pytest>=8.0",
50
+ "pytest-cov>=5.0",
51
+ "ruff>=0.6",
52
+ "ty>=0.0.1a1",
53
+ ]
54
+
55
+ [build-system]
56
+ requires = ["uv_build>=0.12.3,<0.13.0"]
57
+ build-backend = "uv_build"
58
+
59
+ [tool.ruff]
60
+ line-length = 100
61
+ target-version = "py312"
62
+
63
+ [tool.ruff.lint]
64
+ select = [
65
+ "E",
66
+ "F",
67
+ "I",
68
+ "UP",
69
+ "B",
70
+ "NPY",
71
+ "RUF",
72
+ ]
73
+ ignore = ["E501"]
74
+
75
+ [tool.ruff.lint.isort]
76
+ known-first-party = ["vsparse"]
77
+
78
+ [tool.ty.environment]
79
+ python-version = "3.12"
80
+
81
+ [tool.pytest.ini_options]
82
+ testpaths = ["tests"]
83
+ addopts = "-ra"
84
+
85
+ [tool.coverage.run]
86
+ source = ["src/vsparse"]
@@ -0,0 +1,72 @@
1
+ [project]
2
+ name = "vsparse"
3
+ version = "0.1.0"
4
+ description = "Value-Compressed Sparse Column/Row (VCSC/VCSR) arrays, with optional AnnData integration"
5
+ readme = "README.md"
6
+ authors = [
7
+ { name = "Aaron Meyer", email = "git@ameyer.me" }
8
+ ]
9
+ requires-python = ">=3.12"
10
+ license = "MIT"
11
+ keywords = ["anndata", "single-cell", "sparse", "compression"]
12
+ classifiers = [
13
+ "Development Status :: 3 - Alpha",
14
+ "Intended Audience :: Science/Research",
15
+ "Topic :: Scientific/Engineering :: Bio-Informatics",
16
+ "Programming Language :: Python :: 3.12",
17
+ "Programming Language :: Python :: 3.13",
18
+ ]
19
+ dependencies = [
20
+ "numpy>=2.0",
21
+ "scipy>=1.12",
22
+ "numba>=0.60",
23
+ "anndata>=0.13",
24
+ "hdf5plugin>=4.0",
25
+ ]
26
+
27
+ [project.urls]
28
+ Homepage = "https://meyer-lab.github.io/vsparse/"
29
+ Repository = "https://github.com/meyer-lab/vsparse"
30
+ Documentation = "https://meyer-lab.github.io/vsparse/"
31
+ Issues = "https://github.com/meyer-lab/vsparse/issues"
32
+
33
+ [project.optional-dependencies]
34
+ docs = [
35
+ "sphinx>=7.0",
36
+ "furo>=2024.1.29",
37
+ "myst-parser>=3.0",
38
+ "sphinx-autodoc-typehints>=2.0",
39
+ ]
40
+
41
+ [dependency-groups]
42
+ dev = [
43
+ "pytest>=8.0",
44
+ "pytest-cov>=5.0",
45
+ "ruff>=0.6",
46
+ "ty>=0.0.1a1",
47
+ ]
48
+
49
+ [build-system]
50
+ requires = ["uv_build>=0.12.3,<0.13.0"]
51
+ build-backend = "uv_build"
52
+
53
+ [tool.ruff]
54
+ line-length = 100
55
+ target-version = "py312"
56
+
57
+ [tool.ruff.lint]
58
+ select = ["E", "F", "I", "UP", "B", "NPY", "RUF"]
59
+ ignore = ["E501"]
60
+
61
+ [tool.ruff.lint.isort]
62
+ known-first-party = ["vsparse"]
63
+
64
+ [tool.ty.environment]
65
+ python-version = "3.12"
66
+
67
+ [tool.pytest.ini_options]
68
+ testpaths = ["tests"]
69
+ addopts = "-ra"
70
+
71
+ [tool.coverage.run]
72
+ source = ["src/vsparse"]
@@ -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"
@@ -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()