Batch correction¶
Batch correction and integration metrics.
Pick a correction, then check it. harmony (v2) and harmony_v1 (the
original) correct the cached PCA. fast_mnn, seurat_cca and seurat_rpca
work from the counts of the batch-aware HVGs, so run
bv.pp.find_hvg_batch_aware first and hand them its hvg_gene_idx. bbknn
skips the embedding and builds a batch-balanced kNN instead. The calculate_*
functions score the result, and calculate_integration_metrics runs the lot
and returns one row.
What lands where. Harmony, fastMNN, CCA and rPCA write a corrected
embedding to sc.cache.embeddings under "harmony", "harmony_v1", "mnn",
"cca" and "rpca". bbknn writes sc.cache.knn and
sc.cache.connectivities, replacing what is there. All are stamped. The
metrics return records (or a table) and leave the experiment alone. Everything
takes a SingleCells or SingleCellsSubset except seurat_cca and
seurat_rpca, which want a SingleCells. The batch labels are an obs column
named by batch_column; its levels are sorted, an Enum keeps its own order.
bv.pp.find_hvg(sc, hvg_no=2000)
bv.pp.calculate_pca(sc, no_pcs=30)
bv.integrate.harmony(sc, "batch_index")
bv.graph.find_neighbours(sc, embd_to_use="harmony")
metrics = bv.integrate.calculate_integration_metrics(
sc, "batch_index", cell_type_column="cell_grp", embd_to_use="harmony"
)
Gotchas. The kNN metrics (calculate_kbet, calculate_lisi,
calculate_graph_connectivity) read the cached kNN, so rebuild the neighbours
on the corrected embedding before scoring it; on a stale kNN they warn, on one
that covers other cells they raise. The silhouette widths are O(n^2) and
subsample to max_cells (5000). calculate_pcr compares a corrected embedding
with the PCA, so it needs both. For bbknn there is no embedding: pass
embd_to_use=None to calculate_integration_metrics, and the metrics that need
one come back null. A single batch warns and returns without doing anything,
bar fast_mnn, which raises. seurat_cca and seurat_rpca with
use_precomputed_pca=True still need the gene loadings, so they save less than
fastMNN does.
Worked through in Batch correction with bixverse.
Embedding corrections¶
Batch correction and integration metrics.
Pick a correction, then check it. harmony (v2) and harmony_v1 (the
original) correct the cached PCA. fast_mnn, seurat_cca and seurat_rpca
work from the counts of the batch-aware HVGs, so run
bv.pp.find_hvg_batch_aware first and hand them its hvg_gene_idx. bbknn
skips the embedding and builds a batch-balanced kNN instead. The calculate_*
functions score the result, and calculate_integration_metrics runs the lot
and returns one row.
What lands where. Harmony, fastMNN, CCA and rPCA write a corrected
embedding to sc.cache.embeddings under "harmony", "harmony_v1", "mnn",
"cca" and "rpca". bbknn writes sc.cache.knn and
sc.cache.connectivities, replacing what is there. All are stamped. The
metrics return records (or a table) and leave the experiment alone. Everything
takes a SingleCells or SingleCellsSubset except seurat_cca and
seurat_rpca, which want a SingleCells. The batch labels are an obs column
named by batch_column; its levels are sorted, an Enum keeps its own order.
bv.pp.find_hvg(sc, hvg_no=2000)
bv.pp.calculate_pca(sc, no_pcs=30)
bv.integrate.harmony(sc, "batch_index")
bv.graph.find_neighbours(sc, embd_to_use="harmony")
metrics = bv.integrate.calculate_integration_metrics(
sc, "batch_index", cell_type_column="cell_grp", embd_to_use="harmony"
)
Gotchas. The kNN metrics (calculate_kbet, calculate_lisi,
calculate_graph_connectivity) read the cached kNN, so rebuild the neighbours
on the corrected embedding before scoring it; on a stale kNN they warn, on one
that covers other cells they raise. The silhouette widths are O(n^2) and
subsample to max_cells (5000). calculate_pcr compares a corrected embedding
with the PCA, so it needs both. For bbknn there is no embedding: pass
embd_to_use=None to calculate_integration_metrics, and the metrics that need
one come back null. A single batch warns and returns without doing anything,
bar fast_mnn, which raises. seurat_cca and seurat_rpca with
use_precomputed_pca=True still need the gene loadings, so they save less than
fastMNN does.
harmony
¶
harmony(
sc: ScOrScSubset,
batch_column: str,
*,
additional_batch_columns: Sequence[str] | None = None,
embd_to_use: str = "pca",
modality: CacheModality = "rna",
harmony_params: HarmonyV2Params | None = None,
seed: int = 42,
verbose: Verbose = True,
) -> None
Harmony (v2) on the PCA or another embedding.
The corrected embedding goes to the modality's embeddings["harmony"],
stamped as derived from embd_to_use. The original algorithm is
harmony_v1. On ATAC, correct the LSI with embd_to_use="lsi",
modality="atac", then build the neighbours on "harmony" with the same
modality.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sc
|
ScOrScSubset
|
The experiment, with the embedding. |
required |
batch_column
|
str
|
obs column with the primary batch. |
required |
additional_batch_columns
|
Sequence[str] | None
|
Further obs columns to regress out. |
None
|
embd_to_use
|
str
|
The embedding to correct, |
'pca'
|
modality
|
CacheModality
|
The cache to read and write: |
'rna'
|
harmony_params
|
HarmonyV2Params | None
|
The parameters. |
None
|
seed
|
int
|
Seed. |
42
|
verbose
|
Verbose
|
|
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the embedding is stale, or a batch column is missing or incomplete. |
References
Patikas, et al., bioRxiv, 2026.
Examples:
harmony_v1
¶
harmony_v1(
sc: ScOrScSubset,
batch_column: str,
*,
additional_batch_columns: Sequence[str] | None = None,
embd_to_use: str = "pca",
modality: CacheModality = "rna",
harmony_params: HarmonyParams | None = None,
seed: int = 42,
verbose: Verbose = True,
) -> None
The original Harmony (v1) on the PCA or another embedding.
The corrected embedding goes to the modality's embeddings["harmony_v1"],
stamped as derived from embd_to_use.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sc
|
ScOrScSubset
|
The experiment, with the embedding. |
required |
batch_column
|
str
|
obs column with the primary batch. |
required |
additional_batch_columns
|
Sequence[str] | None
|
Further obs columns to regress out. |
None
|
embd_to_use
|
str
|
The embedding to correct, |
'pca'
|
modality
|
CacheModality
|
The cache to read and write: |
'rna'
|
harmony_params
|
HarmonyParams | None
|
The parameters. |
None
|
seed
|
int
|
Seed. |
42
|
verbose
|
Verbose
|
|
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the embedding is stale, or a batch column is missing or incomplete. |
References
Korsunsky, et al., Nat Methods, 2019.
fast_mnn
¶
fast_mnn(
sc: ScOrScSubset,
batch_column: str,
batch_hvg_genes: ndarray
| Sequence[int]
| Sequence[str],
*,
fastmnn_params: FastmnnParams | None = None,
use_precomputed_pca: bool = False,
seed: int = 42,
verbose: Verbose = True,
) -> None
fastMNN on a PCA of the batch-aware HVGs.
The corrected embedding goes to sc.cache.embeddings["mnn"], stamped as
derived from "pca" when the cached PCA was used, else unparented.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sc
|
ScOrScSubset
|
The experiment. |
required |
batch_column
|
str
|
obs column with the batch. |
required |
batch_hvg_genes
|
ndarray | Sequence[int] | Sequence[str]
|
0-based gene indices or gene ids, ideally from
|
required |
fastmnn_params
|
FastmnnParams | None
|
The parameters. |
None
|
use_precomputed_pca
|
bool
|
Use the cached PCA instead of computing one on
|
False
|
seed
|
int
|
Seed. |
42
|
verbose
|
Verbose
|
|
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the batch column is missing or incomplete, or the
cached PCA is stale with |
BixverseError
|
With fewer than two batches. |
References
Haghverdi, et al., Nat Biotechnol, 2018.
Examples:
seurat_cca
¶
seurat_cca(
sc: SingleCells,
batch_column: str,
batch_hvg_genes: ndarray
| Sequence[int]
| Sequence[str],
*,
cca_params: SeuratCcaParams | None = None,
use_precomputed_pca: bool = False,
seed: int = 42,
verbose: Verbose = True,
) -> None
Seurat CCA anchor integration.
The corrected embedding goes to sc.cache.embeddings["cca"], stamped as
derived from "pca" when the cached PCA was used, else unparented. One
batch warns and leaves the experiment alone.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sc
|
SingleCells
|
The experiment. |
required |
batch_column
|
str
|
obs column with the batch. |
required |
batch_hvg_genes
|
ndarray | Sequence[int] | Sequence[str]
|
0-based gene indices or gene ids, ideally from
|
required |
cca_params
|
SeuratCcaParams | None
|
The parameters. |
None
|
use_precomputed_pca
|
bool
|
Correct the cached PCA instead of computing one. The gene-space filter still needs the loadings, so this saves less than it does for fastMNN. |
False
|
seed
|
int
|
Seed. |
42
|
verbose
|
Verbose
|
|
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the batch column is missing or incomplete, or the
cached PCA is stale with |
References
Stuart, et al., Cell, 2019.
Examples:
seurat_rpca
¶
seurat_rpca(
sc: SingleCells,
batch_column: str,
batch_hvg_genes: ndarray
| Sequence[int]
| Sequence[str],
*,
rpca_params: SeuratRpcaParams | None = None,
use_precomputed_pca: bool = False,
seed: int = 42,
verbose: Verbose = True,
) -> None
Seurat reciprocal PCA anchor integration.
The corrected embedding goes to sc.cache.embeddings["rpca"], stamped
as derived from "pca" when the cached PCA was used, else unparented.
One batch warns and leaves the experiment alone.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sc
|
SingleCells
|
The experiment. |
required |
batch_column
|
str
|
obs column with the batch. |
required |
batch_hvg_genes
|
ndarray | Sequence[int] | Sequence[str]
|
0-based gene indices or gene ids, ideally from
|
required |
rpca_params
|
SeuratRpcaParams | None
|
The parameters. |
None
|
use_precomputed_pca
|
bool
|
Correct the cached PCA instead of computing the union PCA; the per-batch PCAs are always computed. |
False
|
seed
|
int
|
Seed. |
42
|
verbose
|
Verbose
|
|
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the batch column is missing or incomplete, or the
cached PCA is stale with |
References
Stuart, et al., Cell, 2019.
Examples:
Batch-balanced neighbours¶
Batch correction and integration metrics.
Pick a correction, then check it. harmony (v2) and harmony_v1 (the
original) correct the cached PCA. fast_mnn, seurat_cca and seurat_rpca
work from the counts of the batch-aware HVGs, so run
bv.pp.find_hvg_batch_aware first and hand them its hvg_gene_idx. bbknn
skips the embedding and builds a batch-balanced kNN instead. The calculate_*
functions score the result, and calculate_integration_metrics runs the lot
and returns one row.
What lands where. Harmony, fastMNN, CCA and rPCA write a corrected
embedding to sc.cache.embeddings under "harmony", "harmony_v1", "mnn",
"cca" and "rpca". bbknn writes sc.cache.knn and
sc.cache.connectivities, replacing what is there. All are stamped. The
metrics return records (or a table) and leave the experiment alone. Everything
takes a SingleCells or SingleCellsSubset except seurat_cca and
seurat_rpca, which want a SingleCells. The batch labels are an obs column
named by batch_column; its levels are sorted, an Enum keeps its own order.
bv.pp.find_hvg(sc, hvg_no=2000)
bv.pp.calculate_pca(sc, no_pcs=30)
bv.integrate.harmony(sc, "batch_index")
bv.graph.find_neighbours(sc, embd_to_use="harmony")
metrics = bv.integrate.calculate_integration_metrics(
sc, "batch_index", cell_type_column="cell_grp", embd_to_use="harmony"
)
Gotchas. The kNN metrics (calculate_kbet, calculate_lisi,
calculate_graph_connectivity) read the cached kNN, so rebuild the neighbours
on the corrected embedding before scoring it; on a stale kNN they warn, on one
that covers other cells they raise. The silhouette widths are O(n^2) and
subsample to max_cells (5000). calculate_pcr compares a corrected embedding
with the PCA, so it needs both. For bbknn there is no embedding: pass
embd_to_use=None to calculate_integration_metrics, and the metrics that need
one come back null. A single batch warns and returns without doing anything,
bar fast_mnn, which raises. seurat_cca and seurat_rpca with
use_precomputed_pca=True still need the gene loadings, so they save less than
fastMNN does.
bbknn
¶
bbknn(
sc: ScOrScSubset,
batch_column: str,
*,
no_neighbours_to_keep: int = 5,
embd_to_use: Literal["pca"] = "pca",
no_embd_to_use: int | None = None,
bbknn_params: BbknnParams | None = None,
seed: int = 42,
verbose: Verbose = True,
) -> None
Batch-balanced kNN.
The kNN goes to sc.cache.knn, stamped as derived from the embedding,
and the max-symmetrised BBKNN connectivities to
sc.cache.connectivities, stamped as derived from "knn". The kNN keeps
the no_neighbours_to_keep nearest of the per-batch neighbours of each
cell, balanced across batches: each batch keeps its nearest
ceil(no_neighbours_to_keep / n_batches), and slots a batch cannot fill go
to the nearest of the rest. Rows are sorted by distance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sc
|
ScOrScSubset
|
The experiment, with a PCA. |
required |
batch_column
|
str
|
obs column with the batch. |
required |
no_neighbours_to_keep
|
int
|
Neighbours per cell in the stored kNN; capped
at |
5
|
embd_to_use
|
Literal['pca']
|
The embedding; only |
'pca'
|
no_embd_to_use
|
int | None
|
Number of leading dimensions to use. |
None
|
bbknn_params
|
BbknnParams | None
|
The parameters. |
None
|
seed
|
int
|
Seed. |
42
|
verbose
|
Verbose
|
|
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the embedding is stale, or the batch column is missing or incomplete. |
References
Polański, et al., Bioinformatics, 2020.
Examples:
All metrics in one table¶
Batch correction and integration metrics.
Pick a correction, then check it. harmony (v2) and harmony_v1 (the
original) correct the cached PCA. fast_mnn, seurat_cca and seurat_rpca
work from the counts of the batch-aware HVGs, so run
bv.pp.find_hvg_batch_aware first and hand them its hvg_gene_idx. bbknn
skips the embedding and builds a batch-balanced kNN instead. The calculate_*
functions score the result, and calculate_integration_metrics runs the lot
and returns one row.
What lands where. Harmony, fastMNN, CCA and rPCA write a corrected
embedding to sc.cache.embeddings under "harmony", "harmony_v1", "mnn",
"cca" and "rpca". bbknn writes sc.cache.knn and
sc.cache.connectivities, replacing what is there. All are stamped. The
metrics return records (or a table) and leave the experiment alone. Everything
takes a SingleCells or SingleCellsSubset except seurat_cca and
seurat_rpca, which want a SingleCells. The batch labels are an obs column
named by batch_column; its levels are sorted, an Enum keeps its own order.
bv.pp.find_hvg(sc, hvg_no=2000)
bv.pp.calculate_pca(sc, no_pcs=30)
bv.integrate.harmony(sc, "batch_index")
bv.graph.find_neighbours(sc, embd_to_use="harmony")
metrics = bv.integrate.calculate_integration_metrics(
sc, "batch_index", cell_type_column="cell_grp", embd_to_use="harmony"
)
Gotchas. The kNN metrics (calculate_kbet, calculate_lisi,
calculate_graph_connectivity) read the cached kNN, so rebuild the neighbours
on the corrected embedding before scoring it; on a stale kNN they warn, on one
that covers other cells they raise. The silhouette widths are O(n^2) and
subsample to max_cells (5000). calculate_pcr compares a corrected embedding
with the PCA, so it needs both. For bbknn there is no embedding: pass
embd_to_use=None to calculate_integration_metrics, and the metrics that need
one come back null. A single batch warns and returns without doing anything,
bar fast_mnn, which raises. seurat_cca and seurat_rpca with
use_precomputed_pca=True still need the gene loadings, so they save less than
fastMNN does.
calculate_integration_metrics
¶
calculate_integration_metrics(
sc: ScOrScSubset,
batch_column: str,
*,
cell_type_column: str | None = None,
embd_to_use: str | None = "pca",
max_cells: int | None = 5000,
seed: int = 42,
verbose: Verbose = True,
) -> DataFrame
The batch mixing and biological conservation metrics in one row.
Every column is on [0, 1] (the PCR comparison can go negative), higher
is better: kbet_accept (1 - rejection rate), batch_asw
(mean(1 - |s|)), ilisi, pcr_comparison, clisi, cell_type_asw
and graph_connectivity. The kNN metrics read the cached kNN, so
rebuild the neighbours on the corrected embedding first. A metric that
cannot run (no kNN, no embedding, embd_to_use=None as for BBKNN, no
cell_type_column) is null.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sc
|
ScOrScSubset
|
The experiment. |
required |
batch_column
|
str
|
obs column with the batch. |
required |
cell_type_column
|
str | None
|
obs column with the cell types; |
None
|
embd_to_use
|
str | None
|
The embedding for the silhouettes and the PCR; |
'pca'
|
max_cells
|
int | None
|
Subsampling for the silhouette widths. |
5000
|
seed
|
int
|
Seed for the subsampling. |
42
|
verbose
|
Verbose
|
|
True
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row: |
DataFrame
|
|
References
Luecken, et al., Nat Methods, 2022.
Examples:
Batch mixing¶
Batch correction and integration metrics.
Pick a correction, then check it. harmony (v2) and harmony_v1 (the
original) correct the cached PCA. fast_mnn, seurat_cca and seurat_rpca
work from the counts of the batch-aware HVGs, so run
bv.pp.find_hvg_batch_aware first and hand them its hvg_gene_idx. bbknn
skips the embedding and builds a batch-balanced kNN instead. The calculate_*
functions score the result, and calculate_integration_metrics runs the lot
and returns one row.
What lands where. Harmony, fastMNN, CCA and rPCA write a corrected
embedding to sc.cache.embeddings under "harmony", "harmony_v1", "mnn",
"cca" and "rpca". bbknn writes sc.cache.knn and
sc.cache.connectivities, replacing what is there. All are stamped. The
metrics return records (or a table) and leave the experiment alone. Everything
takes a SingleCells or SingleCellsSubset except seurat_cca and
seurat_rpca, which want a SingleCells. The batch labels are an obs column
named by batch_column; its levels are sorted, an Enum keeps its own order.
bv.pp.find_hvg(sc, hvg_no=2000)
bv.pp.calculate_pca(sc, no_pcs=30)
bv.integrate.harmony(sc, "batch_index")
bv.graph.find_neighbours(sc, embd_to_use="harmony")
metrics = bv.integrate.calculate_integration_metrics(
sc, "batch_index", cell_type_column="cell_grp", embd_to_use="harmony"
)
Gotchas. The kNN metrics (calculate_kbet, calculate_lisi,
calculate_graph_connectivity) read the cached kNN, so rebuild the neighbours
on the corrected embedding before scoring it; on a stale kNN they warn, on one
that covers other cells they raise. The silhouette widths are O(n^2) and
subsample to max_cells (5000). calculate_pcr compares a corrected embedding
with the PCA, so it needs both. For bbknn there is no embedding: pass
embd_to_use=None to calculate_integration_metrics, and the metrics that need
one come back null. A single batch warns and returns without doing anything,
bar fast_mnn, which raises. seurat_cca and seurat_rpca with
use_precomputed_pca=True still need the gene loadings, so they save less than
fastMNN does.
KbetScores
dataclass
¶
KbetScores(
kbet_score: float,
significant_tests: ndarray,
p_values: ndarray,
chi_square_stats: ndarray,
mean_chi_square: float,
median_chi_square: float,
threshold: float,
n_batches: int,
)
kBET result.
Attributes:
| Name | Type | Description |
|---|---|---|
kbet_score |
float
|
Share of cells whose test is significant; 0 is perfect mixing, 1 none. |
significant_tests |
ndarray
|
Per cell, whether the p-value is at or below
|
p_values |
ndarray
|
Per-cell chi-square p-values. |
chi_square_stats |
ndarray
|
Per-cell chi-square statistics. |
mean_chi_square |
float
|
Mean chi-square statistic. |
median_chi_square |
float
|
Median chi-square statistic. |
threshold |
float
|
The significance threshold. |
n_batches |
int
|
Number of batches. |
LisiScores
dataclass
¶
LisiScores(
per_cell: ndarray,
mean_lisi: float,
median_lisi: float,
lisi_norm: float,
n_labels: int,
type: LisiType,
)
iLISI or cLISI.
Attributes:
| Name | Type | Description |
|---|---|---|
per_cell |
ndarray
|
Per-cell LISI in |
mean_lisi |
float
|
Mean LISI. |
median_lisi |
float
|
Median LISI. |
lisi_norm |
float
|
The scIB rescaling onto |
n_labels |
int
|
Number of distinct labels. |
type |
LisiType
|
|
BatchSilhouetteScores
dataclass
¶
BatchSilhouetteScores(
per_cell: ndarray,
mean_asw: float,
median_asw: float,
n_batches: int,
embedding_used: str,
)
Batch silhouette width.
Attributes:
| Name | Type | Description |
|---|---|---|
per_cell |
ndarray
|
Per-cell silhouettes in |
mean_asw |
float
|
Mean silhouette width. |
median_asw |
float
|
Median silhouette width. |
n_batches |
int
|
Number of batches. |
embedding_used |
str
|
The embedding. |
PcrScores
dataclass
¶
PcrScores(
pcr: float,
pcr_pca: float,
pcr_comparison: float | None,
var_explained: ndarray,
r_squared: ndarray,
embedding_used: str,
)
Principal component regression on batch.
Attributes:
| Name | Type | Description |
|---|---|---|
pcr |
float
|
Variance-weighted R-squared of batch on the embedding. |
pcr_pca |
float
|
The same on the uncorrected PCA. |
pcr_comparison |
float | None
|
|
var_explained |
ndarray
|
Variance per embedding dimension. |
r_squared |
ndarray
|
Batch R-squared per embedding dimension. |
embedding_used |
str
|
The embedding. |
calculate_kbet
¶
calculate_kbet(
sc: ScOrScSubset,
batch_column: str,
*,
threshold: float = 0.05,
verbose: Verbose = True,
) -> KbetScores | None
kBET on the cached kNN.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sc
|
ScOrScSubset
|
The experiment, with a kNN. |
required |
batch_column
|
str
|
obs column with the batch. |
required |
threshold
|
float
|
p-values at or below it count as significant. |
0.05
|
verbose
|
Verbose
|
|
True
|
Returns:
| Type | Description |
|---|---|
KbetScores | None
|
The scores; |
Raises:
| Type | Description |
|---|---|
ValueError
|
On a |
References
Büttner, et al., Nat Methods, 2019.
Examples:
calculate_lisi
¶
calculate_lisi(
sc: ScOrScSubset,
label_column: str,
*,
type: LisiType = "batch",
weighted: bool = False,
perplexity: float = 30.0,
verbose: Verbose = True,
) -> LisiScores | None
LISI on the cached kNN.
iLISI on batch labels, cLISI on cell type labels; lisi_norm is the
scIB rescaling for the chosen type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sc
|
ScOrScSubset
|
The experiment, with a kNN. |
required |
label_column
|
str
|
obs column with the batch or cell type labels. |
required |
type
|
LisiType
|
|
'batch'
|
weighted
|
bool
|
Weight the neighbours with a perplexity-calibrated Gaussian kernel on the kNN distances; else uniformly. |
False
|
perplexity
|
float
|
Perplexity of the weighted version; clamped to k. |
30.0
|
verbose
|
Verbose
|
|
True
|
Returns:
| Type | Description |
|---|---|
LisiScores | None
|
The scores; |
Raises:
| Type | Description |
|---|---|
ValueError
|
On a non-positive |
References
Korsunsky, et al., Nat Methods, 2019; Luecken, et al., Nat Methods, 2022.
Examples:
calculate_batch_asw
¶
calculate_batch_asw(
sc: ScOrScSubset,
batch_column: str,
*,
embd_to_use: str = "pca",
max_cells: int | None = 5000,
seed: int = 42,
verbose: Verbose = True,
) -> BatchSilhouetteScores | None
Batch average silhouette width on an embedding.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sc
|
ScOrScSubset
|
The experiment. |
required |
batch_column
|
str
|
obs column with the batch. |
required |
embd_to_use
|
str
|
The embedding, |
'pca'
|
max_cells
|
int | None
|
Subsample to this many cells, the pass is O(n^2). |
5000
|
seed
|
int
|
Seed for the subsampling. |
42
|
verbose
|
Verbose
|
|
True
|
Returns:
| Type | Description |
|---|---|
BatchSilhouetteScores | None
|
The scores; |
BatchSilhouetteScores | None
|
embedding. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the batch column is missing or incomplete. |
Examples:
calculate_pcr
¶
calculate_pcr(
sc: ScOrScSubset,
batch_column: str,
*,
embd_to_use: str = "pca",
) -> PcrScores | None
Principal component regression on batch.
On a corrected embedding it also runs on the PCA and reports the scIB
comparison (pre - post) / pre: 1 means the batch variance is gone.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sc
|
ScOrScSubset
|
The experiment, with a PCA. |
required |
batch_column
|
str
|
obs column with the batch. |
required |
embd_to_use
|
str
|
The embedding, |
'pca'
|
Returns:
| Type | Description |
|---|---|
PcrScores | None
|
The scores; |
PcrScores | None
|
PCA or the embedding. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the batch column is missing or incomplete. |
References
Büttner, et al., Nat Methods, 2019; Luecken, et al., Nat Methods, 2022.
Examples:
Biological conservation¶
Batch correction and integration metrics.
Pick a correction, then check it. harmony (v2) and harmony_v1 (the
original) correct the cached PCA. fast_mnn, seurat_cca and seurat_rpca
work from the counts of the batch-aware HVGs, so run
bv.pp.find_hvg_batch_aware first and hand them its hvg_gene_idx. bbknn
skips the embedding and builds a batch-balanced kNN instead. The calculate_*
functions score the result, and calculate_integration_metrics runs the lot
and returns one row.
What lands where. Harmony, fastMNN, CCA and rPCA write a corrected
embedding to sc.cache.embeddings under "harmony", "harmony_v1", "mnn",
"cca" and "rpca". bbknn writes sc.cache.knn and
sc.cache.connectivities, replacing what is there. All are stamped. The
metrics return records (or a table) and leave the experiment alone. Everything
takes a SingleCells or SingleCellsSubset except seurat_cca and
seurat_rpca, which want a SingleCells. The batch labels are an obs column
named by batch_column; its levels are sorted, an Enum keeps its own order.
bv.pp.find_hvg(sc, hvg_no=2000)
bv.pp.calculate_pca(sc, no_pcs=30)
bv.integrate.harmony(sc, "batch_index")
bv.graph.find_neighbours(sc, embd_to_use="harmony")
metrics = bv.integrate.calculate_integration_metrics(
sc, "batch_index", cell_type_column="cell_grp", embd_to_use="harmony"
)
Gotchas. The kNN metrics (calculate_kbet, calculate_lisi,
calculate_graph_connectivity) read the cached kNN, so rebuild the neighbours
on the corrected embedding before scoring it; on a stale kNN they warn, on one
that covers other cells they raise. The silhouette widths are O(n^2) and
subsample to max_cells (5000). calculate_pcr compares a corrected embedding
with the PCA, so it needs both. For bbknn there is no embedding: pass
embd_to_use=None to calculate_integration_metrics, and the metrics that need
one come back null. A single batch warns and returns without doing anything,
bar fast_mnn, which raises. seurat_cca and seurat_rpca with
use_precomputed_pca=True still need the gene loadings, so they save less than
fastMNN does.
CellTypeAswScores
dataclass
¶
CellTypeAswScores(
per_cell: ndarray,
mean_asw: float,
median_asw: float,
n_cell_types: int,
embedding_used: str,
)
Cell type silhouette width rescaled to [0, 1].
Attributes:
| Name | Type | Description |
|---|---|---|
per_cell |
ndarray
|
Per-cell rescaled silhouettes. |
mean_asw |
float
|
Mean rescaled silhouette width. |
median_asw |
float
|
Median rescaled silhouette width. |
n_cell_types |
int
|
Number of cell types. |
embedding_used |
str
|
The embedding. |
GraphConnectivityScores
dataclass
¶
GraphConnectivityScores(
per_cell_type: DataFrame,
mean_connectivity: float,
median_connectivity: float,
)
Graph connectivity per cell type.
Attributes:
| Name | Type | Description |
|---|---|---|
per_cell_type |
DataFrame
|
|
mean_connectivity |
float
|
Mean over cell types. |
median_connectivity |
float
|
Median over cell types. |
calculate_cell_type_asw
¶
calculate_cell_type_asw(
sc: ScOrScSubset,
cell_type_column: str,
*,
embd_to_use: str = "pca",
max_cells: int | None = 5000,
seed: int = 42,
verbose: Verbose = True,
) -> CellTypeAswScores | None
Cell type silhouette width on an embedding, rescaled to [0, 1].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sc
|
ScOrScSubset
|
The experiment. |
required |
cell_type_column
|
str
|
obs column with the cell types. |
required |
embd_to_use
|
str
|
The embedding, |
'pca'
|
max_cells
|
int | None
|
Subsample to this many cells. |
5000
|
seed
|
int
|
Seed for the subsampling. |
42
|
verbose
|
Verbose
|
|
True
|
Returns:
| Type | Description |
|---|---|
CellTypeAswScores | None
|
The scores; |
CellTypeAswScores | None
|
embedding. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the cell type column is missing or incomplete. |
References
Luecken, et al., Nat Methods, 2022.
Examples:
calculate_graph_connectivity
¶
calculate_graph_connectivity(
sc: ScOrScSubset, cell_type_column: str
) -> GraphConnectivityScores | None
Graph connectivity per cell type on the cached kNN.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sc
|
ScOrScSubset
|
The experiment, with a kNN. |
required |
cell_type_column
|
str
|
obs column with the cell types. |
required |
Returns:
| Type | Description |
|---|---|
GraphConnectivityScores | None
|
The scores; |
GraphConnectivityScores | None
|
cell type. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the cell type column is missing or incomplete, or the kNN covers other cells. |
References
Luecken, et al., Nat Methods, 2022.
Examples: