NEBULA on AnnData¶
Intro¶
The pseudobulk vignette deals with donors as replicates by summing the cells away. NEBULA keeps the cells. It fits a negative binomial gamma mixed model per gene, with the donor as a random effect, so the donor-to-donor variability is modelled instead of ignored. No pseudobulking, and the cell-level counts still contribute to the dispersion.
edge_rs.nebula() takes an anndata.AnnData directly: raw counts in a
layer, a formula over obs, the donor column. That is the scverse entry
point, and it returns a pandas data frame on purpose, indexed by gene, so it
drops into the rest of that ecosystem. Scanpy is not needed.
import anndata as ad
import bixverse as bv
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import polars as pl
from scipy import sparse
from scipy.stats import spearmanr
import edge_rs
The data¶
The same Kang PBMCs as in the pseudobulk vignette: eight lupus donors, each
split in two and half of it stimulated with IFN-beta. bixverse only
provides the download here. The h5ad has raw counts in X, so we move them
into layers["counts"], which is where nebula() looks by default.
adata = ad.read_h5ad(bv.io.download_kang_pbmc())
adata.layers["counts"] = sparse.csr_matrix(adata.X)
adata.var_names = adata.var["SYMBOL"].astype(str)
adata.var_names_make_unique()
adata = adata[(adata.obs["multiplets"] == "singlet") & adata.obs["cell"].notna()].copy()
adata.obs["ind"] = adata.obs["ind"].astype(str)
adata.obs["stim"] = adata.obs["stim"].astype("category")
adata
AnnData object with n_obs × n_vars = 24673 × 35635
obs: 'ind', 'stim', 'cluster', 'cell', 'multiplets'
var: 'ENSEMBL', 'SYMBOL'
layers: None (.X), 'counts'
One cell type¶
CD14+ monocytes. We subset the cells but keep every gene: NEBULA scales each
cell by its library size over all genes of the layer, so cutting the genes
first would change the offset. The gene set to fit goes in genes= instead.
A fit costs milliseconds to seconds per gene, so we fit the 1000 most highly expressed genes that are detected in at least 5% of the cells.
mono = adata[adata.obs["cell"] == "CD14+ Monocytes"].copy()
x = mono.layers["counts"]
detected = np.asarray((x > 0).mean(axis=0)).ravel()
mean = np.asarray(x.mean(axis=0)).ravel()
order = np.argsort(-mean)
genes = mono.var_names[order][detected[order] >= 0.05][:1000]
pd.crosstab(mono.obs["ind"], mono.obs["stim"])
| stim | ctrl | stim |
|---|---|---|
| ind | ||
| 101 | 202 | 253 |
| 1015 | 779 | 671 |
| 1016 | 369 | 329 |
| 1039 | 126 | 165 |
| 107 | 209 | 169 |
| 1244 | 415 | 290 |
| 1256 | 390 | 375 |
| 1488 | 295 | 348 |
The formula goes through Formulaic. stim is a categorical, treatment coded
against its first level (ctrl), so the coefficient is called
stim[T.stim]. The donor goes in as the subject key, not in the formula.
nebula() returns the fit; test() runs the Wald test on it. The fit doesn't
care what you test, so further coefficients or contrasts cost nothing extra.
fit = edge_rs.nebula(mono, "ind", "~ stim", genes=genes)
res = fit.test(coef="stim[T.stim]")
res.sort_values("z", key=np.abs, ascending=False).head(10)
| log_fc | se | z | p_value | fdr | subject_overdispersion | cell_overdispersion | cell_overdispersion_shrunk | convergence | sigma_at_bound | |
|---|---|---|---|---|---|---|---|---|---|---|
| SYMBOL | ||||||||||
| ISG15 | 4.658567 | 0.028227 | 165.042142 | 0.0 | 0.0 | 0.024460 | 0.518847 | 0.518448 | 1 | False |
| ISG20 | 3.664969 | 0.030968 | 118.345318 | 0.0 | 0.0 | 0.004186 | 0.133458 | 0.133518 | 1 | False |
| APOBEC3A | 3.523317 | 0.030011 | 117.401334 | 0.0 | 0.0 | 0.044682 | 0.277375 | 0.277365 | 1 | False |
| IFITM3 | 3.381169 | 0.029460 | 114.772030 | 0.0 | 0.0 | 0.013847 | 0.090103 | 0.090156 | 1 | False |
| CXCL10 | 5.617618 | 0.052114 | 107.794918 | 0.0 | 0.0 | 0.025086 | 1.094772 | 1.091868 | 1 | False |
| IFI6 | 2.672865 | 0.030232 | 88.410830 | 0.0 | 0.0 | 0.004330 | 0.107573 | 0.107633 | 1 | False |
| LY6E | 3.368378 | 0.038660 | 87.127988 | 0.0 | 0.0 | 0.007149 | 0.101165 | 0.101223 | 1 | False |
| CCL8 | 5.969312 | 0.071186 | 83.854878 | 0.0 | 0.0 | 0.022184 | 1.452719 | 1.447123 | 1 | False |
| TMSB10 | 1.204548 | 0.014798 | 81.401930 | 0.0 | 0.0 | 0.009852 | 0.106562 | 0.106619 | 1 | False |
| IDO1 | 3.873212 | 0.049906 | 77.609424 | 0.0 | 0.0 | 0.033005 | 0.496990 | 0.496615 | 1 | False |
Ranked by |z|, because the p-values of the strongest genes underflow to zero
and tie. The top of the table should be the interferon response, as in the
pseudobulk. log_fc is the natural log, unlike run_edger_ql(), which
reports log2. Divide by np.log(2) to compare.
convergence is the optimiser's status per gene. Anything at or below -20 is
a likely failure and sigma_at_bound flags a donor variance pinned at its
boundary, so look at both before trusting a gene.
pl.DataFrame(
{
"tested": len(res),
"fdr_below_0.05": int((res["fdr"] < 0.05).sum()),
"convergence_failures": int((res["convergence"] <= -20).sum()),
"sigma_at_bound": int(res["sigma_at_bound"].sum()),
}
)
| tested | fdr_below_0.05 | convergence_failures | sigma_at_bound |
|---|---|---|---|
| i64 | i64 | i64 | i64 |
| 1000 | 928 | 0 | 79 |
On the GPU¶
device="gpu" runs the penalised fits on the wgpu device in float32, so
results land close to the CPU ones, not on them. Not here, though: with only
categoricals in the formula, cells share design rows within each donor and the
CPU sums the zero counts from tables, which beats the device. The GPU path
then hands back the CPU result bit for bit. Put a continuous covariate in the
formula and the device takes over.
if edge_rs.gpu_available():
fit_gpu = edge_rs.nebula(mono, "ind", "~ stim", genes=genes, device="gpu")
res_gpu = fit_gpu.test(coef="stim[T.stim]")
diff = (res_gpu["log_fc"] - res.loc[res_gpu.index, "log_fc"]).abs()
print(f"max |diff log_fc|: {diff.max():.2g}")
else:
print("No usable GPU on this machine.")
max |diff log_fc|: 0
Against pseudobulk¶
Same cells, summed per donor and condition and run through edgeR QL with the donor as a blocking factor, as in the pseudobulk vignette.
donors = sorted(mono.obs["ind"].unique())
cols, meta = [], []
for d in donors:
for s in ["ctrl", "stim"]:
m = ((mono.obs["ind"] == d) & (mono.obs["stim"] == s)).to_numpy()
cols.append(np.asarray(mono.layers["counts"][m].sum(axis=0)).ravel())
meta.append((d, s))
pb = np.column_stack(cols) # genes x samples
design = pl.DataFrame(
{
"intercept": np.ones(len(meta)),
**{f"ind{d}": [float(m[0] == d) for m in meta] for d in donors[1:]},
"stim": [float(m[1] == "stim") for m in meta],
}
)
ql = edge_rs.run_edger_ql(pb, design, feature_ids=list(mono.var_names), coef="stim")
ql = pd.DataFrame(ql.to_dict()).set_index("feature_id")
common = res.index.intersection(ql.index)
rho = spearmanr(res.loc[common, "log_fc"], ql.loc[common, "log_fc"]).statistic
fig, ax = plt.subplots(figsize=(5, 5))
ax.scatter(ql.loc[common, "log_fc"], res.loc[common, "log_fc"] / np.log(2), s=3)
ax.axline((0, 0), slope=1, color="black", lw=0.5)
ax.set_xlabel("log2 FC, pseudobulk edgeR QL")
ax.set_ylabel("log2 FC, NEBULA")
plt.show()
print(f"{len(common)} genes in common, Spearman rho of the log fold changes: {rho:.3f}")
1000 genes in common, Spearman rho of the log fold changes: 0.999