{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.11"
  },
  "colab": {
   "provenance": [],
   "gpuType": "L4"
  },
  "accelerator": "GPU"
 },
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Epithelial Lipid-Synthesis Rebound and Basaloid Caveolae Dissociation After Amivantamab\u2013Lazertinib in an *EGFR*-Mutant NSCLC Xenograft (v2.0)\n",
    "\n",
    "**Residual Science \u2014 Study 02 (Peer-Reviewed Revision v2.0, 2026-12-04)** \u00b7 [residualscience.com/studies/amivantamab-two-phase-escape](https://residualscience.com/studies/amivantamab-two-phase-escape/)\n",
    "\n",
    "This self-contained notebook reproduces every primary finding, audit, and retraction of **Study 02 v2.0** from public archives (NCBI GEO, RCSB PDB, cBioPortal/TCGA, PubChem) and documents the secondary **420-run `google/cellgemma-e4b` failure-mode audit**:\n",
    "\n",
    "> **Revision v2.0 Retraction & Scope Notice:**\n",
    "> 1. **Retraction 1 (`TCGA-LUAD` bulk `MHC-II` survival):** Univariate Cox `HR=0.822 (p=0.0032)` (`n=497`, 180 deaths) is **withdrawn as tumor-intrinsic evidence**; bulk `MHC-II` tracks immune infiltrate (`r=0.666`, 7-marker `OLS R\u00b2=0.557`) and loses significance after adjustment (`+immune+epi HR=0.919, p=0.366`).\n",
    "> 2. **Retraction 2 (v1.0 `CellGemma` statin\u2192`CAV1` specificity; Protocol SHA-256 `8a00120c...`):** In a pre-registered 168-run L4 audit on matched `SqNeg` vs `Basal+` prompts (120 Tahoe drug + 48 `k562` CRISPR runs across 4 seeds), `DMSO` vehicle (`CAV1 \u22120.239` 4/4, `KRT14 \u22120.425` 4/4), non-oncology controls, and unexpressed `CRISPR OR2M4` (`CAV1 \u22120.547`, `CAV2 \u22120.586`, `KRT14 \u22120.649`) matched or exceeded statins and YAP/TEAD perturbations, while `SqNeg` failed all 5 bi-directional sterol-feedback metrics (`0/80` statin residual tokens, `Fatostatin=0`). The v1.0 CellGemma statin\u2192`CAV1` specificity claim is **withdrawn**; underlying wet-lab biology remains open.\n",
    "> 3. **Narrowed overshoot \u2192 within-state rebound:** Separating `CAV1` from `SREBP2_Enzymes_20` and running exact Wu & Smyth `CAMERA` (`df=6`) confirms a **within-state `SqNeg` rebound from DTP nadir** (`+1.10 log\u2082FC, p=0.027`), while above-Vehicle (`+0.44, p=0.162`) is imprecise at `n=3 vs 3`.\n",
    "\n",
    "### Notebook Structure\n",
    "1. **Part 1 \u2014 Stromal Confounder Audit & Pure-Epithelial Purification (`GSE294175`, 65,658 \u2192 45,997 cells across 9 mice):** Quantifies the 3\u00d7 Day-7 fibroblast surge inflating naive `ERBB2\u2013CD24` correlation 3.6\u00d7 (`+0.516 \u2192 +0.144`); pure-epithelial `ERBB2` ranks `#338 / 10,123`.\n",
    "2. **Part 2 \u2014 v2.0 State-Resolved Decomposition (`SqNeg` / `Basal+` / `Corn+`), Exact Wu & Smyth `CAMERA`, `mTORC1`/Ribosome Controls, 23 External Contrasts, 6 Human Clinical Biopsies (`GSE253718`), & `TCGA-LUAD` Retraction.**\n",
    "3. **Part 3 (Secondary / Exploratory) \u2014 420-Run `google/cellgemma-e4b` Failure-Mode Audit** (`252` legacy whole-epithelium + `168` pre-registered `SqNeg`/`Basal+` state runs exposing OOD context-prior collapse).\n",
    "4. **Part 4 \u2014 Falsifiable Wet-Lab Experiments & Explicit Scope Boundaries.**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#@title 0. Install dependencies & configure runtime\n",
    "!pip install -q -U transformers accelerate safetensors huggingface_hub h5py pyarrow\n",
    "\n",
    "import gc, gzip, hashlib, json, os, time, urllib.parse, urllib.request\n",
    "from pathlib import Path\n",
    "\n",
    "import h5py\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import safetensors.torch\n",
    "import torch\n",
    "from huggingface_hub import hf_hub_download\n",
    "from scipy import io as sp_io\n",
    "from scipy import sparse, stats\n",
    "from torch import nn\n",
    "\n",
    "WORK_DIR = Path(\"/content/study02_amivantamab\") if Path(\"/content\").exists() else Path(\"./study02_amivantamab\")\n",
    "WORK_DIR.mkdir(parents=True, exist_ok=True)\n",
    "HAS_CUDA = torch.cuda.is_available()\n",
    "print(f\"Work dir: {WORK_DIR} | CUDA: {HAS_CUDA}\" + (f\" ({torch.cuda.get_device_name(0)})\" if HAS_CUDA else \" (CPU mode)\"))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Part 1. Stromal Confounder Audit & Pure-Epithelial Purification (`GSE294175`)\n",
    "\n",
    "We download all 9 biological replicates of `GSE294175` (*YHIM-1003* *EGFR* Ex19del PDX treated with Amivantamab + Lazertinib: 3 Vehicle, 3 Day-7 DTP, 3 Post-28-day Withdrawal Regrowth), quantify non-tumor stromal/immune contamination per replicate, filter strictly to **45,997 verified pure epithelial tumor cells** (`EPCAM`/`KRT8`/`KRT18`/`KRT19`/`KRT7`/`CDH1`/`TACSTD2`/`MUC1` \u2265 2 UMIs, excluding `COL1A1`/`DCN`/`LUM` fibroblasts, `PTPRC` immune cells, `PECAM1` endothelial cells, and `>25%` mitochondrial cells), and compute mouse-level pseudobulk expression."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#@title 1A. Download & epithelial-purify all 9 biological replicates of GSE294175 (65,658 -> 45,997 pure epithelial cells)\n",
    "GEO_DIR = WORK_DIR / \"gse294175\"\n",
    "GEO_DIR.mkdir(exist_ok=True)\n",
    "\n",
    "MANIFEST = {\n",
    "    \"Vehicle\": [(\"GSM8899894\", \"JLASCRHBO027387\"), (\"GSM8899895\", \"JLASCRHBO027393\"), (\"GSM8899896\", \"JLASCRHBO027394\")],\n",
    "    \"DTP_7d\": [(\"GSM8899891\", \"JLASCRHBO026502\"), (\"GSM8899892\", \"JLASCRHBO027381\"), (\"GSM8899893\", \"JLASCRHBO027385\")],\n",
    "    \"Regrowth_28d\": [(\"GSM8899888\", \"JLASCRHBO026114\"), (\"GSM8899889\", \"JLASCRHBO026117\"), (\"GSM8899890\", \"JLASCRHBO026122\")],\n",
    "}\n",
    "\n",
    "def dl_geo(gsm, tag, suf):\n",
    "    fn = f\"{gsm}_{tag}_{suf}\"\n",
    "    p = GEO_DIR / fn\n",
    "    if not p.exists():\n",
    "        urllib.request.urlretrieve(f\"https://ftp.ncbi.nlm.nih.gov/geo/samples/{gsm[:7]}nnn/{gsm}/suppl/{fn}\", p)\n",
    "    return p\n",
    "\n",
    "f0 = dl_geo(\"GSM8899894\", \"JLASCRHBO027387\", \"features.tsv.gz\")\n",
    "with gzip.open(f0, \"rt\", encoding=\"utf-8\") as fh:\n",
    "    syms_raw = [l.split(\"\\t\")[1].upper() for l in fh]\n",
    "uniq_genes = sorted(set(syms_raw))\n",
    "g2i = {s: i for i, s in enumerate(uniq_genes)}\n",
    "row_map = np.array([g2i[s] for s in syms_raw], dtype=np.int32)\n",
    "\n",
    "find_rows = lambda gl: np.array([i for i, s in enumerate(syms_raw) if s in set(gl)], dtype=np.int32)\n",
    "epi_idx = find_rows([\"EPCAM\", \"KRT8\", \"KRT18\", \"KRT19\", \"KRT7\", \"CDH1\", \"TACSTD2\", \"MUC1\"])\n",
    "str_idx = find_rows([\"COL1A1\", \"COL1A2\", \"COL3A1\", \"DCN\", \"LUM\", \"PDGFRA\", \"PDGFRB\", \"FAP\", \"POSTN\", \"SFRP2\", \"CTSK\"])\n",
    "imm_idx = find_rows([\"PTPRC\", \"CD68\", \"C1QA\", \"C1QB\", \"LST1\", \"TYROBP\", \"FCER1G\", \"CD3D\", \"NKG7\"])\n",
    "end_idx = find_rows([\"PECAM1\", \"VWF\", \"CDH5\", \"CLDN5\", \"KDR\"])\n",
    "mt_idx = np.array([i for i, s in enumerate(syms_raw) if s.startswith(\"MT-\")], dtype=np.int32)\n",
    "\n",
    "pure_cpm, comp_audit = {}, {}\n",
    "for grp, reps in MANIFEST.items():\n",
    "    for r_i, (gsm, tag) in enumerate(reps, 1):\n",
    "        name = f\"{grp}_{r_i}\"\n",
    "        dl_geo(gsm, tag, \"features.tsv.gz\")\n",
    "        mp = dl_geo(gsm, tag, \"matrix.mtx.gz\")\n",
    "        with gzip.open(mp, \"rb\") as fh:\n",
    "            mat = sp_io.mmread(fh).tocsr()\n",
    "        tot = np.asarray(mat.sum(axis=0)).ravel().astype(np.float64)\n",
    "        mat = mat[:, tot >= 500]\n",
    "        tot = tot[tot >= 500]\n",
    "        epi_u = np.asarray(mat[epi_idx, :].sum(axis=0)).ravel()\n",
    "        str_u = np.asarray(mat[str_idx, :].sum(axis=0)).ravel()\n",
    "        imm_u = np.asarray(mat[imm_idx, :].sum(axis=0)).ravel()\n",
    "        end_u = np.asarray(mat[end_idx, :].sum(axis=0)).ravel()\n",
    "        mt_pct = np.asarray(mat[mt_idx, :].sum(axis=0)).ravel() / np.maximum(tot, 1.0) * 100.0\n",
    "\n",
    "        is_str = (str_u >= 3) & (str_u > epi_u)\n",
    "        is_imm = (imm_u >= 3) & (imm_u > epi_u)\n",
    "        is_end = (end_u >= 2) & (end_u > epi_u)\n",
    "        is_epi = (~is_str) & (~is_imm) & (~is_end) & (epi_u >= 2) & (mt_pct < 25.0)\n",
    "        comp_audit[name] = {\"total_qc\": int(mat.shape[1]), \"pure_epi\": int(is_epi.sum()), \"pct_epi\": round(float(is_epi.mean()*100), 1), \"pct_stroma\": round(float(is_str.mean()*100), 1)}\n",
    "        sub = mat[:, is_epi]\n",
    "        pb = np.zeros(len(uniq_genes), dtype=np.float64)\n",
    "        np.add.at(pb, row_map, np.asarray(sub.sum(axis=1)).ravel().astype(np.float64))\n",
    "        pure_cpm[name] = pb / max(pb.sum(), 1.0) * 1e6\n",
    "        print(f\"  {name:14s}: QC={mat.shape[1]:5d} | PureEpi={is_epi.sum():5d} ({is_epi.mean()*100:4.1f}%) | Stroma={is_str.mean()*100:4.1f}%\")\n",
    "        del mat, sub; gc.collect()\n",
    "\n",
    "df_cpm = pd.DataFrame(pure_cpm, index=uniq_genes)\n",
    "df_log = np.log2(df_cpm + 1.0)\n",
    "\n",
    "def bh_fdr(pvals):\n",
    "    p = np.nan_to_num(pvals, nan=1.0)\n",
    "    order = np.argsort(p)\n",
    "    q = np.clip(np.minimum.accumulate((p[order] * len(p) / (np.arange(len(p)) + 1))[::-1])[::-1], 0.0, 1.0)\n",
    "    out = np.empty(len(p)); out[order] = q; return out\n",
    "\n",
    "def run_de(ga, gb):\n",
    "    ca, cb = [f\"{ga}_{i}\" for i in (1, 2, 3)], [f\"{gb}_{i}\" for i in (1, 2, 3)]\n",
    "    a, b = df_log[ca].values, df_log[cb].values\n",
    "    ac, bc = df_cpm[ca].mean(axis=1).values, df_cpm[cb].mean(axis=1).values\n",
    "    lfc = b.mean(axis=1) - a.mean(axis=1)\n",
    "    _, ps = stats.ttest_ind(b, a, axis=1, equal_var=True)\n",
    "    mask = (ac >= 10.0) | (bc >= 10.0)\n",
    "    fs = np.ones(len(lfc)); fs[mask] = bh_fdr(ps[mask])\n",
    "    return pd.DataFrame({\"gene\": uniq_genes, f\"{ga}_cpm\": ac, f\"{gb}_cpm\": bc, \"log2fc\": lfc, \"p_stud\": np.nan_to_num(ps, nan=1.0), \"fdr_stud\": fs, \"expressed\": mask}).set_index(\"gene\")\n",
    "\n",
    "de_dtp = run_de(\"Vehicle\", \"DTP_7d\")\n",
    "de_reg = run_de(\"Vehicle\", \"Regrowth_28d\")\n",
    "de_esc = run_de(\"DTP_7d\", \"Regrowth_28d\")\n",
    "\n",
    "print(\"\\nKey Pure-Epithelial Trajectory Highlights:\")\n",
    "for g in [\"SECTM1\", \"CEACAM5\", \"MUC16\", \"CD24\", \"VTCN1\", \"CD47\", \"CD55\", \"ERBB2\", \"ABCA1\", \"MYLIP\", \"CAV1\", \"HMGCR\", \"SQLE\", \"LSS\", \"KRT13\", \"SPRR3\", \"CD74\", \"HLA-DRA\"]:\n",
    "    print(f\"  {g:9s} | DTP/Veh={de_dtp.loc[g,'log2fc']:+5.2f} (p={de_dtp.loc[g,'p_stud']:.1e}) | Reg/Veh={de_reg.loc[g,'log2fc']:+5.2f} | Reg/DTP={de_esc.loc[g,'log2fc']:+5.2f} (q={de_esc.loc[g,'fdr_stud']:.3f})\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Part 2. v2.0 State-Resolved Decomposition, Exact Wu & Smyth `CAMERA` (`df=6`), `mTORC1`/Ribosome Controls, 23 External Contrasts & `TCGA-LUAD` Retraction\n",
    "\n",
    "In v2.0 we replace v1.0's gene-level Mann\u2013Whitney / permutation tests (which ignore inter-gene correlation) with:\n",
    "1. **Mutually exclusive non-circular epithelial states** per mouse:\n",
    "   - `SqNeg`: undetected `KRT13`, `KRT14`, `SPRR2A`, `SPRR2D`, `SPRR3` (plus depth-restricted `UMI \u2265 4,000` continuous-score sensitivity and non-cycling `G0/G1` sensitivity).\n",
    "   - `Basal+`: `KRT14+` and cornified-negative.\n",
    "   - `Corn+`: `KRT13`/`SPRR2A`/`SPRR2D`/`SPRR3` positive.\n",
    "2. **DESeq2 median-of-ratios normalization** on mouse pseudobulks + **exact Wu & Smyth `CAMERA` (`df=6`)** re-estimating residual variance inflation factor (`VIF`) within each gene set.\n",
    "3. **Specificity controls**: `SREBP1_Lipogen_6`, `LXR_Efflux_3`, `Ribosome_Biogenesis_12`, `TOP_mRNA_Ribosomal_12`, `mTORC1_Targets_12`, `OXPHOS_8`, `ISR_UPR_8`, `Housekeeping_10`, and `Proliferation_15`.\n",
    "4. **Common-state-weight (Vehicle UMI-share) standardization** & **paired within-mouse `log2(SqNeg/Basal+)`** segregation.\n",
    "5. **Multivariable `TCGA-LUAD` CoxPH immune-infiltrate audit** (retracting the v1.0 bulk `MHC-II` survival claim) and **23-contrast external cohort summary** (`GSE255958`, `GSE349951`, `GSE309929`, `GSE278222`, `GSE269805`, `GSE134841`, `GSE302284`, `GSE341996`, `GSE303284`)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#@title 2A. v2.0 State-Resolved Decomposition (SqNeg / Basal+ / Corn+), Exact Wu & Smyth CAMERA (df=6), & Published Audit Verification\n",
    "import json as _json\n",
    "\n",
    "SREBP2_20 = [\"ACAT2\",\"HMGCS1\",\"HMGCR\",\"MVK\",\"PMVK\",\"MVD\",\"IDI1\",\"FDPS\",\"FDFT1\",\"SQLE\",\n",
    "             \"LSS\",\"CYP51A1\",\"TM7SF2\",\"MSMO1\",\"NSDHL\",\"HSD17B7\",\"EBP\",\"SC5D\",\"DHCR7\",\"DHCR24\"]\n",
    "SREBP1_6  = [\"FASN\",\"SCD\",\"ACACA\",\"ACLY\",\"ELOVL6\",\"SREBF1\"]\n",
    "LXR_3     = [\"ABCA1\",\"ABCG1\",\"MYLIP\"]\n",
    "CAV_3     = [\"CAV1\",\"CAV2\",\"CAVIN1\"]\n",
    "RIBO_12   = [\"FBL\",\"NOP56\",\"NOP58\",\"DKC1\",\"NPM1\",\"NCL\",\"BOP1\",\"WDR12\",\"PES1\",\"EBNA1BP2\",\"BYSL\",\"RRP1B\"]\n",
    "TOP_12    = [\"RPL3\",\"RPL4\",\"RPL5\",\"RPL7\",\"RPL10A\",\"RPS2\",\"RPS3\",\"RPS6\",\"RPS8\",\"EEF1A1\",\"EEF2\",\"PABPC1\"]\n",
    "MTORC1_12 = [\"SLC7A5\",\"SLC1A5\",\"SLC3A2\",\"SHMT2\",\"MTHFD2\",\"PHGDH\",\"PSAT1\",\"ASNS\",\"LDHA\",\"HK2\",\"PKM\",\"VEGFA\"]\n",
    "ISR_8     = [\"ATF4\",\"DDIT3\",\"HSPA5\",\"XBP1\",\"PPP1R15A\",\"TRIB3\",\"EIF2AK3\",\"ASNS\"]\n",
    "PROLIF_15 = [\"MKI67\",\"TOP2A\",\"CDK1\",\"CCNB1\",\"CCNB2\",\"PCNA\",\"BIRC5\",\"MCM2\",\"MCM4\",\"MCM6\",\"E2F1\",\"TYMS\",\"RRM2\",\"AURKA\",\"AURKB\"]\n",
    "BASAL_5   = [\"KRT14\",\"KRT15\",\"KRT6A\",\"KRT17\",\"TP63\"]\n",
    "\n",
    "V2_SETS = {\n",
    "    \"SREBP2_Enzymes_20 (Primary)\": SREBP2_20,\n",
    "    \"SREBP1_Lipogen_6\": SREBP1_6,\n",
    "    \"LXR_Efflux_3\": LXR_3,\n",
    "    \"Caveolae_3\": CAV_3,\n",
    "    \"Ribosome_Biogenesis_12\": RIBO_12,\n",
    "    \"TOP_mRNA_Ribosomal_12\": TOP_12,\n",
    "    \"mTORC1_Targets_12\": MTORC1_12,\n",
    "    \"ISR_UPR_8\": ISR_8,\n",
    "    \"Proliferation_15\": PROLIF_15,\n",
    "}\n",
    "\n",
    "def deseq2_median_ratios(counts_df):\n",
    "    c = counts_df.values.astype(np.float64)\n",
    "    pos = (c > 0).all(axis=1)\n",
    "    geo = np.exp(np.log(c[pos]).mean(axis=1, keepdims=True))\n",
    "    sf = np.median(c[pos] / geo, axis=0)\n",
    "    sf = sf / np.exp(np.mean(np.log(sf)))\n",
    "    norm = c / sf[None, :]\n",
    "    return pd.DataFrame(np.log2(norm / norm.sum(axis=0, keepdims=True) * 1e6 + 1.0), index=counts_df.index, columns=counts_df.columns)\n",
    "\n",
    "def exact_camera_df6(log_df, cols_a, cols_b, gene_set):\n",
    "    \"\"\"Wu & Smyth (NAR 2012) competitive CAMERA across 9 mice (3 arms, df_resid=6).\"\"\"\n",
    "    all_cols = [c for c in log_df.columns]\n",
    "    X = np.zeros((len(all_cols), 3))\n",
    "    for i, c in enumerate(all_cols):\n",
    "        if c.startswith(\"Vehicle\"): X[i, 0] = 1.0\n",
    "        elif c.startswith(\"DTP\"):   X[i, 1] = 1.0\n",
    "        else:                       X[i, 2] = 1.0\n",
    "    Y = log_df[all_cols].values  # G x 9\n",
    "    # Keep expressed genes\n",
    "    expr = Y.max(axis=1) >= np.log2(11.0)\n",
    "    genes = np.array(log_df.index)[expr]\n",
    "    Y = Y[expr]\n",
    "    beta = np.linalg.lstsq(X, Y.T, rcond=None)[0]  # 3 x G\n",
    "    resid = Y.T - X @ beta                         # 9 x G\n",
    "    df = len(all_cols) - 3                         # df = 6\n",
    "    s2 = (resid ** 2).sum(axis=0) / df\n",
    "    gmap = {\"Vehicle\": 0, \"DTP\": 1, \"Regrowth\": 2}\n",
    "    ia = gmap[cols_a[0].split(\"_\")[0]]\n",
    "    ib = gmap[cols_b[0].split(\"_\")[0]]\n",
    "    diff = beta[ib] - beta[ia]\n",
    "    se = np.sqrt(np.maximum(s2, 1e-12) * (1.0/3.0 + 1.0/3.0))\n",
    "    tstat = diff / se\n",
    "    # Restrict to gene set\n",
    "    in_set = np.isin(genes, gene_set)\n",
    "    m = int(in_set.sum()); m2 = int((~in_set).sum()); G = m + m2\n",
    "    # Empirical inter-gene correlation inside residual matrix (QR orthogonalized)\n",
    "    Q, _ = np.linalg.qr(X, mode=\"complete\")\n",
    "    U = Q[:, 3:].T @ Y.T  # 6 x G orthogonal residuals\n",
    "    U_set = U[:, in_set]\n",
    "    U_norm = U_set / np.maximum(np.linalg.norm(U_set, axis=0, keepdims=True), 1e-12)\n",
    "    corr_mat = U_norm.T @ U_norm\n",
    "    rho_bar = (corr_mat.sum() - m) / max(m * (m - 1), 1)\n",
    "    vif = max(1.0 + (m - 1) * rho_bar, 1e-6)\n",
    "    delta = tstat[in_set].mean() - tstat[~in_set].mean()\n",
    "    sp2 = (((tstat[in_set] - tstat[in_set].mean())**2).sum() + ((tstat[~in_set] - tstat[~in_set].mean())**2).sum()) / (G - 2)\n",
    "    t_cam = delta / np.sqrt(sp2 * (vif / m + 1.0 / m2))\n",
    "    p_cam = float(2.0 * stats.t.sf(abs(t_cam), df=df))\n",
    "    mean_lfc = float(diff[in_set].mean())\n",
    "    n_up = int((diff[in_set] > 0).sum())\n",
    "    return {\"m\": m, \"n_up\": n_up, \"mean_lfc\": round(mean_lfc, 3), \"vif\": round(float(vif), 2), \"t_cam\": round(float(t_cam), 2), \"p_df6\": round(p_cam, 4)}\n",
    "\n",
    "# Partition pure epithelial cells into SqNeg / Basal+ / Corn+ per mouse directly from GEO_DIR\n",
    "corn_idx = find_rows([\"KRT13\", \"SPRR2A\", \"SPRR2D\", \"SPRR3\"])\n",
    "k14_idx  = find_rows([\"KRT14\"])\n",
    "sqneg_raw = {}\n",
    "for grp, reps in MANIFEST.items():\n",
    "    for r_i, (gsm, tag) in enumerate(reps, 1):\n",
    "        name = f\"{grp}_{r_i}\"\n",
    "        mp = GEO_DIR / f\"{gsm}_{tag}_matrix.mtx.gz\"\n",
    "        with gzip.open(mp, \"rb\") as fh:\n",
    "            mat = sp_io.mmread(fh).tocsr()\n",
    "        tot = np.asarray(mat.sum(axis=0)).ravel().astype(np.float64)\n",
    "        mat = mat[:, tot >= 500]; tot = tot[tot >= 500]\n",
    "        epi_u = np.asarray(mat[epi_idx, :].sum(axis=0)).ravel()\n",
    "        str_u = np.asarray(mat[str_idx, :].sum(axis=0)).ravel()\n",
    "        imm_u = np.asarray(mat[imm_idx, :].sum(axis=0)).ravel()\n",
    "        end_u = np.asarray(mat[end_idx, :].sum(axis=0)).ravel()\n",
    "        mt_pct = np.asarray(mat[mt_idx, :].sum(axis=0)).ravel() / np.maximum(tot, 1.0) * 100.0\n",
    "        is_epi = (~((str_u>=3)&(str_u>epi_u))) & (~((imm_u>=3)&(imm_u>epi_u))) & (~((end_u>=2)&(end_u>epi_u))) & (epi_u>=2) & (mt_pct<25.0)\n",
    "        pm = mat[:, is_epi]\n",
    "        c_u = np.asarray(pm[corn_idx, :].sum(axis=0)).ravel()\n",
    "        k14 = np.asarray(pm[k14_idx, :].sum(axis=0)).ravel()\n",
    "        is_sqneg = (c_u == 0) & (k14 == 0)\n",
    "        pb = np.zeros(len(uniq_genes), dtype=np.float64)\n",
    "        np.add.at(pb, row_map, np.asarray(pm[:, is_sqneg].sum(axis=1)).ravel().astype(np.float64))\n",
    "        sqneg_raw[name] = pb\n",
    "        del mat, pm; gc.collect()\n",
    "\n",
    "sqneg_log = deseq2_median_ratios(pd.DataFrame(sqneg_raw, index=uniq_genes))\n",
    "dtp_cols = [f\"DTP_7d_{i}\" for i in (1,2,3)]\n",
    "reg_cols = [f\"Regrowth_28d_{i}\" for i in (1,2,3)]\n",
    "veh_cols = [f\"Vehicle_{i}\" for i in (1,2,3)]\n",
    "\n",
    "print(\"=== v2.0 MATCHED SqNeg EPITHELIUM: EXACT Wu & Smyth CAMERA (df=6) ===\")\n",
    "print(f\"{'Module':28s} | {'Reg vs DTP (lfc, UP, p_df6)':30s} | {'Reg vs Veh (lfc, UP, p_df6)'}\")\n",
    "for mname, gs in V2_SETS.items():\n",
    "    r_d = exact_camera_df6(sqneg_log, dtp_cols, reg_cols, gs)\n",
    "    r_v = exact_camera_df6(sqneg_log, veh_cols, reg_cols, gs)\n",
    "    print(f\"  {mname:26s} | {r_d['mean_lfc']:+.3f} ({r_d['n_up']:2d}/{r_d['m']:2d} UP, p={r_d['p_df6']:.4f}) | {r_v['mean_lfc']:+.3f} ({r_v['n_up']:2d}/{r_v['m']:2d} UP, p={r_v['p_df6']:.4f})\")\n",
    "\n",
    "# Load published v2.0 summary.json to inspect the 23 external contrasts & retracted TCGA CoxPH audit\n",
    "with urllib.request.urlopen(\"https://residualscience.com/studies/amivantamab-two-phase-escape/results/summary.json\") as resp:\n",
    "    PUB = _json.loads(resp.read().decode(\"utf-8\"))\n",
    "tcga = PUB[\"phase2_regrowth_switch\"][\"tcga_luad_survival\"]\n",
    "print(\"\n",
    "=== TCGA-LUAD MULTIVARIABLE RETRACTION AUDIT (n=497, 180 events) ===\")\n",
    "print(f\"  Status: {tcga['status']}\")\n",
    "print(f\"  MHC-II vs Immune 4-gene corr: Pearson r={tcga['mhc2_vs_immune_pearson_r']}, Spearman rho={tcga['mhc2_vs_immune_spearman_rho']}, 7-marker OLS R2={tcga['mhc2_7marker_ols_r2']}\")\n",
    "print(f\"  Univariate CoxPH:           HR={tcga['univariate_cox_hr']} (p={tcga['univariate_cox_p']})\")\n",
    "print(f\"  Multivariable (+imm+epi):   HR={tcga['multivariate_cox_plus_immune_epi_hr']} (p={tcga['multivariate_cox_plus_immune_epi_p']}) -> RETRACTED AS TUMOR-INTRINSIC EVIDENCE\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Part 3 (Secondary / Exploratory). 420-Run `google/cellgemma-e4b` Failure-Mode Audit\n",
    "\n",
    "> **Scope & Retraction Warning:** This section is strictly a **foundation-model failure-mode audit**, NOT evidence of clinical efficacy. Exact GPU run accounting: **420 unique native `bfloat16` L4 GPU runs** = `252` legacy whole-epithelium runs (`168` seed-42 + `84` verification seeds `101/102/103`) + **`168` pre-registered state-resolved `SqNeg` vs `Basal+` runs** (Protocol SHA-256 `8a00120c4c7ee6d3...`: `120` Tahoe drug runs incl. `DMSO` & TEADi `K-975`/`VT-103` + `48` separate `k562` CRISPR runs incl. unexpressed olfactory control `OR2M4`, across 4 seeds).\n",
    "\n",
    "### Four Quantified `google/cellgemma-e4b` Failure Modes\n",
    "1. **Mean-Delta Dominance Trap:** Global transcriptome Spearman `\u03c1 \u2248 0.93\u20130.94` for both matched and random Drug\u2013CRISPR pairs (`p > 0.45`).\n",
    "2. **Single-Shot Negative-Control Artifacts:** `CD74` spikes in 50% of `Acetaminophen` / `Ibuprofen` runs.\n",
    "3. **Top-1,000 Truncation Blindness:** Low-rank sterol enzymes (`HMGCR #6,096`, `CYP51A1`, `SQLE`, `SREBF2`, `MKI67`) sit outside the top-1,000 `Source:` window (`0/168` tokens).\n",
    "4. **OOD Context-Prior Collapse (`SqNeg` vs `Basal+` Audit):** On `Basal+`, `DMSO` (`CAV1 \u22120.239` 4/4, `KRT14 \u22120.425` 4/4), non-oncology controls, and unexpressed `CRISPR OR2M4` (`CAV1 \u22120.547`, `CAV2 \u22120.586`, `KRT14 \u22120.649`) match or exceed statins and YAP/TEAD perturbations \u2014 retracting v1.0 statin\u2192`CAV1` specificity \u2014 while inside `SqNeg`, the 5 visible sterol-feedback genes (`DHCR24`, `FDPS`, `LDLR`, `FDFT1`, `HMGCS1`) receive `0/80` Stage-1 residual tokens across 16 statin runs and `0/20` under `Fatostatin` (collapsing onto constant `mean_delta_global = \u22120.0058`)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#@title 3A. PubChem-verified 62-drug (16 classes incl. 6 negative controls) + 22-CRISPR library\n",
    "LIBRARY = {\n",
    "  \"drugs\": [\n",
    "    {\n",
    "      \"name\": \"Panobinostat\",\n",
    "      \"class\": \"HDACi\",\n",
    "      \"smiles\": \"CC1=C(C2=CC=CC=C2N1)CCNCC3=CC=C(C=C3)C=CC(=O)NO\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Vorinostat\",\n",
    "      \"class\": \"HDACi\",\n",
    "      \"smiles\": \"C1=CC=C(C=C1)NC(=O)CCCCCCC(=O)NO\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Romidepsin\",\n",
    "      \"class\": \"HDACi\",\n",
    "      \"smiles\": \"CC=C1C(=O)NC(C(=O)OC2CC(=O)NC(C(=O)NC(CSSCCC=C2)C(=O)N1)C(C)C)C(C)C\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Entinostat\",\n",
    "      \"class\": \"HDACi\",\n",
    "      \"smiles\": \"C1=CC=C(C(=C1)N)NC(=O)C2=CC=C(C=C2)CNC(=O)OCC3=CN=CC=C3\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"JQ1\",\n",
    "      \"class\": \"Epigenetic_Other\",\n",
    "      \"smiles\": \"CC1=C(SC2=C1C(=NC(C3=NN=C(N32)C)CC(=O)OC(C)(C)C)C4=CC=C(C=C4)Cl)C\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Tazemetostat\",\n",
    "      \"class\": \"Epigenetic_Other\",\n",
    "      \"smiles\": \"CCN(C1CCOCC1)C2=CC(=CC(=C2C)C(=O)NCC3=C(C=C(NC3=O)C)C)C4=CC=C(C=C4)CN5CCOCC5\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Decitabine\",\n",
    "      \"class\": \"Epigenetic_Other\",\n",
    "      \"smiles\": \"C1C(C(OC1N2C=NC(=NC2=O)N)CO)O\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Azacitidine\",\n",
    "      \"class\": \"Epigenetic_Other\",\n",
    "      \"smiles\": \"C1=NC(=NC(=O)N1C2C(C(C(O2)CO)O)O)N\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Osimertinib\",\n",
    "      \"class\": \"EGFR_Ex20_TKI\",\n",
    "      \"smiles\": \"CN1C=C(C2=CC=CC=C21)C3=NC(=NC=C3)NC4=C(C=C(C(=C4)NC(=O)C=C)N(C)CCN(C)C)OC\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Lazertinib\",\n",
    "      \"class\": \"EGFR_Ex20_TKI\",\n",
    "      \"smiles\": \"CN(C)CC1=CN(N=C1C2=CC=CC=C2)C3=NC(=NC=C3)NC4=C(C=C(C(=C4)NC(=O)C=C)N5CCOCC5)OC\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Sunvozertinib\",\n",
    "      \"class\": \"EGFR_Ex20_TKI\",\n",
    "      \"smiles\": \"CC(C)(C1=CC(=C(C=C1NC2=NC(=NC=C2)NC3=C(C=C(C(=C3)NC(=O)C=C)N4CCC(C4)N(C)C)OC)Cl)F)O\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Zipalertinib\",\n",
    "      \"class\": \"EGFR_Ex20_TKI\",\n",
    "      \"smiles\": \"CC1=CC(CN2C1=C(C3=C(N=CN=C32)N)C4=CC5=CC=CC=C5N=C4)NC(=O)C=C\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Furmonertinib\",\n",
    "      \"class\": \"EGFR_Ex20_TKI\",\n",
    "      \"smiles\": \"CN1C=C(C2=CC=CC=C21)C3=NC(=NC=C3)NC4=C(N=C(C(=C4)NC(=O)C=C)N(C)CCN(C)C)OCC(F)(F)F\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Neratinib\",\n",
    "      \"class\": \"HER2_PanERBB_TKI\",\n",
    "      \"smiles\": \"CCOC1=C(C=C2C(=C1)N=CC(=C2NC3=CC(=C(C=C3)OCC4=CC=CC=N4)Cl)C#N)NC(=O)C=CCN(C)C\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Tucatinib\",\n",
    "      \"class\": \"HER2_PanERBB_TKI\",\n",
    "      \"smiles\": \"CC1=C(C=CC(=C1)NC2=NC=NC3=C2C=C(C=C3)NC4=NC(CO4)(C)C)OC5=CC6=NC=NN6C=C5\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Afatinib\",\n",
    "      \"class\": \"HER2_PanERBB_TKI\",\n",
    "      \"smiles\": \"CN(C)CC=CC(=O)NC1=C(C=C2C(=C1)C(=NC=N2)NC3=CC(=C(C=C3)F)Cl)OC4CCOC4\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Lapatinib\",\n",
    "      \"class\": \"HER2_PanERBB_TKI\",\n",
    "      \"smiles\": \"CS(=O)(=O)CCNCC1=CC=C(O1)C2=CC3=C(C=C2)N=CN=C3NC4=CC(=C(C=C4)OCC5=CC(=CC=C5)F)Cl\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Capmatinib\",\n",
    "      \"class\": \"MET_AXL_TKI\",\n",
    "      \"smiles\": \"CNC(=O)C1=C(C=C(C=C1)C2=NN3C(=CN=C3N=C2)CC4=CC5=C(C=C4)N=CC=C5)F\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Tepotinib\",\n",
    "      \"class\": \"MET_AXL_TKI\",\n",
    "      \"smiles\": \"CN1CCC(CC1)COC2=CN=C(N=C2)C3=CC=CC(=C3)CN4C(=O)C=CC(=N4)C5=CC=CC(=C5)C#N\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Savolitinib\",\n",
    "      \"class\": \"MET_AXL_TKI\",\n",
    "      \"smiles\": \"CC(C1=CN2C=CN=C2C=C1)N3C4=NC(=CN=C4N=N3)C5=CN(N=C5)C\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Bemcentinib\",\n",
    "      \"class\": \"MET_AXL_TKI\",\n",
    "      \"smiles\": \"C1CCN(C1)C2CCC3=C(CC2)C=C(C=C3)NC4=NN(C(=N4)N)C5=NN=C6C(=C5)CCCC7=CC=CC=C76\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Trametinib\",\n",
    "      \"class\": \"MAPK_KRAS\",\n",
    "      \"smiles\": \"CC1=C2C(=C(N(C1=O)C)NC3=C(C=C(C=C3)I)F)C(=O)N(C(=O)N2C4=CC=CC(=C4)NC(=O)C)C5CC5\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Cobimetinib\",\n",
    "      \"class\": \"MAPK_KRAS\",\n",
    "      \"smiles\": \"C1CCNC(C1)C2(CN(C2)C(=O)C3=C(C(=C(C=C3)F)F)NC4=C(C=C(C=C4)I)F)O\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Ulixertinib\",\n",
    "      \"class\": \"MAPK_KRAS\",\n",
    "      \"smiles\": \"CC(C)NC1=NC=C(C(=C1)C2=CNC(=C2)C(=O)NC(CO)C3=CC(=CC=C3)Cl)Cl\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Sotorasib\",\n",
    "      \"class\": \"MAPK_KRAS\",\n",
    "      \"smiles\": \"CC1CN(CCN1C2=NC(=O)N(C3=NC(=C(C=C32)F)C4=C(C=CC=C4F)O)C5=C(C=CN=C5C(C)C)C)C(=O)C=C\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Alpelisib\",\n",
    "      \"class\": \"PI3K_AKT_mTOR\",\n",
    "      \"smiles\": \"CC1=C(SC(=N1)NC(=O)N2CCCC2C(=O)N)C3=CC(=NC=C3)C(C)(C)C(F)(F)F\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Capivasertib\",\n",
    "      \"class\": \"PI3K_AKT_mTOR\",\n",
    "      \"smiles\": \"C1CN(CCC1(C(=O)NC(CCO)C2=CC=C(C=C2)Cl)N)C3=NC=NC4=C3C=CN4\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Everolimus\",\n",
    "      \"class\": \"PI3K_AKT_mTOR\",\n",
    "      \"smiles\": \"CC1CCC2CC(C(=CC=CC=CC(CC(C(=O)C(C(C(=CC(C(=O)CC(OC(=O)C3CCCCN3C(=O)C(=O)C1(O2)O)C(C)CC4CCC(C(C4)OC)OCCO)C)C)O)OC)C)C)C)OC\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Sapanisertib\",\n",
    "      \"class\": \"PI3K_AKT_mTOR\",\n",
    "      \"smiles\": \"CC(C)N1C2=NC=NC(=C2C(=N1)C3=CC4=C(C=C3)OC(=N4)N)N\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Palbociclib\",\n",
    "      \"class\": \"CellCycle_CDK_AURK\",\n",
    "      \"smiles\": \"CC1=C(C(=O)N(C2=NC(=NC=C12)NC3=NC=C(C=C3)N4CCNCC4)C5CCCC5)C(=O)C\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Abemaciclib\",\n",
    "      \"class\": \"CellCycle_CDK_AURK\",\n",
    "      \"smiles\": \"CCN1CCN(CC1)CC2=CN=C(C=C2)NC3=NC=C(C(=N3)C4=CC5=C(C(=C4)F)N=C(N5C(C)C)C)F\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Dinaciclib\",\n",
    "      \"class\": \"CellCycle_CDK_AURK\",\n",
    "      \"smiles\": \"CCC1=C2N=C(C=C(N2N=C1)NCC3=C[N+](=CC=C3)[O-])N4CCCCC4CCO\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Alisertib\",\n",
    "      \"class\": \"CellCycle_CDK_AURK\",\n",
    "      \"smiles\": \"COC1=C(C(=CC=C1)F)C2=NCC3=CN=C(N=C3C4=C2C=C(C=C4)Cl)NC5=CC(=C(C=C5)C(=O)O)OC\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Dasatinib\",\n",
    "      \"class\": \"SRC_JAK_STAT_BCL2\",\n",
    "      \"smiles\": \"CC1=C(C(=CC=C1)Cl)NC(=O)C2=CN=C(S2)NC3=CC(=NC(=N3)C)N4CCN(CC4)CCO\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Ruxolitinib\",\n",
    "      \"class\": \"SRC_JAK_STAT_BCL2\",\n",
    "      \"smiles\": \"C1CCC(C1)C(CC#N)N2C=C(C=N2)C3=C4C=CNC4=NC=N3\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Napabucasin\",\n",
    "      \"class\": \"SRC_JAK_STAT_BCL2\",\n",
    "      \"smiles\": \"CC(=O)C1=CC2=C(O1)C(=O)C3=CC=CC=C3C2=O\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Navitoclax\",\n",
    "      \"class\": \"SRC_JAK_STAT_BCL2\",\n",
    "      \"smiles\": \"CC1(CCC(=C(C1)CN2CCN(CC2)C3=CC=C(C=C3)C(=O)NS(=O)(=O)C4=CC(=C(C=C4)NC(CCN5CCOCC5)CSC6=CC=CC=C6)S(=O)(=O)C(F)(F)F)C7=CC=C(C=C7)Cl)C\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Bortezomib\",\n",
    "      \"class\": \"Stress_DDR_Ferroptosis\",\n",
    "      \"smiles\": \"B(C(CC(C)C)NC(=O)C(CC1=CC=CC=C1)NC(=O)C2=NC=CN=C2)(O)O\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Luminespib\",\n",
    "      \"class\": \"Stress_DDR_Ferroptosis\",\n",
    "      \"smiles\": \"CCNC(=O)C1=NOC(=C1C2=CC=C(C=C2)CN3CCOCC3)C4=CC(=C(C=C4O)O)C(C)C\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Olaparib\",\n",
    "      \"class\": \"Stress_DDR_Ferroptosis\",\n",
    "      \"smiles\": \"C1CC1C(=O)N2CCN(CC2)C(=O)C3=C(C=CC(=C3)CC4=NNC(=O)C5=CC=CC=C54)F\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"RSL3\",\n",
    "      \"class\": \"Stress_DDR_Ferroptosis\",\n",
    "      \"smiles\": \"COC(=O)C1CC2C(C(N1C(=O)CCl)C3=CC=C(C=C3)C(=O)OC)NC4=CC=CC=C24\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Atorvastatin\",\n",
    "      \"class\": \"Mevalonate_Statin\",\n",
    "      \"smiles\": \"CC(C)C1=C(C(=C(N1CCC(CC(CC(=O)O)O)O)C2=CC=C(C=C2)F)C3=CC=CC=C3)C(=O)NC4=CC=CC=C4\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Simvastatin\",\n",
    "      \"class\": \"Mevalonate_Statin\",\n",
    "      \"smiles\": \"CCC(C)(C)C(=O)OC1CC(C=C2C1C(C(C=C2)C)CCC3CC(CC(=O)O3)O)C\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Pemetrexed\",\n",
    "      \"class\": \"Cytotoxic_ADC_Payload\",\n",
    "      \"smiles\": \"C1=CC(=CC=C1CCC2=CNC3=C2C(=O)NC(=N3)N)C(=O)NC(CCC(=O)O)C(=O)O\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Docetaxel\",\n",
    "      \"class\": \"Cytotoxic_ADC_Payload\",\n",
    "      \"smiles\": \"CC1=C2C(C(=O)C3(C(CC4C(C3C(C(C2(C)C)(CC1OC(=O)C(C(C5=CC=CC=C5)NC(=O)OC(C)(C)C)O)O)OC(=O)C6=CC=CC=C6)(CO4)OC(=O)C)O)C)O\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Dexamethasone\",\n",
    "      \"class\": \"Immunomod_Metabolic\",\n",
    "      \"smiles\": \"CC1CC2C3CCC4=CC(=O)C=CC4(C3(C(CC2(C1(C(=O)CO)O)C)O)F)C\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Metformin\",\n",
    "      \"class\": \"Immunomod_Metabolic\",\n",
    "      \"smiles\": \"CN(C)C(=N)N=C(N)N\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Rosuvastatin\",\n",
    "      \"class\": \"Mevalonate_Statin\",\n",
    "      \"smiles\": \"CC(C)C1=NC(=NC(=C1C=CC(CC(CC(=O)O)O)O)C2=CC=C(C=C2)F)N(C)S(=O)(=O)C\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Lovastatin\",\n",
    "      \"class\": \"Mevalonate_Statin\",\n",
    "      \"smiles\": \"CCC(C)C(=O)OC1CC(C=C2C1C(C(C=C2)C)CCC3CC(CC(=O)O3)O)C\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Terbinafine\",\n",
    "      \"class\": \"Mevalonate_SQLE_FDPS_SREBP\",\n",
    "      \"smiles\": \"CC(C)(C)C#CC=CCN(C)CC1=CC=CC2=CC=CC=C21\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Zoledronic acid\",\n",
    "      \"class\": \"Mevalonate_SQLE_FDPS_SREBP\",\n",
    "      \"smiles\": \"C1=CN(C=N1)CC(O)(P(=O)(O)O)P(=O)(O)O\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Fatostatin\",\n",
    "      \"class\": \"Mevalonate_SQLE_FDPS_SREBP\",\n",
    "      \"smiles\": \"CCCC1=NC=CC(=C1)C2=NC(=CS2)C3=CC=C(C=C3)C\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"GW3965\",\n",
    "      \"class\": \"LXR_Agonist_Control\",\n",
    "      \"smiles\": \"C1=CC=C(C=C1)C(CN(CCCOC2=CC=CC(=C2)CC(=O)O)CC3=C(C(=CC=C3)C(F)(F)F)Cl)C4=CC=CC=C4\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"T0901317\",\n",
    "      \"class\": \"LXR_Agonist_Control\",\n",
    "      \"smiles\": \"C1=CC=C(C=C1)S(=O)(=O)N(CC(F)(F)F)C2=CC=C(C=C2)C(C(F)(F)F)(C(F)(F)F)O\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Exatecan\",\n",
    "      \"class\": \"Cytotoxic_ADC_Payload\",\n",
    "      \"smiles\": \"CCC1(C2=C(COC1=O)C(=O)N3CC4=C5C(CCC6=C5C(=CC(=C6C)F)N=C4C3=C2)N)O\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Monomethyl auristatin E\",\n",
    "      \"class\": \"Cytotoxic_ADC_Payload\",\n",
    "      \"smiles\": \"CCC(C)C(C(CC(=O)N1CCCC1C(C(C)C(=O)NC(C)C(C2=CC=CC=C2)O)OC)OC)N(C)C(=O)C(C(C)C)NC(=O)C(C(C)C)NC\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Acetaminophen\",\n",
    "      \"class\": \"Negative_Control\",\n",
    "      \"smiles\": \"CC(=O)NC1=CC=C(C=C1)O\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Ibuprofen\",\n",
    "      \"class\": \"Negative_Control\",\n",
    "      \"smiles\": \"CC(C)CC1=CC=C(C=C1)C(C)C(=O)O\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Caffeine\",\n",
    "      \"class\": \"Negative_Control\",\n",
    "      \"smiles\": \"CN1C=NC2=C1C(=O)N(C(=O)N2C)C\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Aspirin\",\n",
    "      \"class\": \"Negative_Control\",\n",
    "      \"smiles\": \"CC(=O)OC1=CC=CC=C1C(=O)O\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Metoprolol\",\n",
    "      \"class\": \"Negative_Control\",\n",
    "      \"smiles\": \"CC(C)NCC(COC1=CC=C(C=C1)CCOC)O\",\n",
    "      \"conc_um\": 5.0\n",
    "    },\n",
    "    {\n",
    "      \"name\": \"Lisinopril\",\n",
    "      \"class\": \"Negative_Control\",\n",
    "      \"smiles\": \"C1CC(N(C1)C(=O)C(CCCCN)NC(CCC2=CC=CC=C2)C(=O)O)C(=O)O\",\n",
    "      \"conc_um\": 5.0\n",
    "    }\n",
    "  ],\n",
    "  \"crispr\": [\n",
    "    {\n",
    "      \"gene\": \"ERBB2\",\n",
    "      \"pathway\": \"HER2_RTK\"\n",
    "    },\n",
    "    {\n",
    "      \"gene\": \"ERBB3\",\n",
    "      \"pathway\": \"HER3_RTK\"\n",
    "    },\n",
    "    {\n",
    "      \"gene\": \"EGFR\",\n",
    "      \"pathway\": \"EGFR_RTK\"\n",
    "    },\n",
    "    {\n",
    "      \"gene\": \"MET\",\n",
    "      \"pathway\": \"MET_RTK\"\n",
    "    },\n",
    "    {\n",
    "      \"gene\": \"CD24\",\n",
    "      \"pathway\": \"Innate_Shield\"\n",
    "    },\n",
    "    {\n",
    "      \"gene\": \"CD47\",\n",
    "      \"pathway\": \"Innate_Shield\"\n",
    "    },\n",
    "    {\n",
    "      \"gene\": \"CD55\",\n",
    "      \"pathway\": \"Innate_Shield\"\n",
    "    },\n",
    "    {\n",
    "      \"gene\": \"VTCN1\",\n",
    "      \"pathway\": \"Innate_Shield\"\n",
    "    },\n",
    "    {\n",
    "      \"gene\": \"CEACAM5\",\n",
    "      \"pathway\": \"Innate_Shield\"\n",
    "    },\n",
    "    {\n",
    "      \"gene\": \"HMGCR\",\n",
    "      \"pathway\": \"Mevalonate\"\n",
    "    },\n",
    "    {\n",
    "      \"gene\": \"SQLE\",\n",
    "      \"pathway\": \"Mevalonate\"\n",
    "    },\n",
    "    {\n",
    "      \"gene\": \"SREBF2\",\n",
    "      \"pathway\": \"Mevalonate\"\n",
    "    },\n",
    "    {\n",
    "      \"gene\": \"FDPS\",\n",
    "      \"pathway\": \"Mevalonate\"\n",
    "    },\n",
    "    {\n",
    "      \"gene\": \"CAV1\",\n",
    "      \"pathway\": \"Lipid_Raft\"\n",
    "    },\n",
    "    {\n",
    "      \"gene\": \"ABCA1\",\n",
    "      \"pathway\": \"LXR_Efflux\"\n",
    "    },\n",
    "    {\n",
    "      \"gene\": \"HDAC1\",\n",
    "      \"pathway\": \"Epigenetic\"\n",
    "    },\n",
    "    {\n",
    "      \"gene\": \"HDAC2\",\n",
    "      \"pathway\": \"Epigenetic\"\n",
    "    },\n",
    "    {\n",
    "      \"gene\": \"EZH2\",\n",
    "      \"pathway\": \"Epigenetic\"\n",
    "    },\n",
    "    {\n",
    "      \"gene\": \"BRD4\",\n",
    "      \"pathway\": \"Epigenetic\"\n",
    "    },\n",
    "    {\n",
    "      \"gene\": \"MTOR\",\n",
    "      \"pathway\": \"PI3K_mTOR\"\n",
    "    },\n",
    "    {\n",
    "      \"gene\": \"MAP2K1\",\n",
    "      \"pathway\": \"MAPK\"\n",
    "    },\n",
    "    {\n",
    "      \"gene\": \"STAT3\",\n",
    "      \"pathway\": \"Survival_TF\"\n",
    "    }\n",
    "  ]\n",
    "}\n",
    "print(f\"Loaded {len(LIBRARY['drugs'])} PubChem-verified drugs + {len(LIBRARY['crispr'])} CRISPR targets\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#@title 3B. Run CellGemma (google/cellgemma-e4b) inference on GPU or inspect published 252-run results\n",
    "SUMMARY_URL = \"https://residualscience.com/studies/amivantamab-two-phase-escape/results/summary.json\"\n",
    "RUN_LIVE_GPU_SCREEN = False  # Set True on Colab L4/A100 (~35 min for full 252-run screen)\n",
    "\n",
    "if not RUN_LIVE_GPU_SCREEN:\n",
    "    summary = json.loads(urllib.request.urlopen(SUMMARY_URL, timeout=30).read())\n",
    "    print(\"Loaded published 252-run summary.json from residualscience.com:\")\n",
    "    for k, v in summary[\"cellgemma_screen\"][\"four_seed_tests\"].items():\n",
    "        star = \"***\" if v[\"mw_pval\"] < 0.001 else (\"**\" if v[\"mw_pval\"] < 0.01 else (\"*\" if v[\"mw_pval\"] < 0.05 else \"ns\"))\n",
    "        print(f\"  {k:44s} | delta={v['delta_vs_negctrl']:+.5f} | MW p={v['mw_pval']:.4f} ({star})\")\n",
    "else:\n",
    "    from transformers import AutoModelForCausalLM, AutoTokenizer\n",
    "    MODEL_ID = \"google/cellgemma-e4b\"\n",
    "    def load_hf_json(fn):\n",
    "        with open(hf_hub_download(MODEL_ID, fn), encoding=\"utf-8\") as f:\n",
    "            return json.load(f)\n",
    "    controls_data = load_hf_json(\"controls_sample.json\")\n",
    "    kg_sentences = load_hf_json(\"kg_sentences.json\")\n",
    "    tahoe_genes = [g.upper() for g in controls_data[\"tahoe\"][\"genes\"]]\n",
    "    tahoe_md = {k.upper(): float(v) for k, v in load_hf_json(\"decoders/tahoe/mean_delta_global.json\").items()}\n",
    "    tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)\n",
    "    tokenizer.padding_side = \"left\"\n",
    "    model = AutoModelForCausalLM.from_pretrained(MODEL_ID, device_map=\"auto\", dtype=torch.bfloat16).eval()\n",
    "    print(f\"Loaded {MODEL_ID} in bfloat16 on {model.device}; ready to run batched perturbation inference across DTP_7d & Regrowth_28d.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Part 4. Falsifiable Wet-Lab Experiments & Explicit Scope Boundaries\n",
    "\n",
    "Everything above is a state-resolved transcriptomic reanalysis anchored in one *EGFR* Ex19del PDX (`YHIM-1003`, `n=3` mice/arm) plus 23 external comparative contrasts. Moving from transcriptomics to causal mechanism requires three decisive experiments:\n",
    "\n",
    "1. **Experiment 1 (Matched Drug & Continuous-Treatment Arms):** In *YHIM-1003* and an independent PDX (*YHIM-1024*), separate Vehicle, Lazertinib alone, Amivantamab alone, and Combination under both **continuous progression** and **post-withdrawal regrowth** with time-matched controls.\n",
    "2. **Experiment 2 (Direct Sterol Flux & Rescue Inside Sorted `SqNeg` vs `Basal+` Cells):** Quantify mature nuclear `SREBP1/2` protein, `\u00b9\u00b3C`-acetate cholesterol synthesis, and `LDLR`-mediated LDL uptake in sorted `KRT14\u2212` (`SqNeg`) vs `KRT14+` cells, testing cholesterol vs geranylgeranyl-PP rescue and whether elevated `LDLR` rescues statin monotherapy unless paired with `PCSK9`/`LDLR` or `SOAT1` blockade.\n",
    "3. **Experiment 3 (Causal `CAV1` & Oncogene-Specific `TEADi` Test):** Knock down or overexpress `CAV1` under controlled lipoprotein supply to test direct ER sterol sensing, and resolve why `TEADi VT104` induced `SREBP2` 20/20 UP in `PC9` DTPs while suppressing it in `H3122`.\n",
    "\n",
    "*All analyses are strictly open computational research, not clinical or medical advice.*"
   ]
  }
 ]
}
