Skip to content

Quality control

Cell QC: per-cell metrics, then MAD or fixed-threshold outlier calls.

Two steps. gene_set_proportions and top_genes_perc read the cell store in Rust and write their metrics to obs. The outlier calls (run_cell_qc, run_cell_qc_fixed) work on plain vectors you pull out of obs and return a CellQc record. get_data turns that into an obs frame, and you decide which cells to keep with sc.set_cells_to_keep. Nothing is deleted. rescue_cells and flag_cells adjust a CellQc afterwards. The metric passes take a SingleCells; the outlier calls know nothing about experiments.

What lands where. gene_set_proportions writes one obs column per gene set, named by its key, as a fraction in [0, 1]. top_genes_perc writes top_<N>_genes_percentage. lib_size and nnz are already in obs from the loaders. The outlier calls write nothing: sc.add_obs(get_data(qc)) stores the calls, and sc.set_cells_to_keep applies the filter.

mito_genes = sc.gene_ids()[:13].tolist()  # on real data: the MT- genes
bv.qc.gene_set_proportions(sc, {"mito": mito_genes})
bv.qc.top_genes_perc(sc)

obs = sc.obs(filtered=True)
metrics = {"lib_size": obs["lib_size"], "nnz": obs["nnz"], "mito": obs["mito"]}
directions = {"lib_size": "below", "nnz": "below", "mito": "above"}
qc = bv.qc.run_cell_qc(metrics, obs["cell_idx"].to_numpy(), directions=directions)

sc.add_obs(bv.qc.get_data(qc))
sc.set_cells_to_keep(qc.cell_idx[~qc.combined])

Gotchas. Pass the metrics for the kept cells (sc.obs(filtered=True)) with their cell_idx, so the two line up. get_data writes the metrics back to obs under their own names, so a transformed metric such as log10_lib_size needs its own key or it overwrites the original column. directions, if given, must name every metric. With groups (donor, sample) MAD runs per group, hard thresholds do not. rescue_cells only clears MAD flags, never hard ones. The metric passes stream the cells in batches above N_CELLS_STREAMING_THRESHOLD kept cells, and streaming= overrides that.

Worked through in Analysing PBMCs with bixverse.

Per-cell metrics

Cell QC: per-cell metrics, then MAD or fixed-threshold outlier calls.

Two steps. gene_set_proportions and top_genes_perc read the cell store in Rust and write their metrics to obs. The outlier calls (run_cell_qc, run_cell_qc_fixed) work on plain vectors you pull out of obs and return a CellQc record. get_data turns that into an obs frame, and you decide which cells to keep with sc.set_cells_to_keep. Nothing is deleted. rescue_cells and flag_cells adjust a CellQc afterwards. The metric passes take a SingleCells; the outlier calls know nothing about experiments.

What lands where. gene_set_proportions writes one obs column per gene set, named by its key, as a fraction in [0, 1]. top_genes_perc writes top_<N>_genes_percentage. lib_size and nnz are already in obs from the loaders. The outlier calls write nothing: sc.add_obs(get_data(qc)) stores the calls, and sc.set_cells_to_keep applies the filter.

mito_genes = sc.gene_ids()[:13].tolist()  # on real data: the MT- genes
bv.qc.gene_set_proportions(sc, {"mito": mito_genes})
bv.qc.top_genes_perc(sc)

obs = sc.obs(filtered=True)
metrics = {"lib_size": obs["lib_size"], "nnz": obs["nnz"], "mito": obs["mito"]}
directions = {"lib_size": "below", "nnz": "below", "mito": "above"}
qc = bv.qc.run_cell_qc(metrics, obs["cell_idx"].to_numpy(), directions=directions)

sc.add_obs(bv.qc.get_data(qc))
sc.set_cells_to_keep(qc.cell_idx[~qc.combined])

Gotchas. Pass the metrics for the kept cells (sc.obs(filtered=True)) with their cell_idx, so the two line up. get_data writes the metrics back to obs under their own names, so a transformed metric such as log10_lib_size needs its own key or it overwrites the original column. directions, if given, must name every metric. With groups (donor, sample) MAD runs per group, hard thresholds do not. rescue_cells only clears MAD flags, never hard ones. The metric passes stream the cells in batches above N_CELLS_STREAMING_THRESHOLD kept cells, and streaming= overrides that.

gene_set_proportions

gene_set_proportions(
    sc: SingleCells,
    gene_set_list: Mapping[str, Sequence[str]],
    *,
    streaming: bool | None = None,
    verbose: Verbose = True,
) -> None

Share of each kept cell's reads in each gene set.

The mitochondrial percentage pattern. One obs column per set, named by its key, as a fraction in [0, 1].

Parameters:

Name Type Description Default
sc SingleCells

The experiment.

required
gene_set_list Mapping[str, Sequence[str]]

Set name to gene ids, as in sc.gene_ids(). Unknown ids warn and drop.

required
streaming bool | None

Read the cells 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 no id of a set matches.

Examples:

>>> bv.qc.gene_set_proportions(sc, {"mito": mito_genes})
>>> bv.qc.gene_set_proportions(sc, {"mito": mito_genes}, streaming=True)

top_genes_perc

top_genes_perc(
    sc: SingleCells,
    *,
    top_n_vals: Sequence[int] = (25, 50, 100),
    streaming: bool | None = None,
    verbose: Verbose = True,
) -> None

Share of each kept cell's reads in its top N genes.

High values flag low-complexity cells. One obs column per N, named top_<N>_genes_percentage, as a fraction in [0, 1].

Parameters:

Name Type Description Default
sc SingleCells

The experiment.

required
top_n_vals Sequence[int]

The N values.

(25, 50, 100)
streaming bool | None

Read the cells 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 top_n_vals is empty or holds a value below 1.

Examples:

>>> bv.qc.top_genes_perc(sc, top_n_vals=(50, 100))

get_available_features

get_available_features(sc: SingleCells) -> DataFrame

Every obs column and gene id.

Parameters:

Name Type Description Default
sc SingleCells

The experiment.

required

Returns:

Type Description
DataFrame

feature_name and origin ("obs" or "counts").

Outlier calls

Cell QC: per-cell metrics, then MAD or fixed-threshold outlier calls.

Two steps. gene_set_proportions and top_genes_perc read the cell store in Rust and write their metrics to obs. The outlier calls (run_cell_qc, run_cell_qc_fixed) work on plain vectors you pull out of obs and return a CellQc record. get_data turns that into an obs frame, and you decide which cells to keep with sc.set_cells_to_keep. Nothing is deleted. rescue_cells and flag_cells adjust a CellQc afterwards. The metric passes take a SingleCells; the outlier calls know nothing about experiments.

What lands where. gene_set_proportions writes one obs column per gene set, named by its key, as a fraction in [0, 1]. top_genes_perc writes top_<N>_genes_percentage. lib_size and nnz are already in obs from the loaders. The outlier calls write nothing: sc.add_obs(get_data(qc)) stores the calls, and sc.set_cells_to_keep applies the filter.

mito_genes = sc.gene_ids()[:13].tolist()  # on real data: the MT- genes
bv.qc.gene_set_proportions(sc, {"mito": mito_genes})
bv.qc.top_genes_perc(sc)

obs = sc.obs(filtered=True)
metrics = {"lib_size": obs["lib_size"], "nnz": obs["nnz"], "mito": obs["mito"]}
directions = {"lib_size": "below", "nnz": "below", "mito": "above"}
qc = bv.qc.run_cell_qc(metrics, obs["cell_idx"].to_numpy(), directions=directions)

sc.add_obs(bv.qc.get_data(qc))
sc.set_cells_to_keep(qc.cell_idx[~qc.combined])

Gotchas. Pass the metrics for the kept cells (sc.obs(filtered=True)) with their cell_idx, so the two line up. get_data writes the metrics back to obs under their own names, so a transformed metric such as log10_lib_size needs its own key or it overwrites the original column. directions, if given, must name every metric. With groups (donor, sample) MAD runs per group, hard thresholds do not. rescue_cells only clears MAD flags, never hard ones. The metric passes stream the cells in batches above N_CELLS_STREAMING_THRESHOLD kept cells, and streaming= overrides that.

CellQc dataclass

CellQc(
    cell_idx: ndarray,
    metrics: dict[str, ndarray],
    groups: ndarray,
    thresholds: DataFrame | None,
    outlier_mat: dict[str, ndarray],
    hard_mat: dict[str, ndarray],
    rescued_mat: dict[str, ndarray],
    hard_thresholds: dict[str, dict[str, float]] | None,
    combined: ndarray,
    per_group_stats: DataFrame | None,
)

Outlier calls over several per-cell metrics.

The per-metric flag dicts all share the metric order of metrics. A cell is an outlier on a metric if MAD flagged it and it was not rescued, or a hard threshold flagged it; combined is that over any metric.

Attributes:

Name Type Description
cell_idx ndarray

0-based store index of each cell.

metrics dict[str, ndarray]

Metric name to its values, dtype as given.

groups ndarray

Group label per cell ("all" without groups).

thresholds DataFrame | None

The MAD thresholds per metric and group (metric, group, median, upper_threshold, lower_threshold), None when MAD was skipped.

outlier_mat dict[str, ndarray]

MAD flags per metric.

hard_mat dict[str, ndarray]

Hard-threshold flags per metric.

rescued_mat dict[str, ndarray]

Rescued MAD flags per metric.

hard_thresholds dict[str, dict[str, float]] | None

The hard bounds applied, per metric.

combined ndarray

The final call per cell.

per_group_stats DataFrame | None

Group-level MAD calls when there is more than one group, else None.

final

final(metric: str) -> ndarray

The final per-metric call: MAD and not rescued, or hard.

MadOutlier dataclass

MadOutlier(
    outlier: ndarray,
    median: float,
    upper_threshold: float | None,
    lower_threshold: float | None,
)

MAD outlier calls on one metric.

Attributes:

Name Type Description
outlier ndarray

One flag per value.

median float

The metric's median.

upper_threshold float | None

median + margin, None for direction "below".

lower_threshold float | None

median - margin, None for direction "above".

run_cell_qc

run_cell_qc(
    metrics: Mapping[str, Vector],
    cells_to_keep: ndarray | Sequence[int],
    *,
    directions: Mapping[str, Direction] | None = None,
    threshold: float = 3.0,
    groups: Sequence[object]
    | ndarray
    | Series
    | None = None,
    hard_thresholds: Mapping[str, Bounds] | None = None,
    mad: bool = True,
    r_standard: bool = True,
) -> CellQc

Outlier detection over several per-cell QC metrics.

MAD runs per group when groups is given; hard thresholds ignore groups.

Parameters:

Name Type Description Default
metrics Mapping[str, Vector]

Metric name to its values, one per cell.

required
cells_to_keep ndarray | Sequence[int]

0-based store index of each cell, aligned to the metrics.

required
directions Mapping[str, Direction] | None

Metric name to direction. Missing means "twosided" for every metric; given, it must name every metric.

None
threshold float

MADs for the outlier calls.

3.0
groups Sequence[object] | ndarray | Series | None

Optional group label per cell (donor, sample).

None
hard_thresholds Mapping[str, Bounds] | None

Optional metric name to {"lower": .., "upper": ..} (either or both), applied regardless of groups.

None
mad bool

Run MAD. False needs hard_thresholds.

True
r_standard bool

Scale the MAD by 1 / qnorm(0.75), see per_cell_qc_outlier.

True

Returns:

Type Description
CellQc

The calls.

Raises:

Type Description
ValueError

On mismatched lengths, unknown metric names, malformed bounds, bounds that contradict a direction, or nothing to do.

Examples:

>>> obs = sc.obs(filtered=True)
>>> metrics = {"lib_size": obs["lib_size"].to_numpy()}
>>> qc = bv.qc.run_cell_qc(metrics, obs["cell_idx"].to_numpy(), threshold=4.0)
>>> sc.add_obs(bv.qc.get_data(qc))
>>> sc.set_cells_to_keep(qc.cell_idx[~qc.combined])

run_cell_qc_fixed

run_cell_qc_fixed(
    metrics: Mapping[str, Vector],
    cells_to_keep: ndarray | Sequence[int],
    hard_thresholds: Mapping[str, Bounds],
    *,
    groups: Sequence[object]
    | ndarray
    | Series
    | None = None,
) -> CellQc

Fixed-threshold cell QC: run_cell_qc with MAD off.

Parameters:

Name Type Description Default
metrics Mapping[str, Vector]

Metric name to its values, one per cell.

required
cells_to_keep ndarray | Sequence[int]

0-based store index of each cell, aligned to the metrics.

required
hard_thresholds Mapping[str, Bounds]

Metric name to {"lower": .., "upper": ..} (either or both).

required
groups Sequence[object] | ndarray | Series | None

Optional group label per cell (donor, sample).

None

Returns:

Type Description
CellQc

The calls.

Examples:

>>> obs = sc.obs(filtered=True)
>>> metrics = {"lib_size": obs["lib_size"].to_numpy()}
>>> bounds = {"lib_size": {"lower": 500}}
>>> qc = bv.qc.run_cell_qc_fixed(metrics, obs["cell_idx"].to_numpy(), bounds)

get_data

get_data(qc: CellQc) -> DataFrame

The calls as an obs frame for SingleCells.add_obs.

Columns: the metrics, cell_idx (0-based), grp, global_outlier, then per metric <m>_is_outlier, <m>_mad_outlier, <m>_hard_outlier and <m>_rescued.

Parameters:

Name Type Description Default
qc CellQc

The calls.

required

Returns:

Type Description
DataFrame

One row per cell.

per_cell_qc_outlier

per_cell_qc_outlier(
    metric: Vector,
    *,
    threshold: float = 3.0,
    direction: Direction = "twosided",
    r_standard: bool = True,
) -> MadOutlier

MAD outlier detection on a per-cell QC metric.

Parameters:

Name Type Description Default
metric Vector

The metric.

required
threshold float

MADs from the median beyond which a value is an outlier.

3.0
direction Direction

Which tail(s) to flag.

'twosided'
r_standard bool

Scale the MAD by 1 / qnorm(0.75) (1.48260..., the exact constant R's mad() rounds to 1.4826), so threshold counts standard deviations under normality. False uses the raw MAD.

True

Returns:

Type Description
MadOutlier

The flags and the applied thresholds.

Examples:

>>> lib_size = sc.obs(filtered=True)["lib_size"]
>>> res = bv.qc.per_cell_qc_outlier(lib_size, threshold=4.0, direction="below")

Adjusting the calls

Cell QC: per-cell metrics, then MAD or fixed-threshold outlier calls.

Two steps. gene_set_proportions and top_genes_perc read the cell store in Rust and write their metrics to obs. The outlier calls (run_cell_qc, run_cell_qc_fixed) work on plain vectors you pull out of obs and return a CellQc record. get_data turns that into an obs frame, and you decide which cells to keep with sc.set_cells_to_keep. Nothing is deleted. rescue_cells and flag_cells adjust a CellQc afterwards. The metric passes take a SingleCells; the outlier calls know nothing about experiments.

What lands where. gene_set_proportions writes one obs column per gene set, named by its key, as a fraction in [0, 1]. top_genes_perc writes top_<N>_genes_percentage. lib_size and nnz are already in obs from the loaders. The outlier calls write nothing: sc.add_obs(get_data(qc)) stores the calls, and sc.set_cells_to_keep applies the filter.

mito_genes = sc.gene_ids()[:13].tolist()  # on real data: the MT- genes
bv.qc.gene_set_proportions(sc, {"mito": mito_genes})
bv.qc.top_genes_perc(sc)

obs = sc.obs(filtered=True)
metrics = {"lib_size": obs["lib_size"], "nnz": obs["nnz"], "mito": obs["mito"]}
directions = {"lib_size": "below", "nnz": "below", "mito": "above"}
qc = bv.qc.run_cell_qc(metrics, obs["cell_idx"].to_numpy(), directions=directions)

sc.add_obs(bv.qc.get_data(qc))
sc.set_cells_to_keep(qc.cell_idx[~qc.combined])

Gotchas. Pass the metrics for the kept cells (sc.obs(filtered=True)) with their cell_idx, so the two line up. get_data writes the metrics back to obs under their own names, so a transformed metric such as log10_lib_size needs its own key or it overwrites the original column. directions, if given, must name every metric. With groups (donor, sample) MAD runs per group, hard thresholds do not. rescue_cells only clears MAD flags, never hard ones. The metric passes stream the cells in batches above N_CELLS_STREAMING_THRESHOLD kept cells, and streaming= overrides that.

flag_cells

flag_cells(
    qc: CellQc,
    hard_thresholds: Mapping[str, Bounds],
    *,
    reset: bool = False,
) -> CellQc

Add hard-threshold flags.

New flags are unioned with the existing ones per metric, and the bounds replace any earlier bounds of the same metric.

Parameters:

Name Type Description Default
qc CellQc

The calls.

required
hard_thresholds Mapping[str, Bounds]

Metric name to {"lower": .., "upper": ..}.

required
reset bool

Clear every existing hard flag and bound first.

False

Returns:

Type Description
CellQc

A new CellQc.

Raises:

Type Description
ValueError

On unknown metrics or malformed bounds.

Examples:

>>> qc = bv.qc.flag_cells(qc, {"lib_size": {"upper": 50000}})

rescue_cells

rescue_cells(
    qc: CellQc, rescue_thresholds: Mapping[str, Bounds]
) -> CellQc

Un-flag MAD outliers that fall within safe bounds.

For each metric named, MAD-flagged cells within [lower, upper] are rescued; this replaces any earlier rescue of that metric. Hard flags are never cleared, and a warning counts the rescued cells they still catch.

Parameters:

Name Type Description Default
qc CellQc

The calls.

required
rescue_thresholds Mapping[str, Bounds]

Metric name to {"lower": .., "upper": ..}.

required

Returns:

Type Description
CellQc

A new CellQc.

Raises:

Type Description
ValueError

On unknown metrics or malformed bounds, or if MAD was skipped.

Examples:

>>> qc = bv.qc.rescue_cells(qc, {"lib_size": {"lower": 1000}})