Python (Scanpy)

Native Python and Scanpy / AnnData workflow for MeDuSA v2.0

Table of Contents

MeDuSA v2.0 provides a native Python implementation built directly on scanpy, anndata, numpy, and scipy (no R installation required), with numerical parity to the R/C++ v2.0 package.

1. Installation #

Install directly from the python/ subdirectory of the MeDuSA GitHub repository (Python >= 3.10):

pip install "git+https://github.com/JianYang-Lab/MeDuSA.git#subdirectory=python"

To include optional matplotlib plotting helpers (medusa.plotting):

pip install "medusa-deconv[plot] @ git+https://github.com/JianYang-Lab/MeDuSA.git#subdirectory=python"

Verify installation:

import medusa as md
print(md.__version__)

2. Preparing a Scanpy Reference (AnnData) #

MeDuSA works directly with anndata.AnnData objects (dense arrays, sparse CSR/CSC matrices, custom layers, or backed .h5ad files). By default, it reads cell types from adata.obs["cell_type"] and 1D pseudotime from adata.obs["cell_trajectory"], and both column names are configurable (cell_type_col, trajectory_col) so Scanpy outputs such as dpt_pseudotime work without renaming.

import numpy as np
import pandas as pd
import scanpy as sc

# Load reference scRNA-seq (cells x genes)
adata = sc.read_h5ad("reference.h5ad")

# Keep linear normalized counts in a dedicated layer (e.g., CP10K) for deconvolution
adata.layers["cp10k"] = adata.X.copy()
sc.pp.normalize_total(adata, target_sum=1e4, layer="cp10k")

# Example: infer diffusion pseudotime (DPT) with Scanpy on log-normalized data
sc.pp.normalize_total(adata, target_sum=1e4)
sc.pp.log1p(adata)
sc.pp.highly_variable_genes(adata, n_top_genes=2000)
sc.tl.pca(adata)
sc.pp.neighbors(adata, n_neighbors=15, n_pcs=20)
sc.tl.diffmap(adata)
adata.uns["iroot"] = np.flatnonzero(adata.obs["cell_type"] == "HSPC")[0]
sc.tl.dpt(adata)

Bulk RNA-seq can be passed either as a pandas.DataFrame (genes x samples) or as an anndata.AnnData (samples x genes, standard AnnData layout), normalized to the same linear scale as the reference (e.g., CP10K):

bulk = pd.read_csv("bulk_counts.tsv", sep="\t", index_col=0)
bulk = bulk.div(bulk.sum(axis=0), axis=1) * 1e4

3. Running MeDuSA v2.0 in Python #

Classic 1D Trajectory Deconvolution #

import medusa as md

# Default model = "gp_map" (REML-calibrated non-negative GP-LMM, automatic smoothness)
res = md.medusa(
    bulk=bulk,
    adata=adata,
    select_ct="mon",
    cell_type_col="cell_type",
    trajectory_col="dpt_pseudotime",
    layer="cp10k",
    resolution=50,
    fractional=True,
)

# Estimated cell-state abundance (states x samples)
ab = res.abundance
time_bin = res.time_bin
markers = res.marker_genes

Including Background Cell Types as Covariates #

Set adj=True to automatically build background cell-type covariates from non-focal cell types in adata, or pass a custom fix_cov DataFrame (genes x covariates):

# Automatic covariates from all other cell types in adata
res_adj = md.medusa(
    bulk=bulk,
    adata=adata,
    select_ct="mon",
    trajectory_col="dpt_pseudotime",
    adj=True,
    layer="cp10k",
    resolution=50,
    fractional=True,
)

# Or supply a pre-computed covariate matrix explicitly
res_cov = md.medusa(
    bulk=bulk,
    adata=adata,
    select_ct="mon",
    trajectory_col="dpt_pseudotime",
    fix_cov=other_ct_means,
    adj=True,
    layer="cp10k",
    resolution=50,
    fractional=True,
)

Marker Gene Selection with Scanpy #

By default, medusa() selects signature genes automatically via Scanpy’s Wilcoxon rank-sum test (method="wilcox"). You can also pre-select markers explicitly with medusa_marker() using "wilcox" or "spline" (fast natural cubic spline F-test):

adata_focal = adata[adata.obs["cell_type"] == "mon"]
markers_wilcox = md.medusa_marker(
    adata_focal,
    bulk,
    gene_number=200,
    nbins=10,
    method="wilcox",
    trajectory_col="dpt_pseudotime",
    layer="cp10k",
)
markers_spline = md.medusa_marker(
    adata_focal,
    bulk,
    gene_number=200,
    nbins=10,
    method="spline",
    trajectory_col="dpt_pseudotime",
    layer="cp10k",
)

4. Branching & Multi-Dimensional Trajectories #

Pass any embedding key in adata.obsm (such as "X_umap" or "X_diffmap") via obsm_key, or pass a custom coords array/DataFrame:

res_branch = md.medusa(
    bulk=bulk,
    adata=adata,
    select_ct="Tcell",
    obsm_key="X_umap",
    dist_metric="geodesic",
    resolution=50,
    model="gp_map",
    kernel="exp",
    layer="cp10k",
    fractional=True,
)

For direct R-vs-Python comparisons on multi-dimensional coordinates when resolution is smaller than the number of distinct coordinate points, supply shared cluster assignments via state_col so state labels match across both implementations.

For pre-defined discrete states or clusters without coordinates, pass state_col (and optionally a symmetric state dist_matrix with kernel="diffusion"):

res_graph = md.medusa(
    bulk=bulk,
    adata=adata,
    select_ct="Tcell",
    state_col="leiden",
    dist_matrix=state_dist_df,
    kernel="diffusion",
    layer="cp10k",
    fractional=True,
)

5. Calibrated Downstream Inference & AnnData Export #

Group Comparison (manova_pro) #

stat = md.manova_pro(
    res,
    degree=3,
    condition=group_labels,      # list, Series, or dict keyed by sample name
    blocks=donor_blocks,         # optional donor/batch stratification
    perm_method="sample",
    n_perm=1000,
)
print(stat)

Variance Explained & Finite-Sample RLRT (medusa_var_explain) #

Supply independently selected indep_markers for valid null p-value calibration:

res_ve = md.medusa(
    bulk=bulk,
    adata=adata,
    select_ct="mon",
    trajectory_col="dpt_pseudotime",
    marker_genes=indep_markers,
    layer="cp10k",
    resolution=50,
)
res_ve = md.medusa_var_explain(res_ve, test="rlrt", n_rlrt_sim=2000)
print(res_ve.var_explain["var_explain"])
print(res_ve.var_explain["pval_rlrt"])

AnnData Interoperability & Plotting #

# Export cell-state abundances as an AnnData object (samples x states)
ab_adata = res.to_anndata()

# Or store directly into an existing bulk AnnData (adds obsm["X_medusa"] and uns["medusa"])
res.write_to_adata(bulk_adata)

# Quick multi-sample curve visualization (requires matplotlib)
from medusa.plotting import plot_abundance
fig, axes = plot_abundance(res, ncols=4)

6. R vs. Python Parameter Mapping #

R (MeDuSA) Python (medusa) Notes
MeDuSA(bulk, sce, select.ct=...) md.medusa(bulk, adata, select_ct=...) bulk accepts DataFrame (genes x samples) or AnnData (samples x genes)
sce$cell_type / sce$cell_trajectory adata.obs[cell_type_col] / adata.obs[trajectory_col] Configurable column names (defaults "cell_type", "cell_trajectory")
coords = Embeddings(sce, "umap") obsm_key="X_umap" or coords=... Direct adata.obsm integration
MeDuSA_marker(..., method="wilcox") md.medusa_marker(..., method="wilcox") Uses scanpy.tl.rank_genes_groups (or "spline" F-test)
MANOVA_Pro(obj, ...) md.manova_pro(res, ...) Identical Pillai trace, sample/block permutation, and gene permutation
MeDuSA_VarExplain(obj, test="rlrt") md.medusa_var_explain(res, test="rlrt") Exact spectral PVE/LRT parity; same Crainiceanu-Ruppert null distribution (independent Monte Carlo RNG stream)
obj@Estimation$cell_state_abundance res.abundance pandas.DataFrame (states x samples)