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.
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.
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
¶
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 |
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 |
2000
|
hvg_params
|
HvgParams | None
|
The HVG parameters. |
None
|
streaming
|
bool | None
|
Read the genes in batches. |
None
|
verbose
|
Verbose
|
|
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
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 |
None
|
hvg_no
|
int
|
Number of genes to flag. |
3000
|
hvg_params
|
HvgParams | None
|
The HVG parameters; |
None
|
streaming
|
bool | None
|
Read the genes in batches. |
None
|
verbose
|
Verbose
|
|
True
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
|
DataFrame
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
On method |
Examples:
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 ( |
2000
|
gene_comb_method
|
GeneCombMethod
|
|
'union'
|
hvg_params
|
HvgParams | None
|
The HVG parameters; |
None
|
streaming
|
bool | None
|
Read the genes in batches. |
None
|
verbose
|
Verbose
|
|
True
|
Returns:
| Type | Description |
|---|---|
BatchHvg
|
The HVGs and the per-batch statistics. |
Raises:
| Type | Description |
|---|---|
ValueError
|
On method |
Examples:
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.
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
|
sparse_svd
|
bool | None
|
Solve on the sparse matrix. |
None
|
hvg
|
ndarray | Sequence[int] | Sequence[str] | None
|
0-based gene indices or gene ids to use instead of
|
None
|
seed
|
int
|
Seed for the randomised SVD. |
42
|
residuals
|
bool
|
Run on the residuals of the model from |
False
|
verbose
|
Verbose
|
|
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:
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.
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
|
|
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. |
CorrectedCounts
dataclass
¶
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'
|
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
( |
None
|
residual_params
|
SctransformParams | AprParams | None
|
|
None
|
gene_batch_size
|
int | None
|
Genes per disk batch. |
None
|
seed
|
int
|
Seed for the step-1 subsampling. |
42
|
verbose
|
Verbose
|
|
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 |
ValueError
|
On a missing group column or unusable covariates. |
Examples:
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
|
build_cell_store
|
bool
|
Also build the cell-major store and the DuckDB and
open the result. |
True
|
overwrite
|
bool
|
Replace an existing store at |
False
|
gene_batch_size
|
int | None
|
Genes per disk batch. |
None
|
verbose
|
Verbose
|
|
True
|
Returns:
| Type | Description |
|---|---|
SingleCells | CorrectedCounts
|
The new experiment, or with |
SingleCells | CorrectedCounts
|
written. |
Raises:
| Type | Description |
|---|---|
FileExistsError
|
If a store exists at |
ValueError
|
Without a usable scTransform fit. |
Examples:
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.
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'
|
magic_params
|
MagicParams | None
|
The MAGIC parameters. |
None
|
verbose
|
Verbose
|
|
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: