Core¶
The experiment classes and the objects they hand around.
Single-cell streaming for Python, in Rust.
Opens a bixverse binary sparse store and yields minibatches fast enough to keep a GPU training loop fed. The decode never leaves Rust: a feeder thread decompresses and materialises batches ahead of the consumer, releasing the GIL while it works.
>>> import bixverse as bv
>>> reader = bv.CellReader("counts.bin")
>>> loader = bv.CellLoader(reader, batch_size=256, layer="norm")
>>> for batch in loader:
... x = batch.scipy_csr()
Batches are sparse CSR by default. Pass sparse=False for a dense
(batch_size, n_genes) array, and expect it to cost a zero-fill and a
scatter over every gene whether or not it holds a count.
SingleCells
¶
Bases: ScBase
A single cell experiment on disk.
The constructor rebuilds the map from the DuckDB (ids from obs / var,
the cell filter from to_keep) with an empty cache, which is what
load_existing() does when no memory file is present. Use
bixverse.io.load_existing to also restore a saved cache.
>>> import bixverse as bv
>>> sc = bv.io.load_existing("my_experiment")
>>> sc.obs(filtered=True)
>>> counts = bv.get_counts(sc, genes=["CD3E", "MS4A1"])
Attributes:
| Name | Type | Description |
|---|---|---|
dir |
The experiment directory. |
|
map |
Ids and index sets. |
|
cache |
Analysis results held in memory. |
Open an experiment directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory
|
Path | str
|
Holds |
required |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If either is missing. |
ValueError
|
If the obs / var tables disagree with the store, or the cell and gene files do not belong to one store. |
obs
¶
obs(
*,
indices: ndarray | Sequence[int] | None = None,
cols: list[str] | None = None,
filtered: bool = False,
) -> DataFrame
The obs table, cell_idx 0-based.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
indices
|
ndarray | Sequence[int] | None
|
Optional 0-based cell indices. |
None
|
cols
|
list[str] | None
|
Optional columns. |
None
|
filtered
|
bool
|
Only the kept cells. |
False
|
var
¶
var(
*,
indices: ndarray | Sequence[int] | None = None,
cols: list[str] | None = None,
) -> DataFrame
The var table, gene_idx 0-based.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
indices
|
ndarray | Sequence[int] | None
|
Optional 0-based gene indices. |
None
|
cols
|
list[str] | None
|
Optional columns. |
None
|
add_obs
¶
Add or replace obs columns.
With a 0-based cell_idx column the frame joins on it. Without one it
must hold one row per kept cell, in ascending cell order. Cells the
frame does not cover get NULL; replacing a column that way warns when
it discards values.
add_var
¶
Add or replace var columns: one row per gene, or a 0-based gene_idx.
drop_obs_cols
¶
Drop obs columns. Protected and missing ones warn and are skipped.
drop_var_cols
¶
Drop var columns. Protected and missing ones warn and are skipped.
rename_obs_col
¶
Rename an obs column. A missing one warns.
rename_var_col
¶
Rename a var column. A missing one warns.
set_cells_to_keep
¶
Restrict the experiment to a set of cells.
Updates the map and the to_keep column. The cells are stored unique
and ascending; results align to that order, not the order given.
Anything cached was computed on the old cell set; it is kept, not
deleted, and a warning names what went stale.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cells
|
Selection
|
0-based store indices or cell ids. |
required |
reset_cells_to_keep
¶
Restore every cell, clearing the HVG selection and the cache.
A PCA or kNN computed on a subset does not describe the full cell
set, so nothing cached survives. A populated cache
needs force=True.
Raises:
| Type | Description |
|---|---|
ValueError
|
If something would be dropped and |
SingleCellsSubset
¶
SingleCellsSubset(
sc: SingleCells, grouping_column: str, group: str
)
Bases: ScBase
The cells of one level of an obs column.
Integer cell selections are 0-based store indices, as on the parent, and must belong to the subset; cell ids are matched against the subset's cells only.
Attributes:
| Name | Type | Description |
|---|---|---|
dir |
The parent's directory; the stores are shared. |
|
map |
Ids (the parent's) and index sets restricted to the subset. |
|
cache |
The subset's own analysis results. |
|
grouping_column |
The obs column the subset was cut on. |
|
group |
The level of |
|
subset_to_original |
0-based store index of each subset obs row. |
Cut the kept cells of sc whose grouping_column equals group.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sc
|
SingleCells
|
The parent experiment. |
required |
grouping_column
|
str
|
obs column defining the groups. |
required |
group
|
str
|
The level to keep, cast to the column's type. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If |
ValueError
|
If no kept cell carries the level. |
cell_ids
¶
Cell ids: the subset's in obs order, kept only in cells_to_keep
order, or for 0-based store indices.
cell_indices
¶
0-based store indices of subset cells by id. Ids outside the subset warn and drop.
obs
¶
obs(
*,
indices: ndarray | Sequence[int] | None = None,
cols: list[str] | None = None,
filtered: bool = False,
) -> DataFrame
The subset's obs, cell_idx the 0-based store index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
indices
|
ndarray | Sequence[int] | None
|
Optional 0-based row positions within the subset. |
None
|
cols
|
list[str] | None
|
Optional columns. |
None
|
filtered
|
bool
|
Accepted for parity with |
False
|
Raises:
| Type | Description |
|---|---|
KeyError
|
If a column is not in obs. |
var
¶
var(
*,
indices: ndarray | Sequence[int] | None = None,
cols: list[str] | None = None,
) -> DataFrame
The parent's var as it was when the subset was cut, gene_idx
0-based.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
indices
|
ndarray | Sequence[int] | None
|
Optional 0-based gene indices. |
None
|
cols
|
list[str] | None
|
Optional columns. |
None
|
Raises:
| Type | Description |
|---|---|
KeyError
|
If a column is not in var. |
add_obs
¶
Add or replace columns of the in-memory obs.
With a 0-based cell_idx column the frame joins on it. Without one
it must hold one row per obs row, in obs (ascending cell) order.
Subset cells the frame does not cover get NULL.
Raises:
| Type | Description |
|---|---|
ValueError
|
On a wrong row count, a |
SingleCellsMultiModal
¶
Bases: SingleCells
A single cell experiment with RNA plus ADT and / or ATAC.
>>> import bixverse as bv
>>> mm = bv.SingleCellsMultiModal("my_experiment")
>>> bv.mm.add_adt_counts(mm, adt, barcodes, proteins, method="clr")
>>> bv.mm.calculate_pca_adt(mm, no_pcs=10)
>>> bv.mm.generate_wnn_graph(mm)
>>> bv.graph.find_clusters(mm, modality="wnn")
Attributes:
| Name | Type | Description |
|---|---|---|
dir |
The experiment directory. |
|
map |
Ids and index sets. |
|
cache |
The RNA cache. |
|
adt |
AdtCounts | None
|
The ADT counts, once added. |
adt_cache |
The ADT cache. |
|
atac |
AtacInfo | None
|
The ATAC store state, once added. |
atac_cache |
The ATAC cache. |
|
wnn |
WnnSlot | None
|
The WNN integration, once generated. |
Open an experiment directory, its ATAC store included when present.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory
|
Path | str
|
Holds |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the root store holds peaks or tiles: that is an
ATAC-only experiment, a |
set_cells_to_keep
¶
Restrict the experiment to a set of cells, gene activity included.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cells
|
Selection
|
0-based store indices or cell ids. |
required |
reset_cells_to_keep
¶
Restore every cell, gene activity included; see SingleCells.
modality_cache
¶
modality_cache(modality: Modality) -> ScCache
The cache of a modality.
Raises:
| Type | Description |
|---|---|
ValueError
|
For |
stamp
¶
stamp(
artefact: str,
*,
parents: Sequence[str] = (),
modality: Modality = "rna",
) -> Stamp
Stamp a cached artefact of a modality against the current cell set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
artefact
|
str
|
|
required |
parents
|
Sequence[str]
|
Labels of the artefacts it was derived from; unqualified
ones are taken from |
()
|
modality
|
Modality
|
The cache the artefact sits in. |
'rna'
|
Raises:
| Type | Description |
|---|---|
KeyError
|
If no artefact sits under the label. |
check_state
¶
True if the artefacts are fresh, else what is stale and why.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
artefacts
|
Sequence[str]
|
Labels, unqualified ones taken from |
required |
modality
|
Modality
|
The modality to qualify against. |
'rna'
|
cache_status
¶
One row per cached artefact over all modalities.
Returns:
| Type | Description |
|---|---|
DataFrame
|
As |
DataFrame
|
|
var
¶
var(
*,
indices: ndarray | Sequence[int] | None = None,
cols: list[str] | None = None,
modality: CacheModality = "rna",
) -> DataFrame
The var table of a modality, gene_idx / feature_idx 0-based.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
indices
|
ndarray | Sequence[int] | None
|
Optional 0-based gene or feature indices. |
None
|
cols
|
list[str] | None
|
Optional columns. |
None
|
modality
|
CacheModality
|
|
'rna'
|
Raises:
| Type | Description |
|---|---|
TableNotFoundError
|
Before the modality was added. |
SingleCellsAtac
¶
Bases: SingleCells
A single cell ATAC experiment on disk: peaks or tiles, no RNA.
>>> import bixverse as bv
>>> x = bv.io.load_atac_fragments(
... "exp", "fragments.tsv.gz", peaks="peaks.bed", min_fragments=1000
... )
>>> bv.atac.fragment_qc(x, "fragments.tsv.gz", "genes.gtf.gz")
>>> bv.atac.run_tfidf(x)
>>> bv.atac.calculate_lsi(x)
>>> bv.graph.find_neighbours(x, embd_to_use="lsi", modality="atac")
modality="atac" and the default "rna" both name this object's own
store and cache, so code written for the ATAC side of a
SingleCellsMultiModal runs unchanged.
Attributes:
| Name | Type | Description |
|---|---|---|
dir |
The experiment directory. |
|
map |
Ids (cell barcodes, region ids) and index sets. |
|
cache |
The ATAC cache; also |
|
atac |
AtacInfo
|
The ATAC store state. |
Open an ATAC experiment directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory
|
Path | str
|
Holds |
required |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If either is missing. |
ValueError
|
If the store holds neither peaks nor tiles. |
atac_cache
property
writable
¶
atac_cache: ScCache
The ATAC cache, which is this object's only cache.
modality_cache
¶
modality_cache(modality: str) -> ScCache
The cache: "rna" and "atac" both name it.
Raises:
| Type | Description |
|---|---|
ValueError
|
For any other modality. |
var
¶
var(
*,
indices: ndarray | Sequence[int] | None = None,
cols: list[str] | None = None,
modality: Literal["rna", "atac"] = "rna",
) -> DataFrame
The var table; with "atac" keyed feature_idx / feature_id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
indices
|
ndarray | Sequence[int] | None
|
Optional 0-based feature indices. |
None
|
cols
|
list[str] | None
|
Optional columns. |
None
|
modality
|
Literal['rna', 'atac']
|
|
'rna'
|
set_cells_to_keep
¶
Restrict the experiment to a set of cells, gene activity included.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cells
|
Selection
|
0-based store indices or cell ids. |
required |
reset_cells_to_keep
¶
Restore every cell, gene activity included; see SingleCells.
MetaCells
¶
MetaCells(
obs: DataFrame,
var: DataFrame,
raw: CsrMatrix,
norm: CsrMatrix,
original_assignment: MetaCellAssignment,
meta_cell_method: str,
*,
other_data: dict[str, object] | None = None,
is_merged: bool = False,
)
Meta cells in memory.
Built by the generators in bixverse.metacells and by
merge_meta_cells, not by hand.
>>> import bixverse as bv
>>> mc = bv.metacells.generate_bt_meta_cells(sc)
>>> bv.pp.find_hvg(mc, hvg_no=2000)
>>> bv.pp.calculate_pca(mc, 30)
>>> bv.graph.find_neighbours(mc)
Attributes:
| Name | Type | Description |
|---|---|---|
raw |
Summed raw counts, meta cells x genes, CSR. |
|
norm |
The counts normalised to the target size and |
|
cache |
Analysis results. |
|
hvg |
ndarray | None
|
0-based gene indices of the highly variable genes, if selected. |
original_assignment |
Provenance of the meta cells. |
|
other_data |
dict[str, object]
|
Method-specific extras (SEACells |
meta_cell_method |
The generator. |
|
is_merged |
Built by |
Assemble a meta cell object; the generators and the loader call it.
Raises:
| Type | Description |
|---|---|
ValueError
|
If the tables and matrices disagree. |
gene_ids
¶
Gene ids, all or for 0-based gene indices.
cell_indices
¶
0-based rows of meta cells by id. Unknown ids warn and drop.
gene_indices
¶
0-based gene indices by id. Unknown ids warn and drop.
obs
¶
obs(
*,
indices: ndarray | Sequence[int] | None = None,
cols: list[str] | None = None,
filtered: bool = False,
) -> DataFrame
The meta cell obs table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
indices
|
ndarray | Sequence[int] | None
|
Optional 0-based rows. |
None
|
cols
|
list[str] | None
|
Optional columns. |
None
|
filtered
|
bool
|
Ignored; meta cells have no cell filter. |
False
|
Raises:
| Type | Description |
|---|---|
KeyError
|
If a column is not in obs. |
var
¶
var(
*,
indices: ndarray | Sequence[int] | None = None,
cols: list[str] | None = None,
) -> DataFrame
The var table.
Raises:
| Type | Description |
|---|---|
KeyError
|
If a column is not in var. |
add_obs
¶
Add or replace obs columns.
With a 0-based meta_cell_idx column the frame joins on it, other
meta cells get NULL. Without one it must hold one row per meta cell,
in row order.
Raises:
| Type | Description |
|---|---|
ValueError
|
On a wrong row count or a protected column. |
add_var
¶
Add or replace var columns: one row per gene, in var order.
Raises:
| Type | Description |
|---|---|
ValueError
|
On a wrong row count or a protected column. |
counts
¶
counts(
*,
cells: ndarray
| Sequence[int]
| Sequence[str]
| None = None,
genes: ndarray
| Sequence[int]
| Sequence[str]
| None = None,
layer: str = "raw",
) -> CsrMatrix
The counts, optionally restricted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cells
|
ndarray | Sequence[int] | Sequence[str] | None
|
0-based rows or meta cell ids, in the row order wanted. |
None
|
genes
|
ndarray | Sequence[int] | Sequence[str] | None
|
0-based gene indices or ids, in the column order wanted. |
None
|
layer
|
str
|
|
'raw'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
On an unknown layer. |
cells_hash
¶
Hash of the meta cell ids, what the cache stamps record.
Meta cells have no cell filter; their set is fixed at construction and identified by the ids, which a merge rewrites.
stamp
¶
stamp(
artefact: str, *, parents: Sequence[str] = ()
) -> Stamp
Stamp a cached artefact against the meta cell set.
check_state
¶
True if the artefacts are fresh, else what is stale and why.
cell_assignments
¶
One row per (source cell, meta cell) membership, in long form.
Columns cell_idx (0-based store index in the source) and
meta_cell_idx. Bootstrapped meta cells overlap, so a cell can
appear more than once; unassigned cells do not appear.
Counts
dataclass
¶
Counts(matrix: CsrMatrix, cells: ndarray, genes: ndarray)
A cells x genes count matrix in CSR, with what its rows and columns are.
Attributes:
| Name | Type | Description |
|---|---|---|
matrix |
CsrMatrix
|
The CSR components. |
cells |
ndarray
|
0-based store index of each row. |
genes |
ndarray
|
0-based store index of each column. |
ScCache
dataclass
¶
ScCache(
pca_factors: ndarray | None = None,
pca_loadings: ndarray | None = None,
pca_singular_vals: ndarray | None = None,
pca_genes: ndarray | None = None,
embeddings: dict[str, ndarray] = dict(),
knn: KnnGraph | None = None,
connectivities: CsrMatrix | None = None,
magic: MagicLayer | None = None,
residual_fit: object | None = None,
stamps: dict[str, Stamp] = dict(),
_embedding_refs: dict[str, ref] = dict(),
)
Analysis results held in memory.
Assigning a slot drops its provenance stamp; stamp it again with
SingleCells.stamp() once the new payload is in place.
Attributes:
| Name | Type | Description |
|---|---|---|
pca_factors |
ndarray | None
|
|
pca_loadings |
ndarray | None
|
|
pca_singular_vals |
ndarray | None
|
|
pca_genes |
ndarray | None
|
|
embeddings |
dict[str, ndarray]
|
Other embeddings by name, e.g. |
knn |
KnnGraph | None
|
The kNN graph. |
connectivities |
CsrMatrix | None
|
The neighbour graph. |
magic |
MagicLayer | None
|
The MAGIC imputed layer. |
residual_fit |
object | None
|
The fitted residual model. Opaque for now and not
persisted by |
stamps |
dict[str, Stamp]
|
Provenance stamp per artefact label. |
artefacts
¶
artefacts() -> dict[str, Stamp | None]
Every present artefact and its stamp, None when unstamped.
In the order: the PCA, the embeddings, kNN, graph, MAGIC, residuals.
Raises:
| Type | Description |
|---|---|
ValueError
|
If an embedding uses a reserved name. |
set_stamp
¶
set_stamp(label: str, stamp: Stamp) -> None
Attach a stamp to a present artefact.
Raises:
| Type | Description |
|---|---|
KeyError
|
If no artefact sits under the label. |
stamp
¶
stamp(
label: str, cells: str, parents: Sequence[str] = ()
) -> Stamp
Mint and attach a stamp.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
The artefact, e.g. |
required |
cells
|
str
|
The current |
required |
parents
|
Sequence[str]
|
Labels of the artefacts it was derived from. Labels that are absent or unstamped are dropped, so a chain built on an unstamped artefact does not claim a provenance it lacks. |
()
|
Returns:
| Type | Description |
|---|---|
Stamp
|
The new stamp. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If no artefact sits under the label. |
ValueError
|
If an embedding uses a reserved name. |
ScMap
dataclass
¶
Ids and index sets of an experiment.
Attributes:
| Name | Type | Description |
|---|---|---|
cell_ids |
ndarray
|
Cell ids; position |
gene_ids |
ndarray
|
Gene ids; position |
cells_to_keep |
ndarray
|
0-based store indices of the cells in use, in the order analysis results are aligned to. |
hvg |
ndarray | None
|
0-based gene indices of the highly variable genes, if selected. |
cell_indices
¶
0-based indices of cells by id. Unknown ids warn and are dropped.
Raises:
| Type | Description |
|---|---|
ValueError
|
If no id matched. |
gene_indices
¶
0-based indices of genes by id. Unknown ids warn and are dropped.
Raises:
| Type | Description |
|---|---|
ValueError
|
If no id matched. |
cell_names
¶
Cell ids, all or only the kept ones in cells_to_keep order.
Stamp
dataclass
¶
Provenance of one cached artefact.
Attributes:
| Name | Type | Description |
|---|---|---|
cells |
str
|
Hash of |
id |
str
|
Unique id of this artefact. |
parents |
tuple[str, ...]
|
Stamp ids of the artefacts it was derived from. |
CsrMatrix
dataclass
¶
A CSR sparse matrix as its three component vectors.
Attributes:
| Name | Type | Description |
|---|---|---|
data |
ndarray
|
|
indices |
ndarray
|
|
indptr |
ndarray
|
|
shape |
tuple[int, int]
|
|
scipy_csr
¶
The matrix as a scipy.sparse.csr_matrix, sharing the buffers.
Needs scipy (the sparse extra).
KnnGraph
dataclass
¶
A kNN result. Both arrays are held in C order (copied if needed).
Attributes:
| Name | Type | Description |
|---|---|---|
indices |
ndarray
|
|
distances |
ndarray
|
|
dist_metric |
str
|
The metric, e.g. |
MagicLayer
dataclass
¶
The MAGIC imputed layer.
Attributes:
| Name | Type | Description |
|---|---|---|
data |
ndarray
|
|
features |
ndarray
|
Gene ids of the columns. |
TableNotFoundError
¶
Bases: Exception
A table the call needs is missing from the DuckDB.
get_counts
¶
get_counts(
sc: ScBase,
*,
cells: Selection | None = None,
genes: Selection | None = None,
layer: Literal["raw", "norm"] = "raw",
assay: Literal["rna", "adt"] = "rna",
use_cells_to_keep: bool = True,
) -> Counts
Read counts for a selection of cells and genes.
With use_cells_to_keep the rows are the kept cells, or the given cells
that are kept, in the order given. The decode runs in Rust with the GIL
released.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sc
|
ScBase
|
The experiment or a subset of it. |
required |
cells
|
Selection | None
|
0-based store indices or ids. |
None
|
genes
|
Selection | None
|
0-based store indices or ids, in the column order wanted.
|
None
|
layer
|
Literal['raw', 'norm']
|
|
'raw'
|
assay
|
Literal['rna', 'adt']
|
The modality: |
'rna'
|
use_cells_to_keep
|
bool
|
Restrict to the kept cells. |
True
|
Returns:
| Type | Description |
|---|---|
Counts
|
The CSR matrix with its row cells and column genes (or features). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no cell is left to read, or on |
merge_subset_obs
¶
merge_subset_obs(
sc: SingleCells,
subsets: SingleCellsSubset
| Sequence[SingleCellsSubset],
*,
cols: Sequence[str] | None = None,
new_names: Sequence[str] | None = None,
prefix_values: bool = False,
overwrite: bool = False,
verbose: Verbose = True,
) -> None
Write obs columns of one or more subsets into the parent's obs.
One join on cell_idx for all subsets; parent cells in none of them get
NULL.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sc
|
SingleCells
|
The parent the subsets were cut from. |
required |
subsets
|
SingleCellsSubset | Sequence[SingleCellsSubset]
|
A subset or several, each from |
required |
cols
|
Sequence[str] | None
|
Subset obs columns to merge. |
None
|
new_names
|
Sequence[str] | None
|
Names in the parent, one per |
None
|
prefix_values
|
bool
|
Prefix each value with its subset's group,
|
False
|
overwrite
|
bool
|
Replace parent columns of the same name. |
False
|
verbose
|
Verbose
|
|
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If a subset is not from |