API reference¶
- class vsparse.VCSCArray(shape, major_ptr, values, value_ptr, indices)[source]¶
Bases:
_VCSBaseValue-Compressed Sparse Column array. Values are deduplicated per column.
- Parameters:
- property T: _VCSBase¶
shares buffers and swaps the VCSC/VCSR dual class.
- Type:
Transpose. Free
- astype(dtype, copy=True)¶
Cast the stored values to
dtype. Structural zeros stay zero implicitly.
- copy()¶
- count_nonzero()¶
Count of stored elements that are actually nonzero (unlike
nnz/getnnz).- Return type:
- classmethod from_scipy(mat)¶
Build from any scipy sparse array/matrix (converted internally).
- Return type:
_VCSBase
- getnnz(axis=None)¶
Count of stored elements along
axis, or overall ifNone.
- indices¶
- log1p()¶
Elementwise
log1p. Structural zeros stay zero implicitly.- Return type:
_VCSBase
- major_ptr¶
- max(axis=None)¶
Maximum value (including implicit zeros) along
axis, or overall ifNone.
- mean(axis=None)¶
Mean of (structural + implicit-zero) values along
axis, or overall ifNone.
- min(axis=None)¶
Minimum value (including implicit zeros) along
axis, or overall ifNone.
- multiply(other)¶
Elementwise multiplication (matches scipy’s sparse-array
.multiply).- Return type:
_VCSBase|ndarray
- normalized()¶
A read-depth-normalized, log-transformed, mean-centered view – see
vsparse._vcs_norm.- Return type:
- shape¶
- sum(axis=None)¶
Sum of (structural) values along
axis(0=rows, 1=columns), or overall ifNone.
- to_scipy()¶
Decompress to the equivalent scipy
csc_array/csr_array.
- transpose()¶
- Return type:
_VCSBase
- value_ptr¶
- values¶
- class vsparse.VCSRArray(shape, major_ptr, values, value_ptr, indices)[source]¶
Bases:
_VCSBaseValue-Compressed Sparse Row array. Values are deduplicated per row.
- Parameters:
- property T: _VCSBase¶
shares buffers and swaps the VCSC/VCSR dual class.
- Type:
Transpose. Free
- astype(dtype, copy=True)¶
Cast the stored values to
dtype. Structural zeros stay zero implicitly.
- copy()¶
- count_nonzero()¶
Count of stored elements that are actually nonzero (unlike
nnz/getnnz).- Return type:
- classmethod from_scipy(mat)¶
Build from any scipy sparse array/matrix (converted internally).
- Return type:
_VCSBase
- getnnz(axis=None)¶
Count of stored elements along
axis, or overall ifNone.
- indices¶
- log1p()¶
Elementwise
log1p. Structural zeros stay zero implicitly.- Return type:
_VCSBase
- major_ptr¶
- max(axis=None)¶
Maximum value (including implicit zeros) along
axis, or overall ifNone.
- mean(axis=None)¶
Mean of (structural + implicit-zero) values along
axis, or overall ifNone.
- min(axis=None)¶
Minimum value (including implicit zeros) along
axis, or overall ifNone.
- multiply(other)¶
Elementwise multiplication (matches scipy’s sparse-array
.multiply).- Return type:
_VCSBase|ndarray
- normalized()¶
A read-depth-normalized, log-transformed, mean-centered view – see
vsparse._vcs_norm.- Return type:
- shape¶
- sum(axis=None)¶
Sum of (structural) values along
axis(0=rows, 1=columns), or overall ifNone.
- to_scipy()¶
Decompress to the equivalent scipy
csc_array/csr_array.
- transpose()¶
- Return type:
_VCSBase
- value_ptr¶
- values¶
- vsparse.from_anndata(adata, layer=None, use_raw=False, format='csc')[source]¶
Convert
adata.X(or a layer /raw.X) into a VCSC/VCSR array.- Parameters:
- Return type:
_VCSBase- Returns:
- vsparse.to_layer(adata, arr, key)[source]¶
Decompress
arrand store it asadata.layers[key].AnnData does not natively understand the VCSC/VCSR layout, so this stores the equivalent scipy sparse array.
- vsparse.load_and_normalize(path, *, min_cell_counts=10.0, gene_threshold=0.0, min_cells=None, obs_filter=None, x_key='X')[source]¶
Load, filter, and depth-normalize a VCSR/IVCSR-backed
.h5adfile.Reproduces
parafac2.normalize.prepare_dataset: cells with total counts <=min_cell_countsand genes with total counts <=gene_threshold * n_cellsare dropped. Whenmin_cellsis given, genes expressed in fewer thanmin_cellscells are also dropped. Gene filters are measured on the raw counts after anyobs_filter. The remaining matrix is row-normalized to the median per-cell depth, then column-normalized by gene sum, then transformed aslog10(1000x + 1). Surrounding metadata (obs,var,obsm, etc.) is sliced to match the retained cells and genes.- Parameters:
path (
str|PathLike[str]) – Path to an.h5adfile whoseX(orlayers[x_key]) was written withformat="ivcsc"/"ivcsr"(seewrite_h5ad()).min_cell_counts (
float) – Cells with total raw counts <= this are dropped.gene_threshold (
float) – Minimum threshold fraction for gene inclusion, as inparafac2.normalize.prepare_dataset: genes with total raw counts <=gene_threshold * n_cellsare dropped.min_cells (
int|None) – Optional gene filter. Genes expressed in fewer than this many cells are dropped. Expression is defined as a raw count > 0.obs_filter (
Callable[[DataFrame],object] |None) – Optional callable receivingobsand returning a one-dimensional boolean mask. When provided, rows are subset before cell filtering, gene filtering, and normalization, so gene totals andgene_thresholdare computed using only the selected cells. The packed IVCSR stream is still read in full, but indices and values are materialized only for selected rows.x_key (
str) – Top-level h5ad group holding the IVCSR array ("X"by default).
- Returns:
Filtered, depth-normalized AnnData object with
Xas a CSR array and sliced metadata.- Return type:
Examples
Select cells using multiple
obscolumns and multiple accepted values:load_and_normalize( path, obs_filter=lambda obs: ( obs["condition"].isin(["control", "vehicle"]) & (obs["timepoint"] == "T3") ), )
- class vsparse.VCSCAnnData(X=None, *, raw_X=None, **kwargs)[source]¶
Bases:
AnnDataAn
AnnDatawhoseXis a VCSCArray/VCSRArray.Standard
AnnDatavalidates every array assigned toX/layers/etc. against a fixed allowlist of types (dense/sparse/ dask), so a plainAnnDatacannot hold aVCSCArraydirectly. This subclass overrides theXproperty to store one without going through that validation. A “raw” VCSC/VCSR matrix, if any, is kept as.raw_X– a plain attribute, not wired into anndata’s own.raw/Rawmachinery, which has the same restriction.Because of this, most operations that need anndata’s normal per-element type dispatch on
X– concatenation, most of scanpy/anndata’s ecosystem – are not supported whileXis VCSC/VCSR-backed. Callto_anndata()first to get a fully-featured, ordinaryAnnData. Indexing (adata[obs_idx, var_idx]) is supported (see__getitem__()), but always as an eager copy, not a lazy view – anndata’s view machinery bypasses theX/raw_Xoverrides here.Persist with
write_h5ad()/write_zarr()andread_h5ad()/read_zarr()(not the top-levelanndata.read_h5ad/read_zarr, which always reconstruct a plainAnnDataand would fail validating a VCSC-typedX).- Parameters:
X (_AnyVCS | None)
raw_X (_AnyVCS | None)
kwargs (Any)
- classmethod from_anndata(adata, format='csc', raw_format=None, *, include_raw=True)[source]¶
Build from a regular
AnnData, compressing X (and raw.X).- Return type:
- Parameters:
- write_h5ad(filename, *, format='vcsc', convert_strings_to_categoricals=True, dataset_kwargs=None, **_kwargs)[source]¶
Write to
.h5ad. Read back withread_h5ad().- Parameters:
format (
str) –"vcsc"(default) storesX/raw_Xwith plain int arrays for the minor-axis indices."ivcsc"(IVCSC/IVCSR) instead byte-packs them (delta + varint encoding) for a smaller file, at the cost of extra work on write/read. Either way,X/raw_Xcome back fromread_h5ad()as ordinary VCSCArray/VCSRArray objects –"ivcsc"is purely an on-disk storage format.convert_strings_to_categoricals (
bool) – Convertobs/varstring columns to categorical in place before writing, asanndata’s own writers do. Only columns with fewer categories than rows are converted.dataset_kwargs (
Mapping[str,Any] |None) – Passed toh5py.Group.create_datasetfor every array written. Defaults to Blosc2+LZ4 compression; pass{}to store uncompressed. Either way, compression is only ever applied to numeric arrays – seevsparse._compression.numeric_only_compression()._kwargs (Any)
- Return type:
- classmethod read_h5ad(filename)[source]¶
Read a file written by
write_h5ad().- Return type:
- Parameters:
- write_zarr(store, *, format='vcsc', convert_strings_to_categoricals=True, dataset_kwargs=None, **_kwargs)[source]¶
Write to a zarr store. Read back with
read_zarr().See
write_h5ad()forformat/convert_strings_to_categoricals/dataset_kwargs(including the numeric-only compression behavior); the default compression here is Blosc+LZ4 vianumcodecs.
- classmethod read_zarr(store)[source]¶
Read a store written by
write_zarr().- Return type:
- Parameters:
store (Any)