Skip to content

Preprocessing

Highly variable genes, PCA, residual models and MAGIC.

Everything here reads the count stores in Rust and works on the cells you kept. Start with find_hvg, then calculate_pca: the PCA uses the HVG set that find_hvg stored. The kNN graph, clustering and embeddings live in bv.graph and bv.embed.

What lands where. find_hvg writes the per-gene statistics to var and the selected genes to sc.map.hvg. calculate_pca writes scores, loadings and singular values to sc.cache. fit_residuals writes the fitted model to sc.cache.residual_fit, which find_hvg (with method="residual"), calculate_pca(residuals=True) and sct_corrected_counts then read. run_magic writes the imputed genes to sc.cache.magic. Every cached result is stamped, so sc prints what has gone stale after the cell filter moves. get_hvg_data, find_hvg_batch_aware and sct_corrected_counts leave the experiment alone and return their result.

Object types. SingleCells works everywhere. A SingleCellsSubset is accepted by all functions except get_hvg_data; on a subset find_hvg stores the selection but leaves var alone. MetaCells is accepted by find_hvg, get_hvg_data, calculate_pca and fit_residuals, and computes on its in-memory counts.

bv.pp.find_hvg(sc, hvg_no=2000)
bv.pp.calculate_pca(sc, no_pcs=30)

The residual route fits a model once and reuses it for the HVGs and the PCA:

bv.pp.fit_residuals(sc, method="analytic_pearson")
bv.pp.find_hvg(sc, hvg_params=bv.params.HvgParams(method="residual"))
bv.pp.calculate_pca(
    sc, 30, pca_params=bv.params.PcaParams(normalise_variance=False), residuals=True
)

Gotchas. calculate_pca without HVGs warns and returns, so run find_hvg first or pass hvg=. A residual model is bound to the current cell set: change the filter and find_hvg or calculate_pca refuse it until you refit. With method="residual", hvg_no counts per group and the union is kept. For several batches use find_hvg_batch_aware and hand its hvg_gene_idx to calculate_pca. run_magic needs a kNN graph over the kept cells from bv.graph.find_neighbours; do not feed its output to correlation-based methods, the smoothing inflates gene-gene correlation.

Worked through in Analysing PBMCs with bixverse and Pearson residuals and scTransform.

Highly variable genes

Highly variable genes, PCA, residual models and MAGIC.

Everything here reads the count stores in Rust and works on the cells you kept. Start with find_hvg, then calculate_pca: the PCA uses the HVG set that find_hvg stored. The kNN graph, clustering and embeddings live in bv.graph and bv.embed.

What lands where. find_hvg writes the per-gene statistics to var and the selected genes to sc.map.hvg. calculate_pca writes scores, loadings and singular values to sc.cache. fit_residuals writes the fitted model to sc.cache.residual_fit, which find_hvg (with method="residual"), calculate_pca(residuals=True) and sct_corrected_counts then read. run_magic writes the imputed genes to sc.cache.magic. Every cached result is stamped, so sc prints what has gone stale after the cell filter moves. get_hvg_data, find_hvg_batch_aware and sct_corrected_counts leave the experiment alone and return their result.

Object types. SingleCells works everywhere. A SingleCellsSubset is accepted by all functions except get_hvg_data; on a subset find_hvg stores the selection but leaves var alone. MetaCells is accepted by find_hvg, get_hvg_data, calculate_pca and fit_residuals, and computes on its in-memory counts.

bv.pp.find_hvg(sc, hvg_no=2000)
bv.pp.calculate_pca(sc, no_pcs=30)

The residual route fits a model once and reuses it for the HVGs and the PCA:

bv.pp.fit_residuals(sc, method="analytic_pearson")
bv.pp.find_hvg(sc, hvg_params=bv.params.HvgParams(method="residual"))
bv.pp.calculate_pca(
    sc, 30, pca_params=bv.params.PcaParams(normalise_variance=False), residuals=True
)

Gotchas. calculate_pca without HVGs warns and returns, so run find_hvg first or pass hvg=. A residual model is bound to the current cell set: change the filter and find_hvg or calculate_pca refuse it until you refit. With method="residual", hvg_no counts per group and the union is kept. For several batches use find_hvg_batch_aware and hand its hvg_gene_idx to calculate_pca. run_magic needs a kNN graph over the kept cells from bv.graph.find_neighbours; do not feed its output to correlation-based methods, the smoothing inflates gene-gene correlation.

BatchHvg dataclass

BatchHvg(
    hvg_genes: ndarray,
    hvg_gene_idx: ndarray,
    hvg_data: DataFrame,
)

Batch-aware HVGs.

Attributes:

Name Type Description
hvg_genes ndarray

Gene ids of the HVGs.

hvg_gene_idx ndarray

Their 0-based gene indices.

hvg_data DataFrame

Per batch and gene statistics, with batch (the label) and gene_idx (0-based).

find_hvg

find_hvg(
    sc: ScOrMc,
    *,
    hvg_no: int = 2000,
    hvg_params: HvgParams | None = None,
    streaming: bool | None = None,
    verbose: Verbose = True,
) -> None

Select highly variable genes over the kept cells.

The per-gene statistics go to var (mean, var, var_exp, var_std for "vst"; mean, dispersion, dispersion_scaled, bin for "meanvarbin" / "dispersion"; scran_mean, scran_var, scran_fitted, scran_residual for "scran"), the top hvg_no genes on the ranking statistic to sc.map.hvg. On a SingleCellsSubset only the selection is stored.

method = "residual" ranks on the residual variance of the model from fit_residuals, writes residual_variance instead, and treats hvg_no as a per-group count whose union is kept.

On MetaCells the statistics come from the in-memory counts (raw for "vst", normalised otherwise) and go to its var, the selection to mc.hvg; the residual method writes no statistics there. streaming is ignored.

Parameters:

Name Type Description Default
sc ScOrMc

The experiment.

required
hvg_no int

Number of HVGs (per group for "residual").

2000
hvg_params HvgParams | None

The HVG parameters. None uses the defaults.

None
streaming bool | None

Read the genes in batches. None streams above N_CELLS_STREAMING_THRESHOLD kept cells.

None
verbose Verbose

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

True

Raises:

Type Description
ValueError

If hvg_no exceeds the gene count, or the residual model is missing or stale.

Examples:

>>> bv.pp.find_hvg(sc, hvg_no=2000)
>>> bv.pp.find_hvg(sc, hvg_params=bv.params.HvgParams(method="meanvarbin"))

get_hvg_data

get_hvg_data(
    sc: SingleCells | MetaCells,
    *,
    cell_ids: Sequence[str] | None = None,
    hvg_no: int = 3000,
    hvg_params: HvgParams | None = None,
    streaming: bool | None = None,
    verbose: Verbose = True,
) -> DataFrame

HVG statistics without touching the experiment.

Parameters:

Name Type Description Default
sc SingleCells | MetaCells

The experiment, or meta cells.

required
cell_ids Sequence[str] | None

The cells (meta cell ids on MetaCells) to compute over. None for the kept cells, or every meta cell.

None
hvg_no int

Number of genes to flag.

3000
hvg_params HvgParams | None

The HVG parameters; "residual" is refused, it needs a model fitted on a fixed cell set.

None
streaming bool | None

Read the genes in batches. None streams above N_CELLS_STREAMING_THRESHOLD cells.

None
verbose Verbose

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

True

Returns:

Type Description
DataFrame

gene_idx (0-based), gene_id, the statistics, is_hvg and

DataFrame

hvg_rank (1 for the most variable, null outside the HVGs).

Raises:

Type Description
ValueError

On method "residual" or an hvg_no past the gene count.

Examples:

>>> hvg_stats = bv.pp.get_hvg_data(sc, hvg_no=500)

find_hvg_batch_aware

find_hvg_batch_aware(
    sc: ScOrScSubset,
    batch_column: str,
    *,
    hvg_no: int = 2000,
    gene_comb_method: GeneCombMethod = "union",
    hvg_params: HvgParams | None = None,
    streaming: bool | None = None,
    verbose: Verbose = True,
) -> BatchHvg

HVGs per batch, combined across batches.

Does not touch the experiment: pass hvg_gene_idx to calculate_pca.

Parameters:

Name Type Description Default
sc ScOrScSubset

The experiment.

required
batch_column str

obs column holding the batch.

required
hvg_no int

HVGs per batch ("union", "intersection") or in total ("average").

2000
gene_comb_method GeneCombMethod

"union" of the per-batch top genes, top genes of the "average" score, or the "intersection" of the per-batch top genes.

'union'
hvg_params HvgParams | None

The HVG parameters; "residual" is refused, fit per batch with fit_residuals(group_column=...) instead.

None
streaming bool | None

Read the genes in batches. None streams above N_CELLS_STREAMING_THRESHOLD kept cells.

None
verbose Verbose

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

True

Returns:

Type Description
BatchHvg

The HVGs and the per-batch statistics.

Raises:

Type Description
ValueError

On method "residual", or a missing or incomplete batch column.

Examples:

>>> batch_hvg = bv.pp.find_hvg_batch_aware(sc, "batch_index", hvg_no=500)
>>> bv.pp.calculate_pca(sc, 20, hvg=batch_hvg.hvg_gene_idx)

PCA

Highly variable genes, PCA, residual models and MAGIC.

Everything here reads the count stores in Rust and works on the cells you kept. Start with find_hvg, then calculate_pca: the PCA uses the HVG set that find_hvg stored. The kNN graph, clustering and embeddings live in bv.graph and bv.embed.

What lands where. find_hvg writes the per-gene statistics to var and the selected genes to sc.map.hvg. calculate_pca writes scores, loadings and singular values to sc.cache. fit_residuals writes the fitted model to sc.cache.residual_fit, which find_hvg (with method="residual"), calculate_pca(residuals=True) and sct_corrected_counts then read. run_magic writes the imputed genes to sc.cache.magic. Every cached result is stamped, so sc prints what has gone stale after the cell filter moves. get_hvg_data, find_hvg_batch_aware and sct_corrected_counts leave the experiment alone and return their result.

Object types. SingleCells works everywhere. A SingleCellsSubset is accepted by all functions except get_hvg_data; on a subset find_hvg stores the selection but leaves var alone. MetaCells is accepted by find_hvg, get_hvg_data, calculate_pca and fit_residuals, and computes on its in-memory counts.

bv.pp.find_hvg(sc, hvg_no=2000)
bv.pp.calculate_pca(sc, no_pcs=30)

The residual route fits a model once and reuses it for the HVGs and the PCA:

bv.pp.fit_residuals(sc, method="analytic_pearson")
bv.pp.find_hvg(sc, hvg_params=bv.params.HvgParams(method="residual"))
bv.pp.calculate_pca(
    sc, 30, pca_params=bv.params.PcaParams(normalise_variance=False), residuals=True
)

Gotchas. calculate_pca without HVGs warns and returns, so run find_hvg first or pass hvg=. A residual model is bound to the current cell set: change the filter and find_hvg or calculate_pca refuse it until you refit. With method="residual", hvg_no counts per group and the union is kept. For several batches use find_hvg_batch_aware and hand its hvg_gene_idx to calculate_pca. run_magic needs a kNN graph over the kept cells from bv.graph.find_neighbours; do not feed its output to correlation-based methods, the smoothing inflates gene-gene correlation.

calculate_pca

calculate_pca(
    sc: ScOrMc,
    no_pcs: int,
    *,
    pca_params: PcaParams | None = None,
    sparse_svd: bool | None = None,
    hvg: ndarray
    | Sequence[int]
    | Sequence[str]
    | None = None,
    seed: int = 42,
    residuals: bool = False,
    verbose: Verbose = True,
) -> None

PCA over the kept cells and the HVGs.

Scores, loadings and the first no_pcs singular values go to sc.cache, stamped "pca" (derived from "residuals" on the residual path).

Parameters:

Name Type Description Default
sc ScOrMc

The experiment.

required
no_pcs int

Number of components.

required
pca_params PcaParams | None

The PCA parameters. None uses the defaults.

None
sparse_svd bool | None

Solve on the sparse matrix. None means True on the normalised path and False on the residual one; above N_CELLS_DENSE_PCA_LIMIT cells the normalised path is always sparse.

None
hvg ndarray | Sequence[int] | Sequence[str] | None

0-based gene indices or gene ids to use instead of sc.map.hvg; they replace it.

None
seed int

Seed for the randomised SVD.

42
residuals bool

Run on the residuals of the model from fit_residuals. Dense only, and needs clr and normalise_variance off.

False
verbose Verbose

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

True

On MetaCells the PCA is dense over the in-memory normalised counts (raw for the residual path) and sparse_svd is ignored.

Raises:

Type Description
ValueError

On a residual run that cannot be honoured, or a missing or stale residual model.

Examples:

>>> bv.pp.calculate_pca(sc, no_pcs=30)
>>> bv.pp.calculate_pca(sc, no_pcs=30, sparse_svd=False, seed=1)

Residuals and scTransform

Highly variable genes, PCA, residual models and MAGIC.

Everything here reads the count stores in Rust and works on the cells you kept. Start with find_hvg, then calculate_pca: the PCA uses the HVG set that find_hvg stored. The kNN graph, clustering and embeddings live in bv.graph and bv.embed.

What lands where. find_hvg writes the per-gene statistics to var and the selected genes to sc.map.hvg. calculate_pca writes scores, loadings and singular values to sc.cache. fit_residuals writes the fitted model to sc.cache.residual_fit, which find_hvg (with method="residual"), calculate_pca(residuals=True) and sct_corrected_counts then read. run_magic writes the imputed genes to sc.cache.magic. Every cached result is stamped, so sc prints what has gone stale after the cell filter moves. get_hvg_data, find_hvg_batch_aware and sct_corrected_counts leave the experiment alone and return their result.

Object types. SingleCells works everywhere. A SingleCellsSubset is accepted by all functions except get_hvg_data; on a subset find_hvg stores the selection but leaves var alone. MetaCells is accepted by find_hvg, get_hvg_data, calculate_pca and fit_residuals, and computes on its in-memory counts.

bv.pp.find_hvg(sc, hvg_no=2000)
bv.pp.calculate_pca(sc, no_pcs=30)

The residual route fits a model once and reuses it for the HVGs and the PCA:

bv.pp.fit_residuals(sc, method="analytic_pearson")
bv.pp.find_hvg(sc, hvg_params=bv.params.HvgParams(method="residual"))
bv.pp.calculate_pca(
    sc, 30, pca_params=bv.params.PcaParams(normalise_variance=False), residuals=True
)

Gotchas. calculate_pca without HVGs warns and returns, so run find_hvg first or pass hvg=. A residual model is bound to the current cell set: change the filter and find_hvg or calculate_pca refuse it until you refit. With method="residual", hvg_no counts per group and the union is kept. For several batches use find_hvg_batch_aware and hand its hvg_gene_idx to calculate_pca. run_magic needs a kNN graph over the kept cells from bv.graph.find_neighbours; do not feed its output to correlation-based methods, the smoothing inflates gene-gene correlation.

ResidualFit dataclass

ResidualFit(
    model: ResidualFit,
    method: ResidualMethod,
    params: SctransformParams | AprParams,
    group_column: str | None,
    covariate_names: tuple[str, ...],
)

A fitted residual model.

Attributes:

Name Type Description
model ResidualFit

The fitted model, held in Rust.

method ResidualMethod

"sctransform" or "analytic_pearson".

params SctransformParams | AprParams

The parameters the fit ran with.

group_column str | None

The obs column the cells were grouped by, if any.

covariate_names tuple[str, ...]

The covariates, in design order.

cell_indices property

cell_indices: ndarray

0-based store indices of the fitted cells, in fitting order.

genes property

genes: ndarray

0-based store genes modelled in every group, ascending.

n_groups property

n_groups: int

Number of groups, one model each.

CorrectedCounts dataclass

CorrectedCounts(
    f_path: Path, genes: ndarray, n_genes: int, n_cells: int
)

A corrected gene-major store written without its cell-major twin.

Attributes:

Name Type Description
f_path Path

The gene-major store.

genes ndarray

0-based source genes written, the new store's gene axis.

n_genes int

Number of genes written.

n_cells int

Number of cells written.

fit_residuals

fit_residuals(
    sc: ScOrMc,
    *,
    method: ResidualMethod = "sctransform",
    group_column: str | None = None,
    covariate_columns: Sequence[str] | None = None,
    residual_params: SctransformParams
    | AprParams
    | None = None,
    gene_batch_size: int | None = None,
    seed: int = 42,
    verbose: Verbose = True,
) -> None

Fit a scTransform (v2) or analytic Pearson residual model over the kept cells.

The model goes to sc.cache.residual_fit, stamped "residuals", and is what find_hvg(method="residual"), calculate_pca(residuals=True) and sct_corrected_counts read. It is bound to the current cell set.

Parameters:

Name Type Description Default
sc ScOrMc

The experiment.

required
method ResidualMethod

"sctransform" or "analytic_pearson".

'sctransform'
group_column str | None

obs column to fit one model per group by (sample, donor), Seurat v5 style.

None
covariate_columns Sequence[str] | None

Numeric obs columns to regress out ("sctransform" only). The library size is never one: it is the model's offset.

None
residual_params SctransformParams | AprParams | None

SctransformParams or AprParams matching method. None uses the defaults.

None
gene_batch_size int | None

Genes per disk batch. None uses the crate default.

None
seed int

Seed for the step-1 subsampling.

42
verbose Verbose

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

True

On MetaCells the model is fitted on the summed counts (still negative binomial, at a far greater depth; "analytic_pearson" is the better choice there) with obs in row order; gene_batch_size does not apply and warns.

Raises:

Type Description
TypeError

If residual_params does not match method.

ValueError

On a missing group column or unusable covariates.

Examples:

>>> bv.pp.fit_residuals(sc, method="analytic_pearson")
>>> bv.pp.find_hvg(sc, hvg_params=bv.params.HvgParams(method="residual"))
>>> bv.pp.fit_residuals(sc, group_column="batch_index")

sct_corrected_counts

sct_corrected_counts(
    sc: ScOrScSubset,
    *,
    dir_out: Path | str | None = None,
    build_cell_store: bool = True,
    overwrite: bool = False,
    gene_batch_size: int | None = None,
    verbose: Verbose = True,
) -> SingleCells | CorrectedCounts

scTransform corrected counts as a new experiment.

The counts each kept cell would have at the median library size under the fitted model, written to a fresh directory. The gene axis is the model's, so the new var table holds only the genes that survived, and the obs table the kept cells in order.

Parameters:

Name Type Description Default
sc ScOrScSubset

The experiment, with a scTransform fit.

required
dir_out Path | str | None

Output directory. None uses sct_corrected inside the experiment directory.

None
build_cell_store bool

Also build the cell-major store and the DuckDB and open the result. False writes only the gene-major store.

True
overwrite bool

Replace an existing store at dir_out.

False
gene_batch_size int | None

Genes per disk batch. None uses the crate default.

None
verbose Verbose

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

True

Returns:

Type Description
SingleCells | CorrectedCounts

The new experiment, or with build_cell_store=False what was

SingleCells | CorrectedCounts

written.

Raises:

Type Description
FileExistsError

If a store exists at dir_out and overwrite is false.

ValueError

Without a usable scTransform fit.

Examples:

>>> bv.pp.fit_residuals(sc)
>>> corrected = bv.pp.sct_corrected_counts(sc, dir_out="corrected")

MAGIC imputation

Highly variable genes, PCA, residual models and MAGIC.

Everything here reads the count stores in Rust and works on the cells you kept. Start with find_hvg, then calculate_pca: the PCA uses the HVG set that find_hvg stored. The kNN graph, clustering and embeddings live in bv.graph and bv.embed.

What lands where. find_hvg writes the per-gene statistics to var and the selected genes to sc.map.hvg. calculate_pca writes scores, loadings and singular values to sc.cache. fit_residuals writes the fitted model to sc.cache.residual_fit, which find_hvg (with method="residual"), calculate_pca(residuals=True) and sct_corrected_counts then read. run_magic writes the imputed genes to sc.cache.magic. Every cached result is stamped, so sc prints what has gone stale after the cell filter moves. get_hvg_data, find_hvg_batch_aware and sct_corrected_counts leave the experiment alone and return their result.

Object types. SingleCells works everywhere. A SingleCellsSubset is accepted by all functions except get_hvg_data; on a subset find_hvg stores the selection but leaves var alone. MetaCells is accepted by find_hvg, get_hvg_data, calculate_pca and fit_residuals, and computes on its in-memory counts.

bv.pp.find_hvg(sc, hvg_no=2000)
bv.pp.calculate_pca(sc, no_pcs=30)

The residual route fits a model once and reuses it for the HVGs and the PCA:

bv.pp.fit_residuals(sc, method="analytic_pearson")
bv.pp.find_hvg(sc, hvg_params=bv.params.HvgParams(method="residual"))
bv.pp.calculate_pca(
    sc, 30, pca_params=bv.params.PcaParams(normalise_variance=False), residuals=True
)

Gotchas. calculate_pca without HVGs warns and returns, so run find_hvg first or pass hvg=. A residual model is bound to the current cell set: change the filter and find_hvg or calculate_pca refuse it until you refit. With method="residual", hvg_no counts per group and the union is kept. For several batches use find_hvg_batch_aware and hand its hvg_gene_idx to calculate_pca. run_magic needs a kNN graph over the kept cells from bv.graph.find_neighbours; do not feed its output to correlation-based methods, the smoothing inflates gene-gene correlation.

run_magic

run_magic(
    sc: ScOrScSubset,
    features: Sequence[str],
    *,
    modality: Modality = "rna",
    magic_params: MagicParams | None = None,
    verbose: Verbose = True,
) -> None

Impute genes with MAGIC over the cached kNN graph.

The imputed layer is RNA whichever graph smoothed it, so it goes to sc.cache.magic, stamped as derived from the modality's "knn". Do not feed it to correlation-based methods: the smoothing inflates gene-gene correlation.

Parameters:

Name Type Description Default
sc ScOrScSubset

The experiment, with a kNN graph over the kept cells.

required
features Sequence[str]

Gene ids to impute. Unknown ids warn and drop.

required
modality Modality

The kNN graph: "rna", or "adt" / "atac" / "wnn" on a SingleCellsMultiModal.

'rna'
magic_params MagicParams | None

The MAGIC parameters. None uses the defaults.

None
verbose Verbose

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

True

Raises:

Type Description
ValueError

If the kNN graph is stale or does not cover the kept cells.

References

van Dijk, et al., Cell, 2018.

Examples:

>>> bv.graph.find_neighbours(sc)
>>> magic = bv.params.MagicParams(n_steps=2)
>>> bv.pp.run_magic(sc, ["gene_0001", "gene_0002"], magic_params=magic)