This repository is a supplement to the main MAGELLAN repository (github.com/jfisher-lab/MAGELLAN), refer there for MAGELLAN itself. This repository provides the benchmarking pipeline that compares MAGELLAN, a pathway-level GNN for perturbation prediction, against single-cell perturbation models. MAGELLAN operates on a discrete ordinal scale (0/1/2) over a curated gene network, while comparison models produce continuous genome-wide predictions. The pipeline handles the full data preparation, training, and evaluation workflow so that all models are assessed on identical train/test splits using the same metrics.
External data and checkpoints can be downloaded from HuggingFace using the
download_external_data.py script (see this
collection).
The pipeline has two phases:
- Data preparation and MAGELLAN training — download a perturbation dataset, map drug names to gene targets, filter genes by Omnipath network coverage, discretise expression to the 0/1/2 scale, create treatment-level train/val/test splits, write MAGELLAN spec CSVs, build the shortest-path network topology, train the MAGELLAN GNN to learn edge weights (early-stopping on validation), predict on all splits using BMA and GNN methods, and evaluate with shared metrics.
- Comparison model evaluation — run foundation models (STATE, GEARS, CPA, scGenePT) on the shared splits in two modes (full-dataset and MAGELLAN-filtered), discretise their predictions to the same 0/1/2 scale, and evaluate all models with identical metrics.
- Python = 3.11 (the orchestrator and MAGELLAN run on 3.11; comparison models use their own Python versions)
- uv package manager
- Graphviz system binary (for network visualisation)
- AWS CLI (only needed for downloading scGenePT checkpoints from S3)
- HuggingFace CLI (only needed for downloading private pre-trained checkpoints)
- Git with submodule support
Install the CLI tools:
# uv (if not already installed)
curl -LsSf https://astral.sh/uv/install.sh | sh
# Graphviz
brew install graphviz # macOS
# apt install graphviz # Debian/Ubuntu
# AWS CLI (for scGenePT S3 downloads — no credentials needed)
pip install awscli
# or: brew install awscli # macOS
# or: apt install awscli # Debian/Ubuntu
# HuggingFace CLI (for private checkpoint downloads)
pip install huggingface_hub[cli]Authenticate HuggingFace (only needed if you will download private pre-trained checkpoints in step 5):
huggingface-cli loginThis prompts for a User Access Token with read scope. The token is stored at ~/.cache/huggingface/token and reused by all subsequent HuggingFace operations (checkpoint upload/download, pipeline checkpointing).
The repository includes Git submodules (MAGELLAN, STATE, GEARS, CPA, scGenePT, PRNet_Comparison). Clone with --recurse-submodules to fetch them all:
git clone --recurse-submodules <repo-url>
cd MAGELLANIf you already cloned without --recurse-submodules, initialise them afterwards:
git submodule update --initThe orchestrator, MAGELLAN, and all pipeline code run in the root virtualenv. This is the only environment needed for Phase 1 (data preparation and MAGELLAN training):
uv venv && source .venv/bin/activate && uv syncThis installs MAGELLAN (via the submodule), pertpy, torch, omnipath, and all other orchestrator dependencies declared in the top-level pyproject.toml.
Each comparison model runs in its own isolated virtualenv under envs/ because they have conflicting Python version and dependency requirements (e.g. CPA pins torch = 2.0.1 while MAGELLAN needs a newer torch). The Makefile manages these environments:
make setup-all # create all four model envs (recommended)Or create them individually:
make setup-gears # envs/gears — Python 3.10 (GEARS + torch_geometric)
make setup-state # envs/state — Python 3.12 (STATE + hydra + transformers)
make setup-cpa # envs/cpa — Python 3.10 (CPA + scvi-tools + torch 2.0)
make setup-scgenept # envs/scgenept — Python 3.10 (scGenePT + GEARS + scgpt backbone)The scGenePT environment also serves the scGPT baseline model (scGPT_baseline in the model registry). Run make help for the full list of targets.
Each environment is defined by a requirements file in environments/ (auxiliary deps not declared by the model’s own package) plus an editable install of the model’s submodule. The --clear flag makes all targets idempotent, re-running rebuilds the env from scratch.
How model isolation works: the orchestrator (running in the root .venv) invokes comparison models via subprocess using run_in_env() from src/models/_subprocess.py. Each model wrapper calls the appropriate driver script (e.g. src/models/_gears_driver.py) inside envs/<name>/bin/python, so there are no import conflicts between models.
scGenePT and scGPT baseline models require pre-trained checkpoints and gene embeddings from a public S3 bucket. This needs the AWS CLI (installed in Prerequisites above) but no AWS credentials as the bucket is public:
make download-scgenept-dataThis fetches the scGPT backbone weights, gene embeddings (NCBI+UniProt variant), and fine-tuned scGenePT and scGPT baseline checkpoints (Norman 2019). The download is idempotent. aws s3 sync only fetches files that are missing or changed.
Pre-trained checkpoints for STATE, GEARS, and CPA are cached on HuggingFace dataset repos under MClarke1991/ in the MAGELLAN benchmarking collection. This needs the HuggingFace CLI with a valid login (see Prerequisites above). Download with:
python scripts/download_external_data.pyThis populates external_data/ with pre-trained checkpoints used for zero-shot comparisons. See src/benchmark/external_checkpoints.py for the full registry of HuggingFace repos.
After setup, verify that model environments are working:
# Root env (MAGELLAN + orchestrator)
uv run python -c "from src.benchmark import Phase1Pipeline; print('Root env OK')"
# Model envs (each should print its version)
envs/gears/bin/python -c "import gears; print('GEARS env OK')"
envs/state/bin/python -c "import state; print('STATE env OK')"
envs/cpa/bin/python -c "import cpa; print('CPA env OK')"
envs/scgenept/bin/python -c "import scgpt; print('scGenePT env OK')"The Phase 1 pipeline downloads a perturbation dataset, produces MAGELLAN-ready spec CSVs, builds the network, trains MAGELLAN’s GNN to learn edge weights, and evaluates predictions. All steps are idempotent — they check for cached outputs before re-running.
Per active cell line, the pipeline:
- subsets AnnData to that cell line before split assignment,
- creates treatment-level train/val/test splits on that subset,
- derives
deg/phenogenes from training treatments only, using genes with at least one non-neutral qualitative effect (qual_effectin{0, 2}), - applies Omnipath filtering to those train-derived genes.
Pipeline behaviour is controlled by a TOML config file. E.g. The Norman 2019 CPA comparison config (K562, CRISPRa) is at configs/norman_2019_cpa.toml. The key sections are:
[dataset]
name = "norman_2019_cpa"
cache_dir = "data"
[cell_lines]
active = ["K562"]
[cell_lines.K562]
control_key = "control"
# Auto-fetch basal driver mutations / CNAs from Cell Model Passports.
auto_basal_from_passports = true
amplifications_as_activating = false
[drug_to_gene]
# CRISPRa = activation = perturbation level 2 on the 0/1/2 ordinal scale.
default_perturbation_level = 2
[gene_filter]
min_primary_sources = 1
# Most topologically downstream DEGs become phenotype nodes,
# producing a hierarchical mut -> deg -> pheno topology.
pheno_strategy = "downstream"
pheno_fraction = 0.25
[discretise]
pseudocount = 1e-10
qvalue_threshold = 0.05
n_jobs = -1
[splits]
# Adopt CPA's own OOD treatments as the test set, re-split the rest
# for MAGELLAN's treatment-level requirement.
adopt_column = "split_hardest"
adopt_label_map = { train = "train", valid = "val", ood = "test" }
resplit_train_val = true
train_fraction = 0.89
val_fraction = 0.11
seed = 42
[network]
thre = 3
weighted_edge = "reciprocal_n_references"
consensus_sign = true
to_combine = [["mut", "deg"], ["deg", "pheno"]]
model_name = "network"
min_range = 0
max_range = 2
visualise = false
[magellan]
min_range = 0
max_range = 2
n_iter = 30
learning_rate = 0.01
epochs = 10000
early_stopping_enabled = true
early_stopping_patience = 50
tf_method = "sum"
# Multi-seed training: trains each seed independently, aggregates
# metrics (mean +/- CI), and picks the median seed as canonical.
seeds = [0, 7, 21]
[output]
spec_dir = "results/K562_Norman_2019_CPA/spec"
cache_dir = "data/K562_Norman_2019_CPA/cache"
network_dir = "results/K562_Norman_2019_CPA/network"
training_dir = "results/K562_Norman_2019_CPA/training"The --phase flag selects which phases run. With no flag, Phase 1 runs by default:
# Genetic perturbation dataset (Norman 2019 CRISPRa, K562) — Phase 1 only
uv run main.py --config configs/norman_2019_cpa.toml
# Other phase selections
uv run main.py --config configs/norman_2019_cpa.toml --phase 2 # Phase 2 only
uv run main.py --config configs/norman_2019_cpa.toml --phase 1 2 # both phases
uv run main.py --config configs/norman_2019_cpa.toml --phase 3 # replot only
uv run main.py --config configs/norman_2019_cpa.toml --phase 1 3 # retrain + replot
# Multi-seed MAGELLAN training, seeds run in parallel
uv run main.py --config configs/norman_2019_cpa.toml --seeds 42,123,456 --parallelData are cached in the data/ directory; pass --force to override the cache.
Genetic perturbation datasets (e.g. Norman 2019 CRISPRa, Replogle CRISPRi) skip the drug-to-gene mapping step entirely. The perturbation gene name maps directly to a MAGELLAN perturbation node. Set default_perturbation_level = 2 for CRISPRa (activation) or 0 for CRISPRi/KO in the [drug_to_gene] config section.
Data preparation is slow (API calls to PubChem, OpenTargets, Omnipath, plus per-gene statistical tests). To avoid re-running it, you can upload the processed artifacts to a HuggingFace dataset repo and download them on subsequent runs.
Add a [checkpointing] section to your config:
[checkpointing]
enabled = true
backend = "huggingface"
repo_id = "magellan-benchmark/norman-2019-cpa-phase1"
private = trueWith enabled = true, checkpointing is applied automatically. On the first run (no checkpoint exists yet), the full pipeline executes and uploads artifacts to HuggingFace. On subsequent runs, the artifacts are downloaded and the pipeline returns immediately.
You can also upload/download manually:
pipeline = Phase1Pipeline.from_config_file("configs/norman_2019_cpa.toml")
pipeline.upload_checkpoint() # push data/cache/ and data/spec/ to HF
pipeline.download_checkpoint() # pull them back from HFAuthentication uses the token stored by huggingface-cli login. The raw h5ad dataset is not uploaded, it is always re-downloaded via pertpy when needed.
| Output | Location | Description |
|---|---|---|
| Dataset | data/<name>.h5ad |
Cached AnnData from pertpy |
| Drug mapping | data/cache/drug_to_chembl.json |
Drug name → ChEMBL ID |
| Target mapping | data/cache/chembl_to_targets.json |
ChEMBL ID → gene targets + mechanism |
| Omnipath interactions | data/cache/omnipath_interactions.parquet |
Pinned Omnipath network (version-controlled) |
| Discretised expression | data/cache/<cell_line>/discretised.parquet |
Per-gene 0/1/2 labels per treatment |
| Split assignment | data/cache/<cell_line>/split_dict.json |
Treatment → split mapping |
| Gene sets | data/cache/<cell_line>/gene_sets.json |
Filtered/prioritised gene sets for network building |
| Spec CSVs | data/spec/<cell_line>/spec_<split>.csv |
MAGELLAN input specs per split |
| Network edge CSV | data/network/<cell_line>/network.csv |
Shortest-path edges with Omnipath annotations |
| Network BMA JSON | data/network/<cell_line>/network.json |
BMA-format JSON for MAGELLAN training |
| Network SVG/PNG | data/network/<cell_line>/network.{svg,png} |
Network visualisation (nodes colour-coded by gene set) |
| Trained network JSON | data/training/<cell_line>/network_trained.json |
BMA JSON with learned edge weights |
| Weight matrix | data/training/<cell_line>/weight_matrix.csv |
Learned edge weight matrix |
| Predictions | data/training/<cell_line>/predictions/ |
BMA and GNN prediction CSVs per split |
| Metrics | data/training/<cell_line>/metrics/ |
Per-split accuracy, F1, MCC, QWK, confusion matrices |
| Long-form predictions | data/training/<cell_line>/predictions/long_form_bma_test.csv |
MAGELLAN test predictions in (treatment, gene) long format |
| Coverage artifact | data/training/<cell_line>/coverage/test_coverage.json |
Adopted vs evaluated test treatments with drop accounting |
| Comparison plot | data/training/<cell_line>/metrics/<cell_line>_test_comparison.png |
BMA vs GNN metric comparison on test set |
The Omnipath interaction table at data/cache/omnipath_interactions.parquet is version-controlled for reproducibility — the pipeline never silently re-queries the Omnipath REST API.
Phase 2 trains comparison models on the same dataset and treatment-level splits produced by Phase 1. Predictions are discretised to the 0/1/2 ordinal scale using the same statistical test (log2FC + Welch t-test + BH FDR) as ground-truth labels, with real control cells as the shared reference.
- Full mode: the model trains on the full AnnData (all genes, all perturbations) with Phase 1 splits. After prediction, results are discretised and restricted to the MAGELLAN gene set for evaluation.
- Filtered mode: the model trains on AnnData filtered to the MAGELLAN gene set and perturbations. Results are discretised and evaluated directly.
uv run main.py --config configs/norman_2019_cpa.toml --phase 2Or from Python, with explicit models and modes:
from src.benchmark.phase2 import Phase2Pipeline
from src.benchmark.abc import ComparisonMode
from src.models import get_model
pipeline = Phase2Pipeline.from_config_file("configs/norman_2019_cpa.toml")
results = pipeline.run(
models=[get_model("CPA")],
modes=[ComparisonMode.FULL],
)Add a [phase2] section to your TOML config. For the Norman 2019 CPA comparison:
[phase2]
modes = ["full"]
output_dir = "results/K562_Norman_2019_CPA/phase2"
# Bootstrap CIs over the shared-eval (treatment, gene) pairs. The comparator
# predicts deterministically from a fixed checkpoint, so a test-set bootstrap
# is its only error bar.
[phase2.bootstrap]
enabled = true
n_boot = 2000
seed = 0
[phase2.models]
active = ["CPA"]
[phase2.CPA]
env_name = "cpa"
perturbation_key = "perturbation"
control_group = "control"
pretrained_checkpoint = "external_data/pre-trained-checkpoints/cpa"
skip_preprocessing = true
seed = 42| Output | Location | Description |
|---|---|---|
| Input h5ad | data/phase2/<cell_line>/<model>/<mode>/input.h5ad |
Mode-filtered AnnData with split labels |
| Prepared data | data/phase2/<cell_line>/<model>/<mode>/prepared/ |
Model-specific preprocessed data |
| Checkpoints | data/phase2/<cell_line>/<model>/<mode>/training/ |
Trained model weights |
| Predictions | data/phase2/<cell_line>/<model>/<mode>/predictions/ |
Predicted expression h5ad |
| Metrics | data/phase2/<cell_line>/<model>/<mode>/metrics/ |
Per-model accuracy, F1, MCC, QWK, confusion matrices |
| Comparison | data/phase2/<cell_line>/comparison/run_<ts>_<sha>/ |
Cross-model comparison plots and CSV (per-universe), versioned per run |
Comparison outputs are written into a per-run subfolder named run_<timestamp>_<short-git-sha> so successive runs do not overwrite each other’s plots. Each run folder also contains manifest.json (git SHA, dirty flag, invocation, timestamp), a config.toml snapshot, and a per_model/ subfolder snapshotting each model’s confusion-matrix PNG + metrics CSV. A latest symlink in comparison/ points at the newest run. Large per-model artifacts (input.h5ad, checkpoints) are intentionally not versioned and keep overwriting in place.
Phase 2 produces metrics under two evaluation universes to prevent comparing models on different (treatment, gene) pair sets:
- all: every overlapping pair between the model’s predictions and ground truth.
- magellan_overlap: only the pairs where MAGELLAN also produced a non-NA prediction (loaded from Phase 1’s long-form export).
Output files include the universe in their filenames (e.g. K562_full_all_metrics.csv, K562_full_magellan_overlap_metrics.csv). Validate that all dual-metric artifacts are present with:
python scripts/validate_dual_metrics.py data/K562_Norman_2019_CPACompare MAGELLAN (trained from scratch on K562) against a pre-trained STATE checkpoint (trained on the other 3 Replogle cell lines, zero-shot on K562). Uses the STATE team’s preprocessed data and gene splits from their TOML config.
uv run main.py --config configs/replogle_k562_state.toml --phase 1 2Key differences from a normal Phase 2 run:
- Dataset is
replogle_k562_state(preprocessed CRISPRi, K562 only, fromexternal_data/training/state/replogle.h5ad). - Splits are adopted from STATE’s TOML config (
external_data/pre-trained-checkpoints/state/k562.toml) rather than an AnnData obs column. - Perturbation type is genetic (CRISPRi knockdown, perturbation level 0).
- STATE prediction uses a standalone driver script (
src/models/_state_driver.py) that loads the HuggingFace checkpoint directory with all required artifacts (pert_onehot_map.pt,config.yaml, etc.). skip_preprocessing = truesince the data is already preprocessed.
Comparison models implement the AbstractPerturbationModel ABC in src/benchmark/abc.py, which defines three abstract methods with file-based boundaries (Path in, Path out): prepare_data, train, and predict. The orchestrator runs each model in its own virtualenv via run_in_env() (src/models/_subprocess.py), calling a driver script (e.g. src/models/_cpa_driver.py) inside envs/<name>/bin/python, so there are no import conflicts between models.
To onboard a new model:
- Create
src/models/<name>.pyimplementingAbstractPerturbationModel(prepare_data/train/predict), plussrc/models/_<name>_driver.pyif the model needs an isolated environment. - Register it in
src/models/__init__.py(_register_builtins()). - Add a
[phase2.<NAME>]section to your config TOML. - Add a Makefile
setup-<name>target (and anenvironments/<name>.txtrequirements file) if a new virtualenv is needed.
Two standalone benchmarks quantify how the models scale with network/data size. Both use the Norman 2019 K562 dataset.
A timing-only analysis: it records training wall-clock over a range of DEG-cap network sizes and writes nothing into the accuracy-result directories. Per DEG cap, it times MAGELLAN’s network/spec setup and pure GNN fit, and CPA’s data preparation and pure fit.
# 1. Record training times (MAGELLAN + CPA, CPU, one seed each).
python scripts/time_magellan_cpa_deg.py \
--max-deg-genes 25 50 9999 \
--deg-selection random --deg-selection-seed 42 \
--magellan-seed 0 --cpa-train-seed 1 \
--device cpu --max-epochs 60 \
--out-root data/training_time
# 2. Plot (training time vs network size, log-y).
python scripts/plot_training_time.py \
--timings data/training_time/timings.csv \
--out-dir data/figures/training_time --log-yOutput: data/training_time/timings.csv (one row per (cap, model, stage)) plus per-cap *_meta.json, and the plot under --out-dir.
Measures accuracy as a function of the number of genes for training available to build the network. Both MAGELLAN and CPA see the same gene-restricted data at each cap level; genes are selected at random (fixed seed) so the cap controls network size without confounding on gene frequency.
# 1. Train CPA on gene-restricted h5ads (one-time, CPU).
python scripts/train_cpa_deg_subsets.py \
--max-deg-genes 25 100 400 800 9999 \
--train-seed 1 \
--deg-selection random \
--deg-selection-seed 42 \
--device cpu --max-epochs 60 \
--out-root external_data/deg-scaling-random
# 2. Generate per-cap configs (multi-seed MAGELLAN).
python scripts/make_deg_scaling_configs.py \
--max-deg-genes 25 100 400 800 9999 \
--train-seed 1 \
--deg-selection random \
--deg-selection-seed 42 \
--magellan-seeds 0 7 21 \
--checkpoint-root external_data/deg-scaling-random \
--data-root data/deg_scaling_random \
--out-dir configs/deg_scaling_random
# 3. Run MAGELLAN Phase 1 + Phase 2 per cap level (seeds parallel within each run).
for cfg in configs/deg_scaling_random/norman_2019_cpa_deg*.toml; do
python main.py --config "$cfg" --phase 1 2 --parallel
done
# 4. Plot (one line plot per metric vs network size).
python scripts/plot_data_scaling.py \
--scaling-var deg --max-deg-genes 25 100 400 800 9999 \
--phase2-base data/deg_scaling_random \
--include-full-baseline data/K562_Norman_2019_CPA \
--cell-line K562 --mode full \
--out-dir data/figures/deg_scaling_randomsrc/
benchmark/
abc.py # AbstractPerturbationModel ABC, ComparisonMode, PredictionResult
pipeline.py # Phase1Pipeline orchestrator (data prep + training + evaluation)
phase2.py # Phase2Pipeline orchestrator (comparison model evaluation)
magellan_model.py # MAGELLAN GNN training and prediction wrapper
evaluator.py # Shared evaluation metrics and plotting for all models
checkpoint.py # HuggingFace upload/download for pipeline artifacts
dataset.py # DatasetAdapter: download, cache, inspect perturbation datasets
drug_to_gene.py # PubChem -> ChEMBL -> OpenTargets drug-to-gene mapping
gene_filter.py # Omnipath gene filtering and prioritisation
discretise.py # log2FC + BH FDR -> 0/1/2 discretisation
splitter.py # Treatment-level train/val/test splitting
spec_builder.py # Build MAGELLAN spec CSVs from discretised data
basal_from_passports.py # Auto-fetch basal perturbations from Cell Model Passports API
network_builder.py # Shortest-path network construction and visualisation
models/
__init__.py # Model registry (register_model, get_model, list_models)
_subprocess.py # run_in_env() helper for isolated virtualenv execution
_cpa_driver.py # CPA subprocess driver (prepare/train/predict actions)
_gears_driver.py # GEARS subprocess driver (prepare/predict actions)
_state_driver.py # STATE zero-shot driver (load checkpoint directly, no training dir)
_scgenept_driver.py # scGenePT/scGPT subprocess driver (prepare/predict actions)
cpa.py # CPAWrapper(AbstractPerturbationModel)
gears.py # GEARSWrapper(AbstractPerturbationModel)
scgenept.py # ScGenePTWrapper + ScGPTBaselineWrapper
state.py # STATEWrapper(AbstractPerturbationModel)
scripts/
download_external_data.py # restore external_data/ from HuggingFace
time_magellan_cpa_deg.py # training-time benchmark (MAGELLAN vs CPA)
plot_training_time.py # plot the training-time benchmark
train_cpa_deg_subsets.py # CPA checkpoints for the DEG-scaling benchmark
make_deg_scaling_configs.py # generate per-DEG-cap configs
plot_data_scaling.py # plot the DEG-scaling benchmark
configs/
srivatsan_sciplex3.toml # Srivatsan SciPlex3 chemical perturbation config
norman_2019.toml # Norman 2019 CRISPRa genetic perturbation config
norman_2019_cpa.toml # Norman 2019 vs CPA comparison config
replogle_k562_state.toml # Replogle K562 vs STATE pre-trained checkpoint
environments/ # Pip requirements files for per-model virtualenvs
envs/ # Per-model virtualenvs (created by Makefile, gitignored)
data/ # Downloaded data and pipeline outputs (gitignored)
MAGELLAN/ # MAGELLAN submodule
STATE/ # STATE submodule
GEARS/ # GEARS submodule
cpa/ # CPA submodule
scGenePT/ # scGenePT submodule
PRNet_Comparison/ # Separate PRNet benchmark (reference only, do not import)
Please cite the following paper when using MAGELLAN:
@article{clarke2025magellan,
author = {Clarke, Matthew A. and Barker, Charlie George and Sun, Yuxin and Roumeliotis, Theodoros I. and Choudhary, Jyoti S. and Fisher, Jasmin},
title = {MAGELLAN: Automated Generation of Interpretable Computational Models for Biological Reasoning},
year = {2025},
doi = {10.1101/2025.05.16.653408},
publisher = {Cold Spring Harbor Laboratory},
URL = {https://www.biorxiv.org/content/early/2025/05/19/2025.05.16.653408},
journal = {bioRxiv}
}