Skip to content

Annotation

Cell type annotation with ScType, reference mapping with Symphony and Seurat.

ScType scores every cell against marker gene sets and calls a type per cell, optionally per cluster. Symphony builds a Harmony-corrected reference from an annotated experiment, maps a query into its embedding and transfers the labels by kNN vote. Start with prepare_cell_markers, calc_sc_type_scores and assign_sc_type for ScType, build_symphony_ref, map_symphony_query and transfer_labels_symphony for Symphony. transfer_labels_seurat transfers labels through Seurat's CCA anchors, RNA to RNA or RNA to the gene activity of an ATAC experiment.

What lands where. The ScType functions leave the experiment alone and return frozen records (ScTypeResults, ScTypeCellResults); put a call into obs yourself. map_symphony_query writes the query embeddings to query.cache.embeddings as "symphony" (corrected), "symphony_pca" (projected) and "symphony_r" (soft cluster assignments). transfer_labels_symphony writes predicted_<column> and confidence_<column> to the query's obs and returns them. build_symphony_ref and add_symphony_labels return a SymphonyReference and touch neither experiment. A reference is immutable: adding labels gives you a new one. All functions take a SingleCells.

ScType wants markers as a frame of cell_type and gene_id, in the id type of the experiment, and scores the kept cells. The neighbour graph smooths the scores, so run bv.graph.find_neighbours first; clusters from bv.graph.find_clusters add a per cluster call.

import polars as pl

genes = sc.gene_ids().tolist()
marker_df = pl.DataFrame(
    {
        "cell_type": ["type_1"] * 10 + ["type_2"] * 10 + ["type_3"] * 10,
        "gene_id": genes[:30],
    }
)
markers = bv.annotate.prepare_cell_markers(sc, marker_df)
scores = bv.annotate.calc_sc_type_scores(sc, markers)
calls = bv.annotate.assign_sc_type(sc, scores, cluster_col="leiden_clustering")
sc.add_obs(pl.DataFrame({"cell_idx": sc.cells_to_keep, "sc_type": calls.hybrid}))

Symphony needs the reference's HVGs, so run bv.pp.find_hvg on it first and hand sc.map.hvg over. Genes match by id; a reference HVG missing from the query becomes a zero column:

ref = bv.annotate.build_symphony_ref(
    sc, "sample_id", sc.map.hvg, label_columns=["cell_grp"]
)
bv.annotate.map_symphony_query(ref, query, batch_column="sample_id")
pred = bv.annotate.transfer_labels_symphony(ref, query, "cell_grp")

Gotchas. Every index is 0-based: marker genes, HVGs and cluster ids. cluster_col of assign_sc_type has to be a non-negative integer obs column with a value for every scored cell, which is what find_clusters writes. Without a neighbour graph assign_sc_type warns and scores without smoothing. calls.hybrid is None unless you gave a cluster_col; calls.assignments is the per cell call, null where the cell is Unknown. Labels are stored in a reference in cells_to_keep order, so add_symphony_labels needs the cell set the reference was built on. transfer_labels_symphony raises on a query that has no current "symphony" embedding: map again after the cell filter moves. save_symphony_ref and load_symphony_ref use one .npz file.

Worked through in Clustering, cell type annotation and reference mapping.

ScType

Cell type annotation with ScType, reference mapping with Symphony and Seurat.

ScType scores every cell against marker gene sets and calls a type per cell, optionally per cluster. Symphony builds a Harmony-corrected reference from an annotated experiment, maps a query into its embedding and transfers the labels by kNN vote. Start with prepare_cell_markers, calc_sc_type_scores and assign_sc_type for ScType, build_symphony_ref, map_symphony_query and transfer_labels_symphony for Symphony. transfer_labels_seurat transfers labels through Seurat's CCA anchors, RNA to RNA or RNA to the gene activity of an ATAC experiment.

What lands where. The ScType functions leave the experiment alone and return frozen records (ScTypeResults, ScTypeCellResults); put a call into obs yourself. map_symphony_query writes the query embeddings to query.cache.embeddings as "symphony" (corrected), "symphony_pca" (projected) and "symphony_r" (soft cluster assignments). transfer_labels_symphony writes predicted_<column> and confidence_<column> to the query's obs and returns them. build_symphony_ref and add_symphony_labels return a SymphonyReference and touch neither experiment. A reference is immutable: adding labels gives you a new one. All functions take a SingleCells.

ScType wants markers as a frame of cell_type and gene_id, in the id type of the experiment, and scores the kept cells. The neighbour graph smooths the scores, so run bv.graph.find_neighbours first; clusters from bv.graph.find_clusters add a per cluster call.

import polars as pl

genes = sc.gene_ids().tolist()
marker_df = pl.DataFrame(
    {
        "cell_type": ["type_1"] * 10 + ["type_2"] * 10 + ["type_3"] * 10,
        "gene_id": genes[:30],
    }
)
markers = bv.annotate.prepare_cell_markers(sc, marker_df)
scores = bv.annotate.calc_sc_type_scores(sc, markers)
calls = bv.annotate.assign_sc_type(sc, scores, cluster_col="leiden_clustering")
sc.add_obs(pl.DataFrame({"cell_idx": sc.cells_to_keep, "sc_type": calls.hybrid}))

Symphony needs the reference's HVGs, so run bv.pp.find_hvg on it first and hand sc.map.hvg over. Genes match by id; a reference HVG missing from the query becomes a zero column:

ref = bv.annotate.build_symphony_ref(
    sc, "sample_id", sc.map.hvg, label_columns=["cell_grp"]
)
bv.annotate.map_symphony_query(ref, query, batch_column="sample_id")
pred = bv.annotate.transfer_labels_symphony(ref, query, "cell_grp")

Gotchas. Every index is 0-based: marker genes, HVGs and cluster ids. cluster_col of assign_sc_type has to be a non-negative integer obs column with a value for every scored cell, which is what find_clusters writes. Without a neighbour graph assign_sc_type warns and scores without smoothing. calls.hybrid is None unless you gave a cluster_col; calls.assignments is the per cell call, null where the cell is Unknown. Labels are stored in a reference in cells_to_keep order, so add_symphony_labels needs the cell set the reference was built on. transfer_labels_symphony raises on a query that has no current "symphony" embedding: map again after the cell filter moves. save_symphony_ref and load_symphony_ref use one .npz file.

CellMarkers dataclass

CellMarkers(
    positive: ndarray,
    negative: ndarray = (lambda: zeros(0, dtype=uint32))(),
)

The marker genes of one cell type, one entry of the prepare_cell_markers() dict.

Attributes:

Name Type Description
positive ndarray

0-based indices of the positive markers.

negative ndarray

0-based indices of the negative markers.

ScTypeResults dataclass

ScTypeResults(cell_types: list[str], scores: ndarray)

Per-cell ScType scores.

Attributes:

Name Type Description
cell_types list[str]

The cell types, in score column order.

scores ndarray

(n_cells, n_cell_types) float64 scores over the kept cells, in cells_to_keep order.

n_cells property

n_cells: int

Number of scored cells.

n_cell_types property

n_cell_types: int

Number of cell types.

ScTypeCellResults dataclass

ScTypeCellResults(
    cell_types: list[str],
    assignments: Series,
    scores: ndarray,
    margins: ndarray,
    agreement: ndarray | None,
    hybrid: Series | None,
    composition: DataFrame | None,
    counts: DataFrame | None,
)

Per-cell ScType calls.

Attributes:

Name Type Description
cell_types list[str]

The scored cell types.

assignments Series

Per-cell call, null for Unknown.

scores ndarray

Winning score per cell, after calibration and smoothing.

margins ndarray

Best minus second best score per cell; a small margin flags an ambiguous call.

agreement ndarray | None

Share of graph neighbours sharing the call; None without smoothing.

hybrid Series | None

The hybrid call, None without a cluster column.

composition DataFrame | None

Per cluster cluster_id, n_cells, n_unknown, dominant, purity, second, second_fraction, entropy and cluster_mixed, or None.

counts DataFrame | None

cluster_id and one count column per cell type, or None.

prepare_cell_markers

prepare_cell_markers(
    sc: SingleCells, marker_df: DataFrame
) -> dict[str, CellMarkers]

Marker genes per cell type.

Genes the experiment does not hold are dropped. Cell types keep their order of first appearance.

Parameters:

Name Type Description Default
sc SingleCells

The experiment.

required
marker_df DataFrame

Columns cell_type and gene_id; the gene ids have to be of the experiment's id type.

required

Returns:

Type Description
dict[str, CellMarkers]

Cell type to its CellMarkers, positive markers only. A cell type

dict[str, CellMarkers]

none of whose genes matched is left out.

Raises:

Type Description
ValueError

If a column is missing.

Examples:

>>> markers = bv.annotate.prepare_cell_markers(sc, marker_df)

calc_sc_type_scores

calc_sc_type_scores(
    sc: SingleCells,
    cell_marker_list: Mapping[str, CellMarkers],
    *,
    sensitivity: bool = True,
    weight_floor: float | None = None,
    verbose: Verbose = True,
) -> ScTypeResults

ScType scores per cell.

Parameters:

Name Type Description Default
sc SingleCells

The experiment.

required
cell_marker_list Mapping[str, CellMarkers]

Cell type to markers, see prepare_cell_markers.

required
sensitivity bool

Downweight markers shared between cell types.

True
weight_floor float | None

In [0, 1], the floor of those weights; None is 0.1.

None
verbose Verbose

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

True

Returns:

Type Description
ScTypeResults

The scores over the kept cells.

Raises:

Type Description
ValueError

If there are no cell types, or a marker index is out of range.

References

Ianevski, et al., Nat Commun, 2022.

Examples:

>>> scores = bv.annotate.calc_sc_type_scores(sc, markers, sensitivity=False)

get_scores

get_scores(
    x: ScTypeResults | ScTypeCellResults,
) -> DataFrame | ndarray

The scores of ScType results.

Parameters:

Name Type Description Default
x ScTypeResults | ScTypeCellResults

ScType results.

required

Returns:

Type Description
DataFrame | ndarray

For ScTypeResults one column per cell type over the cells; for

DataFrame | ndarray

ScTypeCellResults the winning score per cell.

score_clusters

score_clusters(
    x: ScTypeResults,
    cluster_labels: ndarray | Sequence[int],
) -> DataFrame

One ScType call per cluster.

A cluster whose best summed score falls below a quarter of its size is "Unknown".

Parameters:

Name Type Description Default
x ScTypeResults

The scores.

required
cluster_labels ndarray | Sequence[int]

0-based cluster per scored cell.

required

Returns:

Type Description
DataFrame

cluster_id, cell_type, scores and n_cells per non-empty

DataFrame

cluster.

Raises:

Type Description
ValueError

If the labels do not cover the scored cells or are negative.

Examples:

>>> labels = sc.obs(filtered=True)["leiden_clustering"].to_numpy()
>>> per_cluster = bv.annotate.score_clusters(scores, labels)

assign_sc_type

assign_sc_type(
    sc: SingleCells,
    sc_type_res: ScTypeResults,
    *,
    cluster_col: str | None = None,
    sctype_cell_params: SctypeCellsParams | None = None,
    verbose: Verbose = True,
) -> ScTypeCellResults

Per-cell ScType calls.

The score matrix is smoothed over the neighbour graph by label spreading (Zhou et al.), then each cell takes its argmax; cells whose best score falls below score_floor are Unknown. With cluster_col the per-cluster composition and the hybrid call come on top: clusters at or above purity_threshold keep the cluster-level call, mixed ones the per-cell calls.

Parameters:

Name Type Description Default
sc SingleCells

The experiment, ideally with a neighbour graph over the scored cells.

required
sc_type_res ScTypeResults

The scores, see calc_sc_type_scores.

required
cluster_col str | None

Optional obs column with 0-based integer clusters.

None
sctype_cell_params SctypeCellsParams | None

The parameters. None uses the defaults.

None
verbose Verbose

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

True

Returns:

Type Description
ScTypeCellResults

The per-cell calls. Without a neighbour graph it warns and scores

ScTypeCellResults

without smoothing.

Raises:

Type Description
ValueError

If the graph or the clusters do not cover the scored cells.

References

Ianevski, et al., Nat Commun, 2022; Zhou, et al., NIPS, 2004.

Examples:

>>> col = "leiden_clustering"
>>> calls = bv.annotate.assign_sc_type(sc, scores, cluster_col=col)
>>> composition = calls.composition

Symphony reference

Cell type annotation with ScType, reference mapping with Symphony and Seurat.

ScType scores every cell against marker gene sets and calls a type per cell, optionally per cluster. Symphony builds a Harmony-corrected reference from an annotated experiment, maps a query into its embedding and transfers the labels by kNN vote. Start with prepare_cell_markers, calc_sc_type_scores and assign_sc_type for ScType, build_symphony_ref, map_symphony_query and transfer_labels_symphony for Symphony. transfer_labels_seurat transfers labels through Seurat's CCA anchors, RNA to RNA or RNA to the gene activity of an ATAC experiment.

What lands where. The ScType functions leave the experiment alone and return frozen records (ScTypeResults, ScTypeCellResults); put a call into obs yourself. map_symphony_query writes the query embeddings to query.cache.embeddings as "symphony" (corrected), "symphony_pca" (projected) and "symphony_r" (soft cluster assignments). transfer_labels_symphony writes predicted_<column> and confidence_<column> to the query's obs and returns them. build_symphony_ref and add_symphony_labels return a SymphonyReference and touch neither experiment. A reference is immutable: adding labels gives you a new one. All functions take a SingleCells.

ScType wants markers as a frame of cell_type and gene_id, in the id type of the experiment, and scores the kept cells. The neighbour graph smooths the scores, so run bv.graph.find_neighbours first; clusters from bv.graph.find_clusters add a per cluster call.

import polars as pl

genes = sc.gene_ids().tolist()
marker_df = pl.DataFrame(
    {
        "cell_type": ["type_1"] * 10 + ["type_2"] * 10 + ["type_3"] * 10,
        "gene_id": genes[:30],
    }
)
markers = bv.annotate.prepare_cell_markers(sc, marker_df)
scores = bv.annotate.calc_sc_type_scores(sc, markers)
calls = bv.annotate.assign_sc_type(sc, scores, cluster_col="leiden_clustering")
sc.add_obs(pl.DataFrame({"cell_idx": sc.cells_to_keep, "sc_type": calls.hybrid}))

Symphony needs the reference's HVGs, so run bv.pp.find_hvg on it first and hand sc.map.hvg over. Genes match by id; a reference HVG missing from the query becomes a zero column:

ref = bv.annotate.build_symphony_ref(
    sc, "sample_id", sc.map.hvg, label_columns=["cell_grp"]
)
bv.annotate.map_symphony_query(ref, query, batch_column="sample_id")
pred = bv.annotate.transfer_labels_symphony(ref, query, "cell_grp")

Gotchas. Every index is 0-based: marker genes, HVGs and cluster ids. cluster_col of assign_sc_type has to be a non-negative integer obs column with a value for every scored cell, which is what find_clusters writes. Without a neighbour graph assign_sc_type warns and scores without smoothing. calls.hybrid is None unless you gave a cluster_col; calls.assignments is the per cell call, null where the cell is Unknown. Labels are stored in a reference in cells_to_keep order, so add_symphony_labels needs the cell set the reference was built on. transfer_labels_symphony raises on a query that has no current "symphony" embedding: map again after the cell filter moves. save_symphony_ref and load_symphony_ref use one .npz file.

SymphonyReference dataclass

SymphonyReference(
    hvg_gene_names: list[str],
    gene_means: ndarray,
    gene_sds: ndarray,
    loadings: ndarray,
    z_corr: ndarray,
    centroids: ndarray,
    nr: ndarray,
    c_cache: ndarray,
    no_pcs: int,
    harmony_backend: str,
    batch_vars: list[str],
    slim: bool = False,
    z_orig: ndarray | None = None,
    r: ndarray | None = None,
    labels: DataFrame | None = None,
)

A Symphony reference.

Holds the PCA loadings, the per-HVG scaling statistics, the soft cluster centroids and the cached compression terms (nr, c_cache) that map a query without the reference cells, plus the Harmony-corrected embedding for label transfer. Everything numeric is float32, as computed.

Attributes:

Name Type Description
hvg_gene_names list[str]

HVG gene ids in loading row order.

gene_means ndarray

Per-HVG mean of the normalised reference data.

gene_sds ndarray

Per-HVG standard deviation of the normalised reference data.

loadings ndarray

PCA gene loadings, (n_hvgs, d).

z_corr ndarray

Harmony-corrected embedding, (N, d).

centroids ndarray

Cosine-normalised centroids, (K, d).

nr ndarray

Cluster sizes, the row sums of r, (K,).

c_cache ndarray

The compression term r @ z_corr, (K, d).

no_pcs int

Number of principal components.

harmony_backend str

"v1" or "v2".

batch_vars list[str]

The batch columns of the build.

slim bool

Whether z_orig and r were dropped.

z_orig ndarray | None

Pre-Harmony PCA scores, (N, d); None when slim.

r ndarray | None

Soft cluster assignments, (K, N); None when slim.

labels DataFrame | None

Reference cell labels in z_corr row order, or None.

References

Kang, et al., Nat Commun, 2021.

build_symphony_ref

build_symphony_ref(
    sc: SingleCells,
    batch_column: str,
    hvg: ndarray | Sequence[int],
    *,
    additional_batch_columns: Sequence[str] | None = None,
    harmony_params: HarmonyParams
    | HarmonyV2Params
    | None = None,
    pca_params: PcaParams | None = None,
    no_pcs: int = 30,
    slim: bool = False,
    label_columns: Sequence[str] | None = None,
    seed: int = 42,
    verbose: Verbose = True,
) -> SymphonyReference

Build a Symphony reference.

Runs sparse PCA over the HVGs and Harmony over the batches, and compresses the result into the terms a query is mapped with. The Harmony version follows the type of harmony_params. Optionally snapshots obs columns (cell type labels, say) for label transfer.

Parameters:

Name Type Description Default
sc SingleCells

The reference experiment.

required
batch_column str

obs column with the primary batch.

required
hvg ndarray | Sequence[int]

0-based HVG indices into the experiment's genes, e.g. sc.map.hvg.

required
additional_batch_columns Sequence[str] | None

Further obs columns to correct for.

None
harmony_params HarmonyParams | HarmonyV2Params | None

HarmonyV2Params (v2) or HarmonyParams (v1). None is v2 with the defaults; a None k becomes min(round(n_cells / 30), 100).

None
pca_params PcaParams | None

The PCA parameters. None uses the defaults.

None
no_pcs int

Number of principal components.

30
slim bool

Drop z_orig and r. z_corr is always kept.

False
label_columns Sequence[str] | None

obs columns to snapshot, in cells_to_keep order.

None
seed int

Seed.

42
verbose Verbose

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

True

Returns:

Type Description
SymphonyReference

The reference.

Raises:

Type Description
ValueError

If an HVG index is out of range, or a batch or label column is missing or incomplete.

Examples:

>>> bv.pp.find_hvg(sc, hvg_no=2000)
>>> ref = bv.annotate.build_symphony_ref(
...     sc, "sample_id", sc.map.hvg, no_pcs=20, label_columns=["cell_grp"]
... )
References

Kang, et al., Nat Commun, 2021.

add_symphony_labels

add_symphony_labels(
    reference: SymphonyReference,
    sc: SingleCells,
    columns: Sequence[str],
    *,
    overwrite: bool = False,
) -> SymphonyReference

Attach obs columns to a reference.

sc has to keep the cells the reference was built on, in the same order; only the count is checked.

Parameters:

Name Type Description Default
reference SymphonyReference

The reference.

required
sc SingleCells

Typically the experiment the reference was built from.

required
columns Sequence[str]

obs columns to store.

required
overwrite bool

Replace stored columns of the same name instead of raising.

False

Returns:

Type Description
SymphonyReference

A new reference with the labels; the input is left alone.

Raises:

Type Description
ValueError

If the cell count disagrees with z_corr, a column is missing, or a name collides without overwrite.

Examples:

>>> ref = bv.annotate.add_symphony_labels(ref, sc, ["cell_grp"], overwrite=True)

get_symphony_loadings

get_symphony_loadings(
    reference: SymphonyReference,
) -> ndarray

The PCA gene loadings, (n_hvgs, d).

Parameters:

Name Type Description Default
reference SymphonyReference

The Symphony reference.

required

Returns:

Type Description
ndarray

The loadings.

get_symphony_z_corr

get_symphony_z_corr(
    reference: SymphonyReference,
) -> ndarray

The corrected reference embedding, (N, d).

Parameters:

Name Type Description Default
reference SymphonyReference

The Symphony reference.

required

Returns:

Type Description
ndarray

The corrected embedding.

get_symphony_hvg_names

get_symphony_hvg_names(
    reference: SymphonyReference,
) -> list[str]

The HVG gene ids in loading order.

Parameters:

Name Type Description Default
reference SymphonyReference

The Symphony reference.

required

Returns:

Type Description
list[str]

The HVG gene ids.

get_symphony_labels

get_symphony_labels(
    reference: SymphonyReference,
) -> DataFrame | None

The stored labels in z_corr row order.

Parameters:

Name Type Description Default
reference SymphonyReference

The Symphony reference.

required

Returns:

Type Description
DataFrame | None

The labels, or None if the reference has none.

Mapping a query

Cell type annotation with ScType, reference mapping with Symphony and Seurat.

ScType scores every cell against marker gene sets and calls a type per cell, optionally per cluster. Symphony builds a Harmony-corrected reference from an annotated experiment, maps a query into its embedding and transfers the labels by kNN vote. Start with prepare_cell_markers, calc_sc_type_scores and assign_sc_type for ScType, build_symphony_ref, map_symphony_query and transfer_labels_symphony for Symphony. transfer_labels_seurat transfers labels through Seurat's CCA anchors, RNA to RNA or RNA to the gene activity of an ATAC experiment.

What lands where. The ScType functions leave the experiment alone and return frozen records (ScTypeResults, ScTypeCellResults); put a call into obs yourself. map_symphony_query writes the query embeddings to query.cache.embeddings as "symphony" (corrected), "symphony_pca" (projected) and "symphony_r" (soft cluster assignments). transfer_labels_symphony writes predicted_<column> and confidence_<column> to the query's obs and returns them. build_symphony_ref and add_symphony_labels return a SymphonyReference and touch neither experiment. A reference is immutable: adding labels gives you a new one. All functions take a SingleCells.

ScType wants markers as a frame of cell_type and gene_id, in the id type of the experiment, and scores the kept cells. The neighbour graph smooths the scores, so run bv.graph.find_neighbours first; clusters from bv.graph.find_clusters add a per cluster call.

import polars as pl

genes = sc.gene_ids().tolist()
marker_df = pl.DataFrame(
    {
        "cell_type": ["type_1"] * 10 + ["type_2"] * 10 + ["type_3"] * 10,
        "gene_id": genes[:30],
    }
)
markers = bv.annotate.prepare_cell_markers(sc, marker_df)
scores = bv.annotate.calc_sc_type_scores(sc, markers)
calls = bv.annotate.assign_sc_type(sc, scores, cluster_col="leiden_clustering")
sc.add_obs(pl.DataFrame({"cell_idx": sc.cells_to_keep, "sc_type": calls.hybrid}))

Symphony needs the reference's HVGs, so run bv.pp.find_hvg on it first and hand sc.map.hvg over. Genes match by id; a reference HVG missing from the query becomes a zero column:

ref = bv.annotate.build_symphony_ref(
    sc, "sample_id", sc.map.hvg, label_columns=["cell_grp"]
)
bv.annotate.map_symphony_query(ref, query, batch_column="sample_id")
pred = bv.annotate.transfer_labels_symphony(ref, query, "cell_grp")

Gotchas. Every index is 0-based: marker genes, HVGs and cluster ids. cluster_col of assign_sc_type has to be a non-negative integer obs column with a value for every scored cell, which is what find_clusters writes. Without a neighbour graph assign_sc_type warns and scores without smoothing. calls.hybrid is None unless you gave a cluster_col; calls.assignments is the per cell call, null where the cell is Unknown. Labels are stored in a reference in cells_to_keep order, so add_symphony_labels needs the cell set the reference was built on. transfer_labels_symphony raises on a query that has no current "symphony" embedding: map again after the cell filter moves. save_symphony_ref and load_symphony_ref use one .npz file.

map_symphony_query

map_symphony_query(
    reference: SymphonyReference,
    query: SingleCells,
    *,
    batch_column: str | None = None,
    additional_batch_columns: Sequence[str] | None = None,
    params: SymphonyMapParams | None = None,
    verbose: Verbose = True,
) -> None

Map a query onto a reference.

Projects the query through the reference loadings and applies the cached mixture-of-experts correction. Genes match by id against the reference HVGs; HVGs the query lacks are zero columns. Writes query.cache.embeddings["symphony"] (corrected), ["symphony_pca"] (projected) and ["symphony_r"] (soft assignments, (N_q, K)).

Parameters:

Name Type Description Default
reference SymphonyReference

The reference.

required
query SingleCells

The query experiment.

required
batch_column str | None

obs column with the query batch. None skips the correction, so "symphony" equals "symphony_pca".

None
additional_batch_columns Sequence[str] | None

Further obs columns to correct for.

None
params SymphonyMapParams | None

The mapping parameters. None uses the defaults.

None
verbose Verbose

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

True

Raises:

Type Description
ValueError

If a batch column is missing or incomplete.

References

Kang, et al., Nat Commun, 2021.

Examples:

>>> bv.annotate.map_symphony_query(ref, query, batch_column="sample_id")
>>> embedding = query.cache.embeddings["symphony"]

transfer_labels_symphony

transfer_labels_symphony(
    reference: SymphonyReference,
    query: SingleCells,
    label_column: str,
    *,
    knn_params: KnnParams | None = None,
    seed: int = 42,
    verbose: Verbose = True,
) -> DataFrame

kNN majority vote of reference labels onto a mapped query.

The reference z_corr is indexed, the query's "symphony" embedding searched. A missing reference label is its own class, so a query cell can come back null. Ties go to the label sorting last (the crate's max_by_key). The two columns are also written to the query's obs.

Parameters:

Name Type Description Default
reference SymphonyReference

The reference, with stored labels.

required
query SingleCells

The query, mapped with map_symphony_query.

required
label_column str

A stored label column.

required
knn_params KnnParams | None

The kNN parameters. None uses the defaults; distances on z_corr are typically Euclidean.

None
seed int

Seed for the index build.

42
verbose Verbose

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

True

Returns:

Type Description
DataFrame

predicted_<label_column> and confidence_<label_column> (the

DataFrame

winning vote share) per kept query cell, in cells_to_keep order.

Raises:

Type Description
ValueError

If the reference has no such labels, or the query has no current "symphony" embedding.

Examples:

>>> pred = bv.annotate.transfer_labels_symphony(ref, query, "cell_grp")

transfer_labels_seurat

transfer_labels_seurat(
    reference: SingleCells,
    query: SingleCells,
    label_column: str,
    weight_embedding: ndarray,
    *,
    weight_owner: SingleCells | None = None,
    features: Sequence[str] | None = None,
    n_cc: int = 30,
    k_anchor: int = 5,
    k_score: int = 30,
    scale_max: float = 10.0,
    l2_norm: bool = True,
    k_weight: int = 50,
    sd: float = 1.0,
    knn_params: KnnParams | None = None,
    seed: int = 42,
    verbose: Verbose = 0,
) -> DataFrame

Seurat label transfer: CCA anchors, then TransferData.

FindTransferAnchors(reduction = "cca") between the kept cells of both experiments on shared genes, then the anchor labels weighted per query cell in weight_embedding. For RNA to ATAC the query is the gene activity from bv.atac.gene_activity and the weights come from the ATAC LSI, as in the Signac vignette; RNA to RNA works the same with the query PCA.

Parameters:

Name Type Description Default
reference SingleCells

The annotated experiment (RNA).

required
query SingleCells

The experiment to label (RNA or gene activity), matched to the reference on gene_id.

required
label_column str

Reference obs column with the labels.

required
weight_embedding ndarray

Kept query cells x dimensions for the weights, e.g. mm.atac_cache.embeddings["lsi"]. Its rows are matched to the query by position.

required
weight_owner SingleCells | None

The experiment weight_embedding came from. Checked to keep the same cells as the query, so a filter set on one and not the other cannot shift the rows. bv.atac.get_gene_activity brings the gene activity in line with its experiment.

None
features Sequence[str] | None

Gene ids to anchor on. None uses the reference HVGs. Only those in both experiments are used.

None
n_cc int

Canonical correlation vectors.

30
k_anchor int

Neighbours for the anchors.

5
k_score int

Neighbours for the anchor scores.

30
scale_max float

Clip of the scaled features.

10.0
l2_norm bool

L2 normalise the CCA space per cell.

True
k_weight int

Anchors per query cell in the weights, capped at the number of anchor cells.

50
sd float

Bandwidth divisor of the weights.

1.0
knn_params KnnParams | None

kNN backend. None uses the defaults.

None
seed int

Seed of the kNN backend.

42
verbose Verbose

0 silent, 1 normal, 2 detailed.

0

Returns:

Type Description
DataFrame

Per kept query cell predicted_<label_column>,

DataFrame

confidence_<label_column> (the top prediction score) and one

DataFrame

score_<label> column per label. The first two are also written to

DataFrame

the query's obs.

Raises:

Type Description
ValueError

Without features, if weight_embedding does not cover the kept query cells, or weight_owner keeps other cells.

Saving and loading

Cell type annotation with ScType, reference mapping with Symphony and Seurat.

ScType scores every cell against marker gene sets and calls a type per cell, optionally per cluster. Symphony builds a Harmony-corrected reference from an annotated experiment, maps a query into its embedding and transfers the labels by kNN vote. Start with prepare_cell_markers, calc_sc_type_scores and assign_sc_type for ScType, build_symphony_ref, map_symphony_query and transfer_labels_symphony for Symphony. transfer_labels_seurat transfers labels through Seurat's CCA anchors, RNA to RNA or RNA to the gene activity of an ATAC experiment.

What lands where. The ScType functions leave the experiment alone and return frozen records (ScTypeResults, ScTypeCellResults); put a call into obs yourself. map_symphony_query writes the query embeddings to query.cache.embeddings as "symphony" (corrected), "symphony_pca" (projected) and "symphony_r" (soft cluster assignments). transfer_labels_symphony writes predicted_<column> and confidence_<column> to the query's obs and returns them. build_symphony_ref and add_symphony_labels return a SymphonyReference and touch neither experiment. A reference is immutable: adding labels gives you a new one. All functions take a SingleCells.

ScType wants markers as a frame of cell_type and gene_id, in the id type of the experiment, and scores the kept cells. The neighbour graph smooths the scores, so run bv.graph.find_neighbours first; clusters from bv.graph.find_clusters add a per cluster call.

import polars as pl

genes = sc.gene_ids().tolist()
marker_df = pl.DataFrame(
    {
        "cell_type": ["type_1"] * 10 + ["type_2"] * 10 + ["type_3"] * 10,
        "gene_id": genes[:30],
    }
)
markers = bv.annotate.prepare_cell_markers(sc, marker_df)
scores = bv.annotate.calc_sc_type_scores(sc, markers)
calls = bv.annotate.assign_sc_type(sc, scores, cluster_col="leiden_clustering")
sc.add_obs(pl.DataFrame({"cell_idx": sc.cells_to_keep, "sc_type": calls.hybrid}))

Symphony needs the reference's HVGs, so run bv.pp.find_hvg on it first and hand sc.map.hvg over. Genes match by id; a reference HVG missing from the query becomes a zero column:

ref = bv.annotate.build_symphony_ref(
    sc, "sample_id", sc.map.hvg, label_columns=["cell_grp"]
)
bv.annotate.map_symphony_query(ref, query, batch_column="sample_id")
pred = bv.annotate.transfer_labels_symphony(ref, query, "cell_grp")

Gotchas. Every index is 0-based: marker genes, HVGs and cluster ids. cluster_col of assign_sc_type has to be a non-negative integer obs column with a value for every scored cell, which is what find_clusters writes. Without a neighbour graph assign_sc_type warns and scores without smoothing. calls.hybrid is None unless you gave a cluster_col; calls.assignments is the per cell call, null where the cell is Unknown. Labels are stored in a reference in cells_to_keep order, so add_symphony_labels needs the cell set the reference was built on. transfer_labels_symphony raises on a query that has no current "symphony" embedding: map again after the cell filter moves. save_symphony_ref and load_symphony_ref use one .npz file.

save_symphony_ref

save_symphony_ref(
    reference: SymphonyReference, path: Path | str
) -> None

Write a reference to one .npz, readable without pickling.

The arrays go in as they are, the labels as Parquet bytes, everything else as JSON.

Parameters:

Name Type Description Default
reference SymphonyReference

The reference.

required
path Path | str

The target file.

required

Examples:

>>> bv.annotate.save_symphony_ref(ref, "reference.npz")

load_symphony_ref

load_symphony_ref(path: Path | str) -> SymphonyReference

Read a reference written by save_symphony_ref.

Parameters:

Name Type Description Default
path Path | str

The file.

required

Returns:

Type Description
SymphonyReference

The reference.

Raises:

Type Description
ValueError

If the file is not a saved reference of this format.

Examples:

>>> ref = bv.annotate.load_symphony_ref("reference.npz")