Archive 4 checkpoints (1-4)
Browse files- paper-releases/pbisc-diffusion/updates/20261010T153319Z-manuscript-rewrite-from-deck/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/_archive/2026-10-10_metrics_overview_broadcast/sec04_metrics_overview.py +89 -0
- paper-releases/pbisc-diffusion/updates/20261010T153319Z-manuscript-rewrite-from-deck/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/_archive/2026-10-10_rank_sweep_label/sec07_rank_sweep.pdf +0 -0
- paper-releases/pbisc-diffusion/updates/20261010T153319Z-manuscript-rewrite-from-deck/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/_archive/2026-10-10_rank_sweep_label/sec07_rank_sweep.png +3 -0
- paper-releases/pbisc-diffusion/updates/20261010T153319Z-manuscript-rewrite-from-deck/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/_archive/2026-10-10_rank_sweep_label/sec07_rank_sweep.py +268 -0
paper-releases/pbisc-diffusion/updates/20261010T153319Z-manuscript-rewrite-from-deck/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/_archive/2026-10-10_metrics_overview_broadcast/sec04_metrics_overview.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Section 4 of the 2026-09-30 paper-summary deck: how generated cells are scored (metric overview; added 2026-10-02).
|
| 3 |
+
|
| 4 |
+
CPU only; draws a plain table figure. One row per metric used anywhere in the deck: what it asks, what it is compared
|
| 5 |
+
against (control, null or ceiling), and the paper the definition comes from. The definitions match the scorers:
|
| 6 |
+
plans/paired_finetune_intradataset_20260927/tools/score_ft.py (composition, precision/coverage, logFC r, top-50 DEG),
|
| 7 |
+
tools/extra_metrics.py (classifier AUC, MMD^2, E_N) and tools/contrast_extra.py (Spearman, split-half ceiling,
|
| 8 |
+
limma-voom DEG, CAT). References are the PDFs in paper-release-20260928/reference-papers/ (INDEX.md).
|
| 9 |
+
|
| 10 |
+
Outputs: figures/sec04_metrics_overview.{png,pdf}; data/sec04_metrics_overview.csv (the table as text).
|
| 11 |
+
"""
|
| 12 |
+
import os
|
| 13 |
+
|
| 14 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = ""
|
| 15 |
+
import sys
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
import pandas as pd
|
| 19 |
+
|
| 20 |
+
DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/"
|
| 21 |
+
"2026-09-30--paper-summary--r00")
|
| 22 |
+
sys.path.insert(0, str(DECK / "tools"))
|
| 23 |
+
import style # noqa: E402
|
| 24 |
+
import matplotlib.pyplot as plt # noqa: E402
|
| 25 |
+
|
| 26 |
+
FIGDIR = Path(os.environ.get("DECK_FIGDIR", str(DECK / "figures")))
|
| 27 |
+
OUTDATA = Path(os.environ.get("DECK_OUTDATA", str(DECK / "data")))
|
| 28 |
+
|
| 29 |
+
# group, metric, question, compared against, reference
|
| 30 |
+
ROWS = [
|
| 31 |
+
("Cells", "Precision / coverage", "Land on real cells? Cover all real cells?",
|
| 32 |
+
"held-out real cells (R2)", "Kynkäänniemi 2019; Naeem 2020"),
|
| 33 |
+
("Cells", "Classifier AUC", "Can a classifier tell generated from real cells?",
|
| 34 |
+
"0.5 = indistinguishable", "Lopez-Paz & Oquab 2017"),
|
| 35 |
+
("Cells", "MMD²", "How far apart are the two cell distributions?",
|
| 36 |
+
"real vs real", "Gretton 2012"),
|
| 37 |
+
("Cells", "E_N", "scSemiProfiler's own nearest-neighbour error",
|
| 38 |
+
"within-sample split", "Wang 2024"),
|
| 39 |
+
("Composition", "Cell-type L1", "Right mix of the six scANVI cell types?",
|
| 40 |
+
"other donors' mean (null)", "—"),
|
| 41 |
+
("Disease", "logFC r (Pearson / Spearman)", "Same case-vs-control change in each cell type?",
|
| 42 |
+
"broadcast; split-half ceiling", "Roohani 2024; Viñas Torné 2026"),
|
| 43 |
+
("Disease", "Top-50 DEG overlap", "Same top disease genes per cell type?",
|
| 44 |
+
"chance; limma-voom check", "Li 2026; Squair 2021; Law 2014"),
|
| 45 |
+
("Disease", "CAT curve", "Same genes at every list length k?",
|
| 46 |
+
"chance = k / 2G", "Irizarry 2005"),
|
| 47 |
+
("Cost", "GPU time", "How long to apply to a new cohort?",
|
| 48 |
+
"same donors, same GPU", "—"),
|
| 49 |
+
]
|
| 50 |
+
HEAD = ("", "Metric", "Question", "Compared against", "Definition from")
|
| 51 |
+
COLX = (0.0, 0.103, 0.29, 0.607, 0.80)
|
| 52 |
+
GROUP_COL = {"Cells": style.ARM["lora"], "Composition": style.ARM["zs_cal"], "Disease": style.ARM["sconly"],
|
| 53 |
+
"Cost": style.GREY}
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def main() -> int:
|
| 57 |
+
fig = plt.figure(figsize=(12.3, 5.0))
|
| 58 |
+
ax = fig.add_axes([0.0, 0.0, 1.0, 1.0])
|
| 59 |
+
ax.set_axis_off()
|
| 60 |
+
n = len(ROWS)
|
| 61 |
+
top, step = 0.93, 0.093
|
| 62 |
+
fs = style.FS - 2
|
| 63 |
+
for x, h in zip(COLX, HEAD):
|
| 64 |
+
ax.text(x + 0.005, top + 0.045, h, fontsize=fs, fontweight="bold", color=style.INK, va="center")
|
| 65 |
+
ax.plot([0, 1], [top + 0.012, top + 0.012], color=style.INK, lw=1.0)
|
| 66 |
+
prev = None
|
| 67 |
+
for i, (g, m, q, c, r) in enumerate(ROWS):
|
| 68 |
+
y = top - (i + 0.5) * step
|
| 69 |
+
if g != prev:
|
| 70 |
+
if prev is not None:
|
| 71 |
+
ax.plot([0, 1], [y + step / 2, y + step / 2], color="#C8C8C8", lw=0.8)
|
| 72 |
+
ax.text(COLX[0] + 0.005, y, g, fontsize=fs + 1, fontweight="bold", color=GROUP_COL[g], va="center")
|
| 73 |
+
prev = g
|
| 74 |
+
ax.text(COLX[1] + 0.005, y, m, fontsize=fs, color=style.INK, va="center")
|
| 75 |
+
ax.text(COLX[2] + 0.005, y, q, fontsize=fs, color=style.SUBINK, va="center")
|
| 76 |
+
ax.text(COLX[3] + 0.005, y, c, fontsize=fs, color=style.SUBINK, va="center")
|
| 77 |
+
ax.text(COLX[4] + 0.005, y, r, fontsize=fs - 1, color=style.SUBINK, va="center", style="italic")
|
| 78 |
+
ax.plot([0, 1], [top - n * step, top - n * step], color=style.INK, lw=1.0)
|
| 79 |
+
ax.set_xlim(0, 1)
|
| 80 |
+
ax.set_ylim(top - n * step - 0.01, top + 0.08)
|
| 81 |
+
style.save(fig, "sec04_metrics_overview", FIGDIR)
|
| 82 |
+
OUTDATA.mkdir(exist_ok=True)
|
| 83 |
+
pd.DataFrame(ROWS, columns=["group", "metric", "question", "compared_against", "reference"]).to_csv(
|
| 84 |
+
OUTDATA / "sec04_metrics_overview.csv", index=False)
|
| 85 |
+
return 0
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
if __name__ == "__main__":
|
| 89 |
+
sys.exit(main())
|
paper-releases/pbisc-diffusion/updates/20261010T153319Z-manuscript-rewrite-from-deck/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/_archive/2026-10-10_rank_sweep_label/sec07_rank_sweep.pdf
ADDED
|
Binary file (52.1 kB). View file
|
|
|
paper-releases/pbisc-diffusion/updates/20261010T153319Z-manuscript-rewrite-from-deck/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/_archive/2026-10-10_rank_sweep_label/sec07_rank_sweep.png
ADDED
|
Git LFS Details
|
paper-releases/pbisc-diffusion/updates/20261010T153319Z-manuscript-rewrite-from-deck/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/_archive/2026-10-10_rank_sweep_label/sec07_rank_sweep.py
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Section 7 slide (LoRA ablations) of the 2026-09-30 paper-summary deck: LoRA rank r = 4 / 16 / 64 at
|
| 3 |
+
n = 5, 20 and all training pairs (ImMicro, sepsis; donor-level 5-fold CV, pooled cross-fitted scoring).
|
| 4 |
+
|
| 5 |
+
CPU only. Reads plans/paired_finetune_intradataset_20260927/scores/<ds>/rankcal_20261001.json (written by
|
| 6 |
+
tools/aggregate_rankcal.py) and checks every plotted value against the pooled scoring calls it came from:
|
| 7 |
+
r = 16 scores/<ds>/pooled (sepsis: pooled_deg) arms lora_n5__raw, lora_n20__raw, real_lora__raw
|
| 8 |
+
r = 4, 64 scores/<ds>/lora_rank_20261001/pooled arms lora_r{4,64}_n5__raw, lora_r{4,64}_n20__raw, lora_r{4,64}__raw
|
| 9 |
+
Composition L1 / precision / coverage = summary.json headline; logFC r = mean of contrast.csv mean_cp10k r over
|
| 10 |
+
T, B, Monocyte, NK; top-50 DEG = headline deg_top50_sum. Per-donor L1 Wilcoxon vs r = 16 as aggregate_rankcal.py.
|
| 11 |
+
Each LoRA run's rank and checkpoint are checked in runs/<ds>/fold<k>/<arm>/RUN.json.
|
| 12 |
+
|
| 13 |
+
Outputs (deck folder; DECK_FIGDIR / DECK_OUTDATA override):
|
| 14 |
+
figures/sec07_rank_sweep.{png,pdf}, data/sec07_rank_sweep.csv, data/sec07_rank_sweep_slide_text.json
|
| 15 |
+
"""
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import os
|
| 19 |
+
|
| 20 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = "" # plotting only
|
| 21 |
+
|
| 22 |
+
import json
|
| 23 |
+
import re
|
| 24 |
+
import sys
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
|
| 27 |
+
import numpy as np
|
| 28 |
+
import pandas as pd
|
| 29 |
+
from scipy.stats import wilcoxon
|
| 30 |
+
|
| 31 |
+
DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/"
|
| 32 |
+
"2026-09-30--paper-summary--r00")
|
| 33 |
+
sys.path.insert(0, str(DECK / "tools"))
|
| 34 |
+
import style # noqa: E402
|
| 35 |
+
import fold_sizes as FZ # noqa: E402 (the 'all' point is shown as its training-pair count)
|
| 36 |
+
import matplotlib.pyplot as plt # noqa: E402
|
| 37 |
+
from matplotlib.lines import Line2D # noqa: E402
|
| 38 |
+
|
| 39 |
+
PLAN = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/"
|
| 40 |
+
"paired_finetune_intradataset_20260927")
|
| 41 |
+
FINAL_CKPT = ("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/runs/"
|
| 42 |
+
"f01_6k_1x_seed20260627/checkpoint_epoch_016.pt")
|
| 43 |
+
FIGDIR = Path(os.environ.get("DECK_FIGDIR", str(DECK / "figures")))
|
| 44 |
+
OUTDATA = Path(os.environ.get("DECK_OUTDATA", str(DECK / "data")))
|
| 45 |
+
SCRIPT = DECK / "tools" / "sec07_rank_sweep.py"
|
| 46 |
+
DSETS = ["immicro", "ye2026_sepsis"]
|
| 47 |
+
NAME = {"immicro": "ImMicro", "ye2026_sepsis": "Sepsis"}
|
| 48 |
+
RANKS = (4, 16, 64)
|
| 49 |
+
NS = ("5", "20", "all")
|
| 50 |
+
RANK_EXP = "lora_rank_20261001"
|
| 51 |
+
TYPES = ["T cell", "B cell", "Monocyte", "NK cell"]
|
| 52 |
+
FS = style.FS
|
| 53 |
+
# r = 16 is the deck's LoRA (orange); 4 and 64 are lighter / darker shades of it, with their own markers
|
| 54 |
+
RCOL = {4: "#F2AE7B", 16: style.ARM["lora"], 64: "#6E2E00"}
|
| 55 |
+
RMK = {4: "v", 16: "o", 64: "s"}
|
| 56 |
+
PANELS = [("comp_l1", "Composition L1 ↓"), ("coverage", "Coverage ↑"), ("precision", "Precision ↑"),
|
| 57 |
+
("logfc_r", "Disease logFC r ↑"), ("deg", "Top-50 DEG ↑")]
|
| 58 |
+
OFF_STORY = re.compile(r"refcal|reference[ -]calibrat|\bVAE\b|\bTPM\b|\bAIFI\b|\bAIDA\b", re.I)
|
| 59 |
+
KW_MAX, FOOT_MAX = 45, 110
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def arm(r: int, n: str) -> str:
|
| 63 |
+
if r == 16:
|
| 64 |
+
return "real_lora__raw" if n == "all" else f"lora_n{n}__raw"
|
| 65 |
+
return f"lora_r{r}__raw" if n == "all" else f"lora_r{r}_n{n}__raw"
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def call_dir(ds: str, r: int) -> Path:
|
| 69 |
+
S = PLAN / "scores" / ds
|
| 70 |
+
if r != 16:
|
| 71 |
+
return S / RANK_EXP / "pooled"
|
| 72 |
+
return S / "pooled_deg" if (S / "pooled_deg" / "summary.json").exists() else S / "pooled"
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def load():
|
| 76 |
+
rows, pdl, runs = [], {}, []
|
| 77 |
+
for ds in DSETS:
|
| 78 |
+
js_path = PLAN / "scores" / ds / "rankcal_20261001.json"
|
| 79 |
+
js = json.loads(js_path.read_text())
|
| 80 |
+
for r in RANKS:
|
| 81 |
+
d = call_dir(ds, r)
|
| 82 |
+
s = json.loads((d / "summary.json").read_text())
|
| 83 |
+
con = pd.read_csv(d / "contrast.csv") if (d / "contrast.csv").exists() else None
|
| 84 |
+
per = pd.read_csv(d / "per_donor.csv")
|
| 85 |
+
for n in NS:
|
| 86 |
+
a = arm(r, n)
|
| 87 |
+
h, pj = s["headline"][a], js[a]["pooled"]
|
| 88 |
+
v = {"comp_l1": float(h["comp_l1"]), "coverage": float(h["coverage"]), "precision": float(h["precision"]),
|
| 89 |
+
"logfc_r": np.nan, "deg": np.nan}
|
| 90 |
+
if con is not None and s.get("contrast_definition", {}).get("enabled"):
|
| 91 |
+
c = con[(con.arm == a) & (con.statistic == "mean_cp10k") & con.celltype.isin(TYPES)]
|
| 92 |
+
assert set(c.celltype) == set(TYPES), (d, a)
|
| 93 |
+
v["logfc_r"] = float(c.r_generated.mean())
|
| 94 |
+
if h.get("deg_top50_sum") is not None:
|
| 95 |
+
v["deg"] = float(h["deg_top50_sum"])
|
| 96 |
+
# the aggregated JSON must equal the scoring call
|
| 97 |
+
for k, kj in (("comp_l1", "comp_l1"), ("coverage", "coverage"), ("precision", "precision"),
|
| 98 |
+
("logfc_r", "logfc_r"), ("deg", "deg_top50_sum")):
|
| 99 |
+
x = pj.get(kj)
|
| 100 |
+
if x is None:
|
| 101 |
+
assert np.isnan(v[k]), (ds, a, k)
|
| 102 |
+
else:
|
| 103 |
+
assert abs(float(x) - v[k]) < 1e-9, (ds, a, k, x, v[k])
|
| 104 |
+
for k, val in v.items():
|
| 105 |
+
rows.append({"dataset": ds, "rank": r, "pairs": n, "arm": a, "metric": k, "value": val,
|
| 106 |
+
"source": str(d / ("contrast.csv" if k == "logfc_r" else "summary.json")),
|
| 107 |
+
"aggregate": str(js_path)})
|
| 108 |
+
pdl[(ds, r, n)] = per[per.arm == a].set_index("donor")["comp_l1"]
|
| 109 |
+
for k in range(5):
|
| 110 |
+
rp = PLAN / "runs" / ds / f"fold{k}" / a.removesuffix("__raw") / "RUN.json"
|
| 111 |
+
if not rp.exists():
|
| 112 |
+
continue
|
| 113 |
+
R = json.loads(rp.read_text())
|
| 114 |
+
assert R["source_checkpoint"] == FINAL_CKPT, rp
|
| 115 |
+
assert R["mode"] == "lora" and int(R["trainable"]["lora_rank"]) == r, (rp, R["trainable"].get("lora_rank"))
|
| 116 |
+
runs.append({"dataset": ds, "rank": r, "pairs": n, "fold": k, "n_train": len(R["train_rows"]),
|
| 117 |
+
"n_inner_val": len(R["inner_val_rows"]), "selected_step": R["selected_step"],
|
| 118 |
+
"n_trainable": R["trainable"]["n_trainable"], "source": str(rp)})
|
| 119 |
+
return pd.DataFrame(rows), pdl, pd.DataFrame(runs)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def wil(pdl, ds, r, n):
|
| 123 |
+
x, y = pdl[(ds, r, n)], pdl[(ds, 16, n)]
|
| 124 |
+
j = x.to_frame("a").join(y.to_frame("b"), how="inner")
|
| 125 |
+
d = j["a"] - j["b"]
|
| 126 |
+
return float(d.mean()), float(wilcoxon(j["a"], j["b"]).pvalue), len(j)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def fig(df, runs):
|
| 130 |
+
fig, axs = plt.subplots(2, len(PANELS), figsize=style.FULL,
|
| 131 |
+
gridspec_kw=dict(left=0.135, right=0.995, top=0.855, bottom=0.17, hspace=0.42,
|
| 132 |
+
wspace=0.42))
|
| 133 |
+
xs = np.arange(len(NS))
|
| 134 |
+
for i, ds in enumerate(DSETS):
|
| 135 |
+
for j, (mk, lab) in enumerate(PANELS):
|
| 136 |
+
ax = axs[i, j]
|
| 137 |
+
sub = df[(df.dataset == ds) & (df.metric == mk)]
|
| 138 |
+
if sub.value.isna().all():
|
| 139 |
+
for sp in ax.spines.values():
|
| 140 |
+
sp.set_visible(False)
|
| 141 |
+
ax.set_xticks([])
|
| 142 |
+
ax.set_yticks([])
|
| 143 |
+
if j == len(PANELS) - 1: # centred over the empty disease columns, in figure coordinates
|
| 144 |
+
p0, p1 = axs[i, j - 1].get_position(), ax.get_position()
|
| 145 |
+
fig.text((p0.x0 + p1.x1) / 2, (p1.y0 + p1.y1) / 2, "healthy cohort: no contrast", ha="center",
|
| 146 |
+
va="center", fontsize=FS - 2, color="#595959", style="italic")
|
| 147 |
+
else:
|
| 148 |
+
for r in RANKS:
|
| 149 |
+
v = [float(sub[(sub["rank"] == r) & (sub.pairs == n)].value.iloc[0]) for n in NS]
|
| 150 |
+
ax.plot(xs, v, color=RCOL[r], lw=2.2 if r == 16 else 1.8, marker=RMK[r], ms=7,
|
| 151 |
+
mec=style.INK, mew=0.6, zorder=4 if r == 16 else 3)
|
| 152 |
+
ax.set_xticks(xs)
|
| 153 |
+
ax.set_xticklabels([n if n != "all" else FZ.all_label(ds) for n in NS])
|
| 154 |
+
ax.set_xlim(-0.35, len(NS) - 0.65)
|
| 155 |
+
ax.tick_params(axis="both", labelsize=FS - 3)
|
| 156 |
+
ax.yaxis.set_major_locator(plt.MaxNLocator(nbins=4))
|
| 157 |
+
if mk == "deg":
|
| 158 |
+
ax.set_ylim(0, max(sub.value) * 1.15)
|
| 159 |
+
if i == 0:
|
| 160 |
+
ax.set_title(lab, fontsize=FS - 1, pad=8)
|
| 161 |
+
n_d = int(json.loads((call_dir(ds, 16) / "summary.json").read_text())["n_donors"])
|
| 162 |
+
y = (axs[i, 0].get_position().y0 + axs[i, 0].get_position().y1) / 2
|
| 163 |
+
fig.text(0.005, y + 0.02, NAME[ds], fontsize=FS + 1, fontweight="bold", va="bottom", ha="left")
|
| 164 |
+
fig.text(0.005, y + 0.01, f"{n_d} donors", fontsize=FS - 2, va="top", ha="left", color="#4D4D4D")
|
| 165 |
+
iv = sorted(set(runs.n_inner_val))
|
| 166 |
+
ivt = f"{iv[0]}" if len(iv) == 1 else f"{iv[0]}–{iv[-1]}"
|
| 167 |
+
x0, x1 = axs[1, 0].get_position().x0, axs[1, -1].get_position().x1
|
| 168 |
+
fig.text((x0 + x1) / 2, 0.01, f"LoRA training pairs per fold (5-fold CV; +{ivt} inner-val pairs for early stopping; test fold never trained on)",
|
| 169 |
+
ha="center", va="bottom", fontsize=FS - 1)
|
| 170 |
+
handles = [Line2D([0], [0], color=RCOL[r], lw=2.2 if r == 16 else 1.8, marker=RMK[r], ms=7, mec=style.INK,
|
| 171 |
+
mew=0.6, label=f"LoRA rank r = {r}" + (" (used in the deck)" if r == 16 else ""))
|
| 172 |
+
for r in RANKS]
|
| 173 |
+
fig.legend(handles=handles, loc="upper center", bbox_to_anchor=(0.55, 1.0), ncol=3, frameon=False,
|
| 174 |
+
fontsize=FS - 2, handlelength=2.4, columnspacing=2.0, borderaxespad=0.0)
|
| 175 |
+
style.save(fig, "sec07_rank_sweep", FIGDIR)
|
| 176 |
+
return ivt
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def words(s):
|
| 180 |
+
return sum(1 for t in s.split() if re.search(r"[A-Za-z0-9]", t))
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def check(s, what, maxlen=None, maxwords=None):
|
| 184 |
+
if re.search(r"[가-힣]", s) or OFF_STORY.search(s):
|
| 185 |
+
raise ValueError(f"Korean / off-story text in {what}: {s!r}")
|
| 186 |
+
if maxlen and len(s) > maxlen:
|
| 187 |
+
raise ValueError(f"{what} over {maxlen} characters ({len(s)}): {s!r}")
|
| 188 |
+
if maxwords and words(s) > maxwords:
|
| 189 |
+
raise ValueError(f"{what} over {maxwords} words: {s!r}")
|
| 190 |
+
return s
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def main():
|
| 194 |
+
FIGDIR.mkdir(parents=True, exist_ok=True)
|
| 195 |
+
OUTDATA.mkdir(parents=True, exist_ok=True)
|
| 196 |
+
df, pdl, runs = load()
|
| 197 |
+
ivt = fig(df, runs)
|
| 198 |
+
df.to_csv(OUTDATA / "sec07_rank_sweep.csv", index=False, float_format="%.6g")
|
| 199 |
+
runs.to_csv(OUTDATA / "sec07_rank_sweep_runs.csv", index=False)
|
| 200 |
+
|
| 201 |
+
def v(ds, r, n, mk):
|
| 202 |
+
return float(df[(df.dataset == ds) & (df["rank"] == r) & (df.pairs == n) & (df.metric == mk)].value.iloc[0])
|
| 203 |
+
|
| 204 |
+
im, se = "immicro", "ye2026_sepsis"
|
| 205 |
+
c16, c64 = v(im, 16, "all", "coverage"), v(im, 64, "all", "coverage")
|
| 206 |
+
l16, l4 = v(im, 16, "all", "comp_l1"), v(im, 4, "all", "comp_l1")
|
| 207 |
+
p16, p64 = v(im, 16, "all", "precision"), v(im, 64, "all", "precision")
|
| 208 |
+
kw = [f"ImMicro r64 vs r16: coverage {c16:.2f} → {c64:.2f}",
|
| 209 |
+
f"ImMicro r4 vs r16: L1 {l16:.3f} → {l4:.3f}",
|
| 210 |
+
f"Kept r16; r64 precision {p16:.2f} → {p64:.2f}"]
|
| 211 |
+
for k in kw:
|
| 212 |
+
check(k, "keyword", KW_MAX, 7)
|
| 213 |
+
r16, r64, r4 = (v(se, r, "all", "logfc_r") for r in (16, 64, 4))
|
| 214 |
+
d16, d64, d4 = (int(v(se, r, "all", "deg")) for r in (16, 64, 4))
|
| 215 |
+
fs = check(f"Sepsis, {FZ.all_label(se)} pairs/fold: r64 logFC r {r16:.2f} → {r64:.2f}, DEG {d16} → {d64}; "
|
| 216 |
+
f"r4 {r4:.2f}, DEG {d4}. Pooled 5-fold scores.", "footnote_short", FOOT_MAX)
|
| 217 |
+
# footnote_full: every value and the per-donor tests
|
| 218 |
+
parts = []
|
| 219 |
+
for ds in DSETS:
|
| 220 |
+
for n in NS:
|
| 221 |
+
cells = []
|
| 222 |
+
for r in RANKS:
|
| 223 |
+
t = (f"r{r}: L1 {v(ds, r, n, 'comp_l1'):.3f}, P/C {v(ds, r, n, 'precision'):.3f} / "
|
| 224 |
+
f"{v(ds, r, n, 'coverage'):.3f}")
|
| 225 |
+
if not np.isnan(v(ds, r, n, "logfc_r")):
|
| 226 |
+
t += f", logFC r {v(ds, r, n, 'logfc_r'):.2f}, DEG {int(v(ds, r, n, 'deg'))}"
|
| 227 |
+
if r != 16:
|
| 228 |
+
m, p, nn = wil(pdl, ds, r, n)
|
| 229 |
+
t += f" (L1 vs r16 {m:+.3f}, Wilcoxon p {p:.2g}, {nn} donors)"
|
| 230 |
+
cells.append(t)
|
| 231 |
+
parts.append(f"{NAME[ds]} n = {n if n != 'all' else FZ.all_label(ds) + ' (every training donor of the fold)'}: "
|
| 232 |
+
+ "; ".join(cells))
|
| 233 |
+
ntr = runs.groupby(["dataset", "rank"]).n_trainable.first()
|
| 234 |
+
full = (f"LoRA fine-tune of the final model (f01 6k·1x·E16) with rank r and alpha = r, same recipe as the deck's "
|
| 235 |
+
f"r = 16 runs (early stop on {ivt} inner-val pairs, 20k step cap); n = training pairs, nested subsets; "
|
| 236 |
+
f"donor-level 5-fold CV, each pair scored once by its fold model (pooled call). Trainable parameters "
|
| 237 |
+
+ ", ".join(f"r{r} {ntr.loc[(im, r)]:,}" for r in RANKS) + ". "
|
| 238 |
+
+ " | ".join(parts)
|
| 239 |
+
+ ". r64 vs r16 brings small gains in coverage and disease signal but slightly lower precision and no "
|
| 240 |
+
"composition change; r4 is worse with many pairs; at n = 5 the ranks are mixed. r = 16 is kept. "
|
| 241 |
+
"Scores: scores/<cohort>/lora_rank_20261001/pooled (r4, r64) and scores/<cohort>/pooled{,_deg} (r16); "
|
| 242 |
+
"table: scores/<cohort>/rankcal_20261001.md.")
|
| 243 |
+
check(full, "footnote")
|
| 244 |
+
nums = [{"value": f"ImMicro {FZ.all_label(im)} pairs/fold coverage r16 {c16:.3f} -> r64 {c64:.3f}; precision {p16:.3f} -> {p64:.3f}; "
|
| 245 |
+
f"L1 r16 {l16:.3f}, r4 {l4:.3f} (Wilcoxon p {wil(pdl, im, 4, 'all')[1]:.2g})",
|
| 246 |
+
"source": f"{call_dir(im, 16)}/summary.json; {call_dir(im, 4)}/summary.json, per_donor.csv"},
|
| 247 |
+
{"value": f"Sepsis {FZ.all_label(se)} pairs/fold logFC r r16 {r16:.3f}, r64 {r64:.3f}, r4 {r4:.3f}; DEG {d16} / {d64} / {d4}",
|
| 248 |
+
"source": f"{call_dir(se, 16)}/summary.json, contrast.csv; {call_dir(se, 4)}/summary.json, contrast.csv"},
|
| 249 |
+
{"value": "trainable parameters: " + ", ".join(f"r{r} {ntr.loc[(im, r)]}" for r in RANKS),
|
| 250 |
+
"source": "runs/<cohort>/fold<k>/<arm>/RUN.json (trainable.n_trainable)"}]
|
| 251 |
+
spec = {"section": "07-rank", "slides": [{
|
| 252 |
+
"title": "LoRA rank: r = 4, 16, 64", "layout": "full", "figures": [str(FIGDIR / "sec07_rank_sweep.png")],
|
| 253 |
+
"keywords": kw, "footnote": full, "footnote_short": fs, "numbers": nums}],
|
| 254 |
+
"scripts": [str(SCRIPT)], "generated_from": "tools/sec07_rank_sweep.py (rerun to refresh; do not edit by hand)"}
|
| 255 |
+
(OUTDATA / "sec07_rank_sweep_slide_text.json").write_text(json.dumps(spec, indent=1, ensure_ascii=False))
|
| 256 |
+
for p in (OUTDATA / "sec07_rank_sweep_slide_text.json", OUTDATA / "sec07_rank_sweep.csv"):
|
| 257 |
+
m = OFF_STORY.search(p.read_text(encoding="utf-8"))
|
| 258 |
+
if m:
|
| 259 |
+
raise ValueError(f"{p}: off-story text {m.group(0)!r}")
|
| 260 |
+
for k in kw:
|
| 261 |
+
print(" *", k, f"({words(k)} words, {len(k)} chars)")
|
| 262 |
+
print(" footnote_short:", fs, f"({len(fs)} chars)")
|
| 263 |
+
print(" footnote:", full)
|
| 264 |
+
return 0
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
if __name__ == "__main__":
|
| 268 |
+
sys.exit(main())
|