File size: 28,209 Bytes
7325ba1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
"""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", [])]

    @classmethod
    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))