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
¶
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 |
None
|
verbose
|
Verbose
|
Log the download. |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
|
DataFrame
|
single protein, the complex name otherwise), |
DataFrame
|
(the subunit symbols, sorted), |
DataFrame
|
|
Examples:
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, asdeg_tablesays."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 |
required |
method
|
CpdbMethod
|
See above. |
'statistical'
|
deg_table
|
DataFrame | None
|
|
None
|
senders
|
Sequence[str] | None
|
Restrict the pairs to these sender clusters. |
None
|
receivers
|
Sequence[str] | None
|
The same for the receivers. |
None
|
gene_id_col
|
str
|
The var column holding the symbols used in |
'gene_id'
|
params
|
CellphonedbParams | None
|
The parameters. |
None
|
verbose
|
Verbose
|
|
True
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per interaction and pair: |
DataFrame
|
|
DataFrame
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
On a malformed database, no testable interaction, an
unknown sender or receiver, or |
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
|
|
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, |
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
|
|
required |
grn_network
|
DataFrame
|
|
required |
params
|
LigandTargetParams | None
|
The parameters. |
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:
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
|
|
False
|
params
|
LigandTargetParams | None
|
Parameters used to build |
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:
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 |
required |
background
|
Sequence[str] | None
|
Genes to score against. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per gene set and ligand: |
DataFrame
|
|
DataFrame
|
undefined). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If there are no gene sets or the background misses the influence entirely. |
Examples:
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
|
|
DataFrame
|
genes in the order given within each. |
Raises:
| Type | Description |
|---|---|
ValueError
|
On half a condition, no known gene or no cells left. |
Examples:
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
|
|
required |
expression_info
|
DataFrame
|
|
required |
ligand_activities
|
DataFrame
|
|
required |
lr_network
|
DataFrame
|
|
required |
senders_oi
|
Sequence[str]
|
Sender clusters. |
required |
receivers_oi
|
Sequence[str]
|
Receiver clusters. |
required |
condition_de
|
DataFrame | None
|
Optional |
None
|
weights
|
Mapping[str, float] | None
|
Weight per name in |
None
|
scenario
|
Scenario
|
|
'case_control'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per surviving tuple, |
DataFrame
|
|
DataFrame
|
|
DataFrame
|
undefined, from a |
DataFrame
|
with a warning, if no tuple survives. |
Raises:
| Type | Description |
|---|---|
ValueError
|
On malformed tables or more than one row per ligand in
|
Examples:
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 |
required |
scenario
|
Scenario
|
|
required |
has_condition_de
|
bool
|
Whether a condition DE table was supplied. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
Name to weight, in |
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: