Meta cells¶
Meta cell generators, quality metrics, merging and persistence.
Four generators collapse a store into far fewer meta cells held in memory as a
MetaCells: bootstrapped neighbourhoods (hdWGCNA), SEACells, SuperCells and
MetaCells2. Start with one of them, then judge the result with the metrics,
and run the usual bv.pp, bv.graph and bv.embed calls on the MetaCells
itself. save_metacells and load_metacells write and read a meta cell set
as a directory.
What lands where. The generators take a SingleCells or
SingleCellsSubset, leave it alone and return a new MetaCells.
calc_meta_cell_purity writes mc_purity (and optional label and entropy
columns) to the meta cells' obs, calc_diffusion_coordinates writes
density_region to obs and dcs, density_dist and regions to
mc.other_data, and calc_manifold_metrics writes compactness and
separation to obs. get_meta_cell_purity, calc_meta_cell_compactness and
calc_meta_cell_separation return a frame and touch nothing. Each meta cell
keeps the store cells it aggregates in obs original_cell_idx.
merge_meta_cells and meta_cells_per_group return a new object.
Object types. The generators accept SingleCells and SingleCellsSubset;
the metrics and merge_meta_cells take MetaCells.
mc = bv.metacells.generate_supercells(
sc, params=bv.params.SupercellParams(graining_factor=20)
)
bv.metacells.calc_meta_cell_purity(mc, sc.obs()["cell_grp"].to_list())
bv.metacells.calc_diffusion_coordinates(mc, sc.cache.knn)
bv.metacells.calc_manifold_metrics(mc)
mc.obs(cols=["meta_cell_id", "mc_purity", "compactness", "separation"])
From there the meta cells go through the normal chain:
Gotchas. Bootstrapped, SEACells and SuperCells read the cached PCA and kNN
of the source (or build the kNN again with regenerate_knn=True), so run
bv.pp.find_hvg, bv.pp.calculate_pca and bv.graph.find_neighbours on sc
first. A stale PCA or kNN raises. Without a kNN, the bootstrapped and
SuperCells generators warn and return None, SEACells raises. MetaCells2 works
on the raw counts and needs neither. Bootstrapped meta cells overlap; the
others partition, and MetaCells2 leaves outlier cells unassigned. The labels
for the purity are one per row of the source obs, or one per kept cell. The
diffusion map is built from the source kNN, so pass sc.cache.knn, and
calc_manifold_metrics needs calc_diffusion_coordinates first. A merged
object has several index spaces, so both of them warn and do nothing on it:
run them per source before merge_meta_cells. Merging also drops the caches
and the HVGs, so redo the chain afterwards. The residual model is not saved.
Worked through in Meta cells with bixverse.
Generating meta cells¶
Meta cell generators, quality metrics, merging and persistence.
Four generators collapse a store into far fewer meta cells held in memory as a
MetaCells: bootstrapped neighbourhoods (hdWGCNA), SEACells, SuperCells and
MetaCells2. Start with one of them, then judge the result with the metrics,
and run the usual bv.pp, bv.graph and bv.embed calls on the MetaCells
itself. save_metacells and load_metacells write and read a meta cell set
as a directory.
What lands where. The generators take a SingleCells or
SingleCellsSubset, leave it alone and return a new MetaCells.
calc_meta_cell_purity writes mc_purity (and optional label and entropy
columns) to the meta cells' obs, calc_diffusion_coordinates writes
density_region to obs and dcs, density_dist and regions to
mc.other_data, and calc_manifold_metrics writes compactness and
separation to obs. get_meta_cell_purity, calc_meta_cell_compactness and
calc_meta_cell_separation return a frame and touch nothing. Each meta cell
keeps the store cells it aggregates in obs original_cell_idx.
merge_meta_cells and meta_cells_per_group return a new object.
Object types. The generators accept SingleCells and SingleCellsSubset;
the metrics and merge_meta_cells take MetaCells.
mc = bv.metacells.generate_supercells(
sc, params=bv.params.SupercellParams(graining_factor=20)
)
bv.metacells.calc_meta_cell_purity(mc, sc.obs()["cell_grp"].to_list())
bv.metacells.calc_diffusion_coordinates(mc, sc.cache.knn)
bv.metacells.calc_manifold_metrics(mc)
mc.obs(cols=["meta_cell_id", "mc_purity", "compactness", "separation"])
From there the meta cells go through the normal chain:
Gotchas. Bootstrapped, SEACells and SuperCells read the cached PCA and kNN
of the source (or build the kNN again with regenerate_knn=True), so run
bv.pp.find_hvg, bv.pp.calculate_pca and bv.graph.find_neighbours on sc
first. A stale PCA or kNN raises. Without a kNN, the bootstrapped and
SuperCells generators warn and return None, SEACells raises. MetaCells2 works
on the raw counts and needs neither. Bootstrapped meta cells overlap; the
others partition, and MetaCells2 leaves outlier cells unassigned. The labels
for the purity are one per row of the source obs, or one per kept cell. The
diffusion map is built from the source kNN, so pass sc.cache.knn, and
calc_manifold_metrics needs calc_diffusion_coordinates first. A merged
object has several index spaces, so both of them warn and do nothing on it:
run them per source before merge_meta_cells. Merging also drops the caches
and the HVGs, so redo the chain afterwards. The residual model is not saved.
generate_bt_meta_cells
¶
generate_bt_meta_cells(
sc: ScOrScSubset,
*,
params: BtMetacellsParams | None = None,
regenerate_knn: bool = False,
embd_to_use: str = "pca",
no_embd_to_use: int | None = None,
cells_to_use: Sequence[str] | None = None,
target_size: float = 100000.0,
seed: int = 42,
verbose: Verbose = True,
) -> MetaCells | None
Bootstrapped meta cells after hdWGCNA.
Each meta cell is a kNN neighbourhood (the centre and its neighbours), so
meta cells can share cells. The cached kNN is used unless
regenerate_knn asks for one built on the embedding; cells_to_use
always rebuilds it on those cells.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sc
|
ScOrScSubset
|
The experiment or a subset of it. |
required |
params
|
BtMetacellsParams | None
|
The meta cell and kNN parameters. |
None
|
regenerate_knn
|
bool
|
Build the kNN on the embedding instead of using the cached one. |
False
|
embd_to_use
|
str
|
The embedding, |
'pca'
|
no_embd_to_use
|
int | None
|
Leading embedding dimensions to use. |
None
|
cells_to_use
|
Sequence[str] | None
|
Cell ids to restrict the meta cells to. |
None
|
target_size
|
float
|
Library size to normalise the meta cells to. |
100000.0
|
seed
|
int
|
Seed. |
42
|
verbose
|
Verbose
|
|
True
|
Returns:
| Type | Description |
|---|---|
MetaCells | None
|
The meta cells, or |
MetaCells | None
|
missing. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the kNN or embedding is stale. |
References
Morabito, et al., Cell Rep Methods, 2023.
Examples:
generate_seacells
¶
generate_seacells(
sc: ScOrScSubset,
seacell_params: SeacellsParams,
*,
embd_to_use: str = "pca",
no_embd_to_use: int | None = None,
cells_to_use: Sequence[str] | None = None,
regenerate_knn: bool = False,
target_size: float = 100000.0,
seed: int = 42,
verbose: Verbose = True,
) -> MetaCells
SEACells, kernel archetypal analysis.
The kernel is built on the embedding. The cached kNN is used unless
regenerate_knn is set, none is cached, or cells_to_use narrows the
cells; then it is built on the embedding. Archetypes that end up empty
are dropped. other_data holds rss per iteration, the store index
of each meta cell's archetypes and whether the fit converged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sc
|
ScOrScSubset
|
The experiment or a subset of it. |
required |
seacell_params
|
SeacellsParams
|
The SEACells and kNN parameters; |
required |
embd_to_use
|
str
|
The embedding, |
'pca'
|
no_embd_to_use
|
int | None
|
Leading embedding dimensions to use. |
None
|
cells_to_use
|
Sequence[str] | None
|
Cell ids to restrict the meta cells to. |
None
|
regenerate_knn
|
bool
|
Build the kNN on the embedding. |
False
|
target_size
|
float
|
Library size to normalise the meta cells to. |
100000.0
|
seed
|
int
|
Seed. |
42
|
verbose
|
Verbose
|
|
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the embedding is missing, or it or the kNN is stale. |
References
Persad, et al., Nat Biotechnol, 2023.
Examples:
generate_supercells
¶
generate_supercells(
sc: ScOrScSubset,
*,
params: SupercellParams | None = None,
regenerate_knn: bool = False,
embd_to_use: str = "pca",
no_embd_to_use: int | None = None,
cells_to_use: Sequence[str] | None = None,
target_size: float = 100000.0,
seed: int = 42,
verbose: Verbose = True,
) -> MetaCells | None
SuperCells, walktrap on the kNN graph.
ceil(n_cells / graining_factor) meta cells. The cached kNN is used
unless regenerate_knn asks for one built on the embedding;
cells_to_use always rebuilds it on those cells.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sc
|
ScOrScSubset
|
The experiment or a subset of it. |
required |
params
|
SupercellParams | None
|
The SuperCell and kNN parameters. |
None
|
regenerate_knn
|
bool
|
Build the kNN on the embedding. |
False
|
embd_to_use
|
str
|
The embedding, |
'pca'
|
no_embd_to_use
|
int | None
|
Leading embedding dimensions to use. |
None
|
cells_to_use
|
Sequence[str] | None
|
Cell ids to restrict the meta cells to. |
None
|
target_size
|
float
|
Library size to normalise the meta cells to. |
100000.0
|
seed
|
int
|
Seed for a kNN build. |
42
|
verbose
|
Verbose
|
|
True
|
Returns:
| Type | Description |
|---|---|
MetaCells | None
|
The meta cells, or |
MetaCells | None
|
missing. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the kNN or embedding is stale. |
References
Bilous, et al., BMC Bioinform, 2022.
Examples:
generate_metacells2
¶
generate_metacells2(
sc: ScOrScSubset,
*,
mc2_params: Metacells2Params | None = None,
dac_params: Metacells2DacParams | None = None,
cells_to_use: Sequence[str] | None = None,
target_size: float = 100000.0,
seed: int = 42,
verbose: Verbose = True,
) -> MetaCells
MetaCells2 (divide and conquer) on the raw counts.
No embedding or kNN needed. Aims at a target size and UMI count rather
than a number of meta cells and leaves outliers unassigned. other_data
holds cell_info (original_cell_idx 0-based, dissolved, level,
rare_module 0-based or null per included cell), rare_gene_modules
(gene_id, rare_module) and the selected_genes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sc
|
ScOrScSubset
|
The experiment or a subset of it. |
required |
mc2_params
|
Metacells2Params | None
|
The per-pile parameters. |
None
|
dac_params
|
Metacells2DacParams | None
|
The piling and rare gene module parameters. |
None
|
cells_to_use
|
Sequence[str] | None
|
Cell ids to restrict to; ids not kept warn and drop. |
None
|
target_size
|
float
|
Library size to normalise the meta cells to. |
100000.0
|
seed
|
int
|
Seed. |
42
|
verbose
|
Verbose
|
|
True
|
References
Ben-Kiki, et al., Genome Biol, 2022.
Examples:
The MetaCells object¶
Meta cell generators, quality metrics, merging and persistence.
Four generators collapse a store into far fewer meta cells held in memory as a
MetaCells: bootstrapped neighbourhoods (hdWGCNA), SEACells, SuperCells and
MetaCells2. Start with one of them, then judge the result with the metrics,
and run the usual bv.pp, bv.graph and bv.embed calls on the MetaCells
itself. save_metacells and load_metacells write and read a meta cell set
as a directory.
What lands where. The generators take a SingleCells or
SingleCellsSubset, leave it alone and return a new MetaCells.
calc_meta_cell_purity writes mc_purity (and optional label and entropy
columns) to the meta cells' obs, calc_diffusion_coordinates writes
density_region to obs and dcs, density_dist and regions to
mc.other_data, and calc_manifold_metrics writes compactness and
separation to obs. get_meta_cell_purity, calc_meta_cell_compactness and
calc_meta_cell_separation return a frame and touch nothing. Each meta cell
keeps the store cells it aggregates in obs original_cell_idx.
merge_meta_cells and meta_cells_per_group return a new object.
Object types. The generators accept SingleCells and SingleCellsSubset;
the metrics and merge_meta_cells take MetaCells.
mc = bv.metacells.generate_supercells(
sc, params=bv.params.SupercellParams(graining_factor=20)
)
bv.metacells.calc_meta_cell_purity(mc, sc.obs()["cell_grp"].to_list())
bv.metacells.calc_diffusion_coordinates(mc, sc.cache.knn)
bv.metacells.calc_manifold_metrics(mc)
mc.obs(cols=["meta_cell_id", "mc_purity", "compactness", "separation"])
From there the meta cells go through the normal chain:
Gotchas. Bootstrapped, SEACells and SuperCells read the cached PCA and kNN
of the source (or build the kNN again with regenerate_knn=True), so run
bv.pp.find_hvg, bv.pp.calculate_pca and bv.graph.find_neighbours on sc
first. A stale PCA or kNN raises. Without a kNN, the bootstrapped and
SuperCells generators warn and return None, SEACells raises. MetaCells2 works
on the raw counts and needs neither. Bootstrapped meta cells overlap; the
others partition, and MetaCells2 leaves outlier cells unassigned. The labels
for the purity are one per row of the source obs, or one per kept cell. The
diffusion map is built from the source kNN, so pass sc.cache.knn, and
calc_manifold_metrics needs calc_diffusion_coordinates first. A merged
object has several index spaces, so both of them warn and do nothing on it:
run them per source before merge_meta_cells. Merging also drops the caches
and the HVGs, so redo the chain afterwards. The residual model is not saved.
MetaCells
¶
MetaCells(
obs: DataFrame,
var: DataFrame,
raw: CsrMatrix,
norm: CsrMatrix,
original_assignment: MetaCellAssignment,
meta_cell_method: str,
*,
other_data: dict[str, object] | None = None,
is_merged: bool = False,
)
Meta cells in memory.
Built by the generators in bixverse.metacells and by
merge_meta_cells, not by hand.
>>> import bixverse as bv
>>> mc = bv.metacells.generate_bt_meta_cells(sc)
>>> bv.pp.find_hvg(mc, hvg_no=2000)
>>> bv.pp.calculate_pca(mc, 30)
>>> bv.graph.find_neighbours(mc)
Attributes:
| Name | Type | Description |
|---|---|---|
raw |
Summed raw counts, meta cells x genes, CSR. |
|
norm |
The counts normalised to the target size and |
|
cache |
Analysis results. |
|
hvg |
ndarray | None
|
0-based gene indices of the highly variable genes, if selected. |
original_assignment |
Provenance of the meta cells. |
|
other_data |
dict[str, object]
|
Method-specific extras (SEACells |
meta_cell_method |
The generator. |
|
is_merged |
Built by |
Assemble a meta cell object; the generators and the loader call it.
Raises:
| Type | Description |
|---|---|
ValueError
|
If the tables and matrices disagree. |
gene_ids
¶
Gene ids, all or for 0-based gene indices.
cell_indices
¶
0-based rows of meta cells by id. Unknown ids warn and drop.
gene_indices
¶
0-based gene indices by id. Unknown ids warn and drop.
obs
¶
obs(
*,
indices: ndarray | Sequence[int] | None = None,
cols: list[str] | None = None,
filtered: bool = False,
) -> DataFrame
The meta cell obs table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
indices
|
ndarray | Sequence[int] | None
|
Optional 0-based rows. |
None
|
cols
|
list[str] | None
|
Optional columns. |
None
|
filtered
|
bool
|
Ignored; meta cells have no cell filter. |
False
|
Raises:
| Type | Description |
|---|---|
KeyError
|
If a column is not in obs. |
var
¶
var(
*,
indices: ndarray | Sequence[int] | None = None,
cols: list[str] | None = None,
) -> DataFrame
The var table.
Raises:
| Type | Description |
|---|---|
KeyError
|
If a column is not in var. |
add_obs
¶
Add or replace obs columns.
With a 0-based meta_cell_idx column the frame joins on it, other
meta cells get NULL. Without one it must hold one row per meta cell,
in row order.
Raises:
| Type | Description |
|---|---|
ValueError
|
On a wrong row count or a protected column. |
add_var
¶
Add or replace var columns: one row per gene, in var order.
Raises:
| Type | Description |
|---|---|
ValueError
|
On a wrong row count or a protected column. |
counts
¶
counts(
*,
cells: ndarray
| Sequence[int]
| Sequence[str]
| None = None,
genes: ndarray
| Sequence[int]
| Sequence[str]
| None = None,
layer: str = "raw",
) -> CsrMatrix
The counts, optionally restricted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cells
|
ndarray | Sequence[int] | Sequence[str] | None
|
0-based rows or meta cell ids, in the row order wanted. |
None
|
genes
|
ndarray | Sequence[int] | Sequence[str] | None
|
0-based gene indices or ids, in the column order wanted. |
None
|
layer
|
str
|
|
'raw'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
On an unknown layer. |
cells_hash
¶
Hash of the meta cell ids, what the cache stamps record.
Meta cells have no cell filter; their set is fixed at construction and identified by the ids, which a merge rewrites.
stamp
¶
stamp(
artefact: str, *, parents: Sequence[str] = ()
) -> Stamp
Stamp a cached artefact against the meta cell set.
check_state
¶
True if the artefacts are fresh, else what is stale and why.
cell_assignments
¶
One row per (source cell, meta cell) membership, in long form.
Columns cell_idx (0-based store index in the source) and
meta_cell_idx. Bootstrapped meta cells overlap, so a cell can
appear more than once; unassigned cells do not appear.
MetaCellAssignment
dataclass
¶
MetaCellAssignment(
n_cells: int,
n_metacells: int,
n_unassigned: int,
cells_to_keep: ndarray | None = None,
per_source: dict[str, dict[str, int]] | None = None,
)
Where the meta cells came from.
The per-cell assignments are derived from the memberships in obs on
demand, see MetaCells.cell_assignments.
Attributes:
| Name | Type | Description |
|---|---|---|
n_cells |
int
|
Cells (obs rows) in the source store. |
n_metacells |
int
|
Number of meta cells. |
n_unassigned |
int
|
Source cells in no meta cell, QC-dropped ones included. |
cells_to_keep |
ndarray | None
|
The source's |
per_source |
dict[str, dict[str, int]] | None
|
For a merged object, |
Label purity¶
Meta cell generators, quality metrics, merging and persistence.
Four generators collapse a store into far fewer meta cells held in memory as a
MetaCells: bootstrapped neighbourhoods (hdWGCNA), SEACells, SuperCells and
MetaCells2. Start with one of them, then judge the result with the metrics,
and run the usual bv.pp, bv.graph and bv.embed calls on the MetaCells
itself. save_metacells and load_metacells write and read a meta cell set
as a directory.
What lands where. The generators take a SingleCells or
SingleCellsSubset, leave it alone and return a new MetaCells.
calc_meta_cell_purity writes mc_purity (and optional label and entropy
columns) to the meta cells' obs, calc_diffusion_coordinates writes
density_region to obs and dcs, density_dist and regions to
mc.other_data, and calc_manifold_metrics writes compactness and
separation to obs. get_meta_cell_purity, calc_meta_cell_compactness and
calc_meta_cell_separation return a frame and touch nothing. Each meta cell
keeps the store cells it aggregates in obs original_cell_idx.
merge_meta_cells and meta_cells_per_group return a new object.
Object types. The generators accept SingleCells and SingleCellsSubset;
the metrics and merge_meta_cells take MetaCells.
mc = bv.metacells.generate_supercells(
sc, params=bv.params.SupercellParams(graining_factor=20)
)
bv.metacells.calc_meta_cell_purity(mc, sc.obs()["cell_grp"].to_list())
bv.metacells.calc_diffusion_coordinates(mc, sc.cache.knn)
bv.metacells.calc_manifold_metrics(mc)
mc.obs(cols=["meta_cell_id", "mc_purity", "compactness", "separation"])
From there the meta cells go through the normal chain:
Gotchas. Bootstrapped, SEACells and SuperCells read the cached PCA and kNN
of the source (or build the kNN again with regenerate_knn=True), so run
bv.pp.find_hvg, bv.pp.calculate_pca and bv.graph.find_neighbours on sc
first. A stale PCA or kNN raises. Without a kNN, the bootstrapped and
SuperCells generators warn and return None, SEACells raises. MetaCells2 works
on the raw counts and needs neither. Bootstrapped meta cells overlap; the
others partition, and MetaCells2 leaves outlier cells unassigned. The labels
for the purity are one per row of the source obs, or one per kept cell. The
diffusion map is built from the source kNN, so pass sc.cache.knn, and
calc_manifold_metrics needs calc_diffusion_coordinates first. A merged
object has several index spaces, so both of them warn and do nothing on it:
run them per source before merge_meta_cells. Merging also drops the caches
and the HVGs, so redo the chain afterwards. The residual model is not saved.
calc_meta_cell_purity
¶
calc_meta_cell_purity(
mc: MetaCells,
original_cell_type: Sequence[str | None],
*,
add_additional_info: PurityInfo = "none",
add_entropy: bool = False,
) -> None
Label purity of each meta cell, written to obs.
Adds mc_purity (fraction of the meta cell's cells carrying its most
common label), and on request mc_top_label, mc_second_label (null for
a pure meta cell), mc_second_frac and mc_entropy (Shannon entropy of
the labels over log(number of distinct labels), 0 with a single label).
Ties resolve to the label that sorts first, by code point.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mc
|
MetaCells
|
The meta cells. |
required |
original_cell_type
|
Sequence[str | None]
|
Labels of the source cells, either one per obs
row of the source ( |
required |
add_additional_info
|
PurityInfo
|
|
'none'
|
add_entropy
|
bool
|
Add |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the labels fit neither cell space. |
Examples:
get_meta_cell_purity
¶
get_meta_cell_purity(
mc: MetaCells,
original_cell_type: Sequence[str | None],
*,
add_additional_info: PurityInfo = "none",
add_entropy: bool = False,
) -> DataFrame
calc_meta_cell_purity without touching the object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mc
|
MetaCells
|
The meta cells. |
required |
original_cell_type
|
Sequence[str | None]
|
Labels of the source cells, see
|
required |
add_additional_info
|
PurityInfo
|
|
'none'
|
add_entropy
|
bool
|
Add |
False
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
|
Diffusion map and manifold metrics¶
Meta cell generators, quality metrics, merging and persistence.
Four generators collapse a store into far fewer meta cells held in memory as a
MetaCells: bootstrapped neighbourhoods (hdWGCNA), SEACells, SuperCells and
MetaCells2. Start with one of them, then judge the result with the metrics,
and run the usual bv.pp, bv.graph and bv.embed calls on the MetaCells
itself. save_metacells and load_metacells write and read a meta cell set
as a directory.
What lands where. The generators take a SingleCells or
SingleCellsSubset, leave it alone and return a new MetaCells.
calc_meta_cell_purity writes mc_purity (and optional label and entropy
columns) to the meta cells' obs, calc_diffusion_coordinates writes
density_region to obs and dcs, density_dist and regions to
mc.other_data, and calc_manifold_metrics writes compactness and
separation to obs. get_meta_cell_purity, calc_meta_cell_compactness and
calc_meta_cell_separation return a frame and touch nothing. Each meta cell
keeps the store cells it aggregates in obs original_cell_idx.
merge_meta_cells and meta_cells_per_group return a new object.
Object types. The generators accept SingleCells and SingleCellsSubset;
the metrics and merge_meta_cells take MetaCells.
mc = bv.metacells.generate_supercells(
sc, params=bv.params.SupercellParams(graining_factor=20)
)
bv.metacells.calc_meta_cell_purity(mc, sc.obs()["cell_grp"].to_list())
bv.metacells.calc_diffusion_coordinates(mc, sc.cache.knn)
bv.metacells.calc_manifold_metrics(mc)
mc.obs(cols=["meta_cell_id", "mc_purity", "compactness", "separation"])
From there the meta cells go through the normal chain:
Gotchas. Bootstrapped, SEACells and SuperCells read the cached PCA and kNN
of the source (or build the kNN again with regenerate_knn=True), so run
bv.pp.find_hvg, bv.pp.calculate_pca and bv.graph.find_neighbours on sc
first. A stale PCA or kNN raises. Without a kNN, the bootstrapped and
SuperCells generators warn and return None, SEACells raises. MetaCells2 works
on the raw counts and needs neither. Bootstrapped meta cells overlap; the
others partition, and MetaCells2 leaves outlier cells unassigned. The labels
for the purity are one per row of the source obs, or one per kept cell. The
diffusion map is built from the source kNN, so pass sc.cache.knn, and
calc_manifold_metrics needs calc_diffusion_coordinates first. A merged
object has several index spaces, so both of them warn and do nothing on it:
run them per source before merge_meta_cells. Merging also drops the caches
and the HVGs, so redo the chain afterwards. The residual model is not saved.
calc_diffusion_coordinates
¶
calc_diffusion_coordinates(
mc: MetaCells,
knn: KnnGraph,
*,
n_dcs: int = 10,
k_density: int = 150,
seed: int = 42,
verbose: Verbose = True,
) -> None
Diffusion map of the source cells and a density region per meta cell.
Builds multiscale diffusion components off the source kNN, takes the
distance to the k_density-th neighbour in that space as a density
proxy and tags its lower quartile "high", upper quartile "low", the
rest "mid". Each meta cell gets the most common region of its cells in
obs density_region (ties to the name that sorts first); other_data
gains dcs, density_dist and regions.
A merged object warns and is left alone: its memberships live in several index spaces.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mc
|
MetaCells
|
The meta cells. |
required |
knn
|
KnnGraph
|
The kNN of the source cells, one row per kept cell in the
source's |
required |
n_dcs
|
int
|
Diffusion components. |
10
|
k_density
|
int
|
The neighbour giving the density. |
150
|
seed
|
int
|
Seed. |
42
|
verbose
|
Verbose
|
|
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the kNN does not cover the kept source cells. |
References
Persad, et al., Nat Biotechnol, 2023.
Examples:
calc_manifold_metrics
¶
calc_manifold_metrics(mc: MetaCells) -> None
Compactness and separation of each meta cell in the diffusion map.
Compactness is the mean variance over the diffusion components of a meta
cell's cells, lower is better; separation the distance from its centroid
to the nearest other centroid, higher is better. Both go to obs. Needs
calc_diffusion_coordinates first; without it, or on a merged object, a
warning and nothing changes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mc
|
MetaCells
|
The meta cells. |
required |
References
Persad, et al., Nat Biotechnol, 2023.
Examples:
calc_meta_cell_compactness
¶
Compactness of any meta cell assignment in a diffusion map.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dcs
|
ndarray
|
|
required |
assignment
|
Sequence[object]
|
Meta cell of each row of |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
|
References
Persad, et al., Nat Biotechnol, 2023.
Examples:
calc_meta_cell_separation
¶
Separation of any meta cell assignment in a diffusion map. A single
meta cell yields inf.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dcs
|
ndarray
|
|
required |
assignment
|
Sequence[object]
|
Meta cell of each row of |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
|
References
Persad, et al., Nat Biotechnol, 2023.
Examples:
Merging and saving¶
Meta cell generators, quality metrics, merging and persistence.
Four generators collapse a store into far fewer meta cells held in memory as a
MetaCells: bootstrapped neighbourhoods (hdWGCNA), SEACells, SuperCells and
MetaCells2. Start with one of them, then judge the result with the metrics,
and run the usual bv.pp, bv.graph and bv.embed calls on the MetaCells
itself. save_metacells and load_metacells write and read a meta cell set
as a directory.
What lands where. The generators take a SingleCells or
SingleCellsSubset, leave it alone and return a new MetaCells.
calc_meta_cell_purity writes mc_purity (and optional label and entropy
columns) to the meta cells' obs, calc_diffusion_coordinates writes
density_region to obs and dcs, density_dist and regions to
mc.other_data, and calc_manifold_metrics writes compactness and
separation to obs. get_meta_cell_purity, calc_meta_cell_compactness and
calc_meta_cell_separation return a frame and touch nothing. Each meta cell
keeps the store cells it aggregates in obs original_cell_idx.
merge_meta_cells and meta_cells_per_group return a new object.
Object types. The generators accept SingleCells and SingleCellsSubset;
the metrics and merge_meta_cells take MetaCells.
mc = bv.metacells.generate_supercells(
sc, params=bv.params.SupercellParams(graining_factor=20)
)
bv.metacells.calc_meta_cell_purity(mc, sc.obs()["cell_grp"].to_list())
bv.metacells.calc_diffusion_coordinates(mc, sc.cache.knn)
bv.metacells.calc_manifold_metrics(mc)
mc.obs(cols=["meta_cell_id", "mc_purity", "compactness", "separation"])
From there the meta cells go through the normal chain:
Gotchas. Bootstrapped, SEACells and SuperCells read the cached PCA and kNN
of the source (or build the kNN again with regenerate_knn=True), so run
bv.pp.find_hvg, bv.pp.calculate_pca and bv.graph.find_neighbours on sc
first. A stale PCA or kNN raises. Without a kNN, the bootstrapped and
SuperCells generators warn and return None, SEACells raises. MetaCells2 works
on the raw counts and needs neither. Bootstrapped meta cells overlap; the
others partition, and MetaCells2 leaves outlier cells unassigned. The labels
for the purity are one per row of the source obs, or one per kept cell. The
diffusion map is built from the source kNN, so pass sc.cache.knn, and
calc_manifold_metrics needs calc_diffusion_coordinates first. A merged
object has several index spaces, so both of them warn and do nothing on it:
run them per source before merge_meta_cells. Merging also drops the caches
and the HVGs, so redo the chain afterwards. The residual model is not saved.
meta_cells_per_group
¶
meta_cells_per_group(
sc: SingleCells,
group_col: str,
*,
method: MetacellMethod = "bootstrapped",
mc_params: Mapping[str, object] | None = None,
pipeline: Pipeline | None = None,
groups: Sequence[str] | None = None,
feature_space: str = "intersect",
verbose: Verbose = True,
) -> MetaCells
Source-pure meta cells: one generator run per group, merged.
Meta cells never mix two groups (patients, samples), yet end up in one
object. The generators need an embedding and usually a kNN, so pipeline
will normally be step_hvg() >> step_pca(30) >> step_neighbours().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sc
|
SingleCells
|
The experiment. |
required |
group_col
|
str
|
obs column to split on. |
required |
method
|
MetacellMethod
|
|
'bootstrapped'
|
mc_params
|
Mapping[str, object] | None
|
Keyword arguments for the generator; SEACells needs
|
None
|
pipeline
|
Pipeline | None
|
Run on each subset before its meta cells are generated. Must hand back the subset. |
None
|
groups
|
Sequence[str] | None
|
The levels to use; |
None
|
feature_space
|
str
|
Passed to |
'intersect'
|
verbose
|
Verbose
|
|
True
|
Returns:
| Type | Description |
|---|---|
MetaCells
|
The merged meta cells, a |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
On a missing column, or a group without meta cells. |
Examples:
merge_meta_cells
¶
merge_meta_cells(
inputs: Sequence[MetaCells] | dict[str, MetaCells],
*,
source_ids: Sequence[str] | None = None,
feature_space: str = "intersect",
prefix_ids: bool = True,
verbose: Verbose = True,
) -> MetaCells
Row-bind several MetaCells into one.
The typical case is sample-pure meta cells, generated per patient and merged so that downstream methods run across the full set. The normalised counts carry over: they are normalised per meta cell, so row-binding leaves them valid. Caches and HVGs are per source and dropped.
original_cell_idx stays in each source's index space, which is why the
diffusion and manifold metrics refuse a merged object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inputs
|
Sequence[MetaCells] | dict[str, MetaCells]
|
The meta cells; a dict names them by source. |
required |
source_ids
|
Sequence[str] | None
|
Source ids, unique, one per input. |
None
|
feature_space
|
str
|
|
'intersect'
|
prefix_ids
|
bool
|
Prefix the meta cell ids with |
True
|
verbose
|
Verbose
|
|
True
|
Returns:
| Type | Description |
|---|---|
MetaCells
|
The merged meta cells, |
MetaCells
|
the source ids in |
Raises:
| Type | Description |
|---|---|
ValueError
|
On no inputs, mismatched methods or ids, or an empty gene intersection. |
Examples:
save_metacells
¶
save_metacells(
mc: MetaCells, directory: Path | str
) -> None
Write a MetaCells to a directory: Parquet, npz and JSON, no pickle.
The residual model is not written; a warning says so.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mc
|
MetaCells
|
The meta cells. |
required |
directory
|
Path | str
|
Created if missing; existing files of the format are replaced. |
required |
Raises:
| Type | Description |
|---|---|
TypeError
|
On an |
Examples:
load_metacells
¶
load_metacells(directory: Path | str) -> MetaCells
Read a MetaCells written by save_metacells.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory
|
Path | str
|
The directory |
required |
Returns:
| Type | Description |
|---|---|
MetaCells
|
The meta cells. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If a file of the format is missing. |
ValueError
|
On an unknown format version. |
Examples: