Skip to content

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:

bv.pp.find_hvg(mc, hvg_no=500)
bv.pp.calculate_pca(mc, no_pcs=10)
bv.graph.find_neighbours(mc)

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:

bv.pp.find_hvg(mc, hvg_no=500)
bv.pp.calculate_pca(mc, no_pcs=10)
bv.graph.find_neighbours(mc)

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 uses the defaults.

None
regenerate_knn bool

Build the kNN on the embedding instead of using the cached one.

False
embd_to_use str

The embedding, "pca" or a name in sc.cache.embeddings.

'pca'
no_embd_to_use int | None

Leading embedding dimensions to use. None for all.

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

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
MetaCells | None

The meta cells, or None (with a warning) if the kNN or embedding is

MetaCells | None

missing.

Raises:

Type Description
ValueError

If the kNN or embedding is stale.

References

Morabito, et al., Cell Rep Methods, 2023.

Examples:

>>> params = bv.params.BtMetacellsParams(target_no_metacells=100, k=25)
>>> mc = bv.metacells.generate_bt_meta_cells(sc, params=params)
>>> mc = bv.metacells.generate_bt_meta_cells(sc, regenerate_knn=True)

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; n_sea_cells has no default.

required
embd_to_use str

The embedding, "pca" or a name in sc.cache.embeddings.

'pca'
no_embd_to_use int | None

Leading embedding dimensions to use. None for all.

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

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

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:

>>> params = bv.params.SeacellsParams(n_sea_cells=100)
>>> mc = bv.metacells.generate_seacells(sc, params)

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 uses the defaults.

None
regenerate_knn bool

Build the kNN on the embedding.

False
embd_to_use str

The embedding, "pca" or a name in sc.cache.embeddings.

'pca'
no_embd_to_use int | None

Leading embedding dimensions to use. None for all.

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

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
MetaCells | None

The meta cells, or None (with a warning) if the kNN or embedding is

MetaCells | None

missing.

Raises:

Type Description
ValueError

If the kNN or embedding is stale.

References

Bilous, et al., BMC Bioinform, 2022.

Examples:

>>> params = bv.params.SupercellParams(graining_factor=20)
>>> mc = bv.metacells.generate_supercells(sc, params=params)

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 uses the defaults.

None
dac_params Metacells2DacParams | None

The piling and rare gene module parameters. None uses the defaults.

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

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True
References

Ben-Kiki, et al., Genome Biol, 2022.

Examples:

>>> mc = bv.metacells.generate_metacells2(sc)
>>> ids = sc.obs()["cell_id"].head(1500).to_list()
>>> mc = bv.metacells.generate_metacells2(sc, cells_to_use=ids)

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:

bv.pp.find_hvg(mc, hvg_no=500)
bv.pp.calculate_pca(mc, no_pcs=10)
bv.graph.find_neighbours(mc)

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 log1p'd, CSR sharing raw's indices and pointers.

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 rss / archetypes / converged, MetaCells2 cell_info / rare_gene_modules / selected_genes, diffusion dcs / density_dist / regions, merge sources).

meta_cell_method

The generator.

is_merged

Built by merge_meta_cells.

Assemble a meta cell object; the generators and the loader call it.

Raises:

Type Description
ValueError

If the tables and matrices disagree.

n_cells property

n_cells: int

Number of meta cells.

n_genes property

n_genes: int

Number of genes.

shape property

shape: tuple[int, int]

(meta cells, genes).

cell_ids

cell_ids() -> ndarray

The meta cell ids, in row order.

gene_ids

gene_ids(
    indices: ndarray | Sequence[int] | None = None,
) -> ndarray

Gene ids, all or for 0-based gene indices.

cell_indices

cell_indices(cell_ids: Sequence[str]) -> ndarray

0-based rows of meta cells by id. Unknown ids warn and drop.

gene_indices

gene_indices(gene_ids: Sequence[str]) -> ndarray

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.

obs_columns

obs_columns() -> list[str]

The obs column names.

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_obs(frame: DataFrame) -> None

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_var(frame: DataFrame) -> None

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" or "norm".

'raw'

Raises:

Type Description
ValueError

On an unknown layer.

cells_hash

cells_hash() -> str

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.

cache_status

cache_status() -> DataFrame

One row per cached artefact: stamped, stale and why.

check_state

check_state(artefacts: Sequence[str]) -> bool | str

True if the artefacts are fresh, else what is stale and why.

cell_assignments

cell_assignments() -> DataFrame

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 cells_to_keep at generation, the row order of its embeddings, kNN and diffusion maps. None for a merged object.

per_source dict[str, dict[str, int]] | None

For a merged object, n_cells, n_metacells and n_unassigned per source id.

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:

bv.pp.find_hvg(mc, hvg_no=500)
bv.pp.calculate_pca(mc, no_pcs=10)
bv.graph.find_neighbours(mc)

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 (sc.obs()) or one per kept cell in cells_to_keep order; the length decides which. Cells in no meta cell may be missing (None).

required
add_additional_info PurityInfo

"none", "top_label" or "top_two_labels".

'none'
add_entropy bool

Add mc_entropy.

False

Raises:

Type Description
ValueError

If the labels fit neither cell space.

Examples:

>>> labels = sc.obs()["cell_grp"].to_list()
>>> bv.metacells.calc_meta_cell_purity(mc, labels, add_entropy=True)
>>> mc.obs(cols=["meta_cell_id", "mc_purity", "mc_entropy"])

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 calc_meta_cell_purity.

required
add_additional_info PurityInfo

"none", "top_label" or "top_two_labels".

'none'
add_entropy bool

Add mc_entropy.

False

Returns:

Type Description
DataFrame

meta_cell_idx, meta_cell_id and the purity columns, in obs order.

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:

bv.pp.find_hvg(mc, hvg_no=500)
bv.pp.calculate_pca(mc, no_pcs=10)
bv.graph.find_neighbours(mc)

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 cells_to_keep order, e.g. sc.cache.knn.

required
n_dcs int

Diffusion components.

10
k_density int

The neighbour giving the density.

150
seed int

Seed.

42
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Raises:

Type Description
ValueError

If the kNN does not cover the kept source cells.

References

Persad, et al., Nat Biotechnol, 2023.

Examples:

>>> bv.metacells.calc_diffusion_coordinates(mc, sc.cache.knn, n_dcs=10)
>>> dcs = mc.other_data["dcs"]

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:

>>> bv.metacells.calc_diffusion_coordinates(mc, sc.cache.knn)
>>> bv.metacells.calc_manifold_metrics(mc)

calc_meta_cell_compactness

calc_meta_cell_compactness(
    dcs: ndarray, assignment: Sequence[object]
) -> DataFrame

Compactness of any meta cell assignment in a diffusion map.

Parameters:

Name Type Description Default
dcs ndarray

(n_cells, n_dcs) diffusion coordinates, e.g. mc.other_data["dcs"].

required
assignment Sequence[object]

Meta cell of each row of dcs, None for none. Overlapping meta cells cannot be expressed this way; use calc_manifold_metrics for those.

required

Returns:

Type Description
DataFrame

meta_cell and compactness, ordered by sorted level.

References

Persad, et al., Nat Biotechnol, 2023.

Examples:

>>> dcs = mc.other_data["dcs"]
>>> assignment = [str(x) for x in sc.obs()["cell_grp"].to_list()]
>>> compactness = bv.metacells.calc_meta_cell_compactness(dcs, assignment)

calc_meta_cell_separation

calc_meta_cell_separation(
    dcs: ndarray, assignment: Sequence[object]
) -> DataFrame

Separation of any meta cell assignment in a diffusion map. A single meta cell yields inf.

Parameters:

Name Type Description Default
dcs ndarray

(n_cells, n_dcs) diffusion coordinates.

required
assignment Sequence[object]

Meta cell of each row of dcs, None for none.

required

Returns:

Type Description
DataFrame

meta_cell and separation, ordered by sorted level.

References

Persad, et al., Nat Biotechnol, 2023.

Examples:

>>> dcs = mc.other_data["dcs"]
>>> assignment = [str(x) for x in sc.obs()["cell_grp"].to_list()]
>>> separation = bv.metacells.calc_meta_cell_separation(dcs, assignment)

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:

bv.pp.find_hvg(mc, hvg_no=500)
bv.pp.calculate_pca(mc, no_pcs=10)
bv.graph.find_neighbours(mc)

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", "seacells" or "supercells".

'bootstrapped'
mc_params Mapping[str, object] | None

Keyword arguments for the generator; SEACells needs seacell_params.

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 for every level among the kept cells, in order of appearance.

None
feature_space str

Passed to merge_meta_cells.

'intersect'
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
MetaCells

The merged meta cells, a source_id column in obs.

Raises:

Type Description
TypeError

If pipeline cannot run on, or does not return, a SingleCellsSubset, or mc_params do not bind to the generator.

ValueError

On a missing column, or a group without meta cells.

Examples:

>>> pipeline = bv.pipeline.step_hvg(hvg_no=500) >> bv.pipeline.step_pca(20)
>>> pipeline = pipeline >> bv.pipeline.step_neighbours()
>>> mc = bv.metacells.meta_cells_per_group(sc, "batch_index", pipeline=pipeline)

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 takes the dict keys, else source_01, source_02, ...

None
feature_space str

"intersect" or "union" of the gene spaces; with "union" a gene an input lacks is a structural zero for its meta cells.

'intersect'
prefix_ids bool

Prefix the meta cell ids with "<source_id>__". Without it, ids repeated across inputs are an error.

True
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
MetaCells

The merged meta cells, is_merged set, a source_id obs column and

MetaCells

the source ids in other_data["sources"].

Raises:

Type Description
ValueError

On no inputs, mismatched methods or ids, or an empty gene intersection.

Examples:

>>> mc_a = bv.metacells.generate_supercells(sc)
>>> mc_b = bv.metacells.generate_supercells(sc, seed=1)
>>> merged = bv.metacells.merge_meta_cells({"a": mc_a, "b": mc_b})

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 other_data entry that is not an array, a frame, a list of strings or a number.

Examples:

>>> bv.metacells.save_metacells(mc, "meta_cells")

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 save_metacells wrote.

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:

>>> mc = bv.metacells.load_metacells("meta_cells")