| |
| """ |
| B-cell experiment: Adaptive Prompt Selection vs Random Baseline. |
| |
| Uses B cells (lymphocyte of b lineage) as query, other cells as prompt. |
| Compares adaptive prompt selection vs random baseline. |
| Evaluates with cell-eval metrics suite. |
| |
| Usage: |
| python code/adaptive_prompt_selection/run_bcell_experiment.py \ |
| --checkpoint data/tutorial-pred-model/bc_large_aligned.ckpt \ |
| --data data/tutorial-pred-data/openproblems_donor1.h5ad \ |
| --genelist data/tutorial-pred-model/basecount_1000per_15000max.pkl \ |
| --output-dir data/bcell_experiment_results \ |
| --show-progress |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import logging |
| import sys |
| from pathlib import Path |
|
|
| import anndata as ad |
| import numpy as np |
| import pandas as pd |
| from scipy.sparse import issparse |
|
|
| |
| |
| |
| REPO_ROOT = Path(__file__).resolve().parents[2] |
| for _p in [ |
| str(REPO_ROOT / "code" / "stack" / "src"), |
| str(Path(__file__).resolve().parent), |
| str(REPO_ROOT / "code" / "cell-eval" / "src"), |
| ]: |
| if _p not in sys.path: |
| sys.path.insert(0, _p) |
|
|
| from stack.model_loading import load_model_from_checkpoint |
| from adaptive_prompt import adaptive_prompt_selection, run_baseline |
|
|
| LOGGER = logging.getLogger("bcell_experiment") |
|
|
| |
| |
| |
| QUERY_CELL_TYPE_BROAD = "lymphocyte of b lineage" |
| QUERY_CELL_TYPE_FINE = "B cells" |
| CONTROL_NAME = "Dimethyl Sulfoxide" |
| CELL_TYPE_COL = "broad_cell_class" |
| PERTURBATION_COL = "sm_name" |
| CONTROL_COL = "control" |
|
|
|
|
| |
| |
| |
|
|
| def align_genes(adata_pred: ad.AnnData, adata_real: ad.AnnData): |
| """Ensure pred and real have identical var_names in the same order.""" |
| common = adata_pred.var_names.intersection(adata_real.var_names) |
| if len(common) == 0: |
| raise ValueError("No common genes between predicted and real data") |
| LOGGER.info("Gene alignment: pred=%d, real=%d, common=%d", |
| adata_pred.n_vars, adata_real.n_vars, len(common)) |
| return adata_pred[:, common].copy(), adata_real[:, common].copy() |
|
|
|
|
| def run_celleval(adata_pred, adata_real, outdir, label, num_threads=4): |
| """Run cell-eval MetricsEvaluator and return (results, agg_results).""" |
| from cell_eval import MetricsEvaluator |
|
|
| eval_dir = str(Path(outdir) / f"celleval_{label}") |
| evaluator = MetricsEvaluator( |
| adata_pred=adata_pred, |
| adata_real=adata_real, |
| control_pert=CONTROL_NAME, |
| pert_col=PERTURBATION_COL, |
| outdir=eval_dir, |
| allow_discrete=True, |
| num_threads=num_threads, |
| ) |
| results, agg_results = evaluator.compute( |
| profile="full", |
| write_csv=True, |
| break_on_error=False, |
| ) |
| return results, agg_results |
|
|
|
|
| |
| |
| |
|
|
| def build_parser(): |
| p = argparse.ArgumentParser( |
| description="B-cell adaptive prompt experiment with cell-eval evaluation" |
| ) |
| p.add_argument("--checkpoint", required=True, |
| help="Path to Stack-Large-Aligned checkpoint (.ckpt)") |
| p.add_argument("--data", required=True, |
| help="Path to openproblems_donor1.h5ad") |
| p.add_argument("--genelist", required=True, |
| help="Path to gene list pickle") |
| p.add_argument("--output-dir", required=True, |
| help="Output directory") |
| p.add_argument("--drugs", nargs="*", default=None, |
| help="Specific drugs to test (default: all non-DMSO)") |
| |
| p.add_argument("--batch-size", type=int, default=16) |
| p.add_argument("--num-steps", type=int, default=5) |
| p.add_argument("--mode", default="mdm") |
| p.add_argument("--random-seed", type=int, default=42) |
| p.add_argument("--show-progress", action="store_true") |
| |
| p.add_argument("--n-clusters-per-type", type=int, default=5) |
| p.add_argument("--zoom-ratio", type=float, default=0.25) |
| p.add_argument("--top-ratio", type=float, default=0.2) |
| p.add_argument("--temperature", type=float, default=0.06) |
| |
| p.add_argument("--num-threads", type=int, default=4, |
| help="Threads for cell-eval DE computation") |
| p.add_argument("--celleval-profile", default="full", |
| choices=["full", "minimal", "vcc", "de", "anndata"]) |
| return p |
|
|
|
|
| def main(): |
| parsed = build_parser().parse_args() |
| output_dir = Path(parsed.output_dir) |
| output_dir.mkdir(parents=True, exist_ok=True) |
|
|
| logging.basicConfig( |
| level=logging.INFO, |
| format="%(asctime)s %(name)s %(levelname)s %(message)s", |
| handlers=[ |
| logging.StreamHandler(), |
| logging.FileHandler(output_dir / "experiment.log"), |
| ], |
| ) |
|
|
| |
| LOGGER.info("Loading model from %s", parsed.checkpoint) |
| model = load_model_from_checkpoint( |
| parsed.checkpoint, model_class="ICL_FinetunedModel" |
| ) |
| LOGGER.info("Model n_cells=%d", model.n_cells) |
|
|
| |
| LOGGER.info("Loading data from %s", parsed.data) |
| full_adata = ad.read_h5ad(parsed.data) |
| obs = full_adata.obs |
| LOGGER.info("Data shape: %s", full_adata.shape) |
| LOGGER.info("Cell types (broad): %s", |
| obs[CELL_TYPE_COL].value_counts().to_dict()) |
| LOGGER.info("Cell types (fine): %s", |
| obs["cell_type"].value_counts().to_dict()) |
|
|
| |
| all_drugs = sorted( |
| d for d in obs[PERTURBATION_COL].unique() if d != CONTROL_NAME |
| ) |
| drugs = ( |
| [d for d in parsed.drugs if d in all_drugs] |
| if parsed.drugs else all_drugs |
| ) |
| LOGGER.info("Testing %d drugs: %s", len(drugs), drugs) |
|
|
| |
| b_mask = obs["cell_type"] == QUERY_CELL_TYPE_FINE |
| control_B_mask = b_mask & (obs[CONTROL_COL] == True) |
| control_B = full_adata[control_B_mask].copy() |
| LOGGER.info("Control B cells: %d", control_B.n_obs) |
|
|
| |
| adaptive_preds = {} |
| baseline_preds = {} |
| ground_truths = {} |
| bandit_details = {} |
|
|
| for drug in drugs: |
| LOGGER.info("=" * 60) |
| LOGGER.info("Drug: %s", drug) |
| LOGGER.info("=" * 60) |
|
|
| |
| gt_mask = b_mask & (obs[PERTURBATION_COL] == drug) |
| if gt_mask.sum() == 0: |
| LOGGER.warning("No ground truth B cells for %s, skipping", drug) |
| continue |
| LOGGER.info("Ground truth B cells: %d", gt_mask.sum()) |
| ground_truths[drug] = full_adata[gt_mask].copy() |
|
|
| |
| try: |
| LOGGER.info("[Adaptive] Starting...") |
| pred_a, details = adaptive_prompt_selection( |
| model=model, |
| full_adata=full_adata, |
| genelist_path=parsed.genelist, |
| query_cell_type=QUERY_CELL_TYPE_BROAD, |
| perturbation=drug, |
| control_name=CONTROL_NAME, |
| cell_type_col=CELL_TYPE_COL, |
| perturbation_col=PERTURBATION_COL, |
| control_col=CONTROL_COL, |
| n_clusters_per_type=parsed.n_clusters_per_type, |
| zoom_ratio=parsed.zoom_ratio, |
| top_ratio=parsed.top_ratio, |
| temperature=parsed.temperature, |
| batch_size=parsed.batch_size, |
| num_steps=parsed.num_steps, |
| mode=parsed.mode, |
| random_seed=parsed.random_seed, |
| show_progress=parsed.show_progress, |
| ) |
| pred_a.obs[PERTURBATION_COL] = drug |
| pred_a.obs[CONTROL_COL] = False |
| adaptive_preds[drug] = pred_a |
| bandit_details[drug] = details |
| LOGGER.info("[Adaptive] Done: %d cells", pred_a.n_obs) |
| except Exception as e: |
| LOGGER.error("[Adaptive] Failed: %s", e, exc_info=True) |
|
|
| |
| try: |
| LOGGER.info("[Baseline] Starting...") |
| ctx_mask = (~b_mask) & (obs[PERTURBATION_COL] == drug) |
| context = full_adata[ctx_mask].copy() |
| LOGGER.info("[Baseline] Context cells (non-B, %s): %d", |
| drug, context.n_obs) |
|
|
| pred_b = run_baseline( |
| model=model, |
| context_adata=context, |
| query_adata=control_B.copy(), |
| genelist_path=parsed.genelist, |
| batch_size=parsed.batch_size, |
| num_steps=parsed.num_steps, |
| mode=parsed.mode, |
| random_seed=parsed.random_seed, |
| show_progress=parsed.show_progress, |
| ) |
| pred_b.obs[PERTURBATION_COL] = drug |
| pred_b.obs[CONTROL_COL] = False |
| baseline_preds[drug] = pred_b |
| LOGGER.info("[Baseline] Done: %d cells", pred_b.n_obs) |
| except Exception as e: |
| LOGGER.error("[Baseline] Failed: %s", e, exc_info=True) |
|
|
| |
| ok_drugs = sorted( |
| set(adaptive_preds) & set(baseline_preds) & set(ground_truths) |
| ) |
| LOGGER.info("Drugs with both methods OK: %d / %d: %s", |
| len(ok_drugs), len(drugs), ok_drugs) |
| if not ok_drugs: |
| LOGGER.error("No drugs succeeded for both methods, exiting") |
| return |
|
|
| |
| for drug, det in bandit_details.items(): |
| safe = drug.replace(" ", "_") |
| with open(output_dir / f"bandit_{safe}.json", "w") as f: |
| json.dump(det, f, indent=2, default=str) |
|
|
| |
| LOGGER.info("Assembling combined AnnData for cell-eval...") |
|
|
| real_combined = ad.concat( |
| [control_B] + [ground_truths[d] for d in ok_drugs], join="inner" |
| ) |
| adaptive_combined = ad.concat( |
| [control_B] + [adaptive_preds[d] for d in ok_drugs], join="inner" |
| ) |
| baseline_combined = ad.concat( |
| [control_B] + [baseline_preds[d] for d in ok_drugs], join="inner" |
| ) |
|
|
| LOGGER.info("Real: %d cells x %d genes, perts=%s", |
| real_combined.n_obs, real_combined.n_vars, |
| real_combined.obs[PERTURBATION_COL].value_counts().to_dict()) |
| LOGGER.info("Adaptive: %d cells x %d genes", |
| adaptive_combined.n_obs, adaptive_combined.n_vars) |
| LOGGER.info("Baseline: %d cells x %d genes", |
| baseline_combined.n_obs, baseline_combined.n_vars) |
|
|
| |
| adaptive_al, real_for_a = align_genes(adaptive_combined, real_combined) |
| baseline_al, real_for_b = align_genes(baseline_combined, real_combined) |
|
|
| |
| adaptive_al.write_h5ad(output_dir / "adaptive_combined.h5ad") |
| baseline_al.write_h5ad(output_dir / "baseline_combined.h5ad") |
| real_for_a.write_h5ad(output_dir / "real_combined.h5ad") |
|
|
| |
| agg_a, agg_b = None, None |
|
|
| LOGGER.info("Running cell-eval for ADAPTIVE...") |
| try: |
| _, agg_a = run_celleval( |
| adaptive_al, real_for_a, output_dir, "adaptive", |
| num_threads=parsed.num_threads, |
| ) |
| except Exception as e: |
| LOGGER.error("cell-eval (adaptive) failed: %s", e, exc_info=True) |
|
|
| LOGGER.info("Running cell-eval for BASELINE...") |
| try: |
| _, agg_b = run_celleval( |
| baseline_al, real_for_b, output_dir, "baseline", |
| num_threads=parsed.num_threads, |
| ) |
| except Exception as e: |
| LOGGER.error("cell-eval (baseline) failed: %s", e, exc_info=True) |
|
|
| |
| print("\n" + "=" * 70) |
| print("CELL-EVAL RESULTS") |
| print("=" * 70) |
|
|
| if agg_a is not None: |
| print("\n--- Adaptive (aggregated) ---") |
| print(agg_a) |
| agg_a.write_csv(str(output_dir / "agg_adaptive.csv")) |
|
|
| if agg_b is not None: |
| print("\n--- Baseline (aggregated) ---") |
| print(agg_b) |
| agg_b.write_csv(str(output_dir / "agg_baseline.csv")) |
|
|
| if agg_a is not None and agg_b is not None: |
| |
| import polars as pl |
| try: |
| mean_a = agg_a.filter(pl.col("statistic") == "mean").drop("statistic") |
| mean_b = agg_b.filter(pl.col("statistic") == "mean").drop("statistic") |
| |
| a_long = mean_a.unpivot(variable_name="metric", value_name="adaptive") |
| b_long = mean_b.unpivot(variable_name="metric", value_name="baseline") |
| comparison = a_long.join(b_long, on="metric") |
| comparison = comparison.with_columns( |
| (pl.col("adaptive") - pl.col("baseline")).alias("diff") |
| ) |
| print("\n--- Comparison (mean across perturbations) ---") |
| print(comparison) |
| comparison.write_csv(str(output_dir / "comparison_mean.csv")) |
| except Exception as e: |
| LOGGER.warning("Could not build comparison table: %s", e) |
|
|
| LOGGER.info("Experiment complete. Results saved to %s", output_dir) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|