Differential expression and abundance¶
Marker genes, donor-aware differential expression and differential abundance.
Three jobs. Markers: Wilcoxon or Seurat's logistic regression test (method=,
the default on ATAC peaks) between two groups (find_markers), one-vs-rest
for every group of a column (find_all_markers), or markers that hold up
against every rival group separately (find_specific_markers). Expression with
donor structure: pseudobulk edgeR (get_pseudobulked, pseudobulk_dge,
run_edger_ql) or the mixed model nebula. Abundance: Milo neighbourhoods
(get_milor_abundances, test_nhoods, add_nhoods_info) and meld densities.
Start with find_all_markers to look at clusters, pseudobulk_dge or nebula
to compare conditions across donors.
What lands where. Nothing here writes to obs, var or the cache. The marker
tests and pseudobulk_dge return polars frames; find_specific_markers,
nebula, get_milor_abundances and meld return frozen records
(ScSpecificMarkers, ScNebula, MiloR, MeldRes) with getters for their
tables. test_nhoods and add_nhoods_info hand back a new MiloR carrying
nhoods_info.
Object types. The marker functions, get_pseudobulked, pseudobulk_dge and
nebula take a SingleCells or a SingleCellsSubset, so a per cell type
comparison is a subset away. get_milor_abundances and meld take a
SingleCells only.
Condition across donors, one pseudobulk sample per donor. cell_list maps the
sample names to their cells and the rows of the design follow its order:
import polars as pl
obs = sc.obs(filtered=True)
cell_list = {
s: obs.filter(obs["sample_id"] == s)["cell_id"].to_list()
for s in obs["sample_id"].unique().sort()
}
design = pl.DataFrame(
{"(Intercept)": [1.0] * 6, "stim": [0.0, 0.0, 0.0, 1.0, 1.0, 1.0]}
)
pb_res = bv.de.pseudobulk_dge(sc, cell_list, design, coef="stim")
Milo needs a PCA and the kNN over it, and the sample column of obs. The design frame has one row per sample:
bv.pp.find_hvg(sc, hvg_no=500)
bv.pp.calculate_pca(sc, no_pcs=20)
bv.graph.find_neighbours(sc)
design_df = sc.obs().select("sample_id", "condition").unique().sort("sample_id")
milo = bv.de.get_milor_abundances(sc, "sample_id")
milo = bv.de.test_nhoods(milo, "~ condition", design_df)
da = bv.de.get_differential_abundance_res(milo)
Gotchas. Designs are additive formulas over a frame, "~ condition + age":
numeric columns as they are, everything else treatment coded against its first
(sorted) level and named <column><level>. Interactions and transformations
are not parsed. coef takes a 0-based design column or its name, and the last
column is tested if you give neither. Every index is 0-based, Milo's Nhood
included. get_milor_abundances and meld raise on a stale embedding or kNN,
so rerun those after the cell filter moves, and they warn and return None
without a kNN. nebula costs milliseconds to seconds per gene: hand
genes_to_use the HVGs or a candidate set. run_edger_ql wants raw counts and
a design with an intercept and at least one more column.
Worked through in Differential expression with donor structure and Differential abundance with Milo and MELD.
Markers¶
Marker genes, donor-aware differential expression and differential abundance.
Three jobs. Markers: Wilcoxon or Seurat's logistic regression test (method=,
the default on ATAC peaks) between two groups (find_markers), one-vs-rest
for every group of a column (find_all_markers), or markers that hold up
against every rival group separately (find_specific_markers). Expression with
donor structure: pseudobulk edgeR (get_pseudobulked, pseudobulk_dge,
run_edger_ql) or the mixed model nebula. Abundance: Milo neighbourhoods
(get_milor_abundances, test_nhoods, add_nhoods_info) and meld densities.
Start with find_all_markers to look at clusters, pseudobulk_dge or nebula
to compare conditions across donors.
What lands where. Nothing here writes to obs, var or the cache. The marker
tests and pseudobulk_dge return polars frames; find_specific_markers,
nebula, get_milor_abundances and meld return frozen records
(ScSpecificMarkers, ScNebula, MiloR, MeldRes) with getters for their
tables. test_nhoods and add_nhoods_info hand back a new MiloR carrying
nhoods_info.
Object types. The marker functions, get_pseudobulked, pseudobulk_dge and
nebula take a SingleCells or a SingleCellsSubset, so a per cell type
comparison is a subset away. get_milor_abundances and meld take a
SingleCells only.
Condition across donors, one pseudobulk sample per donor. cell_list maps the
sample names to their cells and the rows of the design follow its order:
import polars as pl
obs = sc.obs(filtered=True)
cell_list = {
s: obs.filter(obs["sample_id"] == s)["cell_id"].to_list()
for s in obs["sample_id"].unique().sort()
}
design = pl.DataFrame(
{"(Intercept)": [1.0] * 6, "stim": [0.0, 0.0, 0.0, 1.0, 1.0, 1.0]}
)
pb_res = bv.de.pseudobulk_dge(sc, cell_list, design, coef="stim")
Milo needs a PCA and the kNN over it, and the sample column of obs. The design frame has one row per sample:
bv.pp.find_hvg(sc, hvg_no=500)
bv.pp.calculate_pca(sc, no_pcs=20)
bv.graph.find_neighbours(sc)
design_df = sc.obs().select("sample_id", "condition").unique().sort("sample_id")
milo = bv.de.get_milor_abundances(sc, "sample_id")
milo = bv.de.test_nhoods(milo, "~ condition", design_df)
da = bv.de.get_differential_abundance_res(milo)
Gotchas. Designs are additive formulas over a frame, "~ condition + age":
numeric columns as they are, everything else treatment coded against its first
(sorted) level and named <column><level>. Interactions and transformations
are not parsed. coef takes a 0-based design column or its name, and the last
column is tested if you give neither. Every index is 0-based, Milo's Nhood
included. get_milor_abundances and meld raise on a stale embedding or kNN,
so rerun those after the cell filter moves, and they warn and return None
without a kNN. nebula costs milliseconds to seconds per gene: hand
genes_to_use the HVGs or a candidate set. run_edger_ql wants raw counts and
a design with an intercept and at least one more column.
ScSpecificMarkers
dataclass
¶
One-vs-many specific markers.
Attributes:
| Name | Type | Description |
|---|---|---|
summary |
DataFrame
|
Per reference group and gene, the summaries across every
rival: |
per_comparison |
DataFrame
|
Per reference, rival and gene, |
params |
dict[str, object]
|
The parameters of the run. |
find_all_markers
¶
find_all_markers(
sc: ScOrScSubset,
column_of_interest: str,
*,
method: Method | None = None,
alternative: Alternative = "greater",
min_prop: float = 0.05,
modality: DeModality = "rna",
verbose: Verbose = True,
) -> DataFrame
One-vs-rest Wilcoxon or logistic regression DGE for every group.
All groups are tested in one pass over the genes. Cells without a label are left out of every group and of every rest.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sc
|
ScOrScSubset
|
The experiment. |
required |
column_of_interest
|
str
|
The obs column holding the groups. |
required |
method
|
Method | None
|
|
None
|
alternative
|
Alternative
|
The test alternative; |
'greater'
|
min_prop
|
float
|
A gene is tested for a group if this share of the group or of the rest expresses it. |
0.05
|
modality
|
DeModality
|
|
'rna'
|
verbose
|
Verbose
|
|
True
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
|
DataFrame
|
|
Examples:
find_markers
¶
find_markers(
sc: ScOrScSubset,
cells_1: Selection,
cells_2: Selection,
*,
method: Method | None = None,
alternative: Alternative = "twosided",
min_prop: float = 0.05,
modality: DeModality = "rna",
verbose: Verbose = True,
) -> DataFrame
Wilcoxon or logistic regression DGE between two groups of cells.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sc
|
ScOrScSubset
|
The experiment. |
required |
cells_1
|
Selection
|
0-based cell indices or ids of group 1. |
required |
cells_2
|
Selection
|
0-based cell indices or ids of group 2. |
required |
method
|
Method | None
|
|
None
|
alternative
|
Alternative
|
The test alternative. |
'twosided'
|
min_prop
|
float
|
A gene is tested if this share of either group expresses it. |
0.05
|
modality
|
DeModality
|
|
'rna'
|
verbose
|
Verbose
|
|
True
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
|
DataFrame
|
one row per tested gene in gene order. |
Examples:
find_specific_markers
¶
find_specific_markers(
sc: ScOrScSubset,
column_of_interest: str,
*,
reference_group: str | None = None,
method: Method | None = None,
alternative: Alternative = "greater",
min_prop: float = 0.05,
modality: DeModality = "rna",
verbose: Verbose = True,
) -> ScSpecificMarkers | None
Markers that hold up against every rival group separately.
Each reference is tested against each other group of the column on its
own, then summarised per gene across the rivals: a gene marks the
reference only if min_auroc stays high against all of them. Every arm
comes out of one pass over the genes, and the genes are filtered once,
globally, so every comparison's FDR covers the same gene set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sc
|
ScOrScSubset
|
The experiment. |
required |
column_of_interest
|
str
|
The obs column holding the groups. |
required |
reference_group
|
str | None
|
The one reference to report. |
None
|
method
|
Method | None
|
|
None
|
alternative
|
Alternative
|
The test alternative; |
'greater'
|
min_prop
|
float
|
A gene is tested if this share of any group expresses it. |
0.05
|
modality
|
DeModality
|
|
'rna'
|
verbose
|
Verbose
|
|
True
|
Returns:
| Type | Description |
|---|---|
ScSpecificMarkers | None
|
The |
ScSpecificMarkers | None
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the column is missing, has fewer than two groups, or
|
References
Soneson and Robinson, Nat Methods, 2018; Lun, et al., F1000Research, 2016.
Examples:
get_marker_summary
¶
get_marker_summary(x: ScSpecificMarkers) -> DataFrame
The per-gene summaries across every rival.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ScSpecificMarkers
|
The marker result. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
A copy of the summary table. |
get_marker_comparisons
¶
get_marker_comparisons(x: ScSpecificMarkers) -> DataFrame
The per-rival statistics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ScSpecificMarkers
|
The marker result. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
A copy of the per-comparison table. |
Pseudobulk edgeR¶
Marker genes, donor-aware differential expression and differential abundance.
Three jobs. Markers: Wilcoxon or Seurat's logistic regression test (method=,
the default on ATAC peaks) between two groups (find_markers), one-vs-rest
for every group of a column (find_all_markers), or markers that hold up
against every rival group separately (find_specific_markers). Expression with
donor structure: pseudobulk edgeR (get_pseudobulked, pseudobulk_dge,
run_edger_ql) or the mixed model nebula. Abundance: Milo neighbourhoods
(get_milor_abundances, test_nhoods, add_nhoods_info) and meld densities.
Start with find_all_markers to look at clusters, pseudobulk_dge or nebula
to compare conditions across donors.
What lands where. Nothing here writes to obs, var or the cache. The marker
tests and pseudobulk_dge return polars frames; find_specific_markers,
nebula, get_milor_abundances and meld return frozen records
(ScSpecificMarkers, ScNebula, MiloR, MeldRes) with getters for their
tables. test_nhoods and add_nhoods_info hand back a new MiloR carrying
nhoods_info.
Object types. The marker functions, get_pseudobulked, pseudobulk_dge and
nebula take a SingleCells or a SingleCellsSubset, so a per cell type
comparison is a subset away. get_milor_abundances and meld take a
SingleCells only.
Condition across donors, one pseudobulk sample per donor. cell_list maps the
sample names to their cells and the rows of the design follow its order:
import polars as pl
obs = sc.obs(filtered=True)
cell_list = {
s: obs.filter(obs["sample_id"] == s)["cell_id"].to_list()
for s in obs["sample_id"].unique().sort()
}
design = pl.DataFrame(
{"(Intercept)": [1.0] * 6, "stim": [0.0, 0.0, 0.0, 1.0, 1.0, 1.0]}
)
pb_res = bv.de.pseudobulk_dge(sc, cell_list, design, coef="stim")
Milo needs a PCA and the kNN over it, and the sample column of obs. The design frame has one row per sample:
bv.pp.find_hvg(sc, hvg_no=500)
bv.pp.calculate_pca(sc, no_pcs=20)
bv.graph.find_neighbours(sc)
design_df = sc.obs().select("sample_id", "condition").unique().sort("sample_id")
milo = bv.de.get_milor_abundances(sc, "sample_id")
milo = bv.de.test_nhoods(milo, "~ condition", design_df)
da = bv.de.get_differential_abundance_res(milo)
Gotchas. Designs are additive formulas over a frame, "~ condition + age":
numeric columns as they are, everything else treatment coded against its first
(sorted) level and named <column><level>. Interactions and transformations
are not parsed. coef takes a 0-based design column or its name, and the last
column is tested if you give neither. Every index is 0-based, Milo's Nhood
included. get_milor_abundances and meld raise on a stale embedding or kNN,
so rerun those after the cell filter moves, and they warn and return None
without a kNN. nebula costs milliseconds to seconds per gene: hand
genes_to_use the HVGs or a candidate set. run_edger_ql wants raw counts and
a design with an intercept and at least one more column.
PseudoBulked
dataclass
¶
PseudoBulked(
counts: ndarray | CsrMatrix,
samples: tuple[str, ...],
gene_ids: ndarray,
)
Pseudobulked counts.
Attributes:
| Name | Type | Description |
|---|---|---|
counts |
ndarray | CsrMatrix
|
|
samples |
tuple[str, ...]
|
The pseudobulk sample names, the rows. |
gene_ids |
ndarray
|
The gene ids, the columns. |
pseudobulk_dge
¶
pseudobulk_dge(
sc: ScOrScSubset,
cell_list: Mapping[str, Selection],
design: ndarray | DataFrame,
*,
coef: Coef | None = None,
contrast: ndarray | Sequence[float] | None = None,
edger_params: EdgerQlParams | None = None,
modality: DeModality = "rna",
verbose: Verbose = True,
) -> DataFrame
edgeR quasi-likelihood DGE on pseudobulked cells.
Sums the raw counts per sample and runs run_edger_ql on the result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sc
|
ScOrScSubset
|
The experiment. |
required |
cell_list
|
Mapping[str, Selection]
|
Pseudobulk sample name to its 0-based cell indices or ids.
The rows of |
required |
design
|
ndarray | DataFrame
|
|
required |
coef
|
Coef | None
|
See |
None
|
contrast
|
ndarray | Sequence[float] | None
|
See |
None
|
edger_params
|
EdgerQlParams | None
|
See |
None
|
modality
|
DeModality
|
|
'rna'
|
verbose
|
Verbose
|
|
True
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
See |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the design rows do not match the samples. |
References
Squair, et al., Nat Commun, 2021; Chen, Lun and Smyth, F1000Research, 2016.
Examples:
get_pseudobulked
¶
get_pseudobulked(
sc: ScOrScSubset,
cell_list: Mapping[str, Selection],
*,
return_format: Literal["dense", "sparse"] = "dense",
assay: Literal["raw", "norm"] = "raw",
modality: DeModality = "rna",
verbose: Verbose = True,
) -> PseudoBulked
Pseudobulk groups of cells.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sc
|
ScOrScSubset
|
The experiment. |
required |
cell_list
|
Mapping[str, Selection]
|
Pseudobulk sample name to its 0-based cell indices or ids. |
required |
return_format
|
Literal['dense', 'sparse']
|
A dense array or a CSR matrix. |
'dense'
|
assay
|
Literal['raw', 'norm']
|
|
'raw'
|
modality
|
DeModality
|
|
'rna'
|
verbose
|
Verbose
|
|
True
|
Returns:
| Type | Description |
|---|---|
PseudoBulked
|
The |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a group matches no cell. |
Examples:
run_edger_ql
¶
run_edger_ql(
counts: ndarray,
design: ndarray | DataFrame,
feature_ids: Sequence[str] | ndarray,
*,
coef: Coef | None = None,
contrast: ndarray | Sequence[float] | None = None,
edger_params: EdgerQlParams | None = None,
) -> DataFrame
edgeR's quasi-likelihood chain.
filterByExpr, calcNormFactors, glmQLFit and glmQLFTest, via
edge-rs. The rows do not have to be genes: Milo tests neighbourhoods
through here with filter=False.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
counts
|
ndarray
|
|
required |
design
|
ndarray | DataFrame
|
|
required |
feature_ids
|
Sequence[str] | ndarray
|
One id per row of |
required |
coef
|
Coef | None
|
0-based design column(s) or names to drop from the null model.
|
None
|
contrast
|
ndarray | Sequence[float] | None
|
Weights over the design columns, a vector or an
|
None
|
edger_params
|
EdgerQlParams | None
|
The parameters. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
|
DataFrame
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
On a design with fewer than two columns or a row count
that does not match, negative counts, or both |
References
Chen, Lun and Smyth, F1000Research, 2016.
Examples:
NEBULA¶
Marker genes, donor-aware differential expression and differential abundance.
Three jobs. Markers: Wilcoxon or Seurat's logistic regression test (method=,
the default on ATAC peaks) between two groups (find_markers), one-vs-rest
for every group of a column (find_all_markers), or markers that hold up
against every rival group separately (find_specific_markers). Expression with
donor structure: pseudobulk edgeR (get_pseudobulked, pseudobulk_dge,
run_edger_ql) or the mixed model nebula. Abundance: Milo neighbourhoods
(get_milor_abundances, test_nhoods, add_nhoods_info) and meld densities.
Start with find_all_markers to look at clusters, pseudobulk_dge or nebula
to compare conditions across donors.
What lands where. Nothing here writes to obs, var or the cache. The marker
tests and pseudobulk_dge return polars frames; find_specific_markers,
nebula, get_milor_abundances and meld return frozen records
(ScSpecificMarkers, ScNebula, MiloR, MeldRes) with getters for their
tables. test_nhoods and add_nhoods_info hand back a new MiloR carrying
nhoods_info.
Object types. The marker functions, get_pseudobulked, pseudobulk_dge and
nebula take a SingleCells or a SingleCellsSubset, so a per cell type
comparison is a subset away. get_milor_abundances and meld take a
SingleCells only.
Condition across donors, one pseudobulk sample per donor. cell_list maps the
sample names to their cells and the rows of the design follow its order:
import polars as pl
obs = sc.obs(filtered=True)
cell_list = {
s: obs.filter(obs["sample_id"] == s)["cell_id"].to_list()
for s in obs["sample_id"].unique().sort()
}
design = pl.DataFrame(
{"(Intercept)": [1.0] * 6, "stim": [0.0, 0.0, 0.0, 1.0, 1.0, 1.0]}
)
pb_res = bv.de.pseudobulk_dge(sc, cell_list, design, coef="stim")
Milo needs a PCA and the kNN over it, and the sample column of obs. The design frame has one row per sample:
bv.pp.find_hvg(sc, hvg_no=500)
bv.pp.calculate_pca(sc, no_pcs=20)
bv.graph.find_neighbours(sc)
design_df = sc.obs().select("sample_id", "condition").unique().sort("sample_id")
milo = bv.de.get_milor_abundances(sc, "sample_id")
milo = bv.de.test_nhoods(milo, "~ condition", design_df)
da = bv.de.get_differential_abundance_res(milo)
Gotchas. Designs are additive formulas over a frame, "~ condition + age":
numeric columns as they are, everything else treatment coded against its first
(sorted) level and named <column><level>. Interactions and transformations
are not parsed. coef takes a 0-based design column or its name, and the last
column is tested if you give neither. Every index is 0-based, Milo's Nhood
included. get_milor_abundances and meld raise on a stale embedding or kNN,
so rerun those after the cell filter moves, and they warn and return None
without a kNN. nebula costs milliseconds to seconds per gene: hand
genes_to_use the HVGs or a candidate set. run_edger_ql wants raw counts and
a design with an intercept and at least one more column.
ScNebula
dataclass
¶
NEBULA fits.
Attributes:
| Name | Type | Description |
|---|---|---|
results |
DataFrame
|
One row per gene that survived NEBULA's expression filter:
|
coefficients |
DataFrame
|
|
se |
DataFrame
|
The matching standard errors. |
params |
dict[str, object]
|
The parameters of the run. |
nebula
¶
nebula(
sc: ScOrScSubset,
subject_col: str,
design: str,
*,
coef: int | str | None = None,
contrast: ndarray | Sequence[float] | None = None,
genes_to_use: Selection | None = None,
cells_to_use: Sequence[str] | None = None,
offset: ndarray | Sequence[float] | None = None,
nebula_params: NebulaParams | None = None,
verbose: Verbose = True,
) -> ScNebula
NEBULA's negative binomial gamma mixed model.
The variance splits into a subject-level random effect and a cell-level
overdispersion, so the donor structure is modelled rather than ignored.
Genes stream through in batches, which is exact. A fit takes milliseconds
to seconds per gene, so restrict genes_to_use to the HVGs or a
candidate set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sc
|
ScOrScSubset
|
The experiment. |
required |
subject_col
|
str
|
obs column with the subject (donor), the random effect. |
required |
design
|
str
|
Formula over obs, e.g. |
required |
coef
|
int | str | None
|
The coefficient the Wald test reports, a 0-based design column
or its name. |
None
|
contrast
|
ndarray | Sequence[float] | None
|
One weight per design column. Exclusive with |
None
|
genes_to_use
|
Selection | None
|
0-based gene indices or ids. |
None
|
cells_to_use
|
Sequence[str] | None
|
Cell ids to fit. |
None
|
offset
|
ndarray | Sequence[float] | None
|
Strictly positive scaling per cell, aligned to the cells that
survive the design. |
None
|
nebula_params
|
NebulaParams | None
|
The parameters. |
None
|
verbose
|
Verbose
|
|
True
|
Returns:
| Type | Description |
|---|---|
ScNebula
|
The |
Raises:
| Type | Description |
|---|---|
ValueError
|
On missing columns, no cells left, both |
References
He, et al., Commun Biol, 2021.
Examples:
Milo¶
Marker genes, donor-aware differential expression and differential abundance.
Three jobs. Markers: Wilcoxon or Seurat's logistic regression test (method=,
the default on ATAC peaks) between two groups (find_markers), one-vs-rest
for every group of a column (find_all_markers), or markers that hold up
against every rival group separately (find_specific_markers). Expression with
donor structure: pseudobulk edgeR (get_pseudobulked, pseudobulk_dge,
run_edger_ql) or the mixed model nebula. Abundance: Milo neighbourhoods
(get_milor_abundances, test_nhoods, add_nhoods_info) and meld densities.
Start with find_all_markers to look at clusters, pseudobulk_dge or nebula
to compare conditions across donors.
What lands where. Nothing here writes to obs, var or the cache. The marker
tests and pseudobulk_dge return polars frames; find_specific_markers,
nebula, get_milor_abundances and meld return frozen records
(ScSpecificMarkers, ScNebula, MiloR, MeldRes) with getters for their
tables. test_nhoods and add_nhoods_info hand back a new MiloR carrying
nhoods_info.
Object types. The marker functions, get_pseudobulked, pseudobulk_dge and
nebula take a SingleCells or a SingleCellsSubset, so a per cell type
comparison is a subset away. get_milor_abundances and meld take a
SingleCells only.
Condition across donors, one pseudobulk sample per donor. cell_list maps the
sample names to their cells and the rows of the design follow its order:
import polars as pl
obs = sc.obs(filtered=True)
cell_list = {
s: obs.filter(obs["sample_id"] == s)["cell_id"].to_list()
for s in obs["sample_id"].unique().sort()
}
design = pl.DataFrame(
{"(Intercept)": [1.0] * 6, "stim": [0.0, 0.0, 0.0, 1.0, 1.0, 1.0]}
)
pb_res = bv.de.pseudobulk_dge(sc, cell_list, design, coef="stim")
Milo needs a PCA and the kNN over it, and the sample column of obs. The design frame has one row per sample:
bv.pp.find_hvg(sc, hvg_no=500)
bv.pp.calculate_pca(sc, no_pcs=20)
bv.graph.find_neighbours(sc)
design_df = sc.obs().select("sample_id", "condition").unique().sort("sample_id")
milo = bv.de.get_milor_abundances(sc, "sample_id")
milo = bv.de.test_nhoods(milo, "~ condition", design_df)
da = bv.de.get_differential_abundance_res(milo)
Gotchas. Designs are additive formulas over a frame, "~ condition + age":
numeric columns as they are, everything else treatment coded against its first
(sorted) level and named <column><level>. Interactions and transformations
are not parsed. coef takes a 0-based design column or its name, and the last
column is tested if you give neither. Every index is 0-based, Milo's Nhood
included. get_milor_abundances and meld raise on a stale embedding or kNN,
so rerun those after the cell filter moves, and they warn and return None
without a kNN. nebula costs milliseconds to seconds per gene: hand
genes_to_use the HVGs or a candidate set. run_edger_ql wants raw counts and
a design with an intercept and at least one more column.
MiloRParams
dataclass
¶
MiloRParams(
*,
prop: float = 0.2,
k_refine: int = 20,
refinement_strategy: Literal[
"index", "approximate", "bruteforce"
] = "index",
index_type: Literal[
"nndescent", "hnsw", "annoy", "exhaustive"
] = "nndescent",
ann_dist: Literal["euclidean", "cosine"] = "euclidean",
n_trees: int = 50,
search_budget: int | None = None,
m: int = 16,
ef_construction: int = 200,
ef_search: int = 100,
delta: float = 0.001,
diversify_prob: float = 0.0,
)
Parameters for the Milo neighbourhoods.
It carries the kNN keys the neighbourhood refinement reads.
Attributes:
| Name | Type | Description |
|---|---|---|
prop |
float
|
Share of cells sampled as neighbourhood indices. |
k_refine |
int
|
Neighbours whose median position an index is moved towards. |
refinement_strategy |
Literal['index', 'approximate', 'bruteforce']
|
|
index_type |
Literal['nndescent', 'hnsw', 'annoy', 'exhaustive']
|
The kNN index |
ann_dist |
Literal['euclidean', 'cosine']
|
Distance metric of the refinement. |
n_trees |
int
|
Annoy: number of trees. |
search_budget |
int | None
|
Annoy: search budget per query. |
m |
int
|
HNSW: connections per layer. |
ef_construction |
int
|
HNSW: construction budget. |
ef_search |
int
|
HNSW: search budget. |
delta |
float
|
NNDescent: early termination criterium. |
diversify_prob |
float
|
NNDescent: diversification probability. |
MiloR
dataclass
¶
MiloR(
nhoods: CsrMatrix,
sample_counts: ndarray,
samples: tuple[str, ...],
spatial_dist: ndarray,
nhood_overlap: ndarray,
params: dict[str, object],
nhoods_info: DataFrame | None = None,
)
Milo neighbourhoods and their test.
Attributes:
| Name | Type | Description |
|---|---|---|
nhoods |
CsrMatrix
|
Membership, |
sample_counts |
ndarray
|
|
samples |
tuple[str, ...]
|
The sample names, the columns of |
spatial_dist |
ndarray
|
Squared distance of each index cell to its last kNN
neighbour, the |
nhood_overlap |
ndarray
|
Cells each neighbourhood shares with all the others,
the |
params |
dict[str, object]
|
The parameters, plus |
nhoods_info |
DataFrame | None
|
The differential abundance table once |
get_milor_abundances
¶
get_milor_abundances(
sc: SingleCells,
sample_id_col: str,
*,
embd_to_use: str = "pca",
no_embd_to_use: int | None = None,
milor_params: MiloRParams | None = None,
seed: int = 42,
verbose: Verbose = True,
) -> MiloR | None
Milo neighbourhoods and their cell counts per sample.
Samples a share of the cells, moves each towards the median of its kNN
neighbourhood, and counts the cells of every sample in the neighbourhood
of each refined index. Test them with test_nhoods.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sc
|
SingleCells
|
The experiment, with an embedding and the kNN built on it. |
required |
sample_id_col
|
str
|
obs column with the sample per cell. |
required |
embd_to_use
|
str
|
The embedding the kNN was built on. |
'pca'
|
no_embd_to_use
|
int | None
|
Leading embedding dimensions to use. |
None
|
milor_params
|
MiloRParams | None
|
The parameters. |
None
|
seed
|
int
|
Seed. |
42
|
verbose
|
Verbose
|
|
True
|
Returns:
| Type | Description |
|---|---|
MiloR | None
|
The |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the embedding is missing, it or the kNN is stale, or a kept cell has no sample. |
References
Dann, et al., Nat Biotechnol, 2022.
Examples:
test_nhoods
¶
test_nhoods(
x: MiloR,
design: str,
design_df: DataFrame,
*,
sample_col: str = "sample_id",
coef: Coef | None = None,
contrast: ndarray | Sequence[float] | None = None,
norm_method: MiloNorm = "TMM",
min_mean: float = 0.0,
robust: bool = True,
legacy: bool = True,
fdr_weighting: FdrWeighting = "k-distance",
) -> MiloR
Differential abundance of the neighbourhoods.
edgeR's quasi-likelihood test on the neighbourhood counts, with Milo's
spatial FDR on top. filterByExpr stays off, it means nothing for a
neighbourhood; use min_mean to drop sparse ones.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
MiloR
|
The |
required |
design
|
str
|
Formula over |
required |
design_df
|
DataFrame
|
One row per sample. |
required |
sample_col
|
str
|
The |
'sample_id'
|
coef
|
Coef | None
|
See |
None
|
contrast
|
ndarray | Sequence[float] | None
|
See |
None
|
norm_method
|
MiloNorm
|
Library size normalisation; Milo's |
'TMM'
|
min_mean
|
float
|
Neighbourhoods with a lower mean count are dropped. |
0.0
|
robust
|
bool
|
Robust estimation of the quasi-likelihood dispersion. |
True
|
legacy
|
bool
|
edgeR's pre-4.0 pipeline, which is what Milo itself runs. |
True
|
fdr_weighting
|
FdrWeighting
|
Spatial FDR weights: the k-th neighbour distance, the overlap with other neighbourhoods, or none. |
'k-distance'
|
Returns:
| Type | Description |
|---|---|
MiloR
|
A new |
MiloR
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the design rows and the samples do not match. |
References
Dann, et al., Nat Biotechnol, 2022; Chen, Lun and Smyth, F1000Research, 2016.
Examples:
add_nhoods_info
¶
The majority cell type of each neighbourhood.
Adds majority_celltype (ties go to the first label in sorted order) and
majority_prop to nhoods_info.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
MiloR
|
A tested |
required |
cell_info
|
Sequence[str] | ndarray | Series
|
One label per row of |
required |
Returns:
| Type | Description |
|---|---|
MiloR
|
A new |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
get_differential_abundance_res
¶
get_differential_abundance_res(
x: MiloR,
) -> DataFrame | None
The differential abundance table; warns and returns None if untested.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
MiloR
|
The Milo result. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame | None
|
The neighbourhood table, or |
MELD¶
Marker genes, donor-aware differential expression and differential abundance.
Three jobs. Markers: Wilcoxon or Seurat's logistic regression test (method=,
the default on ATAC peaks) between two groups (find_markers), one-vs-rest
for every group of a column (find_all_markers), or markers that hold up
against every rival group separately (find_specific_markers). Expression with
donor structure: pseudobulk edgeR (get_pseudobulked, pseudobulk_dge,
run_edger_ql) or the mixed model nebula. Abundance: Milo neighbourhoods
(get_milor_abundances, test_nhoods, add_nhoods_info) and meld densities.
Start with find_all_markers to look at clusters, pseudobulk_dge or nebula
to compare conditions across donors.
What lands where. Nothing here writes to obs, var or the cache. The marker
tests and pseudobulk_dge return polars frames; find_specific_markers,
nebula, get_milor_abundances and meld return frozen records
(ScSpecificMarkers, ScNebula, MiloR, MeldRes) with getters for their
tables. test_nhoods and add_nhoods_info hand back a new MiloR carrying
nhoods_info.
Object types. The marker functions, get_pseudobulked, pseudobulk_dge and
nebula take a SingleCells or a SingleCellsSubset, so a per cell type
comparison is a subset away. get_milor_abundances and meld take a
SingleCells only.
Condition across donors, one pseudobulk sample per donor. cell_list maps the
sample names to their cells and the rows of the design follow its order:
import polars as pl
obs = sc.obs(filtered=True)
cell_list = {
s: obs.filter(obs["sample_id"] == s)["cell_id"].to_list()
for s in obs["sample_id"].unique().sort()
}
design = pl.DataFrame(
{"(Intercept)": [1.0] * 6, "stim": [0.0, 0.0, 0.0, 1.0, 1.0, 1.0]}
)
pb_res = bv.de.pseudobulk_dge(sc, cell_list, design, coef="stim")
Milo needs a PCA and the kNN over it, and the sample column of obs. The design frame has one row per sample:
bv.pp.find_hvg(sc, hvg_no=500)
bv.pp.calculate_pca(sc, no_pcs=20)
bv.graph.find_neighbours(sc)
design_df = sc.obs().select("sample_id", "condition").unique().sort("sample_id")
milo = bv.de.get_milor_abundances(sc, "sample_id")
milo = bv.de.test_nhoods(milo, "~ condition", design_df)
da = bv.de.get_differential_abundance_res(milo)
Gotchas. Designs are additive formulas over a frame, "~ condition + age":
numeric columns as they are, everything else treatment coded against its first
(sorted) level and named <column><level>. Interactions and transformations
are not parsed. coef takes a 0-based design column or its name, and the last
column is tested if you give neither. Every index is 0-based, Milo's Nhood
included. get_milor_abundances and meld raise on a stale embedding or kNN,
so rerun those after the cell filter moves, and they warn and return None
without a kNN. nebula costs milliseconds to seconds per gene: hand
genes_to_use the HVGs or a candidate set. run_edger_ql wants raw counts and
a design with an intercept and at least one more column.
MeldRes
dataclass
¶
MELD densities.
Attributes:
| Name | Type | Description |
|---|---|---|
raw_scores |
DataFrame
|
|
norm_scores |
DataFrame
|
The same with negatives clamped to 0 and every row L1 normalised, so probability-like. |
meld
¶
meld(
sc: SingleCells,
sample_id_col: str,
*,
embd_to_use: str = "pca",
meld_params: MeldParams | None = None,
seed: int = 42,
verbose: Verbose = True,
) -> MeldRes | None
MELD sample densities over the kNN graph.
Smooths the one-hot sample indicators over the kNN graph with a Chebyshev-approximated spectral filter, giving a per-cell likelihood for each sample.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sc
|
SingleCells
|
The experiment, with the kNN. |
required |
sample_id_col
|
str
|
obs column with the sample per cell. |
required |
embd_to_use
|
str
|
The embedding the kNN was built on; only checked for staleness, as the kNN is what MELD reads. |
'pca'
|
meld_params
|
MeldParams | None
|
The parameters. |
None
|
seed
|
int
|
Seed for the largest eigenvalue estimate. |
42
|
verbose
|
Verbose
|
|
True
|
Returns:
| Type | Description |
|---|---|
MeldRes | None
|
The |
MeldRes | None
|
is no kNN. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the embedding or the kNN is stale, or a kept cell has no sample. |
References
Burkhardt, et al., Nat Biotechnol, 2021.
Examples: