Multi-modal¶
Multi-modal single cell: ADT counts, their PCA and the WNN graph.
Adds a protein modality to a SingleCellsMultiModal, normalises it (CLR or
DSB), runs a PCA over it and fuses it with the RNA through a weighted nearest
neighbour (WNN) graph. The RNA side is a plain SingleCells, so every RNA
function takes the object as it is.
Start with add_adt_counts, then calculate_pca_adt. Run the RNA PCA the
usual way (bv.pp.find_hvg, bv.pp.calculate_pca) and call
generate_wnn_graph. From there bv.graph.find_clusters and bv.embed
take modality="wnn"; modality="adt" does the same for the protein side
alone. The WNN fuses RNA with ATAC the same way: modality_2="atac",
embd_to_use_2="lsi" (or "harmony" after correcting the LSI), see
bv.atac.
What lands where. add_adt_counts cuts the counts to the kept cells,
normalises them and stores them in mm.adt; it also writes the var_adt table
to the DuckDB and adt_nnz and adt_lib_size to obs. The counts stay in
memory, not in the count store, and bv.io.save keeps them. calculate_pca_adt
writes scores, loadings and singular values to mm.adt_cache.
generate_wnn_graph puts the fused kNN, its graph and the per-cell modality
weights in mm.wnn. new_adt_counts_clr, new_adt_counts_dsb and the
get_* functions return their result and leave the experiment alone.
# adt_counts: dense cells x proteins array; barcodes and proteins: their labels
mm = bv.SingleCellsMultiModal(sc.dir)
bv.mm.add_adt_counts(mm, adt_counts, barcodes, proteins, method="clr")
bv.pp.find_hvg(mm, hvg_no=500)
bv.pp.calculate_pca(mm, no_pcs=20)
bv.mm.calculate_pca_adt(mm, no_pcs=10)
bv.mm.generate_wnn_graph(mm)
bv.graph.find_clusters(mm, modality="wnn")
weights = bv.mm.get_wnn_weights(mm)
Gotchas. Every kept cell needs a row in the ADT barcodes, or
add_adt_counts raises. The matrix is cut to the kept cells when you add it:
dropping cells afterwards is fine, putting dropped cells back is not
(calculate_pca_adt then raises). DSB
wants the isotype controls by default (DsbParams.use_isotype_controls), so
pass isotype_names, or switch the option off. Leave the isotypes out of the
ADT PCA with features=. generate_wnn_graph needs an embedding of both
modalities (the PCA, or the LSI for ATAC), rebuilds the per-modality kNN
graphs itself at knn_range neighbours rather than reusing the cached ones,
and replaces any earlier WNN result with its embeddings.
Worked through in Multi-modal single cell analysis with bixverse.
ADT counts¶
Multi-modal single cell: ADT counts, their PCA and the WNN graph.
Adds a protein modality to a SingleCellsMultiModal, normalises it (CLR or
DSB), runs a PCA over it and fuses it with the RNA through a weighted nearest
neighbour (WNN) graph. The RNA side is a plain SingleCells, so every RNA
function takes the object as it is.
Start with add_adt_counts, then calculate_pca_adt. Run the RNA PCA the
usual way (bv.pp.find_hvg, bv.pp.calculate_pca) and call
generate_wnn_graph. From there bv.graph.find_clusters and bv.embed
take modality="wnn"; modality="adt" does the same for the protein side
alone. The WNN fuses RNA with ATAC the same way: modality_2="atac",
embd_to_use_2="lsi" (or "harmony" after correcting the LSI), see
bv.atac.
What lands where. add_adt_counts cuts the counts to the kept cells,
normalises them and stores them in mm.adt; it also writes the var_adt table
to the DuckDB and adt_nnz and adt_lib_size to obs. The counts stay in
memory, not in the count store, and bv.io.save keeps them. calculate_pca_adt
writes scores, loadings and singular values to mm.adt_cache.
generate_wnn_graph puts the fused kNN, its graph and the per-cell modality
weights in mm.wnn. new_adt_counts_clr, new_adt_counts_dsb and the
get_* functions return their result and leave the experiment alone.
# adt_counts: dense cells x proteins array; barcodes and proteins: their labels
mm = bv.SingleCellsMultiModal(sc.dir)
bv.mm.add_adt_counts(mm, adt_counts, barcodes, proteins, method="clr")
bv.pp.find_hvg(mm, hvg_no=500)
bv.pp.calculate_pca(mm, no_pcs=20)
bv.mm.calculate_pca_adt(mm, no_pcs=10)
bv.mm.generate_wnn_graph(mm)
bv.graph.find_clusters(mm, modality="wnn")
weights = bv.mm.get_wnn_weights(mm)
Gotchas. Every kept cell needs a row in the ADT barcodes, or
add_adt_counts raises. The matrix is cut to the kept cells when you add it:
dropping cells afterwards is fine, putting dropped cells back is not
(calculate_pca_adt then raises). DSB
wants the isotype controls by default (DsbParams.use_isotype_controls), so
pass isotype_names, or switch the option off. Leave the isotypes out of the
ADT PCA with features=. generate_wnn_graph needs an embedding of both
modalities (the PCA, or the LSI for ATAC), rebuilds the per-modality kNN
graphs itself at knn_range neighbours rather than reusing the cached ones,
and replaces any earlier WNN result with its embeddings.
AdtCounts
dataclass
¶
AdtCounts(
raw_counts: ndarray,
norm_counts: ndarray,
cell_ids: ndarray,
cell_idx: ndarray,
feature_ids: ndarray,
type: Literal["CLR", "DSB"],
dsb: DsbInfo | None = None,
)
ADT counts with their normalisation.
Attributes:
| Name | Type | Description |
|---|---|---|
raw_counts |
ndarray
|
|
norm_counts |
ndarray
|
|
cell_ids |
ndarray
|
Barcode of each row. |
cell_idx |
ndarray
|
0-based store index of each row. |
feature_ids |
ndarray
|
Id of each column. |
type |
Literal['CLR', 'DSB']
|
|
dsb |
DsbInfo | None
|
The DSB estimates, for |
DsbInfo
dataclass
¶
DsbInfo(
protein_background_mean: ndarray,
protein_background_sd: ndarray,
technical_component: ndarray,
cellwise_background_mean: ndarray,
isotype_names: tuple[str, ...],
dsb_params: DsbParams,
scale_factor: str,
)
What a DSB normalisation estimated on the way.
Attributes:
| Name | Type | Description |
|---|---|---|
protein_background_mean |
ndarray
|
Per-protein background mean. |
protein_background_sd |
ndarray
|
Per-protein background SD; empty without empty droplets. |
technical_component |
ndarray
|
Per-cell covariate regressed out in step II; empty without denoising. |
cellwise_background_mean |
ndarray
|
Per-cell background mean; empty without denoising. |
isotype_names |
tuple[str, ...]
|
The isotype controls used. |
dsb_params |
DsbParams
|
The parameters. |
scale_factor |
str
|
|
add_adt_counts
¶
add_adt_counts(
mm: SingleCellsMultiModal,
adt_counts: ndarray,
barcodes: Sequence[str] | ndarray | Series,
feature_ids: Sequence[str] | ndarray | Series,
*,
method: Literal["clr", "dsb"] = "clr",
seurat_clr: bool = False,
clean_clr_counts: bool = True,
percentile: float = 0.01,
empty_drops: ndarray | None = None,
isotype_names: Sequence[str] | None = None,
dsb_params: DsbParams | None = None,
scale_factor: Literal[
"standardise", "mean_subtract"
] = "standardise",
seed: int = 42,
verbose: Verbose = True,
) -> None
Add ADT counts for the kept cells.
The counts are cut to the kept cells (in their order) and normalised,
var_adt is (re)written to the DuckDB and obs gains adt_nnz and
adt_lib_size. The counts land in mm.adt.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mm
|
SingleCellsMultiModal
|
The experiment, its RNA already loaded. |
required |
adt_counts
|
ndarray
|
|
required |
barcodes
|
Sequence[str] | ndarray | Series
|
Barcode of each row; every kept cell must be one. |
required |
feature_ids
|
Sequence[str] | ndarray | Series
|
Id of each column. |
required |
method
|
Literal['clr', 'dsb']
|
|
'clr'
|
seurat_clr
|
bool
|
CLR only, see |
False
|
clean_clr_counts
|
bool
|
CLR only. |
True
|
percentile
|
float
|
CLR only. |
0.01
|
empty_drops
|
ndarray | None
|
DSB only, see |
None
|
isotype_names
|
Sequence[str] | None
|
DSB only. |
None
|
dsb_params
|
DsbParams | None
|
DSB only. |
None
|
scale_factor
|
Literal['standardise', 'mean_subtract']
|
DSB only. |
'standardise'
|
seed
|
int
|
DSB only. |
42
|
verbose
|
Verbose
|
DSB only. |
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If a kept cell is not among the barcodes. |
Examples:
new_adt_counts_clr
¶
new_adt_counts_clr(
raw_counts: ndarray,
barcodes: Sequence[str] | ndarray | Series,
feature_ids: Sequence[str] | ndarray | Series,
cell_info: DataFrame,
*,
seurat_clr: bool = False,
clean_clr_counts: bool = True,
percentile: float = 0.01,
) -> AdtCounts
CLR-normalised ADT counts.
The CLR runs per cell: log1p(x) - mean(log1p(x)), or Seurat's
non-negative log1p(x / g). With clean_clr_counts each protein's
percentile quantile is subtracted afterwards to take out background.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raw_counts
|
ndarray
|
|
required |
barcodes
|
Sequence[str] | ndarray | Series
|
Barcode of each row. |
required |
feature_ids
|
Sequence[str] | ndarray | Series
|
Id of each column. |
required |
cell_info
|
DataFrame
|
The cells to keep, in order: |
required |
seurat_clr
|
bool
|
Seurat-style CLR. |
False
|
clean_clr_counts
|
bool
|
Subtract the per-protein |
True
|
percentile
|
float
|
The quantile, in |
0.01
|
Raises:
| Type | Description |
|---|---|
ValueError
|
On a percentile outside |
Examples:
new_adt_counts_dsb
¶
new_adt_counts_dsb(
raw_counts: ndarray,
barcodes: Sequence[str] | ndarray | Series,
feature_ids: Sequence[str] | ndarray | Series,
cell_info: DataFrame,
*,
empty_drops: ndarray | None = None,
isotype_names: Sequence[str] | None = None,
dsb_params: DsbParams | None = None,
scale_factor: Literal[
"standardise", "mean_subtract"
] = "standardise",
seed: int = 42,
verbose: Verbose = True,
) -> AdtCounts
DSB-normalised ADT counts.
With empty_drops the per-protein background comes from the empty
droplets; without, from a two-component k-means on the log counts
("ModelNegativeADTnorm"). Step II regresses out the technical component
built from the isotypes and the per-cell background.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raw_counts
|
ndarray
|
|
required |
barcodes
|
Sequence[str] | ndarray | Series
|
Barcode of each row. |
required |
feature_ids
|
Sequence[str] | ndarray | Series
|
Id of each column. |
required |
cell_info
|
DataFrame
|
The cells to keep, in order: |
required |
empty_drops
|
ndarray | None
|
Optional |
None
|
isotype_names
|
Sequence[str] | None
|
Feature ids of the isotype controls. Needed when
|
None
|
dsb_params
|
DsbParams | None
|
The parameters. |
None
|
scale_factor
|
Literal['standardise', 'mean_subtract']
|
|
'standardise'
|
seed
|
int
|
Seed for the k-means initialisations. |
42
|
verbose
|
Verbose
|
|
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
On isotypes needed but absent or unknown, or the inputs not lining up. |
References
Mulè, et al., Nat Commun, 2022.
Examples:
get_adt_counts
¶
get_adt_counts(
mm: SingleCellsMultiModal,
*,
layer: Literal["raw", "norm"] = "raw",
cells: ndarray
| Sequence[int]
| Sequence[str]
| None = None,
features: ndarray
| Sequence[int]
| Sequence[str]
| None = None,
use_cells_to_keep: bool = True,
) -> ndarray
The dense ADT counts.
The ADT matrix is keyed by barcode and frozen at add time; requested
cells it does not hold warn and drop, so check len() against what you
asked for.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mm
|
SingleCellsMultiModal
|
The experiment, with ADT counts. |
required |
layer
|
Literal['raw', 'norm']
|
|
'raw'
|
cells
|
ndarray | Sequence[int] | Sequence[str] | None
|
0-based store indices or ids, rows in that order. |
None
|
features
|
ndarray | Sequence[int] | Sequence[str] | None
|
0-based ADT feature indices or ids. |
None
|
use_cells_to_keep
|
bool
|
Restrict to the kept cells. |
True
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
Without ADT counts, or if no cell is left. |
get_adt_names
¶
get_adt_names(
adt: AdtCounts | SingleCellsMultiModal,
) -> list[str] | None
The ADT feature ids.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
adt
|
AdtCounts | SingleCellsMultiModal
|
The ADT counts, or a multi-modal experiment. |
required |
Returns:
| Type | Description |
|---|---|
list[str] | None
|
The ids, or |
get_adt_feature_info
¶
get_adt_feature_info(
adt: AdtCounts | SingleCellsMultiModal,
) -> DataFrame
Cells expressing each protein.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
adt
|
AdtCounts | SingleCellsMultiModal
|
The ADT counts, or a multi-modal experiment holding them. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
|
DataFrame
|
because it is written as a double to |
get_adt_sample_info
¶
get_adt_sample_info(
adt: AdtCounts | SingleCellsMultiModal,
) -> DataFrame
ADT capture per cell.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
adt
|
AdtCounts | SingleCellsMultiModal
|
The ADT counts, or a multi-modal experiment holding them. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
|
DataFrame
|
they are written to obs. |
ADT PCA¶
Multi-modal single cell: ADT counts, their PCA and the WNN graph.
Adds a protein modality to a SingleCellsMultiModal, normalises it (CLR or
DSB), runs a PCA over it and fuses it with the RNA through a weighted nearest
neighbour (WNN) graph. The RNA side is a plain SingleCells, so every RNA
function takes the object as it is.
Start with add_adt_counts, then calculate_pca_adt. Run the RNA PCA the
usual way (bv.pp.find_hvg, bv.pp.calculate_pca) and call
generate_wnn_graph. From there bv.graph.find_clusters and bv.embed
take modality="wnn"; modality="adt" does the same for the protein side
alone. The WNN fuses RNA with ATAC the same way: modality_2="atac",
embd_to_use_2="lsi" (or "harmony" after correcting the LSI), see
bv.atac.
What lands where. add_adt_counts cuts the counts to the kept cells,
normalises them and stores them in mm.adt; it also writes the var_adt table
to the DuckDB and adt_nnz and adt_lib_size to obs. The counts stay in
memory, not in the count store, and bv.io.save keeps them. calculate_pca_adt
writes scores, loadings and singular values to mm.adt_cache.
generate_wnn_graph puts the fused kNN, its graph and the per-cell modality
weights in mm.wnn. new_adt_counts_clr, new_adt_counts_dsb and the
get_* functions return their result and leave the experiment alone.
# adt_counts: dense cells x proteins array; barcodes and proteins: their labels
mm = bv.SingleCellsMultiModal(sc.dir)
bv.mm.add_adt_counts(mm, adt_counts, barcodes, proteins, method="clr")
bv.pp.find_hvg(mm, hvg_no=500)
bv.pp.calculate_pca(mm, no_pcs=20)
bv.mm.calculate_pca_adt(mm, no_pcs=10)
bv.mm.generate_wnn_graph(mm)
bv.graph.find_clusters(mm, modality="wnn")
weights = bv.mm.get_wnn_weights(mm)
Gotchas. Every kept cell needs a row in the ADT barcodes, or
add_adt_counts raises. The matrix is cut to the kept cells when you add it:
dropping cells afterwards is fine, putting dropped cells back is not
(calculate_pca_adt then raises). DSB
wants the isotype controls by default (DsbParams.use_isotype_controls), so
pass isotype_names, or switch the option off. Leave the isotypes out of the
ADT PCA with features=. generate_wnn_graph needs an embedding of both
modalities (the PCA, or the LSI for ATAC), rebuilds the per-modality kNN
graphs itself at knn_range neighbours rather than reusing the cached ones,
and replaces any earlier WNN result with its embeddings.
calculate_pca_adt
¶
calculate_pca_adt(
mm: SingleCellsMultiModal,
no_pcs: int,
*,
features: Sequence[str] | None = None,
randomised_svd: bool = False,
seed: int = 42,
) -> None
PCA over the scaled, normalised ADT counts.
Scores, loadings and singular values go to mm.adt_cache, stamped
"adt:pca". The largest-magnitude loading of each component is positive.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mm
|
SingleCellsMultiModal
|
The experiment, with ADT counts. |
required |
no_pcs
|
int
|
Number of components, at most the number of features used. |
required |
features
|
Sequence[str] | None
|
ADT feature ids to restrict to, e.g. without the isotypes.
The loadings rows follow them. |
None
|
randomised_svd
|
bool
|
Randomised SVD, faster and less precise. |
False
|
seed
|
int
|
Seed for the randomised SVD. |
42
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If a kept cell has no ADT counts, or |
Examples:
Weighted nearest neighbours¶
Multi-modal single cell: ADT counts, their PCA and the WNN graph.
Adds a protein modality to a SingleCellsMultiModal, normalises it (CLR or
DSB), runs a PCA over it and fuses it with the RNA through a weighted nearest
neighbour (WNN) graph. The RNA side is a plain SingleCells, so every RNA
function takes the object as it is.
Start with add_adt_counts, then calculate_pca_adt. Run the RNA PCA the
usual way (bv.pp.find_hvg, bv.pp.calculate_pca) and call
generate_wnn_graph. From there bv.graph.find_clusters and bv.embed
take modality="wnn"; modality="adt" does the same for the protein side
alone. The WNN fuses RNA with ATAC the same way: modality_2="atac",
embd_to_use_2="lsi" (or "harmony" after correcting the LSI), see
bv.atac.
What lands where. add_adt_counts cuts the counts to the kept cells,
normalises them and stores them in mm.adt; it also writes the var_adt table
to the DuckDB and adt_nnz and adt_lib_size to obs. The counts stay in
memory, not in the count store, and bv.io.save keeps them. calculate_pca_adt
writes scores, loadings and singular values to mm.adt_cache.
generate_wnn_graph puts the fused kNN, its graph and the per-cell modality
weights in mm.wnn. new_adt_counts_clr, new_adt_counts_dsb and the
get_* functions return their result and leave the experiment alone.
# adt_counts: dense cells x proteins array; barcodes and proteins: their labels
mm = bv.SingleCellsMultiModal(sc.dir)
bv.mm.add_adt_counts(mm, adt_counts, barcodes, proteins, method="clr")
bv.pp.find_hvg(mm, hvg_no=500)
bv.pp.calculate_pca(mm, no_pcs=20)
bv.mm.calculate_pca_adt(mm, no_pcs=10)
bv.mm.generate_wnn_graph(mm)
bv.graph.find_clusters(mm, modality="wnn")
weights = bv.mm.get_wnn_weights(mm)
Gotchas. Every kept cell needs a row in the ADT barcodes, or
add_adt_counts raises. The matrix is cut to the kept cells when you add it:
dropping cells afterwards is fine, putting dropped cells back is not
(calculate_pca_adt then raises). DSB
wants the isotype controls by default (DsbParams.use_isotype_controls), so
pass isotype_names, or switch the option off. Leave the isotypes out of the
ADT PCA with features=. generate_wnn_graph needs an embedding of both
modalities (the PCA, or the LSI for ATAC), rebuilds the per-modality kNN
graphs itself at knn_range neighbours rather than reusing the cached ones,
and replaces any earlier WNN result with its embeddings.
WnnSlot
dataclass
¶
WnnSlot(
cache: ScCache,
weights: DataFrame,
modality_1: str,
modality_2: str,
)
The weighted nearest neighbour integration.
Attributes:
| Name | Type | Description |
|---|---|---|
cache |
ScCache
|
The fused kNN, its graph and embeddings laid out on it. Its PCA slots stay empty. |
weights |
DataFrame
|
|
modality_1 |
str
|
The first modality fused. |
modality_2 |
str
|
The second modality fused. |
generate_wnn_graph
¶
generate_wnn_graph(
mm: SingleCellsMultiModal,
*,
modality_1: CacheModality = "rna",
modality_2: CacheModality = "adt",
embd_to_use_1: str = "pca",
embd_to_use_2: str = "pca",
no_embd_to_use_1: int | None = None,
no_embd_to_use_2: int | None = None,
wnn_params: WnnParams | None = None,
graph_params: KnnGraphDefaults | None = None,
seed: int = 42,
verbose: Verbose = True,
) -> None
Weighted nearest neighbour graph over two modalities.
Per-cell modality weights come from comparing within- and cross-modality
neighbourhood distances; they fuse the two into one kNN. The
per-modality kNN graphs are always rebuilt from the embeddings at
knn_range neighbours, the cached ones are not reused. The fused kNN
(pseudo-distances), its neighbour graph and the weights replace
mm.wnn, and any WNN embeddings with them; use modality="wnn" to
cluster or lay it out.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mm
|
SingleCellsMultiModal
|
The experiment. |
required |
modality_1
|
CacheModality
|
First modality. |
'rna'
|
modality_2
|
CacheModality
|
Second modality, |
'adt'
|
embd_to_use_1
|
str
|
Embedding of the first, |
'pca'
|
embd_to_use_2
|
str
|
Embedding of the second, |
'pca'
|
no_embd_to_use_1
|
int | None
|
Leading dimensions of the first. |
None
|
no_embd_to_use_2
|
int | None
|
Leading dimensions of the second. |
None
|
wnn_params
|
WnnParams | None
|
The WNN parameters. |
None
|
graph_params
|
KnnGraphDefaults | None
|
How the fused kNN becomes the neighbour graph. |
None
|
seed
|
int
|
Seed for the kNN index builds. |
42
|
verbose
|
Verbose
|
|
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If an embedding is absent. |
References
Hao, et al., Cell, 2021.
Examples:
get_wnn_weights
¶
get_wnn_weights(mm: SingleCellsMultiModal) -> DataFrame
The per-cell modality weights of the WNN integration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mm
|
SingleCellsMultiModal
|
The multi-modal experiment. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
Before |