Download predict.py from udgamlabs/biocell: direct link, hf CLI and curl.
- Browser
- Download file 28.2 kB
-
https://huggingface.co/udgamlabs/biocell/resolve/main/predict.py
- Command line
-
hf download hf://udgamlabs/biocell/predict.py
-
curl -L -o predict.py https://huggingface.co/udgamlabs/biocell/resolve/main/predict.py
28.2 kB
| """Virtual-cell model (UdgamCell v2.1b): standalone inference SDK and CLI. Licence: see LICENSE; data files: CC BY 4.0 (see CREDITS.md). | |
| Features: | |
| - Loads in about 1 second on a laptop CPU; one prediction takes 20 to 40 ms with all three copies. | |
| - Automatically loads UdgamCell-v2.1 (modality-aware CRISPRi/CRISPRa + zero-shot calibrated) | |
| OR backward-compatible UdgamCell-v2 checkpoints. | |
| - Supports 5 built-in human cell lines (K562, RPE1, Jurkat, H1 hESC, zero-shot HepG2) | |
| PLUS "Bring Your Own Cells" (`perturb_custom_cells()` / CSV or AnnData .h5ad upload)! | |
| - Computes real Gene Ontology (GO) Cellular System gauges (10 plain-English cell departments), | |
| specific GO Biological Process enrichment (for researchers), 2-gene Synergy vs Additive breakdown, | |
| and an automatic Plain-English "What Happens to This Cell?" explanation! | |
| Example: | |
| from predict import UdgamVirtualCell | |
| vc = UdgamVirtualCell.load("v2/release_bundle") | |
| out = vc.perturb(cell_line="rpe1", genes=["PSMA3"], modality="knockdown") | |
| print(out["plain_summary"]) | |
| """ | |
| import argparse, gzip, io, json, math, os, sys | |
| import numpy as np | |
| import torch | |
| HERE = os.path.dirname(os.path.abspath(__file__)) | |
| sys.path.insert(0, HERE) | |
| from models import SetTransitionTransformer, SetTransitionTransformerV21 | |
| LOG1P_MAX = float(np.log1p(1e4)) | |
| SUPPORTED_LINES = ("k562", "rpe1", "jurkat", "h1", "hepg2") | |
| CELL_LINE_META = { | |
| "k562": { | |
| "short": "Leukaemia cell line (K562)", | |
| "sci": "K562 (chronic myeloid leukaemia)", | |
| "emoji": "", | |
| "desc": "Human bone-marrow blood cancer cells — the most widely studied model in CRISPR genetics.", | |
| "zero_shot": False, | |
| }, | |
| "rpe1": { | |
| "short": "Retina cell line (RPE1)", | |
| "sci": "RPE1 (retinal pigment epithelium, hTERT-immortalised)", | |
| "emoji": "", | |
| "desc": "Non-cancerous human eye cells — great for seeing how normal healthy human cells react.", | |
| "zero_shot": False, | |
| }, | |
| "jurkat": { | |
| "short": "T-cell line (Jurkat)", | |
| "sci": "Jurkat (T lymphocyte)", | |
| "emoji": "", | |
| "desc": "White blood cells from the human immune system.", | |
| "zero_shot": False, | |
| }, | |
| "h1": { | |
| "short": "Stem cell line (H1)", | |
| "sci": "H1 (human embryonic stem cells)", | |
| "emoji": "", | |
| "desc": "Early human embryonic stem cells capable of turning into any tissue in the body.", | |
| "zero_shot": False, | |
| }, | |
| "hepg2": { | |
| "short": "Liver cell line (HepG2), not in training", | |
| "sci": "HepG2 (hepatocellular carcinoma), not in training", | |
| "emoji": "", | |
| "desc": "Human liver cells that the AI NEVER saw during training — a live zero-shot generalization test!", | |
| "zero_shot": True, | |
| }, | |
| } | |
| class UdgamVirtualCell: | |
| def __init__(self, models, version, hvg_syms, prior_map, train_norm, train_syms, | |
| line_data, train_line_names, atlas=None, device="cpu"): | |
| self.models = models | |
| self.version = version | |
| self.hvg_syms = list(hvg_syms) | |
| self.hvg_index = {g: i for i, g in enumerate(self.hvg_syms)} | |
| self.prior_map = prior_map | |
| self.d_prior = len(next(iter(prior_map.values()))) | |
| self.zero_vec = np.zeros(self.d_prior, dtype=np.float32) | |
| self.train_norm = train_norm | |
| self.train_syms = list(train_syms) | |
| self.line_data = line_data | |
| self.train_line_names = list(train_line_names) | |
| self.train_ctx_means = [line_data[n]["ctx_mean"] for n in self.train_line_names if n in line_data] | |
| self.atlas = atlas or {"systems": [], "go_bp_terms": [], "gene_info": {}} | |
| self.gene_info = self.atlas.get("gene_info", {}) | |
| self.device = torch.device(device) | |
| # Precompute numpy index arrays for ultra-fast pathway enrichment (<3 ms) | |
| self._sys_idxs = [np.array(s["hvg_indices"], dtype=np.int64) for s in self.atlas.get("systems", [])] | |
| self._bp_idxs = [np.array(t["hvg_indices"], dtype=np.int64) for t in self.atlas.get("go_bp_terms", [])] | |
| def load(cls, model_dir, device=None): | |
| if device is None: | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| dev = torch.device(device) | |
| # Prefer v2.1 pack if present, else fallback seamlessly to v2.0 | |
| p_rel = os.path.join(model_dir, "inference_pack.npz") # release name | |
| p21 = os.path.join(model_dir, "udgamcell_v21_inference_pack.npz") | |
| if os.path.exists(p_rel): | |
| p21 = p_rel | |
| p20 = os.path.join(model_dir, "udgamcell_v2_inference_pack.npz") | |
| if os.path.exists(p21): | |
| pack_path, version, prefix = p21, "2.1", "udgamcell_v21" | |
| elif os.path.exists(p20): | |
| pack_path, version, prefix = p20, "2.0", "udgamcell_v2" | |
| else: | |
| raise FileNotFoundError(f"No udgamcell inference pack found in {model_dir}") | |
| pack = np.load(pack_path, allow_pickle=False) | |
| hvg_syms = [str(x) for x in pack["hvg_syms"]] | |
| p_syms = [str(x) for x in pack["prior_syms"]] | |
| p_X = pack["prior_X_f16"].astype(np.float32) | |
| prior_map = dict(zip(p_syms, p_X)) | |
| train_norm = pack["train_prior_norm_f16"].astype(np.float32) | |
| train_syms = [str(x) for x in pack["train_syms"]] if "train_syms" in pack else [f"train_{i}" for i in range(len(train_norm))] | |
| train_line_names = [str(x) for x in pack["train_line_names"]] if "train_line_names" in pack else ["k562", "rpe1", "jurkat", "h1"] | |
| line_data = {} | |
| for ln in SUPPORTED_LINES: | |
| if f"{ln}_ctx_mean" in pack: | |
| line_data[ln] = { | |
| "ctx_mean": pack[f"{ln}_ctx_mean"].astype(np.float32), | |
| "ctx_std": pack[f"{ln}_ctx_std"].astype(np.float32), | |
| "ctrl_cells": pack[f"{ln}_ctrl_demo_f16"].astype(np.float32), | |
| } | |
| models = [] | |
| cfg_path = os.path.join(model_dir, "config.json") | |
| cfg = json.load(open(cfg_path)) if os.path.exists(cfg_path) else None | |
| for sd in (0, 1, 2): | |
| st = os.path.join(model_dir, f"model_seed{sd}.safetensors") | |
| p = os.path.join(model_dir, f"{prefix}_s{sd}.pt") | |
| if cfg is not None and os.path.exists(st): | |
| # Release format: plain tensors in safetensors plus config.json; no pickled code is run. | |
| from safetensors.torch import load_file | |
| ck = {"state_dict": load_file(st, device=str(dev)), "arch": cfg} | |
| elif os.path.exists(p): | |
| ck = torch.load(p, map_location=dev, weights_only=True) | |
| else: | |
| continue | |
| arch = ck["arch"] | |
| if arch.get("version") == "2.1" or version == "2.1": | |
| m = SetTransitionTransformerV21( | |
| n_genes=arch["n_genes"], d_prior=arch["d_prior"], | |
| d_model=arch["d_model"], n_layers=arch["n_layers"], n_heads=arch["n_heads"], | |
| d_ctx=arch.get("d_ctx", 64), dropout=0.0, ctx_dropout=0.0 | |
| ).to(dev) | |
| else: | |
| m = SetTransitionTransformer( | |
| n_genes=arch["n_genes"], d_prior=arch["d_prior"], | |
| d_model=arch["d_model"], n_layers=arch["n_layers"], n_heads=arch["n_heads"], dropout=0.0 | |
| ).to(dev) | |
| m.load_state_dict(ck["state_dict"], strict=True) | |
| m.eval() | |
| models.append(m) | |
| assert models, f"No {prefix}_s*.pt checkpoints found in {model_dir}" | |
| # Plain-English gene atlas (CC BY 4.0; see CREDITS.md), if present | |
| atlas = None | |
| atlas_p = os.path.join(model_dir, "bio_atlas.json.gz") | |
| if os.path.exists(atlas_p): | |
| with gzip.open(atlas_p, "rt", encoding="utf-8") as f: | |
| atlas = json.load(f) | |
| return cls(models, version, hvg_syms, prior_map, train_norm, train_syms, | |
| line_data, train_line_names, atlas=atlas, device=device) | |
| def available_genes(self): | |
| return sorted(self.prior_map.keys()) | |
| def gene_card(self, sym): | |
| s = sym.upper() | |
| info = self.gene_info.get(s, {}) | |
| return { | |
| "gene": s, | |
| "role": info.get("short", ""), | |
| "summary": info.get("summary", ""), | |
| "systems": info.get("systems", []), | |
| "in_priors": s in self.prior_map, | |
| } | |
| def search_genes(self, query, limit=12): | |
| """Instant gene search by symbol OR plain-English keyword (e.g. 'ribosome', 'cancer', 'MYC').""" | |
| q = (query or "").strip().lower() | |
| if not q: | |
| return [] | |
| exact, prefix, desc_hits = [], [], [] | |
| for sym in self.prior_map: | |
| sl = sym.lower() | |
| info = self.gene_info.get(sym, {}) | |
| short = info.get("short", "") | |
| if sl == q: | |
| exact.append((sym, short, info.get("systems", []))) | |
| elif sl.startswith(q): | |
| prefix.append((sym, short, info.get("systems", []))) | |
| elif q in short.lower() or any(q in s.lower() for s in info.get("systems", [])): | |
| desc_hits.append((sym, short, info.get("systems", []))) | |
| prefix.sort(key=lambda x: (len(x[0]), x[0])) | |
| out = (exact + prefix + desc_hits)[:limit] | |
| return [{"gene": g, "role": r, "systems": sy} for g, r, sy in out] | |
| def _compute_ctx_scale(self, ctx_mean, is_known_line=False): | |
| if is_known_line or not self.train_ctx_means: | |
| return 1.0, 1.0 | |
| q = ctx_mean / (np.linalg.norm(ctx_mean) + 1e-8) | |
| sims = [float(np.dot(q, tc / (np.linalg.norm(tc) + 1e-8))) for tc in self.train_ctx_means] | |
| max_sim = max(sims) | |
| scale = float(np.clip((max_sim - 0.72) / 0.24, 0.0, 1.0)) | |
| return scale, max_sim | |
| def _run_models(self, X0, ctx_mean, ctx_std, e1_np, e2_np, is_pair, modality_id=0, ctx_scale=1.0): | |
| cm = torch.tensor(ctx_mean, dtype=torch.float32, device=self.device)[None] | |
| cs = torch.tensor(ctx_std, dtype=torch.float32, device=self.device)[None] | |
| e1 = torch.tensor(e1_np, dtype=torch.float32, device=self.device)[None] | |
| e2 = torch.tensor(e2_np, dtype=torch.float32, device=self.device)[None] | |
| ip = torch.tensor([[float(is_pair)]], dtype=torch.float32, device=self.device) | |
| mod_t = torch.tensor([int(modality_id)], dtype=torch.long, device=self.device) | |
| seed_preds = [] | |
| with torch.no_grad(): | |
| for m in self.models: | |
| chunks = [] | |
| for i in range(0, len(X0), 32): | |
| xb = torch.tensor(X0[i:i + 32], dtype=torch.float32, device=self.device)[None] | |
| if isinstance(m, SetTransitionTransformerV21): | |
| yb = m(xb, cm, cs, e1, e2, ip, modality=mod_t, clamp_nonneg=True, ctx_scale=ctx_scale)[0].cpu().numpy() | |
| else: | |
| yb = m(xb, cm, cs, e1, e2, ip, clamp_nonneg=True)[0].cpu().numpy() | |
| chunks.append(yb) | |
| seed_preds.append(np.clip(np.concatenate(chunks, axis=0), 0.0, LOG1P_MAX)) | |
| stack = np.stack(seed_preds, axis=0) # (S, N, G) | |
| pred_cells = stack.mean(axis=0) | |
| seed_spread = float(stack.mean(axis=1).std(axis=0).mean()) if len(seed_preds) > 1 else 0.0 | |
| return pred_cells, seed_spread | |
| def _score_pathways(self, delta): | |
| """Compute z-scored Cellular System gauges + specific GO Biological Process enrichment.""" | |
| mu = float(delta.mean()) | |
| sd = float(delta.std()) + 1e-6 | |
| systems_res = [] | |
| for s_def, idxs in zip(self.atlas.get("systems", []), self._sys_idxs): | |
| if len(idxs) < 5: | |
| continue | |
| vals = delta[idxs] | |
| m_val = float(vals.mean()) | |
| z = (m_val - mu) / (sd / math.sqrt(len(idxs))) | |
| # Top 3 driving genes inside this cellular system | |
| if z >= 0: | |
| ord_i = idxs[np.argsort(-vals)[:3]] | |
| else: | |
| ord_i = idxs[np.argsort(vals)[:3]] | |
| drivers = [{"gene": self.hvg_syms[i], "delta": round(float(delta[i]), 3)} for i in ord_i] | |
| abs_z = abs(z) | |
| if abs_z >= 3.0: | |
| strength = "Strongly Activated" if z > 0 else "Strongly Slowed Down" | |
| elif abs_z >= 1.6: | |
| strength = "Moderately Up" if z > 0 else "Moderately Down" | |
| else: | |
| strength = "Mostly Unchanged" | |
| systems_res.append({ | |
| "id": s_def["id"], | |
| "name": s_def["name"], | |
| "sci_name": s_def["sci_name"], | |
| "icon": "", | |
| "plain_desc": s_def["plain_desc"], | |
| "mean_delta": round(m_val, 4), | |
| "z_score": round(float(z), 2), | |
| "direction": "up" if z > 0.3 else ("down" if z < -0.3 else "flat"), | |
| "status_label": strength, | |
| "n_genes": int(len(idxs)), | |
| "drivers": drivers, | |
| }) | |
| systems_res.sort(key=lambda x: -abs(x["z_score"])) | |
| # Specific GO Biological Process terms (Researcher Mode) | |
| bp_up, bp_dn = [], [] | |
| for t_def, idxs in zip(self.atlas.get("go_bp_terms", []), self._bp_idxs): | |
| vals = delta[idxs] | |
| m_val = float(vals.mean()) | |
| z = (m_val - mu) / (sd / math.sqrt(len(idxs))) | |
| entry = { | |
| "go_id": t_def["id"], "name": t_def["name"], | |
| "z_score": round(float(z), 2), "mean_delta": round(m_val, 4), "n_genes": int(len(idxs)), | |
| } | |
| if z > 1.5: | |
| bp_up.append(entry) | |
| elif z < -1.5: | |
| bp_dn.append(entry) | |
| bp_up.sort(key=lambda x: -x["z_score"]) | |
| bp_dn.sort(key=lambda x: x["z_score"]) | |
| return systems_res, {"up": bp_up[:6], "down": bp_dn[:6]} | |
| def _build_plain_summary(self, cell_label, genes, modality, effect_rms, conf_tier, conf_score, | |
| systems, top_up, top_dn, zero_shot=False, synergy_info=None): | |
| verb = "turn ON (activate)" if modality == "activate" else "turn OFF (knock down)" | |
| gene_bits = [] | |
| for g in genes: | |
| role = self.gene_info.get(g, {}).get("short", "") | |
| gene_bits.append(f"{g} ({role})" if role else g) | |
| gene_txt = " and ".join(gene_bits) | |
| if effect_rms >= 0.18: | |
| mag = "a large change" | |
| elif effect_rms >= 0.08: | |
| mag = "a clear change" | |
| elif effect_rms >= 0.035: | |
| mag = "a small change" | |
| else: | |
| mag = "very little change" | |
| up_sys = [s for s in systems if s["z_score"] >= 1.8][:2] | |
| dn_sys = [s for s in systems if s["z_score"] <= -1.8][:2] | |
| parts = [f"When you {verb} {gene_txt} in {cell_label}, the model predicts {mag}."] | |
| if up_sys: | |
| up_str = " and ".join(f"{s['name']} ({s['sci_name']})" for s in up_sys) | |
| parts.append(f"The cell ramps up {up_str} (led by {', '.join(g['gene'] for g in top_up[:3])}).") | |
| if dn_sys: | |
| dn_str = " and ".join(f"{s['name']} ({s['sci_name']})" for s in dn_sys) | |
| parts.append(f"At the same time, it dials back {dn_str} (led by {', '.join(g['gene'] for g in top_dn[:3])}).") | |
| if not up_sys and not dn_sys: | |
| parts.append(f"Top shifted genes are {', '.join(g['gene'] for g in top_up[:2])} (up) and {', '.join(g['gene'] for g in top_dn[:2])} (down), without a single whole-organelle alarm.") | |
| if synergy_info is not None: | |
| pct = synergy_info["non_additive_pct"] | |
| parts.append("For two genes, compare with each gene alone; `synergy` lists the genes that differ most from adding the two single-gene effects.") | |
| if zero_shot: | |
| parts.append("This cell type was never in training. Expect larger errors in the size of changes.") | |
| parts.append(f"Familiarity: {conf_tier.lower()} (how close this gene and cell type are to what the model has seen; not a probability of being right).") | |
| return " ".join(parts) | |
| def _assemble_result(self, cell_line_id, cell_label, X0, ctx_mean, ctx_std, genes, modality, | |
| top_k=15, zero_shot=False, is_known_line=True, custom_meta=None): | |
| mod_norm = "activate" if str(modality).lower() in ("activate", "crispra", "on", "1") else "knockdown" | |
| mod_id = 1 if mod_norm == "activate" else 0 | |
| missing = [g for g in genes if g not in self.prior_map] | |
| g1 = genes[0] | |
| g2 = genes[1] if len(genes) == 2 else None | |
| is_pair = 1.0 if g2 else 0.0 | |
| e1_np = self.prior_map.get(g1, self.zero_vec) | |
| e2_np = self.prior_map.get(g2, self.zero_vec) if g2 else self.zero_vec | |
| # Prior familiarity + nearest training genes | |
| q = e1_np if not g2 else (e1_np + e2_np) | |
| qn = q / (np.linalg.norm(q) + 1e-8) | |
| sims = self.train_norm @ qn | |
| fam = float(np.max(sims)) if len(sims) else 0.0 | |
| top_n_idx = np.argsort(-sims)[:3] if len(sims) else [] | |
| nearest_train = [{"gene": self.train_syms[i], "sim": round(float(sims[i]), 3)} for i in top_n_idx] | |
| ctx_scale, line_sim = self._compute_ctx_scale(ctx_mean, is_known_line=is_known_line) | |
| pred_cells, seed_spread = self._run_models( | |
| X0, ctx_mean, ctx_std, e1_np, e2_np, is_pair, modality_id=mod_id, ctx_scale=ctx_scale | |
| ) | |
| ctrl_mean = X0.mean(axis=0) | |
| pred_mean = pred_cells.mean(axis=0) | |
| delta = pred_mean - ctrl_mean | |
| # If 2 genes, also compute single-gene additive superposition to show Synergy (1 + 1 != 2)! | |
| synergy_info = None | |
| if g2 is not None: | |
| p1, _ = self._run_models(X0, ctx_mean, ctx_std, e1_np, self.zero_vec, 0.0, modality_id=mod_id, ctx_scale=ctx_scale) | |
| p2, _ = self._run_models(X0, ctx_mean, ctx_std, e2_np, self.zero_vec, 0.0, modality_id=mod_id, ctx_scale=ctx_scale) | |
| d1 = p1.mean(axis=0) - ctrl_mean | |
| d2 = p2.mean(axis=0) - ctrl_mean | |
| d_add = d1 + d2 | |
| d_syn = delta - d_add | |
| syn_rms = float(np.sqrt((d_syn ** 2).mean())) | |
| tot_rms = float(np.sqrt((delta ** 2).mean())) + 1e-8 | |
| top_syn_idx = np.argsort(-np.abs(d_syn))[:6] | |
| synergy_info = { | |
| "non_additive_pct": round(float(100.0 * min(syn_rms / tot_rms, 1.0)), 1), | |
| "synergy_rms": round(syn_rms, 4), | |
| "top_synergy_genes": [ | |
| { | |
| "gene": self.hvg_syms[i], | |
| "role": self.gene_info.get(self.hvg_syms[i], {}).get("short", ""), | |
| "additive_delta": round(float(d_add[i]), 4), | |
| "predicted_delta": round(float(delta[i]), 4), | |
| "synergy_gap": round(float(d_syn[i]), 4), | |
| } | |
| for i in top_syn_idx | |
| ], | |
| } | |
| if missing: | |
| conf_score = 0.05 | |
| conf_tier = "Low" | |
| conf_why = f"Gene(s) {', '.join(missing)} were not found in our biological reference maps." | |
| else: | |
| conf_score = float(np.clip((fam - 0.15) / 0.60, 0.05, 0.98)) | |
| if zero_shot: | |
| conf_score = min(conf_score, 0.72) | |
| conf_tier = "High" if conf_score >= 0.65 else ("Medium" if conf_score >= 0.35 else "Low") | |
| near_txt = ", ".join(x["gene"] for x in nearest_train[:3] if not x["gene"].startswith("train_")) | |
| conf_why = ( | |
| f"Close biological match to training genes ({near_txt}) with tight 3-model agreement." | |
| if conf_tier == "High" and near_txt else | |
| ("Moderate biological overlap with training genes — good for ranking hypotheses, treat exact size cautiously." | |
| if conf_tier == "Medium" else | |
| "Far from genes seen in training — treat as a rough directional guess only.") | |
| ) | |
| def fmt_gene(i): | |
| sym = self.hvg_syms[i] | |
| d_val = float(delta[i]) | |
| fc = float(np.exp(np.clip(d_val, -4.0, 4.0))) | |
| return { | |
| "gene": sym, | |
| "role": self.gene_info.get(sym, {}).get("short", ""), | |
| "systems": self.gene_info.get(sym, {}).get("systems", []), | |
| "delta": round(d_val, 4), | |
| "fold_change": round(fc, 2), | |
| "ctrl": round(float(ctrl_mean[i]), 3), | |
| "pred": round(float(pred_mean[i]), 3), | |
| } | |
| order_up = np.argsort(-delta)[:top_k] | |
| order_dn = np.argsort(delta)[:top_k] | |
| top_up = [fmt_gene(i) for i in order_up] | |
| top_dn = [fmt_gene(i) for i in order_dn] | |
| systems, go_bp = self._score_pathways(delta) | |
| eff_rms = float(np.sqrt((delta ** 2).mean())) | |
| plain_summary = self._build_plain_summary( | |
| cell_label, genes, mod_norm, eff_rms, conf_tier, conf_score, | |
| systems, top_up, top_dn, zero_shot=zero_shot, synergy_info=synergy_info | |
| ) | |
| return { | |
| "model_version": self.version, | |
| "cell_line": cell_line_id, | |
| "cell_line_label": cell_label, | |
| "zero_shot_cell_line": zero_shot, | |
| "cell_line_similarity": round(line_sim, 4), | |
| "ctx_scale_used": round(ctx_scale, 3), | |
| "modality": mod_norm, | |
| "modality_label": "Turn ON (CRISPRa Activation)" if mod_norm == "activate" else "Turn OFF (CRISPRi Knockdown)", | |
| "genes": genes, | |
| "gene_cards": [self.gene_card(g) for g in genes], | |
| "missing_priors": missing, | |
| "n_cells": int(len(pred_cells)), | |
| "effect_rms": round(eff_rms, 4), | |
| "plain_summary": plain_summary, | |
| "systems": systems, | |
| "go_enrichment": go_bp, | |
| "synergy": synergy_info, | |
| "confidence": { | |
| "score": round(conf_score, 3), | |
| "tier": conf_tier, | |
| "why": conf_why, | |
| "prior_familiarity": round(fam, 4), | |
| "ensemble_spread": round(seed_spread, 5), | |
| "nearest_train_genes": nearest_train, | |
| }, | |
| "top_up": top_up, | |
| "top_down": top_dn, | |
| "custom_upload": custom_meta, | |
| "pred_cells": pred_cells, | |
| "ctrl_cells": X0, | |
| "delta_all": delta, | |
| } | |
| def perturb(self, cell_line="k562", genes=("GATA1",), modality="knockdown", n_cells=64, top_k=15): | |
| ln = cell_line.lower() | |
| if ln not in self.line_data: | |
| raise ValueError(f"Unknown cell_line '{cell_line}'. Choose from {list(self.line_data)}") | |
| genes = [g.strip().upper() for g in genes if g.strip()] | |
| if not (1 <= len(genes) <= 2): | |
| raise ValueError("Provide 1 or 2 target gene symbols.") | |
| ld = self.line_data[ln] | |
| X0 = ld["ctrl_cells"][:min(n_cells, len(ld["ctrl_cells"]))] | |
| meta = CELL_LINE_META.get(ln, {"short": ln.upper(), "zero_shot": False}) | |
| is_known = ln in self.train_line_names | |
| return self._assemble_result( | |
| ln, meta['short'], X0, ld["ctx_mean"], ld["ctx_std"], | |
| genes, modality=modality, top_k=top_k, zero_shot=(not is_known), is_known_line=is_known | |
| ) | |
| def perturb_custom_cells(self, cell_matrix, gene_names, genes=("GATA1",), modality="knockdown", | |
| label="Your Uploaded Cells", n_cells=64, top_k=15, auto_log1p=True): | |
| """Bring Your Own Cells: run UdgamCell on any user-supplied control matrix (N_cells x N_genes). | |
| Aligns uploaded gene columns to the 3,000 shared HVGs, auto-normalizes raw counts to log1p(CP10K) | |
| if values exceed log1p scale, and applies automatic zero-shot familiarity calibration.""" | |
| genes = [g.strip().upper() for g in genes if g.strip()] | |
| if not (1 <= len(genes) <= 2): | |
| raise ValueError("Provide 1 or 2 target gene symbols.") | |
| X_in = np.asarray(cell_matrix, dtype=np.float32) | |
| if X_in.ndim == 1: | |
| X_in = X_in[None, :] | |
| g_in = [str(g).strip().upper() for g in gene_names] | |
| if X_in.shape[1] != len(g_in): | |
| raise ValueError(f"Matrix has {X_in.shape[1]} columns but {len(g_in)} gene names.") | |
| # Auto-detect raw counts vs already log1p-normalized expression | |
| normalized_note = "Detected log1p-normalized input" | |
| if auto_log1p and float(np.nanmax(X_in)) > 20.0: | |
| row_sums = np.maximum(X_in.sum(axis=1, keepdims=True), 1.0) | |
| X_in = np.log1p(X_in / row_sums * 1e4) | |
| normalized_note = "Auto-normalized raw counts to log1p(CP10K)" | |
| # Map uploaded genes onto the 3,000 model HVGs | |
| col_map = {g: i for i, g in enumerate(g_in)} | |
| X_aligned = np.zeros((len(X_in), len(self.hvg_syms)), dtype=np.float32) | |
| matched = 0 | |
| for j, hvg in enumerate(self.hvg_syms): | |
| if hvg in col_map: | |
| X_aligned[:, j] = X_in[:, col_map[hvg]] | |
| matched += 1 | |
| if matched < 50: | |
| raise ValueError(f"Only {matched} of your genes matched the 3,000 model genes (need >= 50). Check gene symbols (e.g. GATA1, ACTB, MYC).") | |
| X_aligned = np.clip(np.nan_to_num(X_aligned, nan=0.0), 0.0, LOG1P_MAX) | |
| ctx_mean = X_aligned.mean(axis=0) | |
| ctx_std = X_aligned.std(axis=0) | |
| # If user uploaded only 1 pseudobulk row, replicate with slight realistic noise or keep single row | |
| if len(X_aligned) > n_cells: | |
| rng = np.random.default_rng(0) | |
| X0 = X_aligned[rng.choice(len(X_aligned), size=n_cells, replace=False)] | |
| else: | |
| X0 = X_aligned | |
| cmeta = { | |
| "label": label, | |
| "n_uploaded_cells": int(len(X_in)), | |
| "n_uploaded_genes": int(len(g_in)), | |
| "matched_hvgs": int(matched), | |
| "coverage_pct": round(100.0 * matched / len(self.hvg_syms), 1), | |
| "normalization": normalized_note, | |
| } | |
| return self._assemble_result( | |
| "custom", label, X0, ctx_mean, ctx_std, | |
| genes, modality=modality, top_k=top_k, zero_shot=True, is_known_line=False, custom_meta=cmeta | |
| ) | |
| def perturb_csv_text(self, csv_text, genes=("GATA1",), modality="knockdown", label="Uploaded CSV Cells", top_k=15): | |
| """Parse a CSV (rows = cells, columns = gene symbols; optional first ID column) and run prediction.""" | |
| import csv | |
| rows = list(csv.reader(io.StringIO(csv_text.strip()))) | |
| if len(rows) < 2: | |
| raise ValueError("CSV needs a header row of gene symbols and at least 1 cell row.") | |
| header = [h.strip() for h in rows[0]] | |
| # Detect if column 0 is a cell ID string | |
| start_col = 0 | |
| try: | |
| float(rows[1][0]) | |
| except (ValueError, IndexError): | |
| start_col = 1 | |
| gene_names = header[start_col:] | |
| mat = [] | |
| for r in rows[1:257]: # Cap at 256 cells for snappy browser speed | |
| if len(r) < len(header): | |
| continue | |
| mat.append([float(x) if x.strip() else 0.0 for x in r[start_col:len(header)]]) | |
| if not mat: | |
| raise ValueError("No numeric cell rows parsed from CSV.") | |
| return self.perturb_custom_cells(np.array(mat, dtype=np.float32), gene_names, genes=genes, | |
| modality=modality, label=label, top_k=top_k) | |
| if __name__ == "__main__": | |
| ap = argparse.ArgumentParser(description="UdgamCell-v2 / v2.1 perturbation simulator") | |
| ap.add_argument("--model-dir", required=True) | |
| ap.add_argument("--line", default="k562", choices=SUPPORTED_LINES) | |
| ap.add_argument("--genes", required=True, help="1 or 2 gene symbols, comma-separated (e.g. PSMA3 or CEBPE,CNN1)") | |
| ap.add_argument("--modality", default="knockdown", choices=("knockdown", "activate")) | |
| ap.add_argument("--top-k", type=int, default=10) | |
| a = ap.parse_args() | |
| vc = UdgamVirtualCell.load(a.model_dir) | |
| res = vc.perturb(a.line, a.genes.split(","), modality=a.modality, top_k=a.top_k) | |
| out = {k: v for k, v in res.items() if k not in ("pred_cells", "ctrl_cells", "delta_all")} | |
| print(json.dumps(out, indent=2)) | |