Skip to content

Ligand-receptor

Ligand-receptor analysis, two ways: CellPhoneDB on the expression in your experiment, and NicheNet-style ligand activity and interaction prioritisation.

CellPhoneDB. get_cellphonedb_db fetches the v5 database (once, it is cached) and cellphonedb scores every interaction for every ordered pair of clusters in an obs column. method picks permutation p-values, a DEG-gated test or the plain means. The database speaks gene symbols: if your var ids are Ensembl, point gene_id_col at the symbol column.

NicheNet. Build a ligand to target influence matrix from a signalling and a gene regulatory network with generate_ligand_target_influence, or wrap one you already have with as_ligand_target_influence. ligand_activity_scores ranks the ligands against a gene set (the receiver's DEGs, say) within a background, compute_expression_info gives per-cluster expression of the ligands and receptors, and prioritise_interactions combines it all with the DE tables into one ranked table of sender, ligand, receiver, receptor.

What lands where. Nothing here writes to the experiment. Every function returns a polars frame or a LigandTargetInfluence. Only cellphonedb and compute_expression_info read the counts, and they take a SingleCells (kept cells only); the NicheNet steps work on the networks and tables you hand them. The DE tables come from you: bv.de.find_all_markers renamed to cluster_id, gene, lfc, pval does the job.

import numpy as np
import polars as pl

genes = sc.gene_ids().tolist()
ligands, receptors, tfs, targets = genes[:5], genes[5:10], genes[10:15], genes[20:120]
ppi = pl.DataFrame({"from": ligands + receptors, "to": receptors + tfs, "weight": 1.0})
grn = pl.DataFrame(
    {"from": [t for t in tfs for _ in range(20)], "to": targets, "weight": 1.0}
)

influence = bv.lr.generate_ligand_target_influence(ligands, ppi, grn)
activity = bv.lr.ligand_activity_scores(
    influence, {"degs": targets[:20]}, background=genes[:300]
).filter(pl.col("gene_set") == "degs")

# Per cluster DE and expression: yours would come from bv.de and the experiment
cell_types = sorted(sc.obs()["cell_grp"].unique().to_list())
rng = np.random.default_rng(1)
n = len(cell_types) * len(genes)
celltype_de = pl.DataFrame(
    {
        "cluster_id": np.repeat(cell_types, len(genes)),
        "gene": genes * len(cell_types),
        "lfc": rng.normal(size=n),
        "pval": rng.uniform(1e-6, 1, size=n),
    }
)
expr = bv.lr.compute_expression_info(sc, "cell_grp", ligands + receptors)
prio = bv.lr.prioritise_interactions(
    celltype_de,
    expr,
    activity,
    pl.DataFrame({"ligand": ligands, "receptor": receptors}),
    senders_oi=cell_types[:1],
    receivers_oi=cell_types[1:],
    scenario="one_condition",
)

# CellPhoneDB on the experiment, with an L/R table of your own
lr_db = pl.DataFrame(
    {
        "interaction_id": [f"CPI{i}" for i in range(5)],
        "partner_a": ligands,
        "partner_b": receptors,
        "genes_a": [[g] for g in ligands],
        "genes_b": [[g] for g in receptors],
    }
)
cpdb = bv.lr.cellphonedb(
    sc, "cell_grp", lr_db, params=bv.params.CellphonedbParams(n_perm=100)
)

Gotchas. prioritise_interactions defaults to scenario="case_control", which weighs the condition terms and then refuses to run without a condition_de; pass scenario="one_condition" or your own weights when there is no contrast. It wants one row per ligand in ligand_activities: filter ligand_activity_scores down to a single gene set first. Ligand and receptor ids must be in the same namespace in the networks, the DE table and compute_expression_info, which reads var ids. cellphonedb drops interactions with a subunit missing from the experiment, with a warning, and errors if none are left. get_cellphonedb_db needs a download on first use.

Worked through in Ligand-receptor analysis with bixverse.

CellPhoneDB

Ligand-receptor analysis, two ways: CellPhoneDB on the expression in your experiment, and NicheNet-style ligand activity and interaction prioritisation.

CellPhoneDB. get_cellphonedb_db fetches the v5 database (once, it is cached) and cellphonedb scores every interaction for every ordered pair of clusters in an obs column. method picks permutation p-values, a DEG-gated test or the plain means. The database speaks gene symbols: if your var ids are Ensembl, point gene_id_col at the symbol column.

NicheNet. Build a ligand to target influence matrix from a signalling and a gene regulatory network with generate_ligand_target_influence, or wrap one you already have with as_ligand_target_influence. ligand_activity_scores ranks the ligands against a gene set (the receiver's DEGs, say) within a background, compute_expression_info gives per-cluster expression of the ligands and receptors, and prioritise_interactions combines it all with the DE tables into one ranked table of sender, ligand, receiver, receptor.

What lands where. Nothing here writes to the experiment. Every function returns a polars frame or a LigandTargetInfluence. Only cellphonedb and compute_expression_info read the counts, and they take a SingleCells (kept cells only); the NicheNet steps work on the networks and tables you hand them. The DE tables come from you: bv.de.find_all_markers renamed to cluster_id, gene, lfc, pval does the job.

import numpy as np
import polars as pl

genes = sc.gene_ids().tolist()
ligands, receptors, tfs, targets = genes[:5], genes[5:10], genes[10:15], genes[20:120]
ppi = pl.DataFrame({"from": ligands + receptors, "to": receptors + tfs, "weight": 1.0})
grn = pl.DataFrame(
    {"from": [t for t in tfs for _ in range(20)], "to": targets, "weight": 1.0}
)

influence = bv.lr.generate_ligand_target_influence(ligands, ppi, grn)
activity = bv.lr.ligand_activity_scores(
    influence, {"degs": targets[:20]}, background=genes[:300]
).filter(pl.col("gene_set") == "degs")

# Per cluster DE and expression: yours would come from bv.de and the experiment
cell_types = sorted(sc.obs()["cell_grp"].unique().to_list())
rng = np.random.default_rng(1)
n = len(cell_types) * len(genes)
celltype_de = pl.DataFrame(
    {
        "cluster_id": np.repeat(cell_types, len(genes)),
        "gene": genes * len(cell_types),
        "lfc": rng.normal(size=n),
        "pval": rng.uniform(1e-6, 1, size=n),
    }
)
expr = bv.lr.compute_expression_info(sc, "cell_grp", ligands + receptors)
prio = bv.lr.prioritise_interactions(
    celltype_de,
    expr,
    activity,
    pl.DataFrame({"ligand": ligands, "receptor": receptors}),
    senders_oi=cell_types[:1],
    receivers_oi=cell_types[1:],
    scenario="one_condition",
)

# CellPhoneDB on the experiment, with an L/R table of your own
lr_db = pl.DataFrame(
    {
        "interaction_id": [f"CPI{i}" for i in range(5)],
        "partner_a": ligands,
        "partner_b": receptors,
        "genes_a": [[g] for g in ligands],
        "genes_b": [[g] for g in receptors],
    }
)
cpdb = bv.lr.cellphonedb(
    sc, "cell_grp", lr_db, params=bv.params.CellphonedbParams(n_perm=100)
)

Gotchas. prioritise_interactions defaults to scenario="case_control", which weighs the condition terms and then refuses to run without a condition_de; pass scenario="one_condition" or your own weights when there is no contrast. It wants one row per ligand in ligand_activities: filter ligand_activity_scores down to a single gene set first. Ligand and receptor ids must be in the same namespace in the networks, the DE table and compute_expression_info, which reads var ids. cellphonedb drops interactions with a subunit missing from the experiment, with a warning, and errors if none are left. get_cellphonedb_db needs a download on first use.

get_cellphonedb_db

get_cellphonedb_db(
    cache_dir: Path | str | None = None,
    *,
    verbose: Verbose = True,
) -> DataFrame

The CellPhoneDB v5.0.0 ligand-receptor database.

Fetches cellphonedb.zip from the cellphonedb-data repository unless it is already in cache_dir, and flattens it to one row per interaction. Each partner resolves to the gene symbols of its subunits: one for a single protein, several for a complex.

Parameters:

Name Type Description Default
cache_dir Path | str | None

Where to keep cellphonedb.zip. None uses the bixverse cache.

None
verbose Verbose

Log the download.

True

Returns:

Type Description
DataFrame

interaction_id, partner_a / partner_b (the gene symbol of a

DataFrame

single protein, the complex name otherwise), genes_a / genes_b

DataFrame

(the subunit symbols, sorted), is_complex_a / is_complex_b,

DataFrame

directionality and classification, by interaction_id.

Examples:

>>> cpdb_db = bv.lr.get_cellphonedb_db()
References

Troulé, et al., Nat. Protoc., 2025.

cellphonedb

cellphonedb(
    sc: SingleCells,
    celltype_colname: str,
    lr_db: DataFrame,
    *,
    method: CpdbMethod = "statistical",
    deg_table: DataFrame | None = None,
    senders: Sequence[str] | None = None,
    receivers: Sequence[str] | None = None,
    gene_id_col: str = "gene_id",
    params: CellphonedbParams | None = None,
    verbose: Verbose = True,
) -> DataFrame

CellPhoneDB ligand-receptor analysis.

For every interaction and ordered (sender, receiver) cluster pair, partner a is measured in the sender and partner b in the receiver. The interaction mean is the average of the two partner means, zero if either is not expressed; a complex takes the minimum over its subunits. The gate needs both partners expressed in more than threshold of their cluster's cells.

  • "statistical": permutes the cluster labels, p = #(perm > real) / n_perm, 1 where the mean is zero or the gate fails.
  • "degs": no permutations; the gate also needs partner a to be a DEG of the sender or partner b of the receiver, as deg_table says.
  • "simple": the means and the expression gate only.

Reads the normalised layer of the L/R genes once. Interactions with a subunit missing from sc drop with a warning.

Parameters:

Name Type Description Default
sc SingleCells

The experiment.

required
celltype_colname str

The cluster column in obs. Cells with a missing label are ignored.

required
lr_db DataFrame

The database, see get_cellphonedb_db.

required
method CpdbMethod

See above.

'statistical'
deg_table DataFrame | None

cluster_id and gene, the DEGs per cluster. Needed for "degs", ignored with a warning otherwise.

None
senders Sequence[str] | None

Restrict the pairs to these sender clusters. None uses all.

None
receivers Sequence[str] | None

The same for the receivers.

None
gene_id_col str

The var column holding the symbols used in lr_db. A duplicated symbol resolves to its first gene.

'gene_id'
params CellphonedbParams | 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
DataFrame

One row per interaction and pair: interaction_id, partner_a,

DataFrame

partner_b, sender, receiver, mean, pval (null unless

DataFrame

"statistical") and gate.

Raises:

Type Description
ValueError

On a malformed database, no testable interaction, an unknown sender or receiver, or "degs" without deg_table.

Examples:

>>> cpdb = bv.lr.cellphonedb(sc, "cell_grp", lr_db, method="simple")
>>> cpdb = bv.lr.cellphonedb(
...     sc,
...     "cell_grp",
...     lr_db,
...     senders=["cell_type_1"],
...     params=bv.params.CellphonedbParams(n_perm=200, threshold=0.05),
... )
References

Efremova, et al., Nat. Protoc., 2020; Troulé, et al., Nat. Protoc., 2025.

Ligand-target influence

Ligand-receptor analysis, two ways: CellPhoneDB on the expression in your experiment, and NicheNet-style ligand activity and interaction prioritisation.

CellPhoneDB. get_cellphonedb_db fetches the v5 database (once, it is cached) and cellphonedb scores every interaction for every ordered pair of clusters in an obs column. method picks permutation p-values, a DEG-gated test or the plain means. The database speaks gene symbols: if your var ids are Ensembl, point gene_id_col at the symbol column.

NicheNet. Build a ligand to target influence matrix from a signalling and a gene regulatory network with generate_ligand_target_influence, or wrap one you already have with as_ligand_target_influence. ligand_activity_scores ranks the ligands against a gene set (the receiver's DEGs, say) within a background, compute_expression_info gives per-cluster expression of the ligands and receptors, and prioritise_interactions combines it all with the DE tables into one ranked table of sender, ligand, receiver, receptor.

What lands where. Nothing here writes to the experiment. Every function returns a polars frame or a LigandTargetInfluence. Only cellphonedb and compute_expression_info read the counts, and they take a SingleCells (kept cells only); the NicheNet steps work on the networks and tables you hand them. The DE tables come from you: bv.de.find_all_markers renamed to cluster_id, gene, lfc, pval does the job.

import numpy as np
import polars as pl

genes = sc.gene_ids().tolist()
ligands, receptors, tfs, targets = genes[:5], genes[5:10], genes[10:15], genes[20:120]
ppi = pl.DataFrame({"from": ligands + receptors, "to": receptors + tfs, "weight": 1.0})
grn = pl.DataFrame(
    {"from": [t for t in tfs for _ in range(20)], "to": targets, "weight": 1.0}
)

influence = bv.lr.generate_ligand_target_influence(ligands, ppi, grn)
activity = bv.lr.ligand_activity_scores(
    influence, {"degs": targets[:20]}, background=genes[:300]
).filter(pl.col("gene_set") == "degs")

# Per cluster DE and expression: yours would come from bv.de and the experiment
cell_types = sorted(sc.obs()["cell_grp"].unique().to_list())
rng = np.random.default_rng(1)
n = len(cell_types) * len(genes)
celltype_de = pl.DataFrame(
    {
        "cluster_id": np.repeat(cell_types, len(genes)),
        "gene": genes * len(cell_types),
        "lfc": rng.normal(size=n),
        "pval": rng.uniform(1e-6, 1, size=n),
    }
)
expr = bv.lr.compute_expression_info(sc, "cell_grp", ligands + receptors)
prio = bv.lr.prioritise_interactions(
    celltype_de,
    expr,
    activity,
    pl.DataFrame({"ligand": ligands, "receptor": receptors}),
    senders_oi=cell_types[:1],
    receivers_oi=cell_types[1:],
    scenario="one_condition",
)

# CellPhoneDB on the experiment, with an L/R table of your own
lr_db = pl.DataFrame(
    {
        "interaction_id": [f"CPI{i}" for i in range(5)],
        "partner_a": ligands,
        "partner_b": receptors,
        "genes_a": [[g] for g in ligands],
        "genes_b": [[g] for g in receptors],
    }
)
cpdb = bv.lr.cellphonedb(
    sc, "cell_grp", lr_db, params=bv.params.CellphonedbParams(n_perm=100)
)

Gotchas. prioritise_interactions defaults to scenario="case_control", which weighs the condition terms and then refuses to run without a condition_de; pass scenario="one_condition" or your own weights when there is no contrast. It wants one row per ligand in ligand_activities: filter ligand_activity_scores down to a single gene set first. Ligand and receptor ids must be in the same namespace in the networks, the DE table and compute_expression_info, which reads var ids. cellphonedb drops interactions with a subunit missing from the experiment, with a warning, and errors if none are left. get_cellphonedb_db needs a download on first use.

LigandTargetInfluence dataclass

LigandTargetInfluence(
    influence: ndarray,
    ligand_seeds: tuple[tuple[str, ...], ...],
    ligand_names: tuple[str, ...],
    gene_ids: tuple[str, ...],
    params: LigandTargetParams | None = None,
)

The ligands x genes influence matrix.

Attributes:

Name Type Description
influence ndarray

(n_ligands, n_genes) float64 regulatory potential.

ligand_seeds tuple[tuple[str, ...], ...]

The seed symbols of each row; a group is one complex.

ligand_names tuple[str, ...]

Row names.

gene_ids tuple[str, ...]

Column names, the gene universe of the run.

params LigandTargetParams | None

The parameters used, None for a wrapped matrix.

shape property

shape: tuple[int, int]

(n_ligands, n_genes).

generate_ligand_target_influence

generate_ligand_target_influence(
    ligand_seeds: Mapping[str, Sequence[str] | str]
    | Sequence[Sequence[str] | str],
    ppi_network: DataFrame,
    grn_network: DataFrame,
    params: LigandTargetParams | None = None,
) -> LigandTargetInfluence

The NicheNet-style ligand to target influence matrix.

The gene universe is the union of the nodes of both networks, in order of first appearance (ppi["from"], ppi["to"], grn["from"], grn["to"]).

Parameters:

Name Type Description Default
ligand_seeds Mapping[str, Sequence[str] | str] | Sequence[Sequence[str] | str]

One ligand symbol or a group treated as one complex per row. A mapping names the rows; otherwise they are the symbols joined with +.

required
ppi_network DataFrame

from, to, weight. The signalling layer.

required
grn_network DataFrame

from, to, weight. The gene regulatory layer.

required
params LigandTargetParams | None

The parameters. None uses the defaults.

None

Returns:

Type Description
LigandTargetInfluence

The influence, ligands x gene universe.

Raises:

Type Description
ValueError

On no seeds, a missing column or a seed in neither network.

Examples:

>>> influence = bv.lr.generate_ligand_target_influence(ligands, ppi, grn)
>>> influence = bv.lr.generate_ligand_target_influence(
...     {"complex_ab": ligands[:2], "single": [ligands[2]]},
...     ppi,
...     grn,
...     bv.params.LigandTargetParams(damping_factor=0.7),
... )

get_influence

get_influence(x: LigandTargetInfluence) -> ndarray

The ligands x genes influence; the names are x.ligand_names and x.gene_ids.

Parameters:

Name Type Description Default
x LigandTargetInfluence

The ligand target influence result.

required

as_ligand_target_influence

as_ligand_target_influence(
    x: ndarray,
    row_names: Sequence[str],
    col_names: Sequence[str],
    *,
    ligands_as_cols: bool = False,
    params: LigandTargetParams | None = None,
) -> LigandTargetInfluence

Wrap an existing ligand-target matrix.

For a regulatory potential matrix built elsewhere, for example with NicheNet's ligand-target matrix, so it can be scored with ligand_activity_scores.

Parameters:

Name Type Description Default
x ndarray

Numeric matrix.

required
row_names Sequence[str]

Unique row names.

required
col_names Sequence[str]

Unique column names.

required
ligands_as_cols bool

x is genes x ligands, the NicheNet layout.

False
params LigandTargetParams | None

Parameters used to build x, kept for the record.

None

Returns:

Type Description
LigandTargetInfluence

The influence, each ligand its own seed.

Raises:

Type Description
ValueError

On a non-numeric matrix or names that do not fit it.

Examples:

>>> potential = np.random.default_rng(1).random((len(genes), 3))
>>> wrapped = bv.lr.as_ligand_target_influence(
...     potential, genes, ["lig_1", "lig_2", "lig_3"], ligands_as_cols=True
... )

Ligand activity

Ligand-receptor analysis, two ways: CellPhoneDB on the expression in your experiment, and NicheNet-style ligand activity and interaction prioritisation.

CellPhoneDB. get_cellphonedb_db fetches the v5 database (once, it is cached) and cellphonedb scores every interaction for every ordered pair of clusters in an obs column. method picks permutation p-values, a DEG-gated test or the plain means. The database speaks gene symbols: if your var ids are Ensembl, point gene_id_col at the symbol column.

NicheNet. Build a ligand to target influence matrix from a signalling and a gene regulatory network with generate_ligand_target_influence, or wrap one you already have with as_ligand_target_influence. ligand_activity_scores ranks the ligands against a gene set (the receiver's DEGs, say) within a background, compute_expression_info gives per-cluster expression of the ligands and receptors, and prioritise_interactions combines it all with the DE tables into one ranked table of sender, ligand, receiver, receptor.

What lands where. Nothing here writes to the experiment. Every function returns a polars frame or a LigandTargetInfluence. Only cellphonedb and compute_expression_info read the counts, and they take a SingleCells (kept cells only); the NicheNet steps work on the networks and tables you hand them. The DE tables come from you: bv.de.find_all_markers renamed to cluster_id, gene, lfc, pval does the job.

import numpy as np
import polars as pl

genes = sc.gene_ids().tolist()
ligands, receptors, tfs, targets = genes[:5], genes[5:10], genes[10:15], genes[20:120]
ppi = pl.DataFrame({"from": ligands + receptors, "to": receptors + tfs, "weight": 1.0})
grn = pl.DataFrame(
    {"from": [t for t in tfs for _ in range(20)], "to": targets, "weight": 1.0}
)

influence = bv.lr.generate_ligand_target_influence(ligands, ppi, grn)
activity = bv.lr.ligand_activity_scores(
    influence, {"degs": targets[:20]}, background=genes[:300]
).filter(pl.col("gene_set") == "degs")

# Per cluster DE and expression: yours would come from bv.de and the experiment
cell_types = sorted(sc.obs()["cell_grp"].unique().to_list())
rng = np.random.default_rng(1)
n = len(cell_types) * len(genes)
celltype_de = pl.DataFrame(
    {
        "cluster_id": np.repeat(cell_types, len(genes)),
        "gene": genes * len(cell_types),
        "lfc": rng.normal(size=n),
        "pval": rng.uniform(1e-6, 1, size=n),
    }
)
expr = bv.lr.compute_expression_info(sc, "cell_grp", ligands + receptors)
prio = bv.lr.prioritise_interactions(
    celltype_de,
    expr,
    activity,
    pl.DataFrame({"ligand": ligands, "receptor": receptors}),
    senders_oi=cell_types[:1],
    receivers_oi=cell_types[1:],
    scenario="one_condition",
)

# CellPhoneDB on the experiment, with an L/R table of your own
lr_db = pl.DataFrame(
    {
        "interaction_id": [f"CPI{i}" for i in range(5)],
        "partner_a": ligands,
        "partner_b": receptors,
        "genes_a": [[g] for g in ligands],
        "genes_b": [[g] for g in receptors],
    }
)
cpdb = bv.lr.cellphonedb(
    sc, "cell_grp", lr_db, params=bv.params.CellphonedbParams(n_perm=100)
)

Gotchas. prioritise_interactions defaults to scenario="case_control", which weighs the condition terms and then refuses to run without a condition_de; pass scenario="one_condition" or your own weights when there is no contrast. It wants one row per ligand in ligand_activities: filter ligand_activity_scores down to a single gene set first. Ligand and receptor ids must be in the same namespace in the networks, the DE table and compute_expression_info, which reads var ids. cellphonedb drops interactions with a subunit missing from the experiment, with a warning, and errors if none are left. get_cellphonedb_db needs a download on first use.

ligand_activity_scores

ligand_activity_scores(
    ligand_influence: LigandTargetInfluence,
    gene_sets: Mapping[str, Sequence[str]]
    | Sequence[Sequence[str]]
    | Sequence[str],
    *,
    background: Sequence[str] | None = None,
) -> DataFrame

Ligand activities against gene sets.

The influence is restricted to the background columns first, so the metrics rank within the background (NicheNet practice: the genes expressed in the receiver, the gene set the DEGs).

Parameters:

Name Type Description Default
ligand_influence LigandTargetInfluence

The influence.

required
gene_sets Mapping[str, Sequence[str]] | Sequence[Sequence[str]] | Sequence[str]

One gene set, a list of them, or a mapping naming them. Unnamed sets are called "1", "2", ...

required
background Sequence[str] | None

Genes to score against. None uses every column. Genes not in the influence are dropped silently.

None

Returns:

Type Description
DataFrame

One row per gene set and ligand: gene_set, ligand, auroc,

DataFrame

aupr, aupr_corrected, pearson and spearman (NaN where

DataFrame

undefined).

Raises:

Type Description
ValueError

If there are no gene sets or the background misses the influence entirely.

Examples:

>>> activity = bv.lr.ligand_activity_scores(
...     influence, {"degs": targets[:20]}, background=genes[:300]
... )
>>> sets = [targets[:10], targets[5:20]]
>>> activity = bv.lr.ligand_activity_scores(influence, sets)

Prioritising interactions

Ligand-receptor analysis, two ways: CellPhoneDB on the expression in your experiment, and NicheNet-style ligand activity and interaction prioritisation.

CellPhoneDB. get_cellphonedb_db fetches the v5 database (once, it is cached) and cellphonedb scores every interaction for every ordered pair of clusters in an obs column. method picks permutation p-values, a DEG-gated test or the plain means. The database speaks gene symbols: if your var ids are Ensembl, point gene_id_col at the symbol column.

NicheNet. Build a ligand to target influence matrix from a signalling and a gene regulatory network with generate_ligand_target_influence, or wrap one you already have with as_ligand_target_influence. ligand_activity_scores ranks the ligands against a gene set (the receiver's DEGs, say) within a background, compute_expression_info gives per-cluster expression of the ligands and receptors, and prioritise_interactions combines it all with the DE tables into one ranked table of sender, ligand, receiver, receptor.

What lands where. Nothing here writes to the experiment. Every function returns a polars frame or a LigandTargetInfluence. Only cellphonedb and compute_expression_info read the counts, and they take a SingleCells (kept cells only); the NicheNet steps work on the networks and tables you hand them. The DE tables come from you: bv.de.find_all_markers renamed to cluster_id, gene, lfc, pval does the job.

import numpy as np
import polars as pl

genes = sc.gene_ids().tolist()
ligands, receptors, tfs, targets = genes[:5], genes[5:10], genes[10:15], genes[20:120]
ppi = pl.DataFrame({"from": ligands + receptors, "to": receptors + tfs, "weight": 1.0})
grn = pl.DataFrame(
    {"from": [t for t in tfs for _ in range(20)], "to": targets, "weight": 1.0}
)

influence = bv.lr.generate_ligand_target_influence(ligands, ppi, grn)
activity = bv.lr.ligand_activity_scores(
    influence, {"degs": targets[:20]}, background=genes[:300]
).filter(pl.col("gene_set") == "degs")

# Per cluster DE and expression: yours would come from bv.de and the experiment
cell_types = sorted(sc.obs()["cell_grp"].unique().to_list())
rng = np.random.default_rng(1)
n = len(cell_types) * len(genes)
celltype_de = pl.DataFrame(
    {
        "cluster_id": np.repeat(cell_types, len(genes)),
        "gene": genes * len(cell_types),
        "lfc": rng.normal(size=n),
        "pval": rng.uniform(1e-6, 1, size=n),
    }
)
expr = bv.lr.compute_expression_info(sc, "cell_grp", ligands + receptors)
prio = bv.lr.prioritise_interactions(
    celltype_de,
    expr,
    activity,
    pl.DataFrame({"ligand": ligands, "receptor": receptors}),
    senders_oi=cell_types[:1],
    receivers_oi=cell_types[1:],
    scenario="one_condition",
)

# CellPhoneDB on the experiment, with an L/R table of your own
lr_db = pl.DataFrame(
    {
        "interaction_id": [f"CPI{i}" for i in range(5)],
        "partner_a": ligands,
        "partner_b": receptors,
        "genes_a": [[g] for g in ligands],
        "genes_b": [[g] for g in receptors],
    }
)
cpdb = bv.lr.cellphonedb(
    sc, "cell_grp", lr_db, params=bv.params.CellphonedbParams(n_perm=100)
)

Gotchas. prioritise_interactions defaults to scenario="case_control", which weighs the condition terms and then refuses to run without a condition_de; pass scenario="one_condition" or your own weights when there is no contrast. It wants one row per ligand in ligand_activities: filter ligand_activity_scores down to a single gene set first. Ligand and receptor ids must be in the same namespace in the networks, the DE table and compute_expression_info, which reads var ids. cellphonedb drops interactions with a subunit missing from the experiment, with a warning, and errors if none are left. get_cellphonedb_db needs a download on first use.

compute_expression_info

compute_expression_info(
    sc: SingleCells,
    celltype_colname: str,
    genes: Sequence[str],
    *,
    condition_colname: str | None = None,
    condition_oi: str | None = None,
) -> DataFrame

Per-cluster mean expression and expressing fraction.

Streams the genes off the gene-major store and aggregates over the kept cells per cluster; cells with a missing label are ignored. With a condition only that condition's cells count.

Parameters:

Name Type Description Default
sc SingleCells

The experiment.

required
celltype_colname str

The cluster column in obs.

required
genes Sequence[str]

Gene ids. Unknown ids warn and drop.

required
condition_colname str | None

Optional condition column in obs.

None
condition_oi str | None

The condition level to keep.

None

Returns:

Type Description
DataFrame

cluster_id, gene, avg_expr and frac_expr, clusters sorted,

DataFrame

genes in the order given within each.

Raises:

Type Description
ValueError

On half a condition, no known gene or no cells left.

Examples:

>>> expr = bv.lr.compute_expression_info(sc, "cell_grp", ligands + receptors)
>>> expr_b1 = bv.lr.compute_expression_info(
...     sc,
...     "cell_grp",
...     ligands,
...     condition_colname="batch_index",
...     condition_oi="1",
... )

prioritise_interactions

prioritise_interactions(
    celltype_de: DataFrame,
    expression_info: DataFrame,
    ligand_activities: DataFrame,
    lr_network: DataFrame,
    senders_oi: Sequence[str],
    receivers_oi: Sequence[str],
    *,
    condition_de: DataFrame | None = None,
    weights: Mapping[str, float] | None = None,
    scenario: Scenario = "case_control",
) -> DataFrame

Prioritise sender-ligand-receiver-receptor interactions.

Each (sender, ligand, receiver, receptor) from the L/R network gets a weighted score over ligand DE in the sender, receptor DE in the receiver, the ligand activity, the ligand (receptor) expression specificity across senders (receivers) and the condition specificity of both. A component with weight zero is skipped, its join included; every other one is an inner join, so a tuple missing from it drops out. DE and expression terms count half, as in NicheNet.

Parameters:

Name Type Description Default
celltype_de DataFrame

cluster_id, gene, lfc, pval, one row per cluster and gene, covering senders and receivers.

required
expression_info DataFrame

cluster_id, gene, avg_expr, as compute_expression_info returns.

required
ligand_activities DataFrame

ligand and aupr_corrected, one row per ligand: one gene set of ligand_activity_scores.

required
lr_network DataFrame

ligand, receptor.

required
senders_oi Sequence[str]

Sender clusters.

required
receivers_oi Sequence[str]

Receiver clusters.

required
condition_de DataFrame | None

Optional gene, lfc, pval from a condition contrast. Needed for non-zero condition weights.

None
weights Mapping[str, float] | None

Weight per name in WEIGHT_NAMES. None picks by scenario.

None
scenario Scenario

"case_control" (all weights 1) or "one_condition" (condition weights 0). Ignored if weights is given.

'case_control'

Returns:

Type Description
DataFrame

One row per surviving tuple, sender, receiver, ligand,

DataFrame

receptor first, by descending prioritisation_score with a

DataFrame

prioritisation_rank (ties share the lowest). A score that is

DataFrame

undefined, from a NaN activity, is null and sorts last. Empty,

DataFrame

with a warning, if no tuple survives.

Raises:

Type Description
ValueError

On malformed tables or more than one row per ligand in ligand_activities.

Examples:

>>> prio = bv.lr.prioritise_interactions(
...     celltype_de,
...     expr,
...     activity,
...     lr_network,
...     senders_oi=["cell_type_1"],
...     receivers_oi=["cell_type_2", "cell_type_3"],
...     scenario="one_condition",
... )

resolve_weights

resolve_weights(
    weights: Mapping[str, float] | None,
    scenario: Scenario,
    has_condition_de: bool,
) -> dict[str, float]

The prioritisation weights.

Parameters:

Name Type Description Default
weights Mapping[str, float] | None

One non-negative weight per name in WEIGHT_NAMES; extra names are ignored. None picks by scenario.

required
scenario Scenario

"case_control" weighs everything 1, "one_condition" drops the condition specificity terms.

required
has_condition_de bool

Whether a condition DE table was supplied.

required

Returns:

Type Description
dict[str, float]

Name to weight, in WEIGHT_NAMES order.

Raises:

Type Description
ValueError

On a missing name, a negative or non-finite weight, or non-zero condition weights without a condition DE table.

Examples:

>>> weights = bv.lr.resolve_weights(None, "one_condition", False)