Skip to content

Input and output

Getting counts into an experiment directory, and back out.

Every loader takes the directory to create and returns the opened SingleCells. Pick the one for your format: load_csr for counts already in memory, load_h5ad, load_tenx_h5 or load_mtx for files, and the load_multi_* twins for several files in one go. After the first load you only need load_existing.

What a load does. It applies the cell and gene QC of MinQualityParams (by default at least 100 genes, 250 counts per cell and 10 cells per gene), so dropped cells and genes never enter the store. It then writes the cell-major and gene-major stores and loads obs and var into the DuckDB, adding nnz and lib_size to obs and no_cells_exp to var. Loading into a directory that already holds an experiment overwrites its stores and drops any saved memory_py.*.

Several files. prescan_h5ad_files, prescan_tenx_h5_files and prescan_mtx_dirs read the gene sets first and fix the gene universe (intersection by default, or union), then load_multi_* loads against that prescan. obs gains exp_id and cell_id is prefixed with it. To combine experiments you already loaded, merge_sc_experiments keeps the shared genes and each input's kept cells, and carries no cache over.

Saving. obs and var edits go to the DuckDB at once. save writes what lives in memory: the cell filter, the HVG set and the cache, as memory_py.npz and memory_py.json. It does not write a fitted residual model, and warns. load_existing brings it all back, and restores the stores from counts.bxa if only the archive is left (archive_sc_exp). save_h5ad exports kept cells, obs, var and the embeddings and graph that still match to an h5ad file, save_zarr the same to an AnnData Zarr store; write_h5ad_sc, write_tenx_h5_sc and write_cellranger_output write in-memory counts as files other tools read.

Test data. generate_single_cell_test_data plants cell types in synthetic counts. The generate_* twins serve the ADT, CellSweep and DIALOGUE examples. The download_* functions fetch the vignette data sets into ~/.cache/bixverse and return the path, or the cached one.

params = bv.params.SyntheticDataParams(n_cells=2000, n_genes=500)
sim = bv.io.generate_single_cell_test_data(params, seed=1)
sc = bv.io.load_csr("experiments/demo", sim.counts, sim.obs, sim.var)

bv.pp.find_hvg(sc, hvg_no=200)
bv.io.save(sc)
sc = bv.io.load_existing("experiments/demo")

Gotchas. The loaders want integral raw counts. load_h5ad finds them with detect_raw_count_slot, which prefers layers.counts, then raw.X, then X; set raw_count_slot if it picks wrong, and use load_h5ad_norm for files that only hold log-normalised values. load_mtx takes genes as rows, the 10x convention, unless cells_as_rows says otherwise; get_cell_ranger_params finds the three files for you. The h5ad readers take an anndata Zarr store (v2 or v3) as well. Nothing here needs h5py. A v4 store still opens with a warning; a v3 store no longer opens. upgrade_sc_store converts both.

Worked through in Single-cell data I/O in bixverse and Scaling to millions of cells with bixverse.

Loading one file

Getting counts into an experiment directory, and back out.

Every loader takes the directory to create and returns the opened SingleCells. Pick the one for your format: load_csr for counts already in memory, load_h5ad, load_tenx_h5 or load_mtx for files, and the load_multi_* twins for several files in one go. After the first load you only need load_existing.

What a load does. It applies the cell and gene QC of MinQualityParams (by default at least 100 genes, 250 counts per cell and 10 cells per gene), so dropped cells and genes never enter the store. It then writes the cell-major and gene-major stores and loads obs and var into the DuckDB, adding nnz and lib_size to obs and no_cells_exp to var. Loading into a directory that already holds an experiment overwrites its stores and drops any saved memory_py.*.

Several files. prescan_h5ad_files, prescan_tenx_h5_files and prescan_mtx_dirs read the gene sets first and fix the gene universe (intersection by default, or union), then load_multi_* loads against that prescan. obs gains exp_id and cell_id is prefixed with it. To combine experiments you already loaded, merge_sc_experiments keeps the shared genes and each input's kept cells, and carries no cache over.

Saving. obs and var edits go to the DuckDB at once. save writes what lives in memory: the cell filter, the HVG set and the cache, as memory_py.npz and memory_py.json. It does not write a fitted residual model, and warns. load_existing brings it all back, and restores the stores from counts.bxa if only the archive is left (archive_sc_exp). save_h5ad exports kept cells, obs, var and the embeddings and graph that still match to an h5ad file, save_zarr the same to an AnnData Zarr store; write_h5ad_sc, write_tenx_h5_sc and write_cellranger_output write in-memory counts as files other tools read.

Test data. generate_single_cell_test_data plants cell types in synthetic counts. The generate_* twins serve the ADT, CellSweep and DIALOGUE examples. The download_* functions fetch the vignette data sets into ~/.cache/bixverse and return the path, or the cached one.

params = bv.params.SyntheticDataParams(n_cells=2000, n_genes=500)
sim = bv.io.generate_single_cell_test_data(params, seed=1)
sc = bv.io.load_csr("experiments/demo", sim.counts, sim.obs, sim.var)

bv.pp.find_hvg(sc, hvg_no=200)
bv.io.save(sc)
sc = bv.io.load_existing("experiments/demo")

Gotchas. The loaders want integral raw counts. load_h5ad finds them with detect_raw_count_slot, which prefers layers.counts, then raw.X, then X; set raw_count_slot if it picks wrong, and use load_h5ad_norm for files that only hold log-normalised values. load_mtx takes genes as rows, the 10x convention, unless cells_as_rows says otherwise; get_cell_ranger_params finds the three files for you. The h5ad readers take an anndata Zarr store (v2 or v3) as well. Nothing here needs h5py. A v4 store still opens with a warning; a v3 store no longer opens. upgrade_sc_store converts both.

load_csr

load_csr(
    directory: Path | str,
    counts: CsrLike,
    obs: DataFrame,
    var: DataFrame,
    *,
    qc: MinQualityParams | None = None,
    csc_mem_gb: float | None = None,
    verbose: Verbose = True,
) -> SingleCells

Load an in-memory cells x genes count matrix.

obs and var go in with every column name snake_cased, the first column renamed to cell_id / gene_id (obs names then made unique), only the rows that survive QC.

Parameters:

Name Type Description Default
directory Path | str

The experiment directory, created if missing.

required
counts CsrLike

Cells x genes CSR matrix of integral counts.

required
obs DataFrame

One row per matrix row, identifier first.

required
var DataFrame

One row per matrix column, identifier first.

required
qc MinQualityParams | None

Cell and gene QC thresholds and the target size.

None
csc_mem_gb float | None

Memory in GB for the CSR to CSC conversion buffers. None converts in one pass.

None
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
SingleCells

The experiment.

Raises:

Type Description
ValueError

If obs / var do not match the matrix or the counts are not integral.

Examples:

>>> sc = bv.io.load_csr("experiments/demo", sim.counts, sim.obs, sim.var)
>>> qc = bv.params.MinQualityParams(min_lib_size=500)
>>> sc = bv.io.load_csr("experiments/lax", sim.counts, sim.obs, sim.var, qc=qc)

load_h5ad

load_h5ad(
    directory: Path | str,
    h5_path: Path | str,
    *,
    qc: MinQualityParams | None = None,
    raw_count_slot: Literal["auto"] | RawSlot = "auto",
    cell_id_col: str | None = None,
    h5ad_streaming: bool = True,
    csc_mem_gb: float | None = None,
    verbose: Verbose = True,
) -> SingleCells

Load an h5ad file or anndata Zarr store.

Parameters:

Name Type Description Default
directory Path | str

The experiment directory, created if missing.

required
h5_path Path | str

The h5ad file or anndata Zarr store.

required
qc MinQualityParams | None

Cell and gene QC thresholds and the target size.

None
raw_count_slot Literal['auto'] | RawSlot

Where the raw counts are. "auto" detects it, see detect_raw_count_slot.

'auto'
cell_id_col str | None

obs column to use as cell identifier when the index is not it.

None
h5ad_streaming bool

Stream the counts in batches instead of materialising the filtered matrix first.

True
csc_mem_gb float | None

Memory in GB for the CSR to CSC conversion buffers, and for the cell-major transpose of a streamed CSC h5ad.

None
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
SingleCells

The experiment.

Raises:

Type Description
ValueError

If "auto" finds no slot with raw counts.

Examples:

>>> sc = bv.io.load_h5ad("experiments/h5ad", "path/to/file.h5ad")
>>> qc = bv.params.MinQualityParams(min_cells=5)
>>> sc = bv.io.load_h5ad("experiments/h5ad", "path/to/file.h5ad", qc=qc)

load_h5ad_norm

load_h5ad_norm(
    directory: Path | str,
    h5_path: Path | str,
    obs_lib_size_col: str,
    target_size: float,
    *,
    qc: MinQualityParams | None = None,
    cell_id_col: str | None = None,
    csc_mem_gb: float | None = None,
    verbose: Verbose = True,
) -> SingleCells

Load an h5ad file holding only normalised counts.

Raw counts are reconstructed assuming X = log1p(x / lib_size * target_size), with the library sizes read from an obs column.

Parameters:

Name Type Description Default
directory Path | str

The experiment directory, created if missing.

required
h5_path Path | str

The h5ad file or anndata Zarr store.

required
obs_lib_size_col str

obs column with the total counts per cell.

required
target_size float

Target size of the original normalisation.

required
qc MinQualityParams | None

Cell and gene QC thresholds and the target size.

None
cell_id_col str | None

obs column to use as cell identifier.

None
csc_mem_gb float | None

Memory in GB for the CSR to CSC conversion buffers.

None
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
SingleCells

The experiment.

Examples:

>>> sc = bv.io.load_h5ad_norm("exp/norm", "path/to/norm.h5ad", "lib_size", 1e4)

stream_h5ad

stream_h5ad(
    directory: Path | str,
    h5_path: Path | str,
    *,
    qc: MinQualityParams | None = None,
    raw_count_slot: Literal["auto"] | RawSlot = "auto",
    csc_mem_gb: float | None = None,
    verbose: Verbose = True,
) -> SingleCells

load_h5ad with h5ad_streaming=True.

Parameters:

Name Type Description Default
directory Path | str

The experiment directory, created if missing.

required
h5_path Path | str

The h5ad file or anndata Zarr store.

required
qc MinQualityParams | None

Cell and gene QC thresholds and the target size.

None
raw_count_slot Literal['auto'] | RawSlot

Where the raw counts are. "auto" detects it, see detect_raw_count_slot.

'auto'
csc_mem_gb float | None

Memory in GB for the CSR to CSC conversion buffers.

None
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
SingleCells

The experiment.

load_tenx_h5

load_tenx_h5(
    directory: Path | str,
    h5_path: Path | str,
    *,
    qc: MinQualityParams | None = None,
    feature_type: str | None = "Gene Expression",
    csc_mem_gb: float | None = None,
    verbose: Verbose = True,
) -> SingleCells

Load a 10x CellRanger h5 file.

Only the feature_type modality is loaded (v3); v2 is single modality.

Parameters:

Name Type Description Default
directory Path | str

The experiment directory, created if missing.

required
h5_path Path | str

The 10x h5 file.

required
qc MinQualityParams | None

Cell and gene QC thresholds and the target size.

None
feature_type str | None

Modality to keep. None is gene expression.

'Gene Expression'
csc_mem_gb float | None

Memory in GB for the CSR to CSC conversion buffers.

None
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
SingleCells

The experiment.

Examples:

>>> sc = bv.io.load_tenx_h5("experiments/tenx", "path/to/file.h5")

load_atac_fragments

load_atac_fragments(
    directory: Path | str,
    fragments: Path | str,
    *,
    peaks: Path | str | DataFrame | None = None,
    tile_width: int | None = None,
    chrom_sizes: Mapping[str, int] | None = None,
    mode: CountMode = "insertion",
    barcodes: Sequence[str] | ndarray | None = None,
    cellranger: Path | str | None = None,
    min_fragments: int | None = None,
    exclude_chroms: Sequence[str] = MITO_CHROMS,
    max_mem_gb: float | None = None,
    verbose: Verbose = 1,
) -> SingleCellsAtac

Load an ATAC-only experiment from a fragment file.

The cells come from exactly one of barcodes, cellranger or min_fragments; with the last, every barcode with at least that many fragments (outside exclude_chroms), sorted, as Cell Ranger orders them. See barcode_fragment_counts for the knee plot to pick it from.

Parameters:

Name Type Description Default
directory Path | str

The experiment directory, created if missing.

required
fragments Path | str

The fragment file (BGZF, gzip or plain).

required
peaks Path | str | DataFrame | None

A BED file or a frame with chrom, start, end.

None
tile_width int | None

Tile width in bp, instead of peaks.

None
chrom_sizes Mapping[str, int] | None

Chromosome lengths, for the tiles.

None
mode CountMode

What one count is, see add_atac_fragments.

'insertion'
barcodes Sequence[str] | ndarray | None

The cell barcodes.

None
cellranger Path | str | None

Cell Ranger ATAC's singlecell.csv or filtered h5.

None
min_fragments int | None

Call cells with at least this many fragments.

None
exclude_chroms Sequence[str]

Chromosomes the min_fragments count skips.

MITO_CHROMS
max_mem_gb float | None

Memory budget of the feature-major conversion.

None
verbose Verbose

0 silent, 1 normal, 2 detailed.

1

Returns:

Type Description
SingleCellsAtac

The experiment: obs holds cell_id, lib_size, nnz, to_keep;

SingleCellsAtac

var the features as gene_id (chr:start-end) with chrom,

SingleCellsAtac

start, end, no_cells_exp.

Raises:

Type Description
ValueError

Unless exactly one cell source and exactly one of peaks and tile_width are given, or if no fragment of the cells lies on a feature's chromosome.

load_atac_tenx

load_atac_tenx(
    directory: Path | str,
    h5_path: Path | str,
    *,
    barcodes: Sequence[str] | ndarray | None = None,
    max_mem_gb: float | None = None,
    verbose: Verbose = 1,
) -> SingleCellsAtac

Load an ATAC-only experiment from a 10x peak matrix h5.

Parameters:

Name Type Description Default
directory Path | str

The experiment directory, created if missing.

required
h5_path Path | str

Cell Ranger ATAC's filtered_peak_bc_matrix.h5, or the Cell Ranger ARC h5 (its Peaks rows).

required
barcodes Sequence[str] | ndarray | None

Cells to load; None for every barcode of the h5.

None
max_mem_gb float | None

Memory budget of the feature-major conversion.

None
verbose Verbose

0 silent, 1 normal, 2 detailed.

1

Returns:

Type Description
SingleCellsAtac

The experiment, as load_atac_fragments describes it; the counts

SingleCellsAtac

are insertions.

Raises:

Type Description
ValueError

If a requested barcode is not in the h5.

load_mtx

load_mtx(
    directory: Path | str,
    mtx_params: MtxIoParams,
    *,
    qc: MinQualityParams | None = None,
    csc_mem_gb: float | None = None,
    verbose: Verbose = True,
) -> SingleCells

Load an mtx file with its barcodes and features.

The .mtx (plain or gzipped) is read in one pass with its entries spilled next to the store. obs and var come from the plain text files, the first column as identifier.

Parameters:

Name Type Description Default
directory Path | str

The experiment directory, created if missing.

required
mtx_params MtxIoParams

The three files and their layout.

required
qc MinQualityParams | None

Cell and gene QC thresholds and the target size.

None
csc_mem_gb float | None

Memory in GB for the CSR to CSC conversion buffers.

None
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
SingleCells

The experiment.

Examples:

>>> mtx_params = bv.io.get_cell_ranger_params("path/to/mtx_dir", has_hdr=True)
>>> sc = bv.io.load_mtx("experiments/mtx", mtx_params)

get_cell_ranger_params

get_cell_ranger_params(
    directory: Path | str,
    *,
    cells_as_rows: bool = False,
    has_hdr: bool = False,
) -> MtxIoParams

The mtx parameters for a Cell Ranger output directory.

Picks the first file present of matrix.mtx / mat.mtx, barcodes.tsv / barcodes.csv and features.* / genes.* (Cell Ranger v3 and v2).

Parameters:

Name Type Description Default
directory Path | str

The directory holding the three files.

required
cells_as_rows bool

Do cells represent the rows of the mtx. Cell Ranger writes genes as rows.

False
has_hdr bool

Do the barcode and feature files have headers.

False

Returns:

Type Description
MtxIoParams

The parameters for load_mtx().

Raises:

Type Description
FileNotFoundError

If one of the three files is missing.

Examples:

>>> mtx_params = bv.io.get_cell_ranger_params("path/to/mtx_dir", has_hdr=True)

Loading several files

Getting counts into an experiment directory, and back out.

Every loader takes the directory to create and returns the opened SingleCells. Pick the one for your format: load_csr for counts already in memory, load_h5ad, load_tenx_h5 or load_mtx for files, and the load_multi_* twins for several files in one go. After the first load you only need load_existing.

What a load does. It applies the cell and gene QC of MinQualityParams (by default at least 100 genes, 250 counts per cell and 10 cells per gene), so dropped cells and genes never enter the store. It then writes the cell-major and gene-major stores and loads obs and var into the DuckDB, adding nnz and lib_size to obs and no_cells_exp to var. Loading into a directory that already holds an experiment overwrites its stores and drops any saved memory_py.*.

Several files. prescan_h5ad_files, prescan_tenx_h5_files and prescan_mtx_dirs read the gene sets first and fix the gene universe (intersection by default, or union), then load_multi_* loads against that prescan. obs gains exp_id and cell_id is prefixed with it. To combine experiments you already loaded, merge_sc_experiments keeps the shared genes and each input's kept cells, and carries no cache over.

Saving. obs and var edits go to the DuckDB at once. save writes what lives in memory: the cell filter, the HVG set and the cache, as memory_py.npz and memory_py.json. It does not write a fitted residual model, and warns. load_existing brings it all back, and restores the stores from counts.bxa if only the archive is left (archive_sc_exp). save_h5ad exports kept cells, obs, var and the embeddings and graph that still match to an h5ad file, save_zarr the same to an AnnData Zarr store; write_h5ad_sc, write_tenx_h5_sc and write_cellranger_output write in-memory counts as files other tools read.

Test data. generate_single_cell_test_data plants cell types in synthetic counts. The generate_* twins serve the ADT, CellSweep and DIALOGUE examples. The download_* functions fetch the vignette data sets into ~/.cache/bixverse and return the path, or the cached one.

params = bv.params.SyntheticDataParams(n_cells=2000, n_genes=500)
sim = bv.io.generate_single_cell_test_data(params, seed=1)
sc = bv.io.load_csr("experiments/demo", sim.counts, sim.obs, sim.var)

bv.pp.find_hvg(sc, hvg_no=200)
bv.io.save(sc)
sc = bv.io.load_existing("experiments/demo")

Gotchas. The loaders want integral raw counts. load_h5ad finds them with detect_raw_count_slot, which prefers layers.counts, then raw.X, then X; set raw_count_slot if it picks wrong, and use load_h5ad_norm for files that only hold log-normalised values. load_mtx takes genes as rows, the 10x convention, unless cells_as_rows says otherwise; get_cell_ranger_params finds the three files for you. The h5ad readers take an anndata Zarr store (v2 or v3) as well. Nothing here needs h5py. A v4 store still opens with a warning; a v3 store no longer opens. upgrade_sc_store converts both.

Prescan dataclass

Prescan(
    universe: tuple[str, ...],
    file_tasks: tuple[dict[str, object], ...],
)

The gene universe and per-file tasks of a multi-file load.

Attributes:

Name Type Description
universe tuple[str, ...]

Gene ids in the order of the final var table.

file_tasks tuple[dict[str, object], ...]

One task dict per input, in input order. The keys are the ones the prescans produce and the Rust loaders read; gene_local_to_universe is 0-based with None for genes outside the universe.

universe_size property

universe_size: int

Number of genes in the universe.

task

task(exp_id: str) -> dict[str, object]

The task of one input.

Raises:

Type Description
KeyError

If no input has that exp_id.

prescan_h5ad_files

prescan_h5ad_files(
    h5_paths: InputPaths,
    *,
    gene_universe: GeneUniverse = "intersection",
    var_index: str = "_index",
    raw_count_slot: Literal["auto"] | RawSlot = "auto",
) -> Prescan

Prescan several h5ad files for a multi-file load.

Parameters:

Name Type Description Default
h5_paths InputPaths

The files. A mapping supplies the experiment ids, otherwise the file stems are used.

required
gene_universe GeneUniverse

"intersection" or "union" of the gene names.

'intersection'
var_index str

Dataset in /var holding the gene names.

'_index'
raw_count_slot Literal['auto'] | RawSlot

"auto" detects per file, see detect_raw_count_slot.

'auto'

Returns:

Type Description
Prescan

The universe (sorted) and one task per file with exp_id,

Prescan

h5_path, cs_type, no_cells, no_genes, raw_slot and

Prescan

gene_local_to_universe.

Examples:

>>> files = {"b1": "path/to/b1.h5ad", "b2": "path/to/b2.h5ad"}
>>> prescan = bv.io.prescan_h5ad_files(files, gene_universe="union")

prescan_tenx_h5_files

prescan_tenx_h5_files(
    h5_paths: InputPaths,
    *,
    feature_type: str = "Gene Expression",
    gene_universe: GeneUniverse = "intersection",
) -> Prescan

Prescan several 10x h5 files for a multi-file load.

Genes are matched on the feature id. v2 and v3 files can be mixed; the feature_type filter only applies to v3.

Parameters:

Name Type Description Default
h5_paths InputPaths

The files. A mapping supplies the experiment ids, otherwise the file stems are used.

required
feature_type str

Modality to keep (v3).

'Gene Expression'
gene_universe GeneUniverse

"intersection" or "union" of the feature ids.

'intersection'

Returns:

Type Description
Prescan

The universe (sorted) and one task per file with exp_id,

Prescan

h5_path, version, no_cells, no_genes, feature_type and

Prescan

gene_local_to_universe.

Raises:

Type Description
ValueError

If a v3 file has no feature of the type, or the universe is empty.

Examples:

>>> files = ["path/to/t1.h5", "path/to/t2.h5"]
>>> prescan = bv.io.prescan_tenx_h5_files(files)

prescan_mtx_dirs

prescan_mtx_dirs(
    dirs: Sequence[Path | str],
    exp_ids: Sequence[str],
    *,
    cells_as_rows: bool = False,
    has_hdr: bool = False,
) -> Prescan

Prescan several CellRanger style mtx directories for a multi-file load.

Each directory holds one .mtx (or .mtx.gz), one barcodes and one features (or genes) file. The universe is the intersection of the first feature column, in the order of the first directory.

Parameters:

Name Type Description Default
dirs Sequence[Path | str]

The directories, at least two.

required
exp_ids Sequence[str]

One unique experiment id per directory.

required
cells_as_rows bool

Applied to every input. False is the 10x convention.

False
has_hdr bool

Whether the barcodes and features files have a header.

False

Returns:

Type Description
Prescan

The universe and one task per directory with exp_id, mtx_path,

Prescan

barcodes_path, features_path, cells_as_rows, has_hdr and

Prescan

gene_local_to_universe.

Raises:

Type Description
ValueError

On fewer than two inputs, mismatched or repeated ids, or an empty intersection.

Examples:

>>> dirs = ["path/to/mtx_a", "path/to/mtx_b"]
>>> prescan = bv.io.prescan_mtx_dirs(dirs, ["a", "b"], has_hdr=True)

load_multi_h5ad

load_multi_h5ad(
    directory: Path | str,
    prescan: Prescan,
    *,
    qc: MinQualityParams | None = None,
    cell_id_col: str | None = None,
    csc_mem_gb: float | None = None,
    verbose: Verbose = True,
) -> SingleCells

Load several h5ad files into one experiment.

Gene QC is global across files and cells are indexed file after file. obs gains exp_id and cell_id is prefixed with it; var holds only gene_id.

Parameters:

Name Type Description Default
directory Path | str

The experiment directory, created if missing.

required
prescan Prescan

Output of prescan_h5ad_files.

required
qc MinQualityParams | None

Cell and gene QC thresholds and the target size.

None
cell_id_col str | None

obs column to use as cell identifier.

None
csc_mem_gb float | None

Memory in GB for the CSR to CSC conversion buffers.

None
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
SingleCells

The experiment.

Examples:

>>> files = {"b1": "path/to/b1.h5ad", "b2": "path/to/b2.h5ad"}
>>> prescan = bv.io.prescan_h5ad_files(files)
>>> sc = bv.io.load_multi_h5ad("experiments/multi", prescan)

load_multi_tenx_h5

load_multi_tenx_h5(
    directory: Path | str,
    prescan: Prescan,
    *,
    qc: MinQualityParams | None = None,
    csc_mem_gb: float | None = None,
    verbose: Verbose = True,
) -> SingleCells

Load several 10x h5 files into one experiment.

Parameters:

Name Type Description Default
directory Path | str

The experiment directory, created if missing.

required
prescan Prescan

Output of prescan_tenx_h5_files.

required
qc MinQualityParams | None

Cell and gene QC thresholds and the target size.

None
csc_mem_gb float | None

Memory in GB for the CSR to CSC conversion buffers.

None
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
SingleCells

The experiment.

Examples:

>>> files = ["path/to/t1.h5", "path/to/t2.h5"]
>>> prescan = bv.io.prescan_tenx_h5_files(files)
>>> sc = bv.io.load_multi_tenx_h5("experiments/multi_tenx", prescan)

load_multi_mtx

load_multi_mtx(
    directory: Path | str,
    prescan: Prescan,
    *,
    qc: MinQualityParams | None = None,
    csc_mem_gb: float | None = None,
    verbose: Verbose = True,
) -> SingleCells

Load several mtx directories into one experiment.

Parameters:

Name Type Description Default
directory Path | str

The experiment directory, created if missing.

required
prescan Prescan

Output of prescan_mtx_dirs.

required
qc MinQualityParams | None

Cell and gene QC thresholds and the target size.

None
csc_mem_gb float | None

Memory in GB for the CSR to CSC conversion buffers.

None
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
SingleCells

The experiment.

Examples:

>>> dirs = ["path/to/mtx_a", "path/to/mtx_b"]
>>> prescan = bv.io.prescan_mtx_dirs(dirs, ["a", "b"], has_hdr=True)
>>> sc = bv.io.load_multi_mtx("experiments/multi_mtx", prescan)

merge_sc_experiments

merge_sc_experiments(
    directory: Path | str,
    inputs: Sequence[SingleCells],
    exp_ids: Sequence[str],
    *,
    renormalise: bool = False,
    qc: MinQualityParams | None = None,
    csc_mem_gb: float | None = None,
    verbose: Verbose = True,
) -> SingleCells

Merge several experiments into a new one.

The genes are the intersection of the inputs' genes, in the order of the first input. Only each input's kept cells are carried over. obs gains exp_id; var comes from the first input. Nothing cached is carried over.

Parameters:

Name Type Description Default
directory Path | str

The target directory, created if missing.

required
inputs Sequence[SingleCells]

The experiments, at least two.

required
exp_ids Sequence[str]

One unique experiment id per input.

required
renormalise bool

Recompute the normalised layer against qc.target_size from the surviving raw counts. Without it the stored layer is copied, which is only right if every input used the same target size.

False
qc MinQualityParams | None

Only target_size is used; no QC filtering happens in a merge.

None
csc_mem_gb float | None

Memory in GB for the CSR to CSC conversion buffers.

None
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
SingleCells

The merged experiment.

Raises:

Type Description
ValueError

On fewer than two inputs, mismatched or repeated ids, an input that was itself merged, or an empty intersection.

Examples:

>>> exp_ids = ["a", "b"]
>>> merged = bv.io.merge_sc_experiments("exp/merged", [sc_a, sc_b], exp_ids)

Looking at a file first

Getting counts into an experiment directory, and back out.

Every loader takes the directory to create and returns the opened SingleCells. Pick the one for your format: load_csr for counts already in memory, load_h5ad, load_tenx_h5 or load_mtx for files, and the load_multi_* twins for several files in one go. After the first load you only need load_existing.

What a load does. It applies the cell and gene QC of MinQualityParams (by default at least 100 genes, 250 counts per cell and 10 cells per gene), so dropped cells and genes never enter the store. It then writes the cell-major and gene-major stores and loads obs and var into the DuckDB, adding nnz and lib_size to obs and no_cells_exp to var. Loading into a directory that already holds an experiment overwrites its stores and drops any saved memory_py.*.

Several files. prescan_h5ad_files, prescan_tenx_h5_files and prescan_mtx_dirs read the gene sets first and fix the gene universe (intersection by default, or union), then load_multi_* loads against that prescan. obs gains exp_id and cell_id is prefixed with it. To combine experiments you already loaded, merge_sc_experiments keeps the shared genes and each input's kept cells, and carries no cache over.

Saving. obs and var edits go to the DuckDB at once. save writes what lives in memory: the cell filter, the HVG set and the cache, as memory_py.npz and memory_py.json. It does not write a fitted residual model, and warns. load_existing brings it all back, and restores the stores from counts.bxa if only the archive is left (archive_sc_exp). save_h5ad exports kept cells, obs, var and the embeddings and graph that still match to an h5ad file, save_zarr the same to an AnnData Zarr store; write_h5ad_sc, write_tenx_h5_sc and write_cellranger_output write in-memory counts as files other tools read.

Test data. generate_single_cell_test_data plants cell types in synthetic counts. The generate_* twins serve the ADT, CellSweep and DIALOGUE examples. The download_* functions fetch the vignette data sets into ~/.cache/bixverse and return the path, or the cached one.

params = bv.params.SyntheticDataParams(n_cells=2000, n_genes=500)
sim = bv.io.generate_single_cell_test_data(params, seed=1)
sc = bv.io.load_csr("experiments/demo", sim.counts, sim.obs, sim.var)

bv.pp.find_hvg(sc, hvg_no=200)
bv.io.save(sc)
sc = bv.io.load_existing("experiments/demo")

Gotchas. The loaders want integral raw counts. load_h5ad finds them with detect_raw_count_slot, which prefers layers.counts, then raw.X, then X; set raw_count_slot if it picks wrong, and use load_h5ad_norm for files that only hold log-normalised values. load_mtx takes genes as rows, the 10x convention, unless cells_as_rows says otherwise; get_cell_ranger_params finds the three files for you. The h5ad readers take an anndata Zarr store (v2 or v3) as well. Nothing here needs h5py. A v4 store still opens with a warning; a v3 store no longer opens. upgrade_sc_store converts both.

H5adDims dataclass

H5adDims(n_obs: int, n_var: int, type: str)

Dimensions and storage of an h5ad file, as get_h5ad_dimensions().

Attributes:

Name Type Description
n_obs int

Rows of obs.

n_var int

Rows of var.

type str

"CSR", "CSC", "DENSE_ROW" or "DENSE_COL".

TenxH5Meta dataclass

TenxH5Meta(version: str, n_cells: int, n_genes: int)

Layout and dimensions of a 10x h5 file, as get_tenx_h5_metadata().

Attributes:

Name Type Description
version str

"v2" or "v3".

n_cells int

Barcodes.

n_genes int

Features, every modality included.

detect_raw_count_slot

detect_raw_count_slot(
    f_path: Path | str,
    candidates: Sequence[RawSlot] = RAW_SLOT_CANDIDATES,
    *,
    n_sample: int = 10000,
    threshold: float = 0.99,
) -> RawSlot | None

Detect which slot of an h5ad file or Zarr store holds raw integer counts.

Samples the non-zero values of each candidate in order and returns the first that is integer valued, so dedicated count slots win over X.

Parameters:

Name Type Description Default
f_path Path | str

The h5ad file or anndata Zarr store.

required
candidates Sequence[RawSlot]

Slots to test, in priority order.

RAW_SLOT_CANDIDATES
n_sample int

Values to sample per slot.

10000
threshold float

Minimum fraction of non-zeros that must be whole numbers.

0.99

Returns:

Type Description
RawSlot | None

The slot, or None if none qualifies.

Examples:

>>> slot = bv.io.detect_raw_count_slot("path/to/file.h5ad")

get_h5ad_dimensions

get_h5ad_dimensions(f_path: Path | str) -> H5adDims

Dimensions and storage layout of an h5ad file or anndata Zarr store.

Sparse X is CSR or CSC by its encoding attribute (or the length of indptr). Dense X is DENSE_ROW (cells x genes on disk) or DENSE_COL, with ties going to DENSE_ROW.

Parameters:

Name Type Description Default
f_path Path | str

The h5ad file or anndata Zarr store.

required

Returns:

Type Description
H5adDims

The dimensions and layout.

Raises:

Type Description
FileNotFoundError

If the file is missing.

BixverseError

If X is missing or its shape fits neither ordering.

read_h5ad_metadata

read_h5ad_metadata(f_path: Path | str) -> dict[str, object]

Read the obs and var tables and the layout of an h5ad file or Zarr store.

The tables come through the same reader the loaders use, so column names are snake_cased and the index is cell_id / gene_id.

Parameters:

Name Type Description Default
f_path Path | str

The h5ad file or anndata Zarr store.

required

Returns:

Type Description
dict[str, object]

obs and var (polars), dims ((n_obs, n_var)) and type.

Examples:

>>> meta = bv.io.read_h5ad_metadata("path/to/file.h5ad")

get_tenx_h5_metadata

get_tenx_h5_metadata(f_path: Path | str) -> TenxH5Meta

Detect the layout of a 10x h5 file and read its dimensions.

Parameters:

Name Type Description Default
f_path Path | str

The 10x h5 file.

required

Returns:

Type Description
TenxH5Meta

The version and dimensions.

Raises:

Type Description
FileNotFoundError

If the file is missing.

BixverseError

If neither the v2 nor the v3 layout is found.

read_tenx_h5_metadata

read_tenx_h5_metadata(
    f_path: Path | str,
) -> dict[str, object]

Read the barcode and feature tables and the layout of a 10x h5 file.

Parameters:

Name Type Description Default
f_path Path | str

The 10x h5 file.

required

Returns:

Type Description
dict[str, object]

obs (.id), var (.id, name, plus feature_type for v3),

dict[str, object]

dims ((n_cells, n_genes)), version and feature_types (counts

dict[str, object]

per type, v3 only, else None).

Examples:

>>> meta = bv.io.read_tenx_h5_metadata("path/to/file.h5")

Saving and reopening

Getting counts into an experiment directory, and back out.

Every loader takes the directory to create and returns the opened SingleCells. Pick the one for your format: load_csr for counts already in memory, load_h5ad, load_tenx_h5 or load_mtx for files, and the load_multi_* twins for several files in one go. After the first load you only need load_existing.

What a load does. It applies the cell and gene QC of MinQualityParams (by default at least 100 genes, 250 counts per cell and 10 cells per gene), so dropped cells and genes never enter the store. It then writes the cell-major and gene-major stores and loads obs and var into the DuckDB, adding nnz and lib_size to obs and no_cells_exp to var. Loading into a directory that already holds an experiment overwrites its stores and drops any saved memory_py.*.

Several files. prescan_h5ad_files, prescan_tenx_h5_files and prescan_mtx_dirs read the gene sets first and fix the gene universe (intersection by default, or union), then load_multi_* loads against that prescan. obs gains exp_id and cell_id is prefixed with it. To combine experiments you already loaded, merge_sc_experiments keeps the shared genes and each input's kept cells, and carries no cache over.

Saving. obs and var edits go to the DuckDB at once. save writes what lives in memory: the cell filter, the HVG set and the cache, as memory_py.npz and memory_py.json. It does not write a fitted residual model, and warns. load_existing brings it all back, and restores the stores from counts.bxa if only the archive is left (archive_sc_exp). save_h5ad exports kept cells, obs, var and the embeddings and graph that still match to an h5ad file, save_zarr the same to an AnnData Zarr store; write_h5ad_sc, write_tenx_h5_sc and write_cellranger_output write in-memory counts as files other tools read.

Test data. generate_single_cell_test_data plants cell types in synthetic counts. The generate_* twins serve the ADT, CellSweep and DIALOGUE examples. The download_* functions fetch the vignette data sets into ~/.cache/bixverse and return the path, or the cached one.

params = bv.params.SyntheticDataParams(n_cells=2000, n_genes=500)
sim = bv.io.generate_single_cell_test_data(params, seed=1)
sc = bv.io.load_csr("experiments/demo", sim.counts, sim.obs, sim.var)

bv.pp.find_hvg(sc, hvg_no=200)
bv.io.save(sc)
sc = bv.io.load_existing("experiments/demo")

Gotchas. The loaders want integral raw counts. load_h5ad finds them with detect_raw_count_slot, which prefers layers.counts, then raw.X, then X; set raw_count_slot if it picks wrong, and use load_h5ad_norm for files that only hold log-normalised values. load_mtx takes genes as rows, the 10x convention, unless cells_as_rows says otherwise; get_cell_ranger_params finds the three files for you. The h5ad readers take an anndata Zarr store (v2 or v3) as well. Nothing here needs h5py. A v4 store still opens with a warning; a v3 store no longer opens. upgrade_sc_store converts both.

save

save(sc: SingleCells) -> None

Write the map's index sets and the cache next to the stores.

obs / var changes are in the DuckDB already and need no saving. The residual model is opaque for now and is not written; a warning says so. A SingleCellsMultiModal also writes its ADT counts, ADT cache, ATAC LSI and WNN slot, and load_existing hands it back as one; a SingleCellsAtac its LSI. Everything else about an ATAC store (kind, count mode, TF-IDF) is in the store and comes back without this file.

Parameters:

Name Type Description Default
sc SingleCells

The experiment.

required

Examples:

>>> bv.io.save(sc)

load_existing

load_existing(
    directory: Path | str, *, multi_modal: bool = False
) -> SingleCells

Open an experiment directory and restore any state Python saved.

Parameters:

Name Type Description Default
directory Path | str

The experiment directory.

required
multi_modal bool

Open it as a SingleCellsMultiModal. A memory file a multi-modal experiment saved does so regardless.

False

Returns:

Type Description
SingleCells

The experiment: a SingleCellsAtac when the store holds peaks or

SingleCells

tiles. With memory_py.* present, the cell filter, HVGs and cache

SingleCells

come from there (and for a multi-modal one the ADT counts, ADT cache,

SingleCells

ATAC LSI and WNN slot); otherwise the map is rebuilt from the DuckDB

SingleCells

and the cache is empty. An ATAC store's kind, count mode and TF-IDF

SingleCells

come from the store either way.

Restores the stores from counts.bxa when only the archive is there, and warns about a store in the v4 format.

Raises:

Type Description
FileNotFoundError

If a store, the DuckDB, or one half of the memory file pair is missing.

RuntimeError

If the store is in the v3 format, which no longer opens.

ValueError

If the memory file is of an unknown format or does not fit the store, or multi_modal is asked of an ATAC-only store.

Examples:

>>> sc = bv.io.load_existing("experiments/demo")
>>> mm = bv.io.load_existing("experiments/demo", multi_modal=True)

Exporting

Getting counts into an experiment directory, and back out.

Every loader takes the directory to create and returns the opened SingleCells. Pick the one for your format: load_csr for counts already in memory, load_h5ad, load_tenx_h5 or load_mtx for files, and the load_multi_* twins for several files in one go. After the first load you only need load_existing.

What a load does. It applies the cell and gene QC of MinQualityParams (by default at least 100 genes, 250 counts per cell and 10 cells per gene), so dropped cells and genes never enter the store. It then writes the cell-major and gene-major stores and loads obs and var into the DuckDB, adding nnz and lib_size to obs and no_cells_exp to var. Loading into a directory that already holds an experiment overwrites its stores and drops any saved memory_py.*.

Several files. prescan_h5ad_files, prescan_tenx_h5_files and prescan_mtx_dirs read the gene sets first and fix the gene universe (intersection by default, or union), then load_multi_* loads against that prescan. obs gains exp_id and cell_id is prefixed with it. To combine experiments you already loaded, merge_sc_experiments keeps the shared genes and each input's kept cells, and carries no cache over.

Saving. obs and var edits go to the DuckDB at once. save writes what lives in memory: the cell filter, the HVG set and the cache, as memory_py.npz and memory_py.json. It does not write a fitted residual model, and warns. load_existing brings it all back, and restores the stores from counts.bxa if only the archive is left (archive_sc_exp). save_h5ad exports kept cells, obs, var and the embeddings and graph that still match to an h5ad file, save_zarr the same to an AnnData Zarr store; write_h5ad_sc, write_tenx_h5_sc and write_cellranger_output write in-memory counts as files other tools read.

Test data. generate_single_cell_test_data plants cell types in synthetic counts. The generate_* twins serve the ADT, CellSweep and DIALOGUE examples. The download_* functions fetch the vignette data sets into ~/.cache/bixverse and return the path, or the cached one.

params = bv.params.SyntheticDataParams(n_cells=2000, n_genes=500)
sim = bv.io.generate_single_cell_test_data(params, seed=1)
sc = bv.io.load_csr("experiments/demo", sim.counts, sim.obs, sim.var)

bv.pp.find_hvg(sc, hvg_no=200)
bv.io.save(sc)
sc = bv.io.load_existing("experiments/demo")

Gotchas. The loaders want integral raw counts. load_h5ad finds them with detect_raw_count_slot, which prefers layers.counts, then raw.X, then X; set raw_count_slot if it picks wrong, and use load_h5ad_norm for files that only hold log-normalised values. load_mtx takes genes as rows, the 10x convention, unless cells_as_rows says otherwise; get_cell_ranger_params finds the three files for you. The h5ad readers take an anndata Zarr store (v2 or v3) as well. Nothing here needs h5py. A v4 store still opens with a warning; a v3 store no longer opens. upgrade_sc_store converts both.

save_h5ad

save_h5ad(
    sc: SingleCells,
    h5_path: Path | str,
    *,
    assay: Literal["raw", "norm"] = "raw",
    genes: Selection | None = None,
    chunk_size: int = 10000,
    overwrite: bool = True,
    verbose: Verbose = True,
) -> Path

Write an experiment to a spec compliant h5ad file.

Writes the kept cells in ascending store order, the obs / var tables without the bookkeeping columns, and whatever cached embeddings and graph still match the cells. Counts are streamed from the store in batches and stored as float32. A failed write leaves no file behind.

Parameters:

Name Type Description Default
sc SingleCells

The experiment.

required
h5_path Path | str

File to write.

required
assay Literal['raw', 'norm']

Which counts go into X.

'raw'
genes Selection | None

0-based store indices or ids of the genes to write, in the column order wanted. None writes every gene.

None
chunk_size int

Cells per streaming batch.

10000
overwrite bool

Replace an existing file.

True
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
Path

The written path.

Raises:

Type Description
FileExistsError

If the file exists and overwrite is false.

ValueError

If chunk_size is not positive or genes repeats one.

Examples:

>>> bv.io.save_h5ad(sc, "path/to/out.h5ad", assay="norm")

save_zarr

save_zarr(
    sc: SingleCells,
    zarr_path: Path | str,
    *,
    assay: Literal["raw", "norm"] = "raw",
    genes: Selection | None = None,
    chunk_size: int = 10000,
    overwrite: bool = True,
    verbose: Verbose = True,
) -> Path

Write an experiment to an AnnData Zarr (v3) store.

Writes what save_h5ad writes, as a Zarr directory that anndata.read_zarr opens. A failed write leaves no store behind.

Parameters:

Name Type Description Default
sc SingleCells

The experiment.

required
zarr_path Path | str

Directory to write.

required
assay Literal['raw', 'norm']

Which counts go into X.

'raw'
genes Selection | None

0-based store indices or ids of the genes to write, in the column order wanted. None writes every gene.

None
chunk_size int

Cells per streaming batch.

10000
overwrite bool

Replace an existing store.

True
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
Path

The written path.

Raises:

Type Description
FileExistsError

If the store exists and overwrite is false.

ValueError

If chunk_size is not positive or genes repeats one.

Examples:

>>> bv.io.save_zarr(sc, "path/to/out.zarr")

write_h5ad_sc

write_h5ad_sc(
    f_path: Path | str,
    counts: CsrLike,
    obs: DataFrame,
    var: DataFrame,
    *,
    overwrite: bool = True,
) -> None

Write in-memory counts to a sparse h5ad file.

The first column of obs / var becomes the index, the others are written as they are typed. X is CSR and stored as float32.

Parameters:

Name Type Description Default
f_path Path | str

File to write.

required
counts CsrLike

Cells x genes CSR matrix.

required
obs DataFrame

One row per cell, identifier first.

required
var DataFrame

One row per gene, identifier first.

required
overwrite bool

Replace an existing file.

True

Raises:

Type Description
ValueError

If obs / var do not match the matrix.

Examples:

>>> bv.io.write_h5ad_sc("path/to/file.h5ad", sim.counts, sim.obs, sim.var)

write_tenx_h5_sc

write_tenx_h5_sc(
    f_path: Path | str,
    counts: CsrLike,
    barcodes: Sequence[str],
    features: DataFrame,
    *,
    version: Literal["v3", "v2"] = "v3",
    overwrite: bool = True,
) -> None

Write in-memory counts to a 10x h5 file.

Parameters:

Name Type Description Default
f_path Path | str

File to write.

required
counts CsrLike

Cells x features CSR matrix of integral counts.

required
barcodes Sequence[str]

One per cell.

required
features DataFrame

id and name, plus optionally feature_type (v3; all "Gene Expression" when absent), one row per feature.

required
version Literal['v3', 'v2']

Layout to write.

'v3'
overwrite bool

Replace an existing file.

True

Raises:

Type Description
ValueError

If the inputs do not match the matrix.

Examples:

>>> barcodes = sim.obs["cell_id"].to_list()
>>> features = sim.var.select(id="gene_id", name="gene_id")
>>> bv.io.write_tenx_h5_sc("path/to/file.h5", sim.counts, barcodes, features)

write_cellranger_output

write_cellranger_output(
    f_path: Path | str,
    counts: CsrLike,
    obs: DataFrame,
    var: DataFrame,
    *,
    format_type: Literal["csv", "tsv"] = "csv",
    rows: Literal["cells", "genes"] = "cells",
    overwrite: bool = True,
) -> None

Write counts as a CellRanger style trio.

Writes matrix.mtx (integer coordinate format, 1-based) plus barcodes.<format_type> and features.<format_type> with a header row.

Parameters:

Name Type Description Default
f_path Path | str

Directory to write into, created if missing.

required
counts CsrLike

Cells x genes CSR matrix of integral counts.

required
obs DataFrame

One row per cell.

required
var DataFrame

One row per gene.

required
format_type Literal['csv', 'tsv']

"csv" or "tsv" for the two tables.

'csv'
rows Literal['cells', 'genes']

Whether the rows of the .mtx are cells or genes.

'cells'
overwrite bool

Replace existing files.

True

Raises:

Type Description
FileExistsError

If a file exists and overwrite is false.

Examples:

>>> out = "path/to/mtx_dir"
>>> bv.io.write_cellranger_output(
...     out, sim.counts, sim.obs, sim.var, rows="genes"
... )

Store maintenance

Getting counts into an experiment directory, and back out.

Every loader takes the directory to create and returns the opened SingleCells. Pick the one for your format: load_csr for counts already in memory, load_h5ad, load_tenx_h5 or load_mtx for files, and the load_multi_* twins for several files in one go. After the first load you only need load_existing.

What a load does. It applies the cell and gene QC of MinQualityParams (by default at least 100 genes, 250 counts per cell and 10 cells per gene), so dropped cells and genes never enter the store. It then writes the cell-major and gene-major stores and loads obs and var into the DuckDB, adding nnz and lib_size to obs and no_cells_exp to var. Loading into a directory that already holds an experiment overwrites its stores and drops any saved memory_py.*.

Several files. prescan_h5ad_files, prescan_tenx_h5_files and prescan_mtx_dirs read the gene sets first and fix the gene universe (intersection by default, or union), then load_multi_* loads against that prescan. obs gains exp_id and cell_id is prefixed with it. To combine experiments you already loaded, merge_sc_experiments keeps the shared genes and each input's kept cells, and carries no cache over.

Saving. obs and var edits go to the DuckDB at once. save writes what lives in memory: the cell filter, the HVG set and the cache, as memory_py.npz and memory_py.json. It does not write a fitted residual model, and warns. load_existing brings it all back, and restores the stores from counts.bxa if only the archive is left (archive_sc_exp). save_h5ad exports kept cells, obs, var and the embeddings and graph that still match to an h5ad file, save_zarr the same to an AnnData Zarr store; write_h5ad_sc, write_tenx_h5_sc and write_cellranger_output write in-memory counts as files other tools read.

Test data. generate_single_cell_test_data plants cell types in synthetic counts. The generate_* twins serve the ADT, CellSweep and DIALOGUE examples. The download_* functions fetch the vignette data sets into ~/.cache/bixverse and return the path, or the cached one.

params = bv.params.SyntheticDataParams(n_cells=2000, n_genes=500)
sim = bv.io.generate_single_cell_test_data(params, seed=1)
sc = bv.io.load_csr("experiments/demo", sim.counts, sim.obs, sim.var)

bv.pp.find_hvg(sc, hvg_no=200)
bv.io.save(sc)
sc = bv.io.load_existing("experiments/demo")

Gotchas. The loaders want integral raw counts. load_h5ad finds them with detect_raw_count_slot, which prefers layers.counts, then raw.X, then X; set raw_count_slot if it picks wrong, and use load_h5ad_norm for files that only hold log-normalised values. load_mtx takes genes as rows, the 10x convention, unless cells_as_rows says otherwise; get_cell_ranger_params finds the three files for you. The h5ad readers take an anndata Zarr store (v2 or v3) as well. Nothing here needs h5py. A v4 store still opens with a warning; a v3 store no longer opens. upgrade_sc_store converts both.

archive_sc_exp

archive_sc_exp(
    sc: SingleCells,
    *,
    level: int = 3,
    remove_bins: bool = True,
    verbose: Verbose = True,
) -> dict[str, int]

Archive the counts for cold storage.

Writes counts.bxa, a zstd archive of the cell-based store; the gene-based store is rebuilt on restore. load_existing restores the stores from the archive when they are missing.

Parameters:

Name Type Description Default
sc SingleCells

The experiment.

required
level int

zstd level, 1 to 22.

3
remove_bins bool

Delete both stores afterwards.

True
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
dict[str, int]

n_cells, nnz, n_norm_stored (cells whose normalised values

dict[str, int]

were stored verbatim) and archive_bytes.

Raises:

Type Description
ValueError

If level is outside 1 to 22.

Examples:

>>> stats = bv.io.archive_sc_exp(sc, level=10)
>>> sc = bv.io.load_existing("experiments/demo")

upgrade_sc_store

upgrade_sc_store(
    sc: SingleCells | str | Path,
    *,
    codec: Literal["lz4", "zstd", "none"] = "lz4",
    keep_backup: bool = True,
    verbose: Verbose = True,
) -> SingleCells | None

Convert a v3 or v4 store to the v5 format in place.

Converts into temporary files, checks them and swaps them in, so a failure leaves the store untouched. Nothing else may hold the files open meanwhile. A store already at v5 is left alone. A v3 store no longer opens, so pass its directory instead of an experiment.

Parameters:

Name Type Description Default
sc SingleCells | str | Path

The experiment, or the directory holding the store.

required
codec Literal['lz4', 'zstd', 'none']

Chunk codec of the new files.

'lz4'
keep_backup bool

Keep the originals as <path>.v<n>.bak, n their version.

True
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
SingleCells | None

The experiment, reading the converted store, or None when a

SingleCells | None

directory was passed.

Examples:

>>> sc = bv.io.upgrade_sc_store(sc, codec="zstd")
>>> bv.io.upgrade_sc_store("experiments/old_v3")

Synthetic data

Getting counts into an experiment directory, and back out.

Every loader takes the directory to create and returns the opened SingleCells. Pick the one for your format: load_csr for counts already in memory, load_h5ad, load_tenx_h5 or load_mtx for files, and the load_multi_* twins for several files in one go. After the first load you only need load_existing.

What a load does. It applies the cell and gene QC of MinQualityParams (by default at least 100 genes, 250 counts per cell and 10 cells per gene), so dropped cells and genes never enter the store. It then writes the cell-major and gene-major stores and loads obs and var into the DuckDB, adding nnz and lib_size to obs and no_cells_exp to var. Loading into a directory that already holds an experiment overwrites its stores and drops any saved memory_py.*.

Several files. prescan_h5ad_files, prescan_tenx_h5_files and prescan_mtx_dirs read the gene sets first and fix the gene universe (intersection by default, or union), then load_multi_* loads against that prescan. obs gains exp_id and cell_id is prefixed with it. To combine experiments you already loaded, merge_sc_experiments keeps the shared genes and each input's kept cells, and carries no cache over.

Saving. obs and var edits go to the DuckDB at once. save writes what lives in memory: the cell filter, the HVG set and the cache, as memory_py.npz and memory_py.json. It does not write a fitted residual model, and warns. load_existing brings it all back, and restores the stores from counts.bxa if only the archive is left (archive_sc_exp). save_h5ad exports kept cells, obs, var and the embeddings and graph that still match to an h5ad file, save_zarr the same to an AnnData Zarr store; write_h5ad_sc, write_tenx_h5_sc and write_cellranger_output write in-memory counts as files other tools read.

Test data. generate_single_cell_test_data plants cell types in synthetic counts. The generate_* twins serve the ADT, CellSweep and DIALOGUE examples. The download_* functions fetch the vignette data sets into ~/.cache/bixverse and return the path, or the cached one.

params = bv.params.SyntheticDataParams(n_cells=2000, n_genes=500)
sim = bv.io.generate_single_cell_test_data(params, seed=1)
sc = bv.io.load_csr("experiments/demo", sim.counts, sim.obs, sim.var)

bv.pp.find_hvg(sc, hvg_no=200)
bv.io.save(sc)
sc = bv.io.load_existing("experiments/demo")

Gotchas. The loaders want integral raw counts. load_h5ad finds them with detect_raw_count_slot, which prefers layers.counts, then raw.X, then X; set raw_count_slot if it picks wrong, and use load_h5ad_norm for files that only hold log-normalised values. load_mtx takes genes as rows, the 10x convention, unless cells_as_rows says otherwise; get_cell_ranger_params finds the three files for you. The h5ad readers take an anndata Zarr store (v2 or v3) as well. Nothing here needs h5py. A v4 store still opens with a warning; a v3 store no longer opens. upgrade_sc_store converts both.

SyntheticData dataclass

SyntheticData(
    counts: CsrMatrix, obs: DataFrame, var: DataFrame
)

Synthetic counts with their obs and var tables.

Attributes:

Name Type Description
counts CsrMatrix

Cells x genes raw counts.

obs DataFrame

One row per cell, cell_id first.

var DataFrame

One row per gene, gene_id first.

SyntheticAdtData dataclass

SyntheticAdtData(
    counts: ndarray, obs: DataFrame, var: DataFrame
)

Synthetic ADT counts.

Attributes:

Name Type Description
counts ndarray

(n_cells, n_proteins) float64 raw counts.

obs DataFrame

One row per cell, cell_id first.

var DataFrame

One row per protein: protein_id, is_isotype.

SyntheticCellsweepData dataclass

SyntheticCellsweepData(
    counts: CsrMatrix,
    obs: DataFrame,
    var: DataFrame,
    *,
    ambient_true: ndarray,
    celltype_profiles_true: ndarray,
)

Bases: SyntheticData

Synthetic counts with a planted ambient profile.

Attributes:

Name Type Description
ambient_true ndarray

The soup per gene, in var order, summing to one.

celltype_profiles_true ndarray

(n_celltypes, n_genes), rows sum to one.

SyntheticDialogueData dataclass

SyntheticDialogueData(
    counts: CsrMatrix,
    obs: DataFrame,
    var: DataFrame,
    *,
    features: dict[str, DataFrame],
    latent: dict[str, float],
    planted: dict[str, list[str]],
)

Bases: SyntheticData

Synthetic counts with a planted multicellular programme.

Attributes:

Name Type Description
features dict[str, DataFrame]

Per cell type a frame of cell_id plus feature_01, ..., the input DIALOGUE takes.

latent dict[str, float]

The per-sample latent of the planted programme.

planted dict[str, list[str]]

Per cell type the planted gene ids.

generate_single_cell_test_data

generate_single_cell_test_data(
    params: SyntheticDataParams | None = None,
    *,
    seed: int = 42,
) -> SyntheticData

Synthetic RNA counts with planted cell types.

Parameters:

Name Type Description Default
params SyntheticDataParams | None

Shape of the data.

None
seed int

Seed.

42

Returns:

Type Description
SyntheticData

Counts, obs (cell_id, cell_grp, batch_index, plus sample_id

SyntheticData

with sample membership) and var (gene_id, ensembl_id).

Examples:

>>> params = bv.params.SyntheticDataParams(n_cells=2000, n_genes=500)
>>> sim = bv.io.generate_single_cell_test_data(params, seed=1)

generate_single_cell_test_data_adt

generate_single_cell_test_data_adt(
    params: SyntheticDataAdtParams | None = None,
    *,
    seed: int = 42,
) -> SyntheticAdtData

Synthetic ADT counts, cell for cell with generate_single_cell_test_data.

Parameters:

Name Type Description Default
params SyntheticDataAdtParams | None

Shape of the data.

None
seed int

Seed.

42

Returns:

Type Description
SyntheticAdtData

Dense counts, obs (cell_id, cell_grp, batch_index) and var

SyntheticAdtData

(protein_id, is_isotype).

Examples:

>>> adt_params = bv.params.SyntheticDataAdtParams(n_cells=2000, n_proteins=15)
>>> adt = bv.io.generate_single_cell_test_data_adt(adt_params, seed=1)

generate_cellsweep_test_data

generate_cellsweep_test_data(
    params: SyntheticCellsweepParams | None = None,
    *,
    seed: int = 42,
) -> SyntheticCellsweepData

Synthetic counts with a planted ambient profile, for CellSweep.

Real barcodes come first, empty droplets after. Load them with a fully permissive MinQualityParams, or the ingest drops the empty droplets the model trains on.

Parameters:

Name Type Description Default
params SyntheticCellsweepParams | None

Shape of the data.

None
seed int

Seed.

42

Returns:

Type Description
SyntheticCellsweepData

Counts, obs (cell_id, cell_grp null for empties, sample_id,

SyntheticCellsweepData

is_empty, alpha_true null for empties), var and the ground truth.

Examples:

>>> sweep_params = bv.params.SyntheticCellsweepParams(n_real=300, n_empty=1000)
>>> sweep = bv.io.generate_cellsweep_test_data(sweep_params)

generate_dialogue_test_data

generate_dialogue_test_data(
    params: SyntheticDialogueParams | None = None,
    *,
    seed: int = 42,
) -> SyntheticDialogueData

Synthetic counts with a planted multicellular programme, for DIALOGUE.

Cells are laid out by cell type and, within one, by sample. Only the first feature column and the planted genes carry the shared per-sample latent.

Parameters:

Name Type Description Default
params SyntheticDialogueParams | None

Shape of the data.

None
seed int

Seed.

42

Returns:

Type Description
SyntheticDialogueData

Counts, obs (cell_id, cell_grp, sample_id, cell_quality, the

SyntheticDialogueData

last pure noise), var, the per cell type features, the latent and the

SyntheticDialogueData

planted genes.

Examples:

>>> dlg_params = bv.params.SyntheticDialogueParams(n_samples=10)
>>> dialogue = bv.io.generate_dialogue_test_data(dlg_params)

Example data sets

Getting counts into an experiment directory, and back out.

Every loader takes the directory to create and returns the opened SingleCells. Pick the one for your format: load_csr for counts already in memory, load_h5ad, load_tenx_h5 or load_mtx for files, and the load_multi_* twins for several files in one go. After the first load you only need load_existing.

What a load does. It applies the cell and gene QC of MinQualityParams (by default at least 100 genes, 250 counts per cell and 10 cells per gene), so dropped cells and genes never enter the store. It then writes the cell-major and gene-major stores and loads obs and var into the DuckDB, adding nnz and lib_size to obs and no_cells_exp to var. Loading into a directory that already holds an experiment overwrites its stores and drops any saved memory_py.*.

Several files. prescan_h5ad_files, prescan_tenx_h5_files and prescan_mtx_dirs read the gene sets first and fix the gene universe (intersection by default, or union), then load_multi_* loads against that prescan. obs gains exp_id and cell_id is prefixed with it. To combine experiments you already loaded, merge_sc_experiments keeps the shared genes and each input's kept cells, and carries no cache over.

Saving. obs and var edits go to the DuckDB at once. save writes what lives in memory: the cell filter, the HVG set and the cache, as memory_py.npz and memory_py.json. It does not write a fitted residual model, and warns. load_existing brings it all back, and restores the stores from counts.bxa if only the archive is left (archive_sc_exp). save_h5ad exports kept cells, obs, var and the embeddings and graph that still match to an h5ad file, save_zarr the same to an AnnData Zarr store; write_h5ad_sc, write_tenx_h5_sc and write_cellranger_output write in-memory counts as files other tools read.

Test data. generate_single_cell_test_data plants cell types in synthetic counts. The generate_* twins serve the ADT, CellSweep and DIALOGUE examples. The download_* functions fetch the vignette data sets into ~/.cache/bixverse and return the path, or the cached one.

params = bv.params.SyntheticDataParams(n_cells=2000, n_genes=500)
sim = bv.io.generate_single_cell_test_data(params, seed=1)
sc = bv.io.load_csr("experiments/demo", sim.counts, sim.obs, sim.var)

bv.pp.find_hvg(sc, hvg_no=200)
bv.io.save(sc)
sc = bv.io.load_existing("experiments/demo")

Gotchas. The loaders want integral raw counts. load_h5ad finds them with detect_raw_count_slot, which prefers layers.counts, then raw.X, then X; set raw_count_slot if it picks wrong, and use load_h5ad_norm for files that only hold log-normalised values. load_mtx takes genes as rows, the 10x convention, unless cells_as_rows says otherwise; get_cell_ranger_params finds the three files for you. The h5ad readers take an anndata Zarr store (v2 or v3) as well. Nothing here needs h5py. A v4 store still opens with a warning; a v3 store no longer opens. upgrade_sc_store converts both.

download_pbmc3k

download_pbmc3k(
    cache_dir: Path | str | None = None,
    *,
    quiet: bool = False,
) -> Path

The 10x PBMC 3k filtered matrices.

Parameters:

Name Type Description Default
cache_dir Path | str | None

Where to cache the data. Defaults to ~/.cache/bixverse.

None
quiet bool

Suppress progress logging.

False

Returns:

Type Description
Path

The extracted filtered_gene_bc_matrices/hg19 directory.

Examples:

>>> pbmc_dir = bv.io.download_pbmc3k()
>>> mtx_params = bv.io.get_cell_ranger_params(pbmc_dir)
>>> sc = bv.io.load_mtx("experiments/pbmc3k", mtx_params)

download_pbmc8k

download_pbmc8k(
    cache_dir: Path | str | None = None,
    *,
    quiet: bool = False,
) -> Path

The 10x PBMC 8k data.

Parameters:

Name Type Description Default
cache_dir Path | str | None

Where to cache the data. Defaults to ~/.cache/bixverse.

None
quiet bool

Suppress progress logging.

False

Returns:

Type Description
Path

The extracted pmbc-8k directory.

download_pbmc_1k_5p

download_pbmc_1k_5p(
    cache_dir: Path | str | None = None,
    *,
    quiet: bool = False,
) -> Path

The unfiltered 10x PBMC 1k 5' matrix.

Every barcode is in there, empty droplets included, which is what CellSweep needs. The file also carries Antibody Capture features. The GitHub release copy comes first; the 10x CDN refuses Python's downloader.

Parameters:

Name Type Description Default
cache_dir Path | str | None

Where to cache the data. Defaults to ~/.cache/bixverse.

None
quiet bool

Suppress progress logging.

False

Returns:

Type Description
Path

The h5 file.

download_pbmc_batches

download_pbmc_batches(
    cache_dir: Path | str | None = None,
    *,
    quiet: bool = False,
) -> Path

Two PBMC h5ad files, for batch correction.

Parameters:

Name Type Description Default
cache_dir Path | str | None

Where to cache the data. Defaults to ~/.cache/bixverse.

None
quiet bool

Suppress progress logging.

False

Returns:

Type Description
Path

The extracted pbmc_batches directory.

download_pbmc_multiome

download_pbmc_multiome(
    cache_dir: Path | str | None = None,
    *,
    quiet: bool = False,
) -> Path

The 10x PBMC unsorted 3k multiome (Cell Ranger ARC 2.0).

The filtered feature barcode matrix (RNA and Cell Ranger's peak counts in one h5), the fragment file with its tabix index, Cell Ranger's peaks, the GENCODE v32 annotation its GRCh38 reference was built from, and the ENCODE hg38 blacklist (v2, Amemiya et al. 2019). 10x Genomics data, CC BY 4.0.

Parameters:

Name Type Description Default
cache_dir Path | str | None

Where to cache the data. Defaults to ~/.cache/bixverse.

None
quiet bool

Suppress progress logging.

False

Returns:

Type Description
Path

The pbmc_multiome directory holding the files under their 10x names.

download_pbmc_totalseq_data

download_pbmc_totalseq_data(
    cache_dir: Path | str | None = None,
    *,
    quiet: bool = False,
) -> Path

The 10k PBMC TotalSeq-B data, with ADT counts.

Parameters:

Name Type Description Default
cache_dir Path | str | None

Where to cache the data. Defaults to ~/.cache/bixverse.

None
quiet bool

Suppress progress logging.

False

Returns:

Type Description
Path

The 10x h5 file.

download_kang_pbmc

download_kang_pbmc(
    cache_dir: Path | str | None = None,
    *,
    quiet: bool = False,
) -> Path

The Kang et al. IFN-beta stimulated PBMCs (Nat Biotechnol, 2018).

The raw counts with the cell and gene annotations, as h5ad.

Parameters:

Name Type Description Default
cache_dir Path | str | None

Where to cache the data. Defaults to ~/.cache/bixverse.

None
quiet bool

Suppress progress logging.

False

Returns:

Type Description
Path

The h5ad file.

download_demuxlet_pbmc

download_demuxlet_pbmc(
    cache_dir: Path | str | None = None,
    *,
    quiet: bool = False,
) -> Path

PBMCs with demuxlet doublet calls, for doublet detection.

Parameters:

Name Type Description Default
cache_dir Path | str | None

Where to cache the data. Defaults to ~/.cache/bixverse.

None
quiet bool

Suppress progress logging.

False

Returns:

Type Description
Path

The extracted demuxlet_PBMCs directory.

download_cd34_data

download_cd34_data(
    cache_dir: Path | str | None = None,
    *,
    quiet: bool = False,
) -> Path

The CD34 data set of the SEACells paper.

Persad et al., Nat Biotechnol, 2023.

Parameters:

Name Type Description Default
cache_dir Path | str | None

Where to cache the data. Defaults to ~/.cache/bixverse.

None
quiet bool

Suppress progress logging.

False

Returns:

Type Description
Path

The h5ad file.

download_marrow_cd34

download_marrow_cd34(
    cache_dir: Path | str | None = None,
    *,
    quiet: bool = False,
) -> Path

The bone marrow CD34 data of the Palantir paper.

Setty et al., Nat Biotechnol, 2019.

Parameters:

Name Type Description Default
cache_dir Path | str | None

Where to cache the data. Defaults to ~/.cache/bixverse.

None
quiet bool

Suppress progress logging.

False

Returns:

Type Description
Path

The h5ad file.

download_dialogue_uc

download_dialogue_uc(
    cache_dir: Path | str | None = None,
    *,
    quiet: bool = False,
) -> Path

The ulcerative colitis subset of the DIALOGUE paper.

The published log2(TPM / 10 + 1) matrix, linearised back to the TPM/10 scale and rounded so it loads like counts (Smillie et al., Cell, 2019; Jerby-Arnon and Regev, Nat Biotechnol, 2022).

Parameters:

Name Type Description Default
cache_dir Path | str | None

Where to cache the data. Defaults to ~/.cache/bixverse.

None
quiet bool

Suppress progress logging.

False

Returns:

Type Description
Path

The h5ad file.

download_thymus_ageing

download_thymus_ageing(
    cache_dir: Path | str | None = None,
    *,
    quiet: bool = False,
) -> Path

The Baran-Gale et al. ageing thymus data (Development, 2020).

The raw counts with the cell and gene annotations, as h5ad.

Parameters:

Name Type Description Default
cache_dir Path | str | None

Where to cache the data. Defaults to ~/.cache/bixverse.

None
quiet bool

Suppress progress logging.

False

Returns:

Type Description
Path

The h5ad file.