{
  "nbformat": 4,
  "nbformat_minor": 5,
  "metadata": {
    "colab": {
      "provenance": [],
      "gpuType": "L4"
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python",
      "version": "3.11"
    },
    "accelerator": "GPU"
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Understanding How Amivantamab Works on *EGFR* Exon 20 Insertion Lung Adenocarcinoma\n",
        "\n",
        "This notebook is a deep, multi-modal scientific walkthrough designed to visualize and dissect **how amivantamab (Rybrevant; an EGFR \u00d7 MET bispecific IgG1 antibody) acts on a lung adenocarcinoma driven by an *EGFR* exon 20 insertion (`D770delinsGY`) with co-occurring *TP53* loss-of-function (`I254fs`) and high TMB**, using **Google DeepMind's CellGemma** alongside **real 3D crystal structures**, **real human TCGA tumor transcriptomes**, and **real wet-lab amivantamab RNA-seq / scRNA-seq datasets**.\n",
        "\n",
        "> **Important scientific & clinical note:** CellGemma is a preclinical research model that predicts *intracellular transcriptional shifts* (mRNA up/down) from baseline gene expression\u2014not DNA mutations directly, not antibody binding affinity, and not clinical efficacy. It is **not** for clinical decision-making. Here we combine it with structural biology and published wet-lab datasets so every piece of amivantamab's mechanism is accurately represented.\n",
        "\n",
        "---\n",
        "\n",
        "### How the 3 Physical Mechanisms of Amivantamab Map to This Notebook\n",
        "\n",
        "| Amivantamab Mechanism | What Happens Biologically | Where This Notebook Shows It |\n",
        "| :--- | :--- | :--- |\n",
        "| **1. Extracellular Receptor Binding & Lysosomal Degradation** | Binds the *outside* of EGFR and MET (unaffected by the intracellular `D770delinsGY` kinase-pocket insertion), crosslinks them, and destroys both receptors \u2192 shuts down MAPK/ERK & PI3K/AKT survival signaling and activates pro-apoptotic BIM (`BCL2L11`). | **Part 1** (3D crystal structures `4LRM`, `6WVZ`, `1YY9`) + **Part 3** (CellGemma dual `EGFR`+`MET` knockdown & TKI proxies on `tahoe` NSCLC single cells + real TCGA *EGFR* exon 20 + *TP53* tumors) + **Part 4** (real wet-lab amivantamab+lazertinib NSCLC scRNA-seq `GSE294175`) |\n",
        "| **2. Macrophage/Monocyte Trogocytosis (ADCT)** | Low-fucose Fc tail binds Fc\u03b3RIIIa on monocytes/macrophages, which physically strip EGFR- and MET-bearing membrane patches off tumor cells. | **Part 5** (`CSF2`/GM-CSF & `CCL3`/`CCL4` macrophage-recruitment axis in `GSE341700`) + biological synthesis |\n",
        "| **3. NK-Cell Cytotoxicity (ADCC) & Immune Recruitment** | Low-fucose Fc tail bridges NK cells to tumor cells \u2192 triggers `EGR1`, `TNF`, `IFNG`, `GZMB` (Granzyme B), `FASLG` killing and `XCL1`/`XCL2` dendritic-cell recruitment (synergizing with high tumor mutational burden). | **Part 5** (real wet-lab NK-cell + amivantamab co-culture RNA-seq `GSE341700`) |\n",
        "\n",
        "---\n",
        "\n",
        "### Runtime Tips (Google Colab)\n",
        "- **Recommended GPU:** **L4 (24 GB)** or **A100 (40+ GB)** runs CellGemma in native `bfloat16`.\n",
        "- **Free Colab T4 (16 GB)** works automatically\u2014the setup cell detects VRAM `< 20 GB` and enables 4-bit `bitsandbytes` loading + faster token/cell defaults.\n",
        "- **Zero wasted work:** Every CellGemma inference call is cached to `/content/amivantamab_results/cellgemma_cache.json`. If you tweak plots or reconnect, cached predictions reload instantly.\n",
        "- **Want fast results first?** Parts **1** (3D structures), **4A** (real wet-lab NSCLC scRNA-seq), and **5** (real wet-lab NK-cell ADCC) run purely on CPU in seconds!"
      ],
      "id": "cell-00"
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 0. Setup & Hardware Auto-Configuration\n",
        "\n",
        "Installs required libraries, checks GPU VRAM, and configures whether to load CellGemma in native `bfloat16` (L4/A100) or 4-bit quantization (free T4)."
      ],
      "id": "cell-01"
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "#@title Install dependencies & detect GPU\n",
        "# Only install/upgrade HF + 3D viewer packages (keep Colab's preinstalled numpy/scipy/pandas/matplotlib intact to avoid runtime restart)\n",
        "!pip install -q -U transformers accelerate safetensors huggingface_hub bitsandbytes py3Dmol\n",
        "\n",
        "import gc\n",
        "import gzip\n",
        "import hashlib\n",
        "import io\n",
        "import json\n",
        "import math\n",
        "import os\n",
        "import time\n",
        "import urllib.request\n",
        "from pathlib import Path\n",
        "\n",
        "import matplotlib.pyplot as plt\n",
        "import numpy as np\n",
        "import pandas as pd\n",
        "import safetensors.torch\n",
        "import seaborn as sns\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",
        "# Clean plotting defaults\n",
        "sns.set_theme(style=\"whitegrid\", context=\"notebook\")\n",
        "plt.rcParams[\"figure.dpi\"] = 120\n",
        "\n",
        "RESULTS_DIR = Path(\"/content/amivantamab_results\") if Path(\"/content\").exists() else Path(\"./amivantamab_results\")\n",
        "RESULTS_DIR.mkdir(parents=True, exist_ok=True)\n",
        "CACHE_PATH = RESULTS_DIR / \"cellgemma_cache.json\"\n",
        "\n",
        "HAS_CUDA = torch.cuda.is_available()\n",
        "VRAM_GB = torch.cuda.get_device_properties(0).total_memory / 1e9 if HAS_CUDA else 0.0\n",
        "GPU_NAME = torch.cuda.get_device_name(0) if HAS_CUDA else \"CPU only\"\n",
        "\n",
        "# Auto-tune precision, batch size, and generation budget to hardware\n",
        "USE_4BIT = HAS_CUDA and VRAM_GB < 20.0       # Free Colab T4 (15-16 GB) -> 4-bit; L4/A100 -> bf16\n",
        "BATCH_SIZE = 3 if USE_4BIT else (5 if VRAM_GB >= 22.0 else 1)\n",
        "MAX_NEW_TOKENS = 1024 if USE_4BIT else 1536  # Full DEG list finishes ~800-1400 tokens; bump to 4096-8192 on A100\n",
        "N_TAHOE_CELLS = 3 if USE_4BIT else 5         # Number of EGFR+/MET+ NSCLC cells to average\n",
        "TEMPERATURE = 0.7                            # Matches CellGemma evaluation protocol\n",
        "SEED = 42\n",
        "\n",
        "print(f\"Device: {GPU_NAME} ({VRAM_GB:.1f} GB VRAM)\")\n",
        "if not HAS_CUDA:\n",
        "    print(\"WARNING: No GPU detected! Parts 1 (3D structures) and 5 (NK-cell ADCC) work on CPU,\")\n",
        "    print(\"         but for CellGemma (Parts 2-4) go to Runtime -> Change runtime type -> T4 / L4 / A100 GPU.\")\n",
        "print(f\"4-bit={USE_4BIT} | BATCH_SIZE={BATCH_SIZE} | MAX_NEW_TOKENS={MAX_NEW_TOKENS} | N_TAHOE_CELLS={N_TAHOE_CELLS}\")\n",
        "print(f\"Outputs & cache directory: {RESULTS_DIR}\")"
      ],
      "id": "cell-02"
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Part 1. Interactive 3D Structural View: Why Amivantamab Bypasses `EGFR D770delinsGY`\n",
        "\n",
        "Before running any transcriptomic model, it helps to **see the physical geometry** in 3D using real X-ray crystal structures from the RCSB Protein Data Bank:\n",
        "\n",
        "1. **`4LRM` \u2014 Intracellular *EGFR* `D770` exon 20 insertion kinase domain (`D770_N771insNPG`):**\n",
        "   - Look at the **red spheres (`residues 770\u2013773`)** right behind the **orange \u03b1C-helix (`753\u2013767`)**.\n",
        "   - Inserting extra residues at position `D770` (just like `D770delinsGY`) acts as a rigid structural wedge that pushes the \u03b1C-helix inward into a **permanently active (\"ON\") conformation**, while distorting the adjacent ATP-binding pocket (cyan ligand) so 1st/2nd-generation oral EGFR TKIs (erlotinib, gefitinib, afatinib) lose selectivity.\n",
        "2. **`6WVZ` \u2014 Amivantamab's actual anti-MET Fab arm bound to human MET:**\n",
        "   - **Gold/violet** = amivantamab's heavy & light Fab chains gripping the **teal** extracellular SEMA domain of MET\u2014blocking HGF ligand binding and pulling MET in for degradation.\n",
        "3. **`1YY9` \u2014 Anti-EGFR Fab gripping EGFR Extracellular Domain III:**\n",
        "   - Shows the **extracellular** domain III epitope targeted by anti-EGFR antibodies (blocking EGF ligand binding and driving receptor internalization). Because this binding site sits on the *outside* of the cell membrane, it is completely unaffected by the `D770delinsGY` insertion inside the cell!\n",
        "\n",
        "*(Drag to rotate, scroll to zoom in each 3D viewer below.)*"
      ],
      "id": "cell-03"
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "#@title Render interactive 3D crystal structures (4LRM, 6WVZ, 1YY9)\n",
        "import py3Dmol\n",
        "\n",
        "def fetch_pdb(pdb_id: str) -> str:\n",
        "    url = f\"https://files.rcsb.org/download/{pdb_id}.pdb\"\n",
        "    with urllib.request.urlopen(url, timeout=20) as r:\n",
        "        return r.read().decode(\"utf-8\", errors=\"replace\")\n",
        "\n",
        "# 1A: Intracellular EGFR D770 Exon 20 Insertion Kinase Domain (4LRM)\n",
        "print(\"1A. PDB 4LRM \u2014 Intracellular EGFR D770 Exon 20 Insertion Kinase Domain\")\n",
        "print(\"    Orange = alpha-C helix (753-767) | Red spheres = D770 exon 20 insertion wedge (770-773) | Cyan = ATP-pocket inhibitor\")\n",
        "pdb_4lrm = fetch_pdb(\"4LRM\")\n",
        "v1 = py3Dmol.view(width=820, height=400)\n",
        "v1.addModel(pdb_4lrm, \"pdb\")\n",
        "v1.setStyle({\"chain\": \"A\"}, {\"cartoon\": {\"color\": \"#94a3b8\", \"opacity\": 0.85}})\n",
        "v1.setStyle({\"chain\": [\"B\", \"C\", \"D\", \"E\"]}, {})  # Show single kinase monomer cleanly\n",
        "v1.setStyle({\"chain\": \"A\", \"resi\": list(range(753, 768))}, {\"cartoon\": {\"color\": \"#f97316\"}})\n",
        "v1.setStyle({\"chain\": \"A\", \"resi\": [770, 771, 772, 773]}, {\"stick\": {\"color\": \"#ef4444\", \"radius\": 0.3}, \"sphere\": {\"color\": \"#ef4444\", \"scale\": 0.45}})\n",
        "v1.setStyle({\"chain\": \"A\", \"resn\": \"YUN\"}, {\"stick\": {\"colorscheme\": \"cyanCarbon\", \"radius\": 0.25}, \"sphere\": {\"color\": \"#06b6d4\", \"scale\": 0.3}})\n",
        "v1.addLabel(\"D770 Exon 20 Wedge\", {\"position\": {\"chain\": \"A\", \"resi\": 770}, \"backgroundColor\": \"#ef4444\", \"fontColor\": \"white\", \"fontSize\": 12})\n",
        "v1.addLabel(\"alpha-C Helix\", {\"position\": {\"chain\": \"A\", \"resi\": 760}, \"backgroundColor\": \"#f97316\", \"fontColor\": \"white\", \"fontSize\": 12})\n",
        "v1.addLabel(\"ATP Pocket\", {\"position\": {\"chain\": \"A\", \"resn\": \"YUN\"}, \"backgroundColor\": \"#0891b2\", \"fontColor\": \"white\", \"fontSize\": 12})\n",
        "v1.zoomTo({\"chain\": \"A\", \"resi\": list(range(750, 795))})\n",
        "v1.show()\n",
        "\n",
        "# 1B: Actual Amivantamab Anti-MET Fab Bound to Human MET Extracellular Domain (6WVZ)\n",
        "print(\"\\n1B. PDB 6WVZ \u2014 Amivantamab Anti-MET Fab Arm Bound to Human MET Extracellular Domain\")\n",
        "print(\"    Teal = Human MET receptor (chain M) | Gold = Amivantamab Heavy Chain (H) | Violet = Amivantamab Light Chain (L)\")\n",
        "pdb_6wvz = fetch_pdb(\"6WVZ\")\n",
        "v2 = py3Dmol.view(width=820, height=400)\n",
        "v2.addModel(pdb_6wvz, \"pdb\")\n",
        "v2.setStyle({\"chain\": \"M\"}, {\"cartoon\": {\"color\": \"#14b8a6\"}})\n",
        "v2.addSurface(py3Dmol.VDW, {\"opacity\": 0.22, \"color\": \"#14b8a6\"}, {\"chain\": \"M\"})\n",
        "v2.setStyle({\"chain\": \"H\"}, {\"cartoon\": {\"color\": \"#eab308\"}})\n",
        "v2.setStyle({\"chain\": \"L\"}, {\"cartoon\": {\"color\": \"#8b5cf6\"}})\n",
        "v2.addLabel(\"Human MET (Extracellular)\", {\"position\": {\"chain\": \"M\", \"resi\": 200}, \"backgroundColor\": \"#0d9488\", \"fontColor\": \"white\", \"fontSize\": 12})\n",
        "v2.addLabel(\"Amivantamab Anti-MET Fab\", {\"position\": {\"chain\": \"H\", \"resi\": 100}, \"backgroundColor\": \"#ca8a04\", \"fontColor\": \"white\", \"fontSize\": 12})\n",
        "v2.zoomTo()\n",
        "v2.show()\n",
        "\n",
        "# 1C: Anti-EGFR Antibody Fab Bound to EGFR Extracellular Domain III (1YY9)\n",
        "print(\"\\n1C. PDB 1YY9 \u2014 Extracellular Anti-EGFR Fab Bound to EGFR Domain III (Outside the Cell)\")\n",
        "print(\"    Blue = EGFR Extracellular Domain (chain A) | Coral/Pink = Anti-EGFR Fab (chains D/C) \u2014 untouched by intracellular D770 mutation\")\n",
        "pdb_1yy9 = fetch_pdb(\"1YY9\")\n",
        "v3 = py3Dmol.view(width=820, height=400)\n",
        "v3.addModel(pdb_1yy9, \"pdb\")\n",
        "v3.setStyle({\"chain\": \"A\"}, {\"cartoon\": {\"color\": \"#3b82f6\"}})\n",
        "v3.addSurface(py3Dmol.VDW, {\"opacity\": 0.22, \"color\": \"#3b82f6\"}, {\"chain\": \"A\"})\n",
        "v3.setStyle({\"chain\": \"D\"}, {\"cartoon\": {\"color\": \"#f43f5e\"}})\n",
        "v3.setStyle({\"chain\": \"C\"}, {\"cartoon\": {\"color\": \"#fb7185\"}})\n",
        "v3.addLabel(\"EGFR Extracellular Domain III\", {\"position\": {\"chain\": \"A\", \"resi\": 380}, \"backgroundColor\": \"#2563eb\", \"fontColor\": \"white\", \"fontSize\": 12})\n",
        "v3.addLabel(\"Anti-EGFR Fab\", {\"position\": {\"chain\": \"D\", \"resi\": 100}, \"backgroundColor\": \"#e11d48\", \"fontColor\": \"white\", \"fontSize\": 12})\n",
        "v3.zoomTo()\n",
        "v3.show()"
      ],
      "id": "cell-04"
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Part 2. Load CellGemma (`google/cellgemma-e4b`) & Matched NSCLC Tumor Baselines\n",
        "\n",
        "We load:\n",
        "1. **`google/cellgemma-e4b`** (Stage 1 language model with 20K dedicated human protein-coding gene tokens).\n",
        "2. **Stage 2 `ExpressionDecoder`s** for both:\n",
        "   - **`tahoe`** (19,720 genes; single-cell cancer screen, target library depth `1,543`, `log1p`) \u2014 calibrated for single cancer cells.\n",
        "   - **`tisch`** (18,542 genes; clinical patient tumor microenvironment cohorts, `CP10K`, `log1p`) \u2014 calibrated for primary human patient tumor profiles.\n",
        "3. **Two complementary lung adenocarcinoma baseline cohorts:**\n",
        "   - **Cohort A (`tahoe` EGFR+/MET+ A549 single cells):** Unlike the default Colab walkthrough (where `cell_idx=0` has `EGFR` ranked #1,864 and **truncated out of the top-1,000 `Source:` input!**), we explicitly select cells where **both `EGFR` and `MET`** are highly expressed inside the top-1,000 genes.\n",
        "   - **Cohort B (Real human *EGFR* exon 20 insertion + *TP53*-mutant lung adenocarcinoma tumors from TCGA-LUAD via cBioPortal API):**\n",
        "     - `TCGA-44-5645-01`: **`EGFR A767_V769dup`** (near-loop exon 20 insertion, same structural class as `D770delinsGY`) + **`TP53 Q354*`** (truncating TP53 loss-of-function, mirroring `I254fs`)\n",
        "     - `TCGA-50-6673-01`: **`EGFR H773dup`** (exon 20 insertion) + **`TP53 R337C`**\n",
        "     - *Transparency note:* TCGA-LUAD is bulk RNA-seq (RSEM), whereas CellGemma decoders were trained on single-cell pseudobulks\u2014so running both Cohort A (calibrated single-cell) and Cohort B (real *EGFR* ex20ins + *TP53* human tumor transcriptomes) gives us both calibration fidelity and mutation-context fidelity!"
      ],
      "id": "cell-05"
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "#@title Load ExpressionDecoder architecture, bundled assets, and CellGemma model\n",
        "from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig\n",
        "\n",
        "MODEL_ID = \"google/cellgemma-e4b\"\n",
        "\n",
        "def load_hf_json(filename: str, repo_id: str = MODEL_ID):\n",
        "    with open(hf_hub_download(repo_id, filename), encoding=\"utf-8\") as f:\n",
        "        return json.load(f)\n",
        "\n",
        "controls_data = load_hf_json(\"controls_sample.json\")\n",
        "kg_sentences = load_hf_json(\"kg_sentences.json\")\n",
        "\n",
        "class ExpressionDecoder(nn.Module):\n",
        "    '''Dataset-specific Stage 2 MLP reconstructing continuous residual deltas.'''\n",
        "    def __init__(self, input_dim: int, hidden_dims: list[int], max_exp_arg: float = 88.0):\n",
        "        super().__init__()\n",
        "        self.input_dim = input_dim\n",
        "        self.max_exp_arg = max_exp_arg\n",
        "        self.bn0 = nn.BatchNorm1d(input_dim + 1)\n",
        "        layers, d = [self.bn0], input_dim + 1\n",
        "        for h in hidden_dims:\n",
        "            layers += [nn.Linear(d, h), nn.ReLU()]\n",
        "            d = h\n",
        "        self.mlp = nn.Sequential(*layers, nn.Linear(d, 1))\n",
        "\n",
        "    def forward(self, features: torch.Tensor, control_expression: torch.Tensor) -> torch.Tensor:\n",
        "        eps, ctrl = 1e-6, control_expression.view(-1, 1)\n",
        "        x = self.mlp(torch.cat([features, ctrl], dim=1))\n",
        "        ctrl_safe = ctrl - torch.where(x >= 0, eps, -eps)\n",
        "        exp_term = (x / ctrl_safe).clamp(max=self.max_exp_arg)\n",
        "        neg_delta = ctrl_safe * (torch.exp(exp_term) - 1.0)\n",
        "        return torch.where(x > 0, x, neg_delta) + eps\n",
        "\n",
        "def load_decoder(name: str):\n",
        "    cfg = load_hf_json(f\"decoders/{name}/config.json\")\n",
        "    decoder = ExpressionDecoder(cfg[\"input_dim\"], cfg[\"hidden_dims\"])\n",
        "    weights = hf_hub_download(MODEL_ID, f\"decoders/{name}/model.safetensors\")\n",
        "    decoder.load_state_dict(safetensors.torch.load_file(weights))\n",
        "    raw_md = load_hf_json(f\"decoders/{name}/mean_delta_global.json\")\n",
        "    mean_deltas = {k.upper(): float(v) for k, v in raw_md.items()}\n",
        "    return decoder.eval(), mean_deltas\n",
        "\n",
        "tahoe_decoder, tahoe_mean_deltas = load_decoder(\"tahoe\")\n",
        "tisch_decoder, tisch_mean_deltas = load_decoder(\"tisch\")\n",
        "tahoe_genes = [g.upper() for g in controls_data[\"tahoe\"][\"genes\"]]\n",
        "tahoe_g2i = {g: i for i, g in enumerate(tahoe_genes)}\n",
        "tisch_genes = list(tisch_mean_deltas.keys())\n",
        "tisch_g2i = {g: i for i, g in enumerate(tisch_genes)}\n",
        "\n",
        "print(f\"Loaded decoders: tahoe ({len(tahoe_genes):,} genes), tisch ({len(tisch_genes):,} genes)\")\n",
        "print(f\"KG entries verified: EGFR={('EGFR' in kg_sentences)}, MET={('MET' in kg_sentences)}\")\n",
        "\n",
        "# Load Stage 1 CellGemma LLM\n",
        "tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)\n",
        "tokenizer.padding_side = \"left\"\n",
        "if USE_4BIT:\n",
        "    bnb_cfg = BitsAndBytesConfig(\n",
        "        load_in_4bit=True,\n",
        "        bnb_4bit_quant_type=\"nf4\",\n",
        "        bnb_4bit_compute_dtype=torch.bfloat16,\n",
        "        bnb_4bit_use_double_quant=True,\n",
        "    )\n",
        "    model = AutoModelForCausalLM.from_pretrained(\n",
        "        MODEL_ID,\n",
        "        device_map=\"auto\",\n",
        "        quantization_config=bnb_cfg,\n",
        "    ).eval()\n",
        "    print(f\"Loaded {MODEL_ID} in 4-bit NF4 on {model.device}.\")\n",
        "else:\n",
        "    model = AutoModelForCausalLM.from_pretrained(\n",
        "        MODEL_ID,\n",
        "        device_map=\"auto\",\n",
        "        dtype=torch.bfloat16 if HAS_CUDA else torch.float32,\n",
        "    ).eval()\n",
        "    print(f\"Loaded {MODEL_ID} in {model.dtype} on {model.device}.\")"
      ],
      "id": "cell-06"
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "#@title Core CellGemma prompt, inference (with disk caching), and reconstruction helpers\n",
        "PROMPT_INSTRUCTION = (\n",
        "    \"Examine how the single-cell sample, captured in 'Source:', responds\"\n",
        "    \" transcriptionally to the perturbation under the stated experimental\"\n",
        "    \" conditions. You are given the dataset-wide average prediction in 'Mean\"\n",
        "    \" Global prediction:' and you need to predict the residual from that mean\"\n",
        "    \" to the true final expression.\"\n",
        ")\n",
        "_MEAN_GLOBAL_TASK_ONE_HOT = [0.0] * 7 + [1.0]\n",
        "\n",
        "# Persistent disk cache so GPU predictions are never lost across reruns\n",
        "def load_cache() -> dict:\n",
        "    if CACHE_PATH.exists():\n",
        "        return json.loads(CACHE_PATH.read_text(encoding=\"utf-8\"))\n",
        "    return {}\n",
        "\n",
        "def save_cache(cache: dict) -> None:\n",
        "    CACHE_PATH.write_text(json.dumps(cache), encoding=\"utf-8\")\n",
        "\n",
        "PRED_CACHE = load_cache()\n",
        "\n",
        "def build_source_sentence(expr: np.ndarray, gene_names: list[str], top_k: int = 1000) -> str:\n",
        "    ranked = [gene_names[i] for i in np.argsort(expr)[::-1] if expr[i] > 0]\n",
        "    return \" \".join(ranked[:top_k])\n",
        "\n",
        "def build_prompt(perturbation_text: str, gene_names: list[str], ctrl_expr: np.ndarray, baseline: np.ndarray) -> str:\n",
        "    return (\n",
        "        f\"{PROMPT_INSTRUCTION}\\n\\n\"\n",
        "        f\"{perturbation_text}\\n\\n\"\n",
        "        f\"Source: {build_source_sentence(ctrl_expr, gene_names)}\\n\\n\"\n",
        "        f\"Mean Global prediction: {build_source_sentence(baseline, gene_names)}\\n\"\n",
        "        \"Target: \"\n",
        "    )\n",
        "\n",
        "def drug_perturbation_text(drug_name: str, smiles: str, concentration_um: float) -> str:\n",
        "    return (\n",
        "        f\"Drug name: {drug_name}\\n\"\n",
        "        f\"Drug SMILES: {smiles}\\n\"\n",
        "        f\"Concentration: {concentration_um} uM\"\n",
        "    )\n",
        "\n",
        "def knockdown_perturbation_text(target_gene: str) -> str:\n",
        "    return f\"Gene knockdown: {kg_sentences[target_gene.upper()].strip()}\"\n",
        "\n",
        "def align_and_normalize(\n",
        "    raw_expr_by_gene: dict[str, float],\n",
        "    target_genes: list[str],\n",
        "    mean_deltas: dict[str, float],\n",
        "    target_depth: float = 1543.0,\n",
        ") -> tuple[np.ndarray, np.ndarray]:\n",
        "    '''Align external expression dict to decoder gene order, library-normalize, log1p, and compute baseline.'''\n",
        "    raw = np.array([max(0.0, float(raw_expr_by_gene.get(g, 0.0))) for g in target_genes], dtype=np.float64)\n",
        "    total = raw.sum()\n",
        "    if total > 0:\n",
        "        norm = np.log1p(raw / total * target_depth).astype(np.float32)\n",
        "    else:\n",
        "        norm = np.zeros(len(target_genes), dtype=np.float32)\n",
        "    mean_vec = np.array([mean_deltas.get(g, 0.0) for g in target_genes], dtype=np.float32)\n",
        "    baseline = np.maximum(0.0, norm + mean_vec)\n",
        "    return norm, baseline\n",
        "\n",
        "def load_tahoe_control_cell(cell_idx: int) -> tuple[np.ndarray, np.ndarray]:\n",
        "    ctrl_expr = np.array(controls_data[\"tahoe\"][\"cells\"][cell_idx][\"expression\"], dtype=np.float32)\n",
        "    mean_vec = np.array([tahoe_mean_deltas[g] for g in tahoe_genes], dtype=np.float32)\n",
        "    baseline = np.maximum(0.0, ctrl_expr + mean_vec)\n",
        "    return ctrl_expr, baseline\n",
        "\n",
        "def generate_cellgemma_batch(\n",
        "    prompts: list[str],\n",
        "    cache_tags: list[str],\n",
        "    temperature: float = TEMPERATURE,\n",
        "    max_new_tokens: int = MAX_NEW_TOKENS,\n",
        "    batch_size: int = BATCH_SIZE,\n",
        ") -> list[str]:\n",
        "    '''Runs batched Stage 1 CellGemma generation (~3.5x faster on L4/A100) with per-item disk caching.'''\n",
        "    assert len(prompts) == len(cache_tags)\n",
        "    results: list[str | None] = [None] * len(prompts)\n",
        "    pending: list[tuple[int, str, str, str]] = []\n",
        "\n",
        "    for i, (p, tag) in enumerate(zip(prompts, cache_tags)):\n",
        "        key_raw = f\"{tag}|t={temperature}|m={max_new_tokens}|{p}\"\n",
        "        key = hashlib.sha256(key_raw.encode(\"utf-8\")).hexdigest()[:24]\n",
        "        if key in PRED_CACHE:\n",
        "            results[i] = PRED_CACHE[key]\n",
        "        else:\n",
        "            pending.append((i, key, tag, p))\n",
        "\n",
        "    if not pending:\n",
        "        return [r for r in results if r is not None]\n",
        "\n",
        "    # Sort pending by prompt length to minimize left-padding waste\n",
        "    pending.sort(key=lambda x: len(x[3]))\n",
        "    eot_id = tokenizer.convert_tokens_to_ids(\"<turn|>\")\n",
        "    stop_ids = {tid for tid in (tokenizer.eos_token_id, eot_id) if tid is not None}\n",
        "\n",
        "    for start in range(0, len(pending), max(1, batch_size)):\n",
        "        chunk = pending[start : start + max(1, batch_size)]\n",
        "        formatted = [f\"<bos><|turn>user\\n{item[3]}<turn|>\\n<|turn>model\\n\" for item in chunk]\n",
        "        torch.manual_seed(SEED + start)\n",
        "        inputs = tokenizer(\n",
        "            formatted,\n",
        "            return_tensors=\"pt\",\n",
        "            padding=True,\n",
        "            add_special_tokens=False,\n",
        "        ).to(model.device)\n",
        "        in_len = inputs[\"input_ids\"].shape[1]\n",
        "        gen_kwargs = dict(\n",
        "            **inputs,\n",
        "            max_new_tokens=max_new_tokens,\n",
        "            do_sample=(temperature > 0.01),\n",
        "            pad_token_id=tokenizer.pad_token_id,\n",
        "            eos_token_id=list(stop_ids),\n",
        "        )\n",
        "        if temperature > 0.01:\n",
        "            gen_kwargs[\"temperature\"] = temperature\n",
        "\n",
        "        t0 = time.perf_counter()\n",
        "        with torch.no_grad():\n",
        "            outputs = model.generate(**gen_kwargs)\n",
        "        dt = time.perf_counter() - t0\n",
        "\n",
        "        total_gen_toks = 0\n",
        "        for b_idx, (orig_i, key, tag, _) in enumerate(chunk):\n",
        "            seq = outputs[b_idx, in_len:].tolist()\n",
        "            # Slice cleanly at first stop token\n",
        "            cut = next((pos for pos, tid in enumerate(seq) if tid in stop_ids), len(seq))\n",
        "            seq = seq[:cut]\n",
        "            total_gen_toks += len(seq)\n",
        "            text = tokenizer.decode(seq, skip_special_tokens=True).strip()\n",
        "            results[orig_i] = text\n",
        "            PRED_CACHE[key] = text\n",
        "\n",
        "        save_cache(PRED_CACHE)\n",
        "        tags_str = \", \".join(item[2] for item in chunk)\n",
        "        print(\n",
        "            f\"  [batch x{len(chunk)}] {tags_str} -> {total_gen_toks} tok in {dt:.1f}s \"\n",
        "            f\"({total_gen_toks/max(dt,1e-3):.1f} agg tok/s)\",\n",
        "            flush=True,\n",
        "        )\n",
        "        del inputs, outputs\n",
        "        if HAS_CUDA:\n",
        "            torch.cuda.empty_cache()\n",
        "\n",
        "    return [r or \"\" for r in results]\n",
        "\n",
        "def generate_cellgemma_response(\n",
        "    prompt: str,\n",
        "    cache_tag: str = \"\",\n",
        "    temperature: float = TEMPERATURE,\n",
        "    max_new_tokens: int = MAX_NEW_TOKENS,\n",
        ") -> str:\n",
        "    '''Runs Stage 1 CellGemma generation for a single prompt (delegates to cached batch helper).'''\n",
        "    return generate_cellgemma_batch(\n",
        "        [prompt], [cache_tag], temperature=temperature, max_new_tokens=max_new_tokens, batch_size=1\n",
        "    )[0]\n",
        "\n",
        "def parse_output_sentence(sentence: str, gene_to_idx: dict[str, int]) -> tuple[list[str], list[str]]:\n",
        "    up, down, seen = [], [], set()\n",
        "    for tok in sentence.split():\n",
        "        if len(tok) < 2 or tok[0] not in (\"+\", \"-\"):\n",
        "            continue\n",
        "        g = tok[1:].upper()\n",
        "        if g in gene_to_idx and g not in seen:\n",
        "            seen.add(g)\n",
        "            if tok[0] == \"+\":\n",
        "                up.append(g)\n",
        "            else:\n",
        "                down.append(g)\n",
        "    return up, down\n",
        "\n",
        "def reconstruct_expression(\n",
        "    response_text: str,\n",
        "    gene_names: list[str],\n",
        "    ctrl_expr: np.ndarray,\n",
        "    baseline: np.ndarray,\n",
        "    decoder: ExpressionDecoder,\n",
        "    max_new_tokens: int = MAX_NEW_TOKENS,\n",
        ") -> tuple[np.ndarray, np.ndarray, list[str], list[str]]:\n",
        "    '''Stage 2 ExpressionDecoder reconstruction returning (pred_expr, pred_lfc, up_genes, down_genes).'''\n",
        "    gene_to_idx = {g: i for i, g in enumerate(gene_names)}\n",
        "    up, down = parse_output_sentence(response_text, gene_to_idx)\n",
        "    residual_vec = np.zeros_like(baseline)\n",
        "\n",
        "    if up or down:\n",
        "        # Match Hugging Face Space truncation adjustment when capped below 2048 tokens\n",
        "        is_truncated = (max_new_tokens < 2048) and ((len(up) + len(down)) >= int(max_new_tokens * 0.45))\n",
        "        eff_up = float(max(len(up), 550) if is_truncated else len(up))\n",
        "        eff_dn = float(max(len(down), 550) if is_truncated else len(down))\n",
        "\n",
        "        features, ctrl_vals, indices = [], [], []\n",
        "        for is_up, g_list in ((1.0, up), (0.0, down)):\n",
        "            for rank, g in enumerate(g_list):\n",
        "                idx = gene_to_idx[g]\n",
        "                features.append([is_up, float(rank), eff_up, eff_dn] + _MEAN_GLOBAL_TASK_ONE_HOT)\n",
        "                ctrl_vals.append(float(baseline[idx]))\n",
        "                indices.append(idx)\n",
        "        with torch.no_grad():\n",
        "            deltas = decoder(\n",
        "                torch.tensor(features, dtype=torch.float32),\n",
        "                torch.tensor(ctrl_vals, dtype=torch.float32),\n",
        "            )\n",
        "        residual_vec[indices] = deltas.cpu().numpy().flatten()\n",
        "\n",
        "    pred_expr = baseline + residual_vec\n",
        "    pred_lfc = pred_expr - ctrl_expr\n",
        "    return pred_expr, pred_lfc, up, down\n",
        "\n",
        "# Curated oncology pathway signatures shared across Parts 3, 4, and 6\n",
        "PATHWAYS = {\n",
        "    \"MAPK / ERK Output\": [\n",
        "        \"DUSP4\", \"DUSP5\", \"DUSP6\", \"SPRY2\", \"SPRY4\", \"ETV4\", \"ETV5\",\n",
        "        \"EGR1\", \"FOSL1\", \"MYC\", \"PHLDA1\", \"CCND1\", \"AREG\", \"EREG\",\n",
        "    ],\n",
        "    \"PI3K / AKT / Survival\": [\n",
        "        \"AKT1\", \"AKT3\", \"MTOR\", \"RPS6\", \"EIF4EBP1\", \"BCL2L1\", \"MCL1\",\n",
        "        \"MDM2\", \"TXNIP\", \"NDRG1\", \"SQSTM1\",\n",
        "    ],\n",
        "    \"Proliferation / Cell Cycle\": [\n",
        "        \"MKI67\", \"TOP2A\", \"CDK4\", \"CDK6\", \"CCNB1\", \"PCNA\", \"AURKA\",\n",
        "        \"BIRC5\", \"MCM2\", \"TYMS\", \"CDC20\",\n",
        "    ],\n",
        "    \"Apoptosis & Growth Arrest\": [\n",
        "        \"BCL2L11\", \"BBC3\", \"BAX\", \"CDKN1A\", \"GADD45A\", \"BTG1\", \"BTG2\",\n",
        "        \"DDIT3\", \"PPP1R15A\", \"PMAIP1\",\n",
        "    ],\n",
        "    \"Immune Surface Visibility\": [\n",
        "        \"B2M\", \"HLA-A\", \"HLA-B\", \"HLA-C\", \"ICAM1\", \"CALR\", \"CD274\",\n",
        "        \"MICA\", \"ULBP2\", \"PVR\", \"TAP1\",\n",
        "    ],\n",
        "    \"Bypass / HER2 / EMT Tracks\": [\n",
        "        \"ERBB2\", \"ERBB3\", \"AXL\", \"IGF1R\", \"FGFR1\", \"PDGFRA\", \"VIM\",\n",
        "        \"ZEB1\", \"SERPINE1\", \"MET\", \"EGFR\", \"LRP1\",\n",
        "    ],\n",
        "}\n",
        "\n",
        "def score_pathways(lfc_vec: np.ndarray, gene_to_idx: dict[str, int]) -> dict[str, float]:\n",
        "    out = {}\n",
        "    for pname, glist in PATHWAYS.items():\n",
        "        vals = [float(lfc_vec[gene_to_idx[g]]) for g in glist if g in gene_to_idx]\n",
        "        out[pname] = float(np.mean(vals)) if vals else 0.0\n",
        "    return out\n",
        "\n",
        "# Verified PubChem canonical SMILES & 6 perturbation arm definitions (usable by Parts 3 & 4 independently)\n",
        "SMILES = {\n",
        "    \"Sunvozertinib\": \"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",
        "    \"Lazertinib\":    \"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",
        "    \"Capmatinib\":    \"CNC(=O)C1=C(C=C(C=C1)C2=NN3C(=CN=C3N=C2)CC4=CC5=C(C=C4)N=CC=C5)F\",\n",
        "}\n",
        "\n",
        "ARMS = {\n",
        "    \"EGFR_KD\": knockdown_perturbation_text(\"EGFR\"),\n",
        "    \"MET_KD\": knockdown_perturbation_text(\"MET\"),\n",
        "    \"DUAL_EGFR_MET_KD\": (\n",
        "        f\"{knockdown_perturbation_text('EGFR')}\\n\"\n",
        "        f\"{knockdown_perturbation_text('MET')}\"\n",
        "    ),\n",
        "    \"SUNVO_PLUS_CAP\": (\n",
        "        drug_perturbation_text(\"Sunvozertinib\", SMILES[\"Sunvozertinib\"], 0.5) + \"\\n\"\n",
        "        + drug_perturbation_text(\"Capmatinib\", SMILES[\"Capmatinib\"], 0.5)\n",
        "    ),\n",
        "    \"LAZ_PLUS_CAP\": (\n",
        "        drug_perturbation_text(\"Lazertinib\", SMILES[\"Lazertinib\"], 0.5) + \"\\n\"\n",
        "        + drug_perturbation_text(\"Capmatinib\", SMILES[\"Capmatinib\"], 0.5)\n",
        "    ),\n",
        "    \"AMI_ZEROSHOT\": (\n",
        "        \"Drug name: Amivantamab\\n\"\n",
        "        \"Drug description: Bispecific IgG1 monoclonal antibody targeting extracellular domains \"\n",
        "        \"of EGFR and MET receptors, blocking ligand binding and promoting receptor internalization \"\n",
        "        \"and lysosomal degradation in EGFR exon 20 insertion non-small cell lung cancer.\"\n",
        "    ),\n",
        "}\n",
        "\n",
        "print(\"Helper functions, pathway modules, and 6 perturbation arms ready.\")"
      ],
      "id": "cell-07"
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "#@title Select top EGFR+/MET+ Tahoe NSCLC cells & fetch real TCGA-LUAD EGFR exon 20 + TP53 tumors\n",
        "def get_gene_rank(expr: np.ndarray, gene_names: list[str], symbol: str) -> tuple[int, float]:\n",
        "    idx = gene_names.index(symbol.upper())\n",
        "    order = np.argsort(expr)[::-1]\n",
        "    rank = int(np.where(order == idx)[0][0]) + 1\n",
        "    return rank, float(expr[idx])\n",
        "\n",
        "# --- Cohort A: Rank Tahoe A549 cells by combined EGFR & MET rank inside top-1000 ---\n",
        "tahoe_candidates = []\n",
        "for idx in range(len(controls_data[\"tahoe\"][\"cells\"])):\n",
        "    v = np.array(controls_data[\"tahoe\"][\"cells\"][idx][\"expression\"], dtype=np.float32)\n",
        "    e_rank, e_val = get_gene_rank(v, tahoe_genes, \"EGFR\")\n",
        "    m_rank, m_val = get_gene_rank(v, tahoe_genes, \"MET\")\n",
        "    if e_rank <= 1000 and m_rank <= 1000:\n",
        "        tahoe_candidates.append((e_rank + m_rank, idx, e_rank, e_val, m_rank, m_val))\n",
        "tahoe_candidates.sort()\n",
        "\n",
        "SELECTED_TAHOE_CELLS = [row[1] for row in tahoe_candidates[:N_TAHOE_CELLS]]\n",
        "c0_e_rank, c0_e_val = get_gene_rank(\n",
        "    np.array(controls_data[\"tahoe\"][\"cells\"][0][\"expression\"], dtype=np.float32), tahoe_genes, \"EGFR\"\n",
        ")\n",
        "print(f\"Why we skip default cell_idx=0: EGFR rank in cell 0 is #{c0_e_rank} (outside top-1,000 Source: cutoff!).\")\n",
        "print(f\"Selected top {len(SELECTED_TAHOE_CELLS)} Tahoe EGFR+/MET+ NSCLC cells:\")\n",
        "for _, idx, er, ev, mr, mv in tahoe_candidates[:N_TAHOE_CELLS]:\n",
        "    print(f\"  cell_idx={idx:2d}: EGFR rank #{er:3d} ({ev:.2f}) | MET rank #{mr:3d} ({mv:.2f})\")\n",
        "\n",
        "# --- Cohort B: Live fetch real TCGA-LUAD EGFR Exon 20 Insertion + TP53-mutant tumors via cBioPortal ---\n",
        "TCGA_SAMPLES = {\n",
        "    \"TCGA-44-5645-01\": \"EGFR A767_V769dup (near-loop ex20ins) + TP53 Q354* (truncating)\",\n",
        "    \"TCGA-50-6673-01\": \"EGFR H773dup (ex20ins) + TP53 R337C\",\n",
        "}\n",
        "\n",
        "def fetch_tcga_luad_rnaseq(sample_ids: list[str]) -> dict[str, dict[str, float]]:\n",
        "    print(\"\\nFetching full protein-coding RNA-seq from cBioPortal (TCGA-LUAD PanCancer Atlas)...\")\n",
        "    genes_meta = json.loads(\n",
        "        urllib.request.urlopen(\n",
        "            \"https://www.cbioportal.org/api/genes?pageSize=25000&projection=SUMMARY\", timeout=25\n",
        "        ).read()\n",
        "    )\n",
        "    pc_genes = [g for g in genes_meta if g.get(\"type\") == \"protein-coding\"]\n",
        "    eids = [g[\"entrezGeneId\"] for g in pc_genes]\n",
        "    eid_to_sym = {g[\"entrezGeneId\"]: g[\"hugoGeneSymbol\"].upper() for g in pc_genes}\n",
        "\n",
        "    expr_map = {sid: {} for sid in sample_ids}\n",
        "    for i in range(0, len(eids), 5000):\n",
        "        chunk = eids[i : i + 5000]\n",
        "        req = urllib.request.Request(\n",
        "            \"https://www.cbioportal.org/api/molecular-profiles/luad_tcga_pan_can_atlas_2018_rna_seq_v2_mrna/molecular-data/fetch\",\n",
        "            data=json.dumps({\"sampleIds\": sample_ids, \"entrezGeneIds\": chunk}).encode(\"utf-8\"),\n",
        "            headers={\"Accept\": \"application/json\", \"Content-Type\": \"application/json\"},\n",
        "        )\n",
        "        rows = json.loads(urllib.request.urlopen(req, timeout=30).read())\n",
        "        for r in rows:\n",
        "            sym = eid_to_sym.get(r[\"entrezGeneId\"])\n",
        "            val = r.get(\"value\")\n",
        "            if sym and val is not None and not math.isnan(float(val)):\n",
        "                expr_map[r[\"sampleId\"]][sym] = float(val)\n",
        "    return expr_map\n",
        "\n",
        "tcga_raw = fetch_tcga_luad_rnaseq(list(TCGA_SAMPLES.keys()))\n",
        "tcga_aligned_tahoe = {}\n",
        "tcga_aligned_tisch = {}\n",
        "for sid, desc in TCGA_SAMPLES.items():\n",
        "    ctrl_t, base_t = align_and_normalize(tcga_raw[sid], tahoe_genes, tahoe_mean_deltas, target_depth=1543.0)\n",
        "    ctrl_c, base_c = align_and_normalize(tcga_raw[sid], tisch_genes, tisch_mean_deltas, target_depth=10000.0)\n",
        "    tcga_aligned_tahoe[sid] = (ctrl_t, base_t)\n",
        "    tcga_aligned_tisch[sid] = (ctrl_c, base_c)\n",
        "    er, ev = get_gene_rank(ctrl_t, tahoe_genes, \"EGFR\")\n",
        "    mr, mv = get_gene_rank(ctrl_t, tahoe_genes, \"MET\")\n",
        "    h2r, h2v = get_gene_rank(ctrl_t, tahoe_genes, \"ERBB2\")\n",
        "    print(f\"  {sid} ({desc}):\")\n",
        "    print(f\"    {len(tcga_raw[sid]):,} genes loaded | EGFR rank #{er} ({ev:.2f}) | MET rank #{mr} ({mv:.2f}) | ERBB2/HER2 rank #{h2r} ({h2v:.2f})\")"
      ],
      "id": "cell-08"
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Part 3. CellGemma Multi-Arm Simulation (Mechanism #1 \u2014 Intracellular Pathway Shutdown)\n",
        "\n",
        "To isolate what amivantamab's **receptor degradation** does inside a lung cancer cell\u2014and specifically **what hitting MET adds on top of hitting EGFR alone**\u2014we run **6 perturbation arms**:\n",
        "\n",
        "| Arm | Perturbation Input | Why We Include It |\n",
        "| :--- | :--- | :--- |\n",
        "| **`EGFR_KD`** | `Gene knockdown: EGFR` (STRING KG) | Baseline effect of eliminating EGFR signaling alone |\n",
        "| **`MET_KD`** | `Gene knockdown: MET` (STRING KG) | Baseline effect of eliminating MET signaling alone |\n",
        "| **`DUAL_EGFR_MET_KD`** | Dual `EGFR` + `MET` knockdown (combinatorial KG) | **Closest CellGemma-native mechanistic proxy** to amivantamab's dual EGFR/MET receptor destruction |\n",
        "| **`SUNVO_PLUS_CAP`** | **Sunvozertinib** (exon-20-selective EGFR TKI) + **Capmatinib** (MET TKI) | In-distribution small-molecule pathway surrogate (verified PubChem SMILES) |\n",
        "| **`LAZ_PLUS_CAP`** | **Lazertinib** (MARIPOSA EGFR TKI) + **Capmatinib** (MET TKI) | Second in-distribution small-molecule surrogate for cross-modality concordance |\n",
        "| **`AMI_ZEROSHOT`** | `Drug name: Amivantamab` + mechanism description (no SMILES) | Exploratory zero-shot test (out-of-distribution; compare against arms 3\u20135!) |\n",
        "\n",
        "*(All predictions are cached to disk as each call completes.)*"
      ],
      "id": "cell-09"
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "#@title Run CellGemma across all 6 arms on Tahoe EGFR+/MET+ NSCLC cells + TCGA Ex20ins tumors\n",
        "# 1. Run all 6 arms across selected Tahoe EGFR+/MET+ NSCLC single cells (batched per arm!)\n",
        "tahoe_arm_lfcs = {}\n",
        "tahoe_arm_raw = {}\n",
        "print(f\"=== Running {len(ARMS)} arms x {len(SELECTED_TAHOE_CELLS)} Tahoe EGFR+/MET+ NSCLC cells (BATCH_SIZE={BATCH_SIZE}) ===\")\n",
        "for arm_name, pert_text in ARMS.items():\n",
        "    print(f\"\\nArm: {arm_name}\")\n",
        "    cell_data = [load_tahoe_control_cell(cidx) for cidx in SELECTED_TAHOE_CELLS]\n",
        "    prompts = [build_prompt(pert_text, tahoe_genes, ctrl, base) for ctrl, base in cell_data]\n",
        "    tags = [f\"tahoe_c{cidx}_{arm_name}\" for cidx in SELECTED_TAHOE_CELLS]\n",
        "    responses = generate_cellgemma_batch(prompts, tags)\n",
        "\n",
        "    lfcs, raws = [], []\n",
        "    for (ctrl, base), resp in zip(cell_data, responses):\n",
        "        _, lfc, up, dn = reconstruct_expression(resp, tahoe_genes, ctrl, base, tahoe_decoder)\n",
        "        lfcs.append(lfc)\n",
        "        raws.append((len(up), len(dn), up[:8], dn[:8]))\n",
        "    tahoe_arm_lfcs[arm_name] = np.mean(lfcs, axis=0)\n",
        "    tahoe_arm_raw[arm_name] = raws\n",
        "    mean_up = np.mean([r[0] for r in raws])\n",
        "    mean_dn = np.mean([r[1] for r in raws])\n",
        "    print(f\"  Avg predicted DEGs: +{mean_up:.0f} up / -{mean_dn:.0f} down\")\n",
        "\n",
        "# 2. Run key arms on real human TCGA-LUAD EGFR Exon 20 Insertion + TP53 tumors (batched!)\n",
        "TCGA_ARMS = [\"EGFR_KD\", \"MET_KD\", \"DUAL_EGFR_MET_KD\", \"SUNVO_PLUS_CAP\", \"AMI_ZEROSHOT\"]\n",
        "tcga_tahoe_lfcs = {sid: {} for sid in TCGA_SAMPLES}\n",
        "tcga_tisch_lfcs = {sid: {} for sid in TCGA_SAMPLES}\n",
        "\n",
        "print(\"\\n=== Running CellGemma on real human TCGA-LUAD EGFR exon 20 + TP53 tumors (batched) ===\")\n",
        "tcga_jobs = []\n",
        "for sid in TCGA_SAMPLES:\n",
        "    ctrl_t, base_t = tcga_aligned_tahoe[sid]\n",
        "    ctrl_c, base_c = tcga_aligned_tisch[sid]\n",
        "    for arm_name in TCGA_ARMS:\n",
        "        pert_text = ARMS[arm_name]\n",
        "        tcga_jobs.append((\"tahoe\", sid, arm_name, build_prompt(pert_text, tahoe_genes, ctrl_t, base_t), f\"{sid}_tahoe_{arm_name}\"))\n",
        "        if arm_name in (\"DUAL_EGFR_MET_KD\", \"AMI_ZEROSHOT\"):\n",
        "            clinical_text = \"Amivantamab\" if arm_name == \"AMI_ZEROSHOT\" else pert_text\n",
        "            tcga_jobs.append((\"tisch\", sid, arm_name, build_prompt(clinical_text, tisch_genes, ctrl_c, base_c), f\"{sid}_tisch_{arm_name}\"))\n",
        "\n",
        "tcga_resps = generate_cellgemma_batch([j[3] for j in tcga_jobs], [j[4] for j in tcga_jobs])\n",
        "for (dec_kind, sid, arm_name, _, _), resp in zip(tcga_jobs, tcga_resps):\n",
        "    if dec_kind == \"tahoe\":\n",
        "        ctrl_t, base_t = tcga_aligned_tahoe[sid]\n",
        "        _, lfc_t, _, _ = reconstruct_expression(resp, tahoe_genes, ctrl_t, base_t, tahoe_decoder)\n",
        "        tcga_tahoe_lfcs[sid][arm_name] = lfc_t\n",
        "    else:\n",
        "        ctrl_c, base_c = tcga_aligned_tisch[sid]\n",
        "        _, lfc_c, _, _ = reconstruct_expression(resp, tisch_genes, ctrl_c, base_c, tisch_decoder)\n",
        "        tcga_tisch_lfcs[sid][arm_name] = lfc_c\n",
        "\n",
        "print(\"\\nAll CellGemma Stage 1 + Stage 2 predictions complete!\")"
      ],
      "id": "cell-10"
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "#@title Pathway dissection, \"What MET adds over EGFR\", and Genetic-Chemical concordance plots\n",
        "# Build pathway matrix across all 6 arms (Tahoe) + TCGA-44-5645-01 & TCGA-50-6673-01 dual KD\n",
        "pw_rows = {}\n",
        "for arm_name, lfc in tahoe_arm_lfcs.items():\n",
        "    pw_rows[f\"Tahoe | {arm_name}\"] = score_pathways(lfc, tahoe_g2i)\n",
        "for sid in TCGA_SAMPLES:\n",
        "    pw_rows[f\"{sid} | DUAL_EGFR_MET_KD\"] = score_pathways(tcga_tahoe_lfcs[sid][\"DUAL_EGFR_MET_KD\"], tahoe_g2i)\n",
        "    pw_rows[f\"{sid} | SUNVO_PLUS_CAP\"] = score_pathways(tcga_tahoe_lfcs[sid][\"SUNVO_PLUS_CAP\"], tahoe_g2i)\n",
        "\n",
        "pw_df = pd.DataFrame(pw_rows).T\n",
        "\n",
        "# --- FIGURE 1: Pathway Heatmap + Top Shifted Genes ---\n",
        "fig, axes = plt.subplots(1, 2, figsize=(16, 6), gridspec_kw={\"width_ratios\": [1.3, 1.0]})\n",
        "\n",
        "vmax = max(0.05, float(np.abs(pw_df.values).max()))\n",
        "sns.heatmap(\n",
        "    pw_df,\n",
        "    ax=axes[0],\n",
        "    cmap=\"RdBu_r\",\n",
        "    center=0.0,\n",
        "    vmin=-vmax,\n",
        "    vmax=vmax,\n",
        "    annot=True,\n",
        "    fmt=\".3f\",\n",
        "    linewidths=0.5,\n",
        "    cbar_kws={\"label\": \"Mean Predicted Log-Expr Shift (LFC)\"},\n",
        ")\n",
        "axes[0].set_title(\"CellGemma Predicted Pathway Shifts Across Perturbation Arms\", fontsize=12, fontweight=\"bold\")\n",
        "axes[0].tick_params(axis=\"x\", rotation=28)\n",
        "\n",
        "# Right panel: What Dual EGFR+MET adds over EGFR alone (Tahoe mean LFC)\n",
        "delta_met_added = tahoe_arm_lfcs[\"DUAL_EGFR_MET_KD\"] - tahoe_arm_lfcs[\"EGFR_KD\"]\n",
        "top_pos = np.argsort(delta_met_added)[::-1][:10]\n",
        "top_neg = np.argsort(delta_met_added)[:10]\n",
        "sel = np.concatenate([top_pos, top_neg[::-1]])\n",
        "labels = [tahoe_genes[i] for i in sel]\n",
        "vals = [float(delta_met_added[i]) for i in sel]\n",
        "colors = [\"#dc2626\" if v > 0 else \"#2563eb\" for v in vals]\n",
        "\n",
        "axes[1].barh(labels[::-1], vals[::-1], color=colors[::-1])\n",
        "axes[1].axvline(0, color=\"black\", linewidth=0.8)\n",
        "axes[1].set_title(\"What Blocking MET Adds Beyond EGFR Alone\\n(DUAL_EGFR_MET_KD minus EGFR_KD)\", fontsize=12, fontweight=\"bold\")\n",
        "axes[1].set_xlabel(\"Additional Predicted LFC from Dual EGFR+MET\")\n",
        "plt.tight_layout()\n",
        "plt.savefig(RESULTS_DIR / \"fig1_cellgemma_pathways_and_met_delta.png\", dpi=150, bbox_inches=\"tight\")\n",
        "plt.show()\n",
        "\n",
        "# --- FIGURE 2: Genetic-Chemical Concordance & Key Marker Gene Comparison ---\n",
        "fig, axes = plt.subplots(1, 2, figsize=(15, 5.5))\n",
        "\n",
        "x = tahoe_arm_lfcs[\"DUAL_EGFR_MET_KD\"]\n",
        "y_sunvo = tahoe_arm_lfcs[\"SUNVO_PLUS_CAP\"]\n",
        "y_laz = tahoe_arm_lfcs[\"LAZ_PLUS_CAP\"]\n",
        "mask = (np.abs(x) > 1e-4) | (np.abs(y_sunvo) > 1e-4)\n",
        "r_sunvo, _ = stats.pearsonr(x[mask], y_sunvo[mask]) if mask.sum() > 2 else (0.0, 1.0)\n",
        "mask2 = (np.abs(x) > 1e-4) | (np.abs(y_laz) > 1e-4)\n",
        "r_laz, _ = stats.pearsonr(x[mask2], y_laz[mask2]) if mask2.sum() > 2 else (0.0, 1.0)\n",
        "\n",
        "axes[0].scatter(x[mask], y_sunvo[mask], s=14, alpha=0.45, color=\"#0d9488\", label=f\"Sunvozertinib+Capmatinib (r={r_sunvo:.2f})\")\n",
        "axes[0].scatter(x[mask2], y_laz[mask2], s=14, alpha=0.35, color=\"#7c3aed\", label=f\"Lazertinib+Capmatinib (r={r_laz:.2f})\")\n",
        "axes[0].axhline(0, color=\"gray\", lw=0.7, ls=\"--\")\n",
        "axes[0].axvline(0, color=\"gray\", lw=0.7, ls=\"--\")\n",
        "# Label standout concordant genes\n",
        "concord = np.abs(x) + np.abs(y_sunvo)\n",
        "for i in np.argsort(concord)[::-1][:12]:\n",
        "    if abs(x[i]) > 0.02 or abs(y_sunvo[i]) > 0.02:\n",
        "        axes[0].annotate(tahoe_genes[i], (x[i], y_sunvo[i]), fontsize=8, alpha=0.9)\n",
        "axes[0].set_xlabel(\"Dual EGFR+MET Knockdown LFC (Genetic)\")\n",
        "axes[0].set_ylabel(\"EGFR TKI + MET TKI LFC (Small-Molecule)\")\n",
        "axes[0].set_title(\"Target-Drug Concordance (Genetic vs. Chemical Surrogates)\", fontsize=11, fontweight=\"bold\")\n",
        "axes[0].legend()\n",
        "\n",
        "# Key cancer biology genes across arms\n",
        "key_genes = [\n",
        "    \"EGFR\", \"MET\", \"ERBB2\", \"ERBB3\", \"DUSP5\", \"DUSP6\", \"MYC\", \"CCND1\",\n",
        "    \"BCL2L11\", \"CDKN1A\", \"MDM2\", \"VIM\", \"SERPINE1\", \"LRP1\", \"CALR\", \"B2M\",\n",
        "]\n",
        "key_present = [g for g in key_genes if g in tahoe_g2i]\n",
        "km = pd.DataFrame({\n",
        "    arm: [float(tahoe_arm_lfcs[arm][tahoe_g2i[g]]) for g in key_present]\n",
        "    for arm in [\"EGFR_KD\", \"MET_KD\", \"DUAL_EGFR_MET_KD\", \"SUNVO_PLUS_CAP\", \"LAZ_PLUS_CAP\", \"AMI_ZEROSHOT\"]\n",
        "}, index=key_present)\n",
        "vmax2 = max(0.05, float(np.abs(km.values).max()))\n",
        "sns.heatmap(km, ax=axes[1], cmap=\"RdBu_r\", center=0.0, vmin=-vmax2, vmax=vmax2, annot=True, fmt=\".2f\", linewidths=0.4)\n",
        "axes[1].set_title(\"Key Signaling, Apoptosis, Surface & Bypass Genes\", fontsize=11, fontweight=\"bold\")\n",
        "axes[1].tick_params(axis=\"x\", rotation=28)\n",
        "\n",
        "plt.tight_layout()\n",
        "plt.savefig(RESULTS_DIR / \"fig2_concordance_and_marker_genes.png\", dpi=150, bbox_inches=\"tight\")\n",
        "plt.show()\n",
        "\n",
        "# Print top 12 up & down genes for Dual EGFR+MET KD and TCGA-44-5645-01\n",
        "for title, vec in [\n",
        "    (\"Tahoe EGFR+/MET+ NSCLC \u2014 DUAL_EGFR_MET_KD\", tahoe_arm_lfcs[\"DUAL_EGFR_MET_KD\"]),\n",
        "    (\"Tahoe EGFR+/MET+ NSCLC \u2014 SUNVO_PLUS_CAP\", tahoe_arm_lfcs[\"SUNVO_PLUS_CAP\"]),\n",
        "    (\"TCGA-44-5645-01 (EGFR ex20ins + TP53*) \u2014 DUAL_EGFR_MET_KD\", tcga_tahoe_lfcs[\"TCGA-44-5645-01\"][\"DUAL_EGFR_MET_KD\"]),\n",
        "]:\n",
        "    up12 = [(tahoe_genes[i], round(float(vec[i]), 3)) for i in np.argsort(vec)[::-1][:12]]\n",
        "    dn12 = [(tahoe_genes[i], round(float(vec[i]), 3)) for i in np.argsort(vec)[:12]]\n",
        "    print(f\"\\n{title}\")\n",
        "    print(\"  Top UP:  \", up12)\n",
        "    print(\"  Top DOWN:\", dn12)"
      ],
      "id": "cell-11"
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Part 4. Real Wet-Lab Single-Cell RNA-seq of Human *EGFR*-Mutant NSCLC Treated with Amivantamab + Lazertinib (`GSE294175`) + CellGemma Validation\n",
        "\n",
        "Rather than relying purely on in-silico predictions, we download **actual 10x Genomics human single-cell RNA-seq** from NCBI GEO **`GSE294175`** (*\"HER2 Overexpression Drives Drug-Tolerant Persisters to First-Line Amivantamab and Lazertinib in EGFR-Mutant Non-Small Cell Lung Cancer\"*):\n",
        "\n",
        "- **Vehicle (`GSM8899894`)**: Untreated human *EGFR*-mutant lung adenocarcinoma PDX (`YHIM-1003`)\n",
        "- **7-Day Treated / Drug-Tolerant Persister (`GSM8899891`, \"Internal\")**: Surviving tumor cells after 7 days of **amivantamab + lazertinib** \u2014 shows the *real* on-treatment transcriptional response!\n",
        "- **28-Day Regrowth (`GSM8899888`)**: Tumor cells that eventually regrew after therapy \u2014 shows the *real* resistance/escape trajectory (**HER2 / `ERBB2` upregulation**)!\n",
        "\n",
        "We do two things here:\n",
        "1. Measure the **real wet-lab single-cell gene expression shifts** (`7-day Treated vs. Vehicle` and `Regrowth vs. Vehicle`) across the exact same oncology pathways.\n",
        "2. **Validate CellGemma directly on the real human tumor:** We pseudobulk cells from `GSE294175` Vehicle (using CellGemma's exact `k=20`, depth `1,543`, `log1p` recipe), run CellGemma (`DUAL_EGFR_MET_KD` and `LAZ_PLUS_CAP`), and measure how closely CellGemma's predictions match the real wet-lab 7-day response!\n",
        "\n",
        "*(Downloads ~300 MB total for 1 replicate/group \u2014 takes ~10\u201315 seconds on Colab. Set `USE_ALL_3_REPLICATES = True` if you want all 9 samples.)*"
      ],
      "id": "cell-12"
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "#@title Download & parse GSE294175 real human EGFR-mutant NSCLC scRNA-seq (Vehicle, 7-day DTP, Regrowth)\n",
        "USE_ALL_3_REPLICATES = False  # Set True to pool all 3 replicates per group (~900 MB total)\n",
        "\n",
        "GSE294175_MANIFEST = {\n",
        "    \"Vehicle\": [\n",
        "        (\"GSM8899894\", \"JLASCRHBO027387\"),\n",
        "        (\"GSM8899895\", \"JLASCRHBO027393\"),\n",
        "        (\"GSM8899896\", \"JLASCRHBO027394\"),\n",
        "    ],\n",
        "    \"Treated_7d_DTP\": [\n",
        "        (\"GSM8899891\", \"JLASCRHBO026502\"),\n",
        "        (\"GSM8899892\", \"JLASCRHBO027381\"),\n",
        "        (\"GSM8899893\", \"JLASCRHBO027385\"),\n",
        "    ],\n",
        "    \"Regrowth_Escape\": [\n",
        "        (\"GSM8899888\", \"JLASCRHBO026114\"),\n",
        "        (\"GSM8899889\", \"JLASCRHBO026117\"),\n",
        "        (\"GSM8899890\", \"JLASCRHBO026122\"),\n",
        "    ],\n",
        "}\n",
        "\n",
        "GEO_DIR = RESULTS_DIR / \"gse294175\"\n",
        "GEO_DIR.mkdir(exist_ok=True)\n",
        "\n",
        "def download_geo_file(gsm: str, tag: str, suffix: str) -> Path:\n",
        "    fname = f\"{gsm}_{tag}_{suffix}\"\n",
        "    local = GEO_DIR / fname\n",
        "    if not local.exists():\n",
        "        url = f\"https://ftp.ncbi.nlm.nih.gov/geo/samples/{gsm[:7]}nnn/{gsm}/suppl/{fname}\"\n",
        "        print(f\"  Downloading {fname} ...\")\n",
        "        urllib.request.urlretrieve(url, local)\n",
        "    return local\n",
        "\n",
        "def load_10x_aligned_to_tahoe(gsm: str, tag: str, max_cells_keep: int = 3000) -> tuple[np.ndarray, np.ndarray]:\n",
        "    '''Loads a 10x Genomics human matrix, sums duplicate HGNC symbols, aligns to tahoe_genes,\n",
        "    returns (pseudobulk_log1p_vector, single_cell_submatrix_counts_for_pseudobulks).'''\n",
        "    feat_path = download_geo_file(gsm, tag, \"features.tsv.gz\")\n",
        "    mtx_path = download_geo_file(gsm, tag, \"matrix.mtx.gz\")\n",
        "\n",
        "    with gzip.open(feat_path, \"rt\", encoding=\"utf-8\") as f:\n",
        "        feat_syms = [line.split(\"\\t\")[1].upper() for line in f]\n",
        "\n",
        "    with gzip.open(mtx_path, \"rb\") as f:\n",
        "        mat = sp_io.mmread(f).tocsc()  # shape: (n_features, n_cells)\n",
        "\n",
        "    # Filter low-UMI empty droplets / debris (>= 500 UMIs)\n",
        "    cell_umis = np.asarray(mat.sum(axis=0)).ravel()\n",
        "    keep_cells = np.where(cell_umis >= 500)[0]\n",
        "    mat = mat[:, keep_cells]\n",
        "    print(f\"    {gsm}: {mat.shape[1]:,} QC-passed human tumor cells (median {np.median(cell_umis[keep_cells]):.0f} UMIs/cell)\")\n",
        "\n",
        "    # Map 10x rows -> tahoe_genes (handling the 10 duplicate symbols by summing)\n",
        "    row_to_tahoe = np.array([tahoe_g2i.get(s, -1) for s in feat_syms], dtype=np.int32)\n",
        "    valid_rows = np.where(row_to_tahoe >= 0)[0]\n",
        "\n",
        "    # Pseudobulk across all QC-passed cells\n",
        "    gene_sums_raw = np.asarray(mat.sum(axis=1)).ravel()\n",
        "    pb_counts = np.zeros(len(tahoe_genes), dtype=np.float64)\n",
        "    np.add.at(pb_counts, row_to_tahoe[valid_rows], gene_sums_raw[valid_rows])\n",
        "    pb_log1p = np.log1p(pb_counts / max(pb_counts.sum(), 1.0) * 1543.0).astype(np.float32)\n",
        "\n",
        "    # Also keep a random sample of cells (in tahoe gene space) to build k=20 pseudobulks for CellGemma\n",
        "    rng = np.random.default_rng(SEED)\n",
        "    n_sample = min(max_cells_keep, mat.shape[1])\n",
        "    sub_idx = rng.choice(mat.shape[1], size=n_sample, replace=False)\n",
        "    sub_mat = mat[:, sub_idx].tocsr()\n",
        "\n",
        "    # Build sparse projection matrix P: (len(tahoe_genes), n_features)\n",
        "    P = sparse.csr_matrix(\n",
        "        (np.ones(len(valid_rows), dtype=np.float32), (row_to_tahoe[valid_rows], valid_rows)),\n",
        "        shape=(len(tahoe_genes), len(feat_syms)),\n",
        "    )\n",
        "    aligned_cells = (P @ sub_mat).tocsc()  # (19720, n_sample)\n",
        "    del mat, sub_mat\n",
        "    gc.collect()\n",
        "    return pb_log1p, aligned_cells\n",
        "\n",
        "gse_pb = {}\n",
        "gse_vehicle_cells = None\n",
        "for group, reps in GSE294175_MANIFEST.items():\n",
        "    use_reps = reps if USE_ALL_3_REPLICATES else reps[:1]\n",
        "    print(f\"\\nLoading GSE294175 group: {group}\")\n",
        "    pbs = []\n",
        "    for gsm, tag in use_reps:\n",
        "        pb, cells_csc = load_10x_aligned_to_tahoe(gsm, tag)\n",
        "        pbs.append(pb)\n",
        "        if group == \"Vehicle\" and gse_vehicle_cells is None:\n",
        "            gse_vehicle_cells = cells_csc\n",
        "    gse_pb[group] = np.mean(pbs, axis=0)\n",
        "\n",
        "real_lfc_dtp = gse_pb[\"Treated_7d_DTP\"] - gse_pb[\"Vehicle\"]\n",
        "real_lfc_regrowth = gse_pb[\"Regrowth_Escape\"] - gse_pb[\"Vehicle\"]\n",
        "\n",
        "# Check ERBB2/HER2, EGFR, MET, MAPK, and Proliferation in real wet-lab data!\n",
        "print(\"\\n=== REAL WET-LAB GSE294175 SHIFTS (log1p depth=1543 scale) ===\")\n",
        "for g in [\"EGFR\", \"MET\", \"ERBB2\", \"ERBB3\", \"DUSP6\", \"SPRY2\", \"ETV4\", \"MYC\", \"MKI67\", \"CCND1\", \"BCL2L11\", \"CDKN1A\", \"B2M\", \"HLA-A\", \"VIM\"]:\n",
        "    if g in tahoe_g2i:\n",
        "        i = tahoe_g2i[g]\n",
        "        print(\n",
        "            f\"  {g:8s}: Vehicle={gse_pb['Vehicle'][i]:.3f} | \"\n",
        "            f\"7d DTP={gse_pb['Treated_7d_DTP'][i]:.3f} (\u0394={real_lfc_dtp[i]:+.3f}) | \"\n",
        "            f\"Regrowth={gse_pb['Regrowth_Escape'][i]:.3f} (\u0394={real_lfc_regrowth[i]:+.3f})\"\n",
        "        )"
      ],
      "id": "cell-13"
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "#@title Head-to-head validation: Run CellGemma on real GSE294175 Vehicle cells & compare with wet-lab 7-day response\n",
        "# Build k=20 pseudobulk control cells from GSE294175 Vehicle (matching CellGemma's Tahoe preprocessing!)\n",
        "rng = np.random.default_rng(SEED)\n",
        "n_avail = gse_vehicle_cells.shape[1]\n",
        "n_pb = min(3, n_avail // 20)\n",
        "mean_vec_tahoe = np.array([tahoe_mean_deltas[g] for g in tahoe_genes], dtype=np.float32)\n",
        "\n",
        "gse_cg_preds = {\"DUAL_EGFR_MET_KD\": [], \"LAZ_PLUS_CAP\": [], \"AMI_ZEROSHOT\": []}\n",
        "print(f\"Running CellGemma on {n_pb} real GSE294175 human NSCLC pseudobulk cells (k=20, batched)...\")\n",
        "\n",
        "pb_list = []\n",
        "for pb_idx in range(n_pb):\n",
        "    chosen = rng.choice(n_avail, size=20, replace=False)\n",
        "    counts = np.asarray(gse_vehicle_cells[:, chosen].sum(axis=1)).ravel().astype(np.float64)\n",
        "    ctrl_pb = np.log1p(counts / max(counts.sum(), 1.0) * 1543.0).astype(np.float32)\n",
        "    base_pb = np.maximum(0.0, ctrl_pb + mean_vec_tahoe)\n",
        "    pb_list.append((pb_idx, ctrl_pb, base_pb))\n",
        "    if pb_idx == 0:\n",
        "        er, ev = get_gene_rank(ctrl_pb, tahoe_genes, \"EGFR\")\n",
        "        mr, mv = get_gene_rank(ctrl_pb, tahoe_genes, \"MET\")\n",
        "        print(f\"  GSE294175 Vehicle pseudobulk #0: EGFR rank #{er} ({ev:.2f}), MET rank #{mr} ({mv:.2f})\")\n",
        "\n",
        "gse_jobs = []\n",
        "for arm_name in gse_cg_preds:\n",
        "    for pb_idx, ctrl_pb, base_pb in pb_list:\n",
        "        gse_jobs.append((arm_name, pb_idx, ctrl_pb, base_pb, build_prompt(ARMS[arm_name], tahoe_genes, ctrl_pb, base_pb), f\"gse294175_pb{pb_idx}_{arm_name}\"))\n",
        "\n",
        "gse_resps = generate_cellgemma_batch([j[4] for j in gse_jobs], [j[5] for j in gse_jobs])\n",
        "for (arm_name, pb_idx, ctrl_pb, base_pb, _, _), resp in zip(gse_jobs, gse_resps):\n",
        "    _, lfc, _, _ = reconstruct_expression(resp, tahoe_genes, ctrl_pb, base_pb, tahoe_decoder)\n",
        "    gse_cg_preds[arm_name].append(lfc)\n",
        "\n",
        "gse_cg_mean = {k: np.mean(v, axis=0) for k, v in gse_cg_preds.items()}\n",
        "\n",
        "# --- FIGURE 3: Real Wet-Lab GSE294175 Trajectory + CellGemma Head-to-Head Comparison ---\n",
        "fig, axes = plt.subplots(1, 3, figsize=(18, 5.5))\n",
        "\n",
        "# Panel A: Real wet-lab pathway trajectory (7-day DTP vs 28-day Regrowth)\n",
        "wet_pw = pd.DataFrame({\n",
        "    \"Wet-Lab: 7-Day Amivantamab+Laz (DTP)\": score_pathways(real_lfc_dtp, tahoe_g2i),\n",
        "    \"Wet-Lab: 28-Day Regrowth (Escape)\": score_pathways(real_lfc_regrowth, tahoe_g2i),\n",
        "    \"CellGemma: DUAL_EGFR_MET_KD\": score_pathways(gse_cg_mean[\"DUAL_EGFR_MET_KD\"], tahoe_g2i),\n",
        "    \"CellGemma: LAZ_PLUS_CAP\": score_pathways(gse_cg_mean[\"LAZ_PLUS_CAP\"], tahoe_g2i),\n",
        "}).T\n",
        "vm = max(0.05, float(np.abs(wet_pw.values).max()))\n",
        "sns.heatmap(wet_pw, ax=axes[0], cmap=\"RdBu_r\", center=0.0, vmin=-vm, vmax=vm, annot=True, fmt=\".3f\", linewidths=0.5)\n",
        "axes[0].set_title(\"Real Wet-Lab (GSE294175) vs. CellGemma Pathways\", fontsize=11, fontweight=\"bold\")\n",
        "axes[0].tick_params(axis=\"x\", rotation=30)\n",
        "\n",
        "# Panel B: Real wet-lab 7-day DTP vs 28-day Regrowth (highlighting HER2 / ERBB2 escape!)\n",
        "expressed = (gse_pb[\"Vehicle\"] > 0.05) | (gse_pb[\"Treated_7d_DTP\"] > 0.05) | (gse_pb[\"Regrowth_Escape\"] > 0.05)\n",
        "axes[1].scatter(real_lfc_dtp[expressed], real_lfc_regrowth[expressed], s=10, alpha=0.25, color=\"#64748b\")\n",
        "axes[1].axhline(0, color=\"black\", lw=0.7, ls=\"--\")\n",
        "axes[1].axvline(0, color=\"black\", lw=0.7, ls=\"--\")\n",
        "for g, col in [(\"ERBB2\", \"#dc2626\"), (\"ERBB3\", \"#ea580c\"), (\"EGFR\", \"#2563eb\"), (\"MET\", \"#0d9488\"),\n",
        "               (\"DUSP6\", \"#7c3aed\"), (\"MKI67\", \"#7c3aed\"), (\"MYC\", \"#7c3aed\"), (\"VIM\", \"#d97706\"), (\"B2M\", \"#059669\")]:\n",
        "    if g in tahoe_g2i:\n",
        "        i = tahoe_g2i[g]\n",
        "        axes[1].scatter([real_lfc_dtp[i]], [real_lfc_regrowth[i]], s=65, color=col, edgecolor=\"black\", zorder=5)\n",
        "        axes[1].annotate(g, (real_lfc_dtp[i], real_lfc_regrowth[i]), xytext=(5, 4), textcoords=\"offset points\", fontsize=9, fontweight=\"bold\", color=col)\n",
        "axes[1].set_xlabel(\"Real Wet-Lab 7-Day DTP Shift (\u0394 vs Vehicle)\")\n",
        "axes[1].set_ylabel(\"Real Wet-Lab 28-Day Regrowth Shift (\u0394 vs Vehicle)\")\n",
        "axes[1].set_title(\"Real Human NSCLC Trajectory on Amivantamab+Laz\\n(Notice ERBB2/HER2 Escape Track)\", fontsize=11, fontweight=\"bold\")\n",
        "\n",
        "# Panel C: Quantitative CellGemma vs Real Wet-Lab Top-200 DEG concordance\n",
        "top200_real = np.argsort(np.abs(real_lfc_dtp))[::-1][:200]\n",
        "for arm_name, col in [(\"DUAL_EGFR_MET_KD\", \"#0d9488\"), (\"LAZ_PLUS_CAP\", \"#7c3aed\"), (\"AMI_ZEROSHOT\", \"#f59e0b\")]:\n",
        "    pred_v = gse_cg_mean[arm_name][top200_real]\n",
        "    true_v = real_lfc_dtp[top200_real]\n",
        "    r_p, _ = stats.pearsonr(true_v, pred_v)\n",
        "    r_s, _ = stats.spearmanr(true_v, pred_v)\n",
        "    dir_acc = float(np.mean(np.sign(pred_v[pred_v != 0]) == np.sign(true_v[pred_v != 0]))) if np.any(pred_v != 0) else 0.0\n",
        "    print(f\"CellGemma {arm_name:18s} vs Real GSE294175 Top-200 DEGs -> Pearson r={r_p:+.3f}, Spearman \u03c1={r_s:+.3f}, sign agreement={dir_acc*100:.1f}%\")\n",
        "    if arm_name in (\"DUAL_EGFR_MET_KD\", \"LAZ_PLUS_CAP\"):\n",
        "        axes[2].scatter(true_v, pred_v, s=22, alpha=0.6, color=col, label=f\"{arm_name} (r={r_p:+.2f}, dir={dir_acc*100:.0f}%)\")\n",
        "\n",
        "axes[2].axhline(0, color=\"gray\", lw=0.7, ls=\"--\")\n",
        "axes[2].axvline(0, color=\"gray\", lw=0.7, ls=\"--\")\n",
        "axes[2].set_xlabel(\"Real Wet-Lab 7-Day Shift (GSE294175)\")\n",
        "axes[2].set_ylabel(\"CellGemma Predicted Shift\")\n",
        "axes[2].set_title(\"Head-to-Head: CellGemma vs. Real Wet-Lab\\n(Top 200 Real DEGs)\", fontsize=11, fontweight=\"bold\")\n",
        "axes[2].legend(fontsize=9)\n",
        "\n",
        "plt.tight_layout()\n",
        "plt.savefig(RESULTS_DIR / \"fig3_real_gse294175_and_cellgemma_validation.png\", dpi=150, bbox_inches=\"tight\")\n",
        "plt.show()"
      ],
      "id": "cell-14"
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Part 5. Real Wet-Lab Immune Killing (Mechanism #3): NK-Cell ADCC Triggered by Amivantamab (`GSE341700`)\n",
        "\n",
        "CellGemma models a **single isolated cancer cell**\u2014so it is blind to amivantamab's **low-fucose Fc tail**, which recruits **natural killer (NK) cells** and **macrophages** to attack antibody-coated tumor cells.\n",
        "\n",
        "To show what that immune arm actually looks like transcriptionally, we load NCBI GEO **`GSE341700`** (4.9 MB): sorted human **NK cells** co-cultured with EGFR+/MET+ tumor cells **without drug (`NC_1..3`)** vs. **with Amivantamab (`Ami_1..3`)**.\n",
        "\n",
        "Watch three distinct immune programs ignite simultaneously when amivantamab bridges the NK cell to the tumor:\n",
        "1. **Fc\u03b3RIIIa (CD16) trigger & direct tumor lysis:** `EGR1` (immediate-early Fc-receptor firing), `TNF`, `IFNG`, `GZMB` (Granzyme B), `FASLG`, `PRF1`\n",
        "2. **Macrophage/monocyte recruitment (fueling trogocytosis & phagocytosis):** `CSF2` (GM-CSF), `CCL3`, `CCL3L3`, `CCL4`, `CCL4L2`\n",
        "3. **Conventional dendritic cell (cDC1) & adaptive T-cell recruitment:** `XCL1`, `XCL2` \u2014 especially intriguing in a tumor with **high TMB (`24.01 mut/Mb`)**, where dying tumor cells release abundant neoantigens for dendritic cells to cross-present to T cells."
      ],
      "id": "cell-15"
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "#@title Download & visualize GSE341700 real wet-lab NK-cell ADCC activation by Amivantamab\n",
        "fpkm_url = \"https://ftp.ncbi.nlm.nih.gov/geo/series/GSE341nnn/GSE341700/suppl/GSE341700_FPKM_allsamples.txt.gz\"\n",
        "fpkm_path = RESULTS_DIR / \"GSE341700_FPKM_allsamples.txt.gz\"\n",
        "if not fpkm_path.exists():\n",
        "    urllib.request.urlretrieve(fpkm_url, fpkm_path)\n",
        "\n",
        "nk_df = pd.read_csv(fpkm_path, compression=\"gzip\", sep=\"\\t\", low_memory=False)\n",
        "nc_cols = [\"NC_1\", \"NC_2\", \"NC_3\"]\n",
        "ami_cols = [\"Ami_1\", \"Ami_2\", \"Ami_3\"]\n",
        "\n",
        "for col in nc_cols + ami_cols:\n",
        "    nk_df[col] = pd.to_numeric(nk_df[col], errors=\"coerce\")\n",
        "nk_df = nk_df.dropna(subset=nc_cols + ami_cols).copy()\n",
        "\n",
        "nk_df[\"nc_mean\"] = nk_df[nc_cols].mean(axis=1)\n",
        "nk_df[\"ami_mean\"] = nk_df[ami_cols].mean(axis=1)\n",
        "nk_df[\"log2fc\"] = np.log2((nk_df[\"ami_mean\"] + 1.0) / (nk_df[\"nc_mean\"] + 1.0))\n",
        "\n",
        "# Welch's t-test on log2(FPKM + 1) across the 3 replicates\n",
        "nc_log = np.log2(nk_df[nc_cols].values + 1.0)\n",
        "ami_log = np.log2(nk_df[ami_cols].values + 1.0)\n",
        "_, pvals = stats.ttest_ind(ami_log, nc_log, axis=1, equal_var=False)\n",
        "nk_df[\"pval\"] = np.nan_to_num(pvals, nan=1.0)\n",
        "nk_df[\"neg_log10_p\"] = -np.log10(np.clip(nk_df[\"pval\"], 1e-12, 1.0))\n",
        "\n",
        "# Curated ADCC / Macrophage / cDC1 effector genes\n",
        "IMMUNE_MODULES = {\n",
        "    \"Fc\u03b3RIIIa Trigger\": [\"EGR1\", \"CRTAM\", \"TNFRSF9\"],\n",
        "    \"Direct NK Killing\": [\"TNF\", \"IFNG\", \"GZMB\", \"FASLG\", \"PRF1\"],\n",
        "    \"Macrophage / Trogocytosis Call\": [\"CSF2\", \"CCL4L2\", \"CCL3L3\", \"CCL4\", \"CCL3\"],\n",
        "    \"Dendritic Cell (cDC1) Call\": [\"XCL2\", \"XCL1\"],\n",
        "}\n",
        "module_colors = {\n",
        "    \"Fc\u03b3RIIIa Trigger\": \"#eab308\",\n",
        "    \"Direct NK Killing\": \"#dc2626\",\n",
        "    \"Macrophage / Trogocytosis Call\": \"#2563eb\",\n",
        "    \"Dendritic Cell (cDC1) Call\": \"#0d9488\",\n",
        "}\n",
        "\n",
        "fig, axes = plt.subplots(1, 2, figsize=(16, 6), gridspec_kw={\"width_ratios\": [1.15, 1.0]})\n",
        "\n",
        "# Left: Volcano plot of NK cells + Tumor + Amivantamab vs NK cells + Tumor alone\n",
        "expressed_nk = nk_df[(nk_df[\"nc_mean\"] + nk_df[\"ami_mean\"]) >= 2.0]\n",
        "axes[0].scatter(expressed_nk[\"log2fc\"], expressed_nk[\"neg_log10_p\"], s=10, alpha=0.25, color=\"#94a3b8\")\n",
        "sig_up = expressed_nk[(expressed_nk[\"log2fc\"] >= 0.4) & (expressed_nk[\"pval\"] < 0.05)]\n",
        "axes[0].scatter(sig_up[\"log2fc\"], sig_up[\"neg_log10_p\"], s=20, alpha=0.7, color=\"#ef4444\", label=f\"Significantly UP (n={len(sig_up)})\")\n",
        "\n",
        "label_offsets = {\n",
        "    \"EGR1\": (6, 5), \"CRTAM\": (6, 4), \"TNFRSF9\": (-62, 10),\n",
        "    \"TNF\": (18, -14), \"IFNG\": (-42, -8), \"GZMB\": (-48, 2),\n",
        "    \"FASLG\": (14, -10), \"PRF1\": (8, -6),\n",
        "    \"CSF2\": (12, 8), \"CCL4\": (16, -6), \"CCL3\": (18, -16),\n",
        "    \"CCL4L2\": (8, 5), \"CCL3L3\": (14, -4),\n",
        "    \"XCL1\": (-36, 10), \"XCL2\": (-42, 4),\n",
        "}\n",
        "for mod, glist in IMMUNE_MODULES.items():\n",
        "    sub = nk_df[nk_df[\"id\"].isin(glist)]\n",
        "    axes[0].scatter(sub[\"log2fc\"], sub[\"neg_log10_p\"], s=65, color=module_colors[mod], edgecolor=\"black\", zorder=5, label=mod)\n",
        "    for _, row in sub.iterrows():\n",
        "        off = label_offsets.get(row[\"id\"], (5, 4))\n",
        "        axes[0].annotate(\n",
        "            row[\"id\"], (row[\"log2fc\"], row[\"neg_log10_p\"]),\n",
        "            xytext=off, textcoords=\"offset points\", fontsize=8.2, fontweight=\"bold\",\n",
        "            arrowprops=dict(arrowstyle=\"-\", color=\"#475569\", lw=0.6, alpha=0.7),\n",
        "        )\n",
        "\n",
        "axes[0].axvline(0, color=\"black\", lw=0.8, ls=\"--\")\n",
        "axes[0].axhline(-np.log10(0.05), color=\"gray\", lw=0.8, ls=\":\")\n",
        "axes[0].set_xlim(-2.2, 2.5)\n",
        "axes[0].set_xlabel(\"log2 Fold Change in NK Cells (Amivantamab vs. No Drug)\")\n",
        "axes[0].set_ylabel(\"-log10(p-value)\")\n",
        "axes[0].set_title(\"Real Wet-Lab NK-Cell Activation by Amivantamab (GSE341700)\", fontsize=11.5, fontweight=\"bold\")\n",
        "axes[0].legend(fontsize=8.5, loc=\"upper left\")\n",
        "\n",
        "# Right: Bar chart of curated effector genes with absolute FPKM annotations\n",
        "bar_rows = []\n",
        "for mod, glist in IMMUNE_MODULES.items():\n",
        "    for g in glist:\n",
        "        hit = nk_df[nk_df[\"id\"] == g]\n",
        "        if len(hit):\n",
        "            r = hit.iloc[0]\n",
        "            bar_rows.append((g, r[\"log2fc\"], r[\"nc_mean\"], r[\"ami_mean\"], module_colors[mod], mod))\n",
        "\n",
        "bar_df = pd.DataFrame(bar_rows, columns=[\"gene\", \"log2fc\", \"nc\", \"ami\", \"color\", \"module\"])\n",
        "y_pos = np.arange(len(bar_df))\n",
        "axes[1].barh(y_pos, bar_df[\"log2fc\"], color=bar_df[\"color\"])\n",
        "axes[1].set_yticks(y_pos)\n",
        "axes[1].set_yticklabels(bar_df[\"gene\"], fontweight=\"bold\")\n",
        "axes[1].invert_yaxis()\n",
        "axes[1].axvline(0, color=\"black\", lw=0.8)\n",
        "for idx, r in bar_df.iterrows():\n",
        "    axes[1].text(\n",
        "        r[\"log2fc\"] + 0.03, idx, f\"{r['nc']:.0f} \u2192 {r['ami']:.0f} FPKM\",\n",
        "        va=\"center\", fontsize=8, color=\"#1e293b\",\n",
        "    )\n",
        "axes[1].set_xlim(0, max(1.8, float(bar_df[\"log2fc\"].max()) + 0.65))\n",
        "axes[1].set_xlabel(\"log2 Fold Change (Amivantamab + NK vs. NK alone)\")\n",
        "axes[1].set_title(\"Immune Effector, Macrophage & cDC1 Recruitment Genes\", fontsize=11.5, fontweight=\"bold\")\n",
        "\n",
        "plt.tight_layout()\n",
        "plt.savefig(RESULTS_DIR / \"fig4_real_nk_adcc_amivantamab.png\", dpi=150, bbox_inches=\"tight\")\n",
        "plt.show()"
      ],
      "id": "cell-16"
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Part 6. Integrated Summary Report (All 3 Mechanisms Together)\n",
        "\n",
        "Pulls the quantitative readouts from every module into one clean summary table and saves a JSON export to `/content/amivantamab_results/summary.json`."
      ],
      "id": "cell-17"
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "#@title Print integrated summary & export results JSON\n",
        "summary = {\n",
        "    \"genomic_context\": {\n",
        "        \"driver\": \"EGFR D770delinsGY (near-loop exon 20 insertion)\",\n",
        "        \"co_mutation\": \"TP53 I254fs (loss-of-function)\",\n",
        "        \"tmb_mut_per_mb\": 24.01,\n",
        "        \"tcga_matched_tumors\": TCGA_SAMPLES,\n",
        "    },\n",
        "    \"cellgemma_pathway_scores_tahoe\": {\n",
        "        arm: {k: round(v, 4) for k, v in score_pathways(vec, tahoe_g2i).items()}\n",
        "        for arm, vec in tahoe_arm_lfcs.items()\n",
        "    },\n",
        "    \"cellgemma_pathway_scores_tcga_dual_kd\": {\n",
        "        sid: {k: round(v, 4) for k, v in score_pathways(tcga_tahoe_lfcs[sid][\"DUAL_EGFR_MET_KD\"], tahoe_g2i).items()}\n",
        "        for sid in TCGA_SAMPLES\n",
        "    },\n",
        "    \"real_wetlab_gse294175_pathways\": {\n",
        "        \"7d_DTP_vs_Vehicle\": {k: round(v, 4) for k, v in score_pathways(real_lfc_dtp, tahoe_g2i).items()},\n",
        "        \"28d_Regrowth_vs_Vehicle\": {k: round(v, 4) for k, v in score_pathways(real_lfc_regrowth, tahoe_g2i).items()},\n",
        "        \"ERBB2_HER2_shift\": {\n",
        "            \"7d_DTP_delta\": round(float(real_lfc_dtp[tahoe_g2i[\"ERBB2\"]]), 4),\n",
        "            \"28d_Regrowth_delta\": round(float(real_lfc_regrowth[tahoe_g2i[\"ERBB2\"]]), 4),\n",
        "        },\n",
        "    },\n",
        "    \"real_wetlab_gse341700_nk_adcc_log2fc\": {\n",
        "        r[\"gene\"]: {\"nc_fpkm\": round(r[\"nc\"], 1), \"ami_fpkm\": round(r[\"ami\"], 1), \"log2fc\": round(r[\"log2fc\"], 3)}\n",
        "        for _, r in bar_df.iterrows()\n",
        "    },\n",
        "}\n",
        "\n",
        "out_json = RESULTS_DIR / \"summary.json\"\n",
        "out_json.write_text(json.dumps(summary, indent=2), encoding=\"utf-8\")\n",
        "\n",
        "print(\"==========================================================================\")\n",
        "print(\"INTEGRATED MECHANISTIC SUMMARY \u2014 AMIVANTAMAB IN EGFR EXON 20 INS NSCLC\")\n",
        "print(\"==========================================================================\")\n",
        "print(\"\\n1. Structural Geometry (Part 1):\")\n",
        "print(\"   - PDB 4LRM: D770 insertion wedges behind alpha-C helix -> kinase locked ON, blocks 1st/2nd-gen TKIs.\")\n",
        "print(\"   - PDB 6WVZ & 1YY9: Amivantamab binds EXTRACELLULAR EGFR & MET -> bypasses intracellular insertion.\")\n",
        "\n",
        "print(\"\\n2. Intracellular Pathway Shutdown (Part 3 \u2014 CellGemma Dual EGFR+MET KD on Tahoe & TCGA Ex20ins):\")\n",
        "for pw_name in PATHWAYS:\n",
        "    t_egfr = summary[\"cellgemma_pathway_scores_tahoe\"][\"EGFR_KD\"][pw_name]\n",
        "    t_dual = summary[\"cellgemma_pathway_scores_tahoe\"][\"DUAL_EGFR_MET_KD\"][pw_name]\n",
        "    tcga1 = summary[\"cellgemma_pathway_scores_tcga_dual_kd\"][\"TCGA-44-5645-01\"][pw_name]\n",
        "    wet7 = summary[\"real_wetlab_gse294175_pathways\"][\"7d_DTP_vs_Vehicle\"][pw_name]\n",
        "    print(f\"   {pw_name:28s} | EGFR_KD={t_egfr:+.3f} | DUAL={t_dual:+.3f} | TCGA_Ex20={tcga1:+.3f} | WetLab_7d={wet7:+.3f}\")\n",
        "\n",
        "print(\"\\n3. Real Wet-Lab Escape Track (Part 4 \u2014 GSE294175):\")\n",
        "h2 = summary[\"real_wetlab_gse294175_pathways\"][\"ERBB2_HER2_shift\"]\n",
        "print(f\"   ERBB2 (HER2) shift: 7-day DTP \u0394={h2['7d_DTP_delta']:+.3f} -> 28-day Regrowth \u0394={h2['28d_Regrowth_delta']:+.3f}\")\n",
        "\n",
        "print(\"\\n4. Real Wet-Lab Immune Killing / ADCC & Macrophage Call (Part 5 \u2014 GSE341700 NK Cells):\")\n",
        "for g in [\"EGR1\", \"TNF\", \"IFNG\", \"GZMB\", \"CSF2\", \"CCL4\", \"CCL4L2\", \"XCL2\", \"XCL1\"]:\n",
        "    if g in summary[\"real_wetlab_gse341700_nk_adcc_log2fc\"]:\n",
        "        d = summary[\"real_wetlab_gse341700_nk_adcc_log2fc\"][g]\n",
        "        print(f\"   {g:8s}: {d['nc_fpkm']:7.1f} -> {d['ami_fpkm']:7.1f} FPKM (log2FC = {d['log2fc']:+.2f})\")\n",
        "\n",
        "print(f\"\\nSaved summary JSON and 4 high-resolution PNG figures to: {RESULTS_DIR}\")"
      ],
      "id": "cell-18"
    }
  ]
}