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
|
verbose
|
Verbose
|
|
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:
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'
|
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
|
|
True
|
Returns:
| Type | Description |
|---|---|
SingleCells
|
The experiment. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
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
|
|
True
|
Returns:
| Type | Description |
|---|---|
SingleCells
|
The experiment. |
Examples:
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'
|
csc_mem_gb
|
float | None
|
Memory in GB for the CSR to CSC conversion buffers. |
None
|
verbose
|
Verbose
|
|
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. |
'Gene Expression'
|
csc_mem_gb
|
float | None
|
Memory in GB for the CSR to CSC conversion buffers. |
None
|
verbose
|
Verbose
|
|
True
|
Returns:
| Type | Description |
|---|---|
SingleCells
|
The experiment. |
Examples:
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 |
None
|
tile_width
|
int | None
|
Tile width in bp, instead of |
None
|
chrom_sizes
|
Mapping[str, int] | None
|
Chromosome lengths, for the tiles. |
None
|
mode
|
CountMode
|
What one count is, see |
'insertion'
|
barcodes
|
Sequence[str] | ndarray | None
|
The cell barcodes. |
None
|
cellranger
|
Path | str | None
|
Cell Ranger ATAC's |
None
|
min_fragments
|
int | None
|
Call cells with at least this many fragments. |
None
|
exclude_chroms
|
Sequence[str]
|
Chromosomes the |
MITO_CHROMS
|
max_mem_gb
|
float | None
|
Memory budget of the feature-major conversion. |
None
|
verbose
|
Verbose
|
|
1
|
Returns:
| Type | Description |
|---|---|
SingleCellsAtac
|
The experiment: obs holds |
SingleCellsAtac
|
var the features as |
SingleCellsAtac
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
Unless exactly one cell source and exactly one of |
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 |
required |
barcodes
|
Sequence[str] | ndarray | None
|
Cells to load; |
None
|
max_mem_gb
|
float | None
|
Memory budget of the feature-major conversion. |
None
|
verbose
|
Verbose
|
|
1
|
Returns:
| Type | Description |
|---|---|
SingleCellsAtac
|
The experiment, as |
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
|
|
True
|
Returns:
| Type | Description |
|---|---|
SingleCells
|
The experiment. |
Examples:
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 |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If one of the three files is missing. |
Examples:
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
¶
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;
|
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'
|
var_index
|
str
|
Dataset in |
'_index'
|
raw_count_slot
|
Literal['auto'] | RawSlot
|
|
'auto'
|
Returns:
| Type | Description |
|---|---|
Prescan
|
The universe (sorted) and one task per file with |
Prescan
|
|
Prescan
|
|
Examples:
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'
|
Returns:
| Type | Description |
|---|---|
Prescan
|
The universe (sorted) and one task per file with |
Prescan
|
|
Prescan
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If a v3 file has no feature of the type, or the universe is empty. |
Examples:
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
|
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 |
Prescan
|
|
Prescan
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
On fewer than two inputs, mismatched or repeated ids, or an empty intersection. |
Examples:
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 |
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
|
|
True
|
Returns:
| Type | Description |
|---|---|
SingleCells
|
The experiment. |
Examples:
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 |
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
|
|
True
|
Returns:
| Type | Description |
|---|---|
SingleCells
|
The experiment. |
Examples:
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 |
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
|
|
True
|
Returns:
| Type | Description |
|---|---|
SingleCells
|
The experiment. |
Examples:
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 |
False
|
qc
|
MinQualityParams | None
|
Only |
None
|
csc_mem_gb
|
float | None
|
Memory in GB for the CSR to CSC conversion buffers. |
None
|
verbose
|
Verbose
|
|
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:
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
¶
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
|
|
TenxH5Meta
dataclass
¶
Layout and dimensions of a 10x h5 file, as get_tenx_h5_metadata().
Attributes:
| Name | Type | Description |
|---|---|---|
version |
str
|
|
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 |
Examples:
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 |
read_h5ad_metadata
¶
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]
|
|
Examples:
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 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]
|
|
dict[str, object]
|
|
dict[str, object]
|
per type, v3 only, else |
Examples:
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:
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 |
False
|
Returns:
| Type | Description |
|---|---|
SingleCells
|
The experiment: a |
SingleCells
|
tiles. With |
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 |
Examples:
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 |
'raw'
|
genes
|
Selection | None
|
0-based store indices or ids of the genes to write, in the
column order wanted. |
None
|
chunk_size
|
int
|
Cells per streaming batch. |
10000
|
overwrite
|
bool
|
Replace an existing file. |
True
|
verbose
|
Verbose
|
|
True
|
Returns:
| Type | Description |
|---|---|
Path
|
The written path. |
Raises:
| Type | Description |
|---|---|
FileExistsError
|
If the file exists and |
ValueError
|
If |
Examples:
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 |
'raw'
|
genes
|
Selection | None
|
0-based store indices or ids of the genes to write, in the
column order wanted. |
None
|
chunk_size
|
int
|
Cells per streaming batch. |
10000
|
overwrite
|
bool
|
Replace an existing store. |
True
|
verbose
|
Verbose
|
|
True
|
Returns:
| Type | Description |
|---|---|
Path
|
The written path. |
Raises:
| Type | Description |
|---|---|
FileExistsError
|
If the store exists and |
ValueError
|
If |
Examples:
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:
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
|
|
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:
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'
|
rows
|
Literal['cells', 'genes']
|
Whether the rows of the |
'cells'
|
overwrite
|
bool
|
Replace existing files. |
True
|
Raises:
| Type | Description |
|---|---|
FileExistsError
|
If a file exists and |
Examples:
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
|
|
True
|
Returns:
| Type | Description |
|---|---|
dict[str, int]
|
|
dict[str, int]
|
were stored verbatim) and |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
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 |
True
|
verbose
|
Verbose
|
|
True
|
Returns:
| Type | Description |
|---|---|
SingleCells | None
|
The experiment, reading the converted store, or |
SingleCells | None
|
directory was passed. |
Examples:
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, |
var |
DataFrame
|
One row per gene, |
SyntheticAdtData
dataclass
¶
Synthetic ADT counts.
Attributes:
| Name | Type | Description |
|---|---|---|
counts |
ndarray
|
|
obs |
DataFrame
|
One row per cell, |
var |
DataFrame
|
One row per protein: |
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
|
|
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 |
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 ( |
SyntheticData
|
with sample membership) and var ( |
Examples:
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 ( |
SyntheticAdtData
|
( |
Examples:
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 ( |
SyntheticCellsweepData
|
|
Examples:
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 ( |
SyntheticDialogueData
|
last pure noise), var, the per cell type features, the latent and the |
SyntheticDialogueData
|
planted genes. |
Examples:
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
¶
The 10x PBMC 3k filtered matrices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cache_dir
|
Path | str | None
|
Where to cache the data. Defaults to |
None
|
quiet
|
bool
|
Suppress progress logging. |
False
|
Returns:
| Type | Description |
|---|---|
Path
|
The extracted |
Examples:
download_pbmc8k
¶
The 10x PBMC 8k data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cache_dir
|
Path | str | None
|
Where to cache the data. Defaults to |
None
|
quiet
|
bool
|
Suppress progress logging. |
False
|
Returns:
| Type | Description |
|---|---|
Path
|
The extracted |
download_pbmc_1k_5p
¶
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 |
None
|
quiet
|
bool
|
Suppress progress logging. |
False
|
Returns:
| Type | Description |
|---|---|
Path
|
The h5 file. |
download_pbmc_batches
¶
Two PBMC h5ad files, for batch correction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cache_dir
|
Path | str | None
|
Where to cache the data. Defaults to |
None
|
quiet
|
bool
|
Suppress progress logging. |
False
|
Returns:
| Type | Description |
|---|---|
Path
|
The extracted |
download_pbmc_multiome
¶
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 |
None
|
quiet
|
bool
|
Suppress progress logging. |
False
|
Returns:
| Type | Description |
|---|---|
Path
|
The |
download_pbmc_totalseq_data
¶
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 |
None
|
quiet
|
bool
|
Suppress progress logging. |
False
|
Returns:
| Type | Description |
|---|---|
Path
|
The 10x h5 file. |
download_kang_pbmc
¶
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 |
None
|
quiet
|
bool
|
Suppress progress logging. |
False
|
Returns:
| Type | Description |
|---|---|
Path
|
The h5ad file. |
download_demuxlet_pbmc
¶
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 |
None
|
quiet
|
bool
|
Suppress progress logging. |
False
|
Returns:
| Type | Description |
|---|---|
Path
|
The extracted |
download_cd34_data
¶
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 |
None
|
quiet
|
bool
|
Suppress progress logging. |
False
|
Returns:
| Type | Description |
|---|---|
Path
|
The h5ad file. |
download_marrow_cd34
¶
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 |
None
|
quiet
|
bool
|
Suppress progress logging. |
False
|
Returns:
| Type | Description |
|---|---|
Path
|
The h5ad file. |
download_dialogue_uc
¶
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 |
None
|
quiet
|
bool
|
Suppress progress logging. |
False
|
Returns:
| Type | Description |
|---|---|
Path
|
The h5ad file. |
download_thymus_ageing
¶
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 |
None
|
quiet
|
bool
|
Suppress progress logging. |
False
|
Returns:
| Type | Description |
|---|---|
Path
|
The h5ad file. |