Archive 4 checkpoints (1-4)
Browse files- paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec08_pairs_needed.py +897 -0
- paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec09_cat_curves.py +161 -0
- paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec09_extra_metrics.py +738 -0
- paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec09_paired_validation.py +0 -0
paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec08_pairs_needed.py
ADDED
|
@@ -0,0 +1,897 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Section 8 of the 2026-09-30 paper-summary deck: how many bulk-sc pairs LoRA needs (learning curve).
|
| 2 |
+
|
| 3 |
+
CPU only. Reads the pooled 5-fold scoring calls of the paired fine-tune plan and the per-fold RUN.json files,
|
| 4 |
+
then draws two slide figures:
|
| 5 |
+
figures/sec08_pairs_realism.{png,pdf} FULL: composition L1, coverage, selected step x (ImMicro, sepsis)
|
| 6 |
+
figures/sec08_pairs_signal.{png,pdf} TALL: ImMicro NK fraction r, sepsis logFC r, sepsis top-50 DEG
|
| 7 |
+
Every plotted/quoted number is read from a score file here and written with its source to data/sec08_*.csv.
|
| 8 |
+
Model: final f01 6k 1x epoch-16 checkpoint + LoRA (checked against every RUN.json).
|
| 9 |
+
x axis: "0" = no LoRA training. Two zero-shot points sit there, side by side: the pretrained model fed the real bulk
|
| 10 |
+
as measured (score arm zs__raw; uses no pair) and fed gene-wise calibrated bulk (zs__cal). Calibration (back as a
|
| 11 |
+
comparator, user decision 2026-10-01): alpha_g = mean CPM(pseudobulk_g) / mean CPM(bulk_g) over ALL paired training
|
| 12 |
+
donors of the fold (train + inner-val; tools/prepare_dataset.py `fit = fold != f`), applied as bulk CPM x alpha, then
|
| 13 |
+
renormalised. So zs__cal is not pair-free: its alpha uses the same 85-86 / 65-66 donors that LoRA "all" trains and
|
| 14 |
+
early-stops on. LoRA n = training pairs, and every LoRA run also early-stops on 7-8 paired inner-val donors
|
| 15 |
+
(RUN.json inner_val_rows). The LoRA arms are conditioned on the real bulk (*__raw) and share one real-bulk broadcast.
|
| 16 |
+
Cap-limited = ran to max_steps before the patience window closed; its late inner-val loss drop is read from
|
| 17 |
+
history.json.
|
| 18 |
+
When a zero-shot point lies far outside every other value of a panel (BREAK_RATIO), that panel gets a y-axis
|
| 19 |
+
break with a short segment at the same data scale, instead of squeezing the LoRA curve.
|
| 20 |
+
|
| 21 |
+
Equal-budget calibration (optional, drawn only if present): zero-shot + calibration with alpha fitted on exactly the
|
| 22 |
+
pairs a lora_n{5,10,20,40} run saw (n training + its inner-val pairs), per fold. The scores folder is scanned for
|
| 23 |
+
summary.json files (scores/<dataset>/**/summary.json, outside arms/) whose arm names match CAL_N_RE (contain "cal"
|
| 24 |
+
and an n<digits> token) and carry no fine-tune tag (FT_TAGS). An arm is drawn only from a scoring call over the
|
| 25 |
+
same donors as the pooled call (same reference cells, so metrics are comparable). If found, it is drawn as a second
|
| 26 |
+
line across n, ending at "all" with zs__cal (alpha from the same pairs LoRA "all" saw). If none is found, only the
|
| 27 |
+
two x = 0 points are drawn and a note is printed.
|
| 28 |
+
|
| 29 |
+
scSemiProfiler line (optional, drawn only if present; added 2026-10-02): scSemiProfiler trained with n pairs as
|
| 30 |
+
representatives (arms scsemi_n{5,10,20,40}__raw in scores/<dataset>/scsemi_budget_20261002/pooled*/) and with all
|
| 31 |
+
training pairs ("all" = arm scsemi__raw of the 5-fold CV run in scores/<dataset>/scsemi_cv_20261002/pooled*/), looked up
|
| 32 |
+
by tools/scsemi_results.py and drawn only for calls over the same donors and reference cells as the pooled call. If
|
| 33 |
+
nothing is found, a note is printed and the figures are unchanged. DECK_FIGDIR / DECK_OUTDATA redirect the outputs and
|
| 34 |
+
DECK_SCSEMI_PLAN_ROOT the scSemiProfiler lookup (synthetic presence test).
|
| 35 |
+
"""
|
| 36 |
+
import os
|
| 37 |
+
import json
|
| 38 |
+
import re
|
| 39 |
+
import sys
|
| 40 |
+
from pathlib import Path
|
| 41 |
+
|
| 42 |
+
import numpy as np
|
| 43 |
+
import pandas as pd
|
| 44 |
+
from scipy.stats import wilcoxon
|
| 45 |
+
|
| 46 |
+
DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/"
|
| 47 |
+
"2026-09-30--paper-summary--r00")
|
| 48 |
+
sys.path.insert(0, str(DECK / "tools"))
|
| 49 |
+
import style # noqa: E402
|
| 50 |
+
import scsemi_results as SR # noqa: E402
|
| 51 |
+
import fold_sizes as FZ # noqa: E402 (2026-10-02: the "all" point is labelled with its training-pair count)
|
| 52 |
+
import matplotlib.pyplot as plt # noqa: E402
|
| 53 |
+
from matplotlib.lines import Line2D # noqa: E402
|
| 54 |
+
|
| 55 |
+
PLAN = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/"
|
| 56 |
+
"paired_finetune_intradataset_20260927")
|
| 57 |
+
FINAL_CKPT = ("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/runs/"
|
| 58 |
+
"f01_6k_1x_seed20260627/checkpoint_epoch_016.pt")
|
| 59 |
+
FIGDIR = Path(os.environ.get("DECK_FIGDIR", str(DECK / "figures")))
|
| 60 |
+
DATADIR = Path(os.environ.get("DECK_OUTDATA", str(DECK / "data")))
|
| 61 |
+
FIGDIR.mkdir(exist_ok=True)
|
| 62 |
+
DATADIR.mkdir(exist_ok=True)
|
| 63 |
+
|
| 64 |
+
DSETS = ["immicro", "ye2026_sepsis"]
|
| 65 |
+
DS_LABEL = {"immicro": "ImMicro", "ye2026_sepsis": "Sepsis"}
|
| 66 |
+
LC_N = [5, 10, 20, 40]
|
| 67 |
+
LORA_ARMS = [f"lora_n{n}__raw" for n in LC_N] + ["real_lora__raw"]
|
| 68 |
+
RUN_ARMS = [f"lora_n{n}" for n in LC_N] + ["real_lora"]
|
| 69 |
+
ZS = "zs__raw" # zero-shot on the real bulk as measured: 0 pairs
|
| 70 |
+
ZS_CAL = "zs__cal" # zero-shot + calibration, alpha from all fold pairs (train + inner-val)
|
| 71 |
+
# 2026-10-02 (user): x = 0 must use no paired data. The second x = 0 point is now the zero-shot model fed the real bulk
|
| 72 |
+
# after exon-length correction (no pairs); zs__cal (alpha from every training pair of the fold) is only drawn where it
|
| 73 |
+
# belongs, as the right end of the equal-budget calibration line (same pairs as the rightmost LoRA point).
|
| 74 |
+
ZS_LEN = "zs__len" # zero-shot, exon-length-corrected real bulk (tools/build_tpm_zeroshot.py)
|
| 75 |
+
LEN_SUB = "zeroshot_tpm_20261002/pooled" # its scoring call (same donors and reference cells as scores/<ds>/pooled)
|
| 76 |
+
X_LAB = ["0", "5", "10", "20", "40", "all"]
|
| 77 |
+
KEY_LAB = ["zero_shot", "5", "10", "20", "40", "all"] # the same points, as keys in sec08_slide_numbers.csv
|
| 78 |
+
X_POS = [0.0, 1.3, 2.3, 3.3, 4.3, 5.55] # small gap after the zero-shot points; extra room for the "78–79" tick
|
| 79 |
+
DX0 = 0.2 # raw zero-shot left of x = 0, calibrated right of it
|
| 80 |
+
X_RAW, X_CAL = X_POS[0] - DX0, X_POS[0] + DX0 # X_CAL: position of the second zero-shot point
|
| 81 |
+
XLIM = (-0.5, X_POS[-1] + 0.5) # same x range as the selected-step panel
|
| 82 |
+
COL_RAW, COL_CAL = style.ARM["zs_raw"], style.ARM["zs_cal"] # archived pair: pale = raw, #0072B2 = calibrated
|
| 83 |
+
RAW_EDGE = "#5E8FB5" # edge of the pale raw marker (same as sec05 RAW_EDGE)
|
| 84 |
+
COL_LEN = style.ARM["tpm"] # zero-shot, length-corrected bulk (sand)
|
| 85 |
+
# equal-budget calibration arms: "cal" and an n<digits> token, and no fine-tune tag
|
| 86 |
+
CAL_N_RE = re.compile(r"(?:^|[^a-z0-9])n(\d+)(?![0-9])", re.I)
|
| 87 |
+
FT_TAGS = ("lora", "real", "pseudo", "full", "condenc", "multik", "recipe")
|
| 88 |
+
BREAK_RATIO = 1.5 # y-axis break when the zero-shot point sits > 1.5 spans of the other values beyond them
|
| 89 |
+
CELLTYPES = ["T cell", "B cell", "Monocyte", "NK cell"]
|
| 90 |
+
DEG_TYPES = ["T cell", "B cell", "Monocyte", "NK cell", "DC"]
|
| 91 |
+
RAW_ARMS = LORA_ARMS + ["zs__raw", "real_full__raw", "pseudo_full__raw"] # all conditioned on raw real bulk
|
| 92 |
+
|
| 93 |
+
REF = { # reference-line styles; pseudo/broadcast copied from sec09 REFSTYLE so the deck is consistent
|
| 94 |
+
"pseudo": dict(ls=(0, (4, 2)), color=style.ARM["pseudo"], lw=1.6, label="Zero-shot from sc pseudobulk"),
|
| 95 |
+
"broadcast": dict(ls=(0, (1, 1.2)), color=style.ARM["broadcast"], lw=2.4, label="Real-bulk broadcast"),
|
| 96 |
+
"null": dict(ls=(0, (6, 2, 1.5, 2)), color=style.GREY, lw=1.4, label="Cohort-mean null"),
|
| 97 |
+
}
|
| 98 |
+
LEG_ZS = "Zero-shot, real bulk as measured (no pairs)"
|
| 99 |
+
LEG_LEN = "Zero-shot, exon-length-corrected bulk (no pairs)"
|
| 100 |
+
LEG_CAL_N = "Zero-shot + calibration, α from the same pairs"
|
| 101 |
+
COL_SC = style.ARM["scsemi"]
|
| 102 |
+
LEG_SC = "scSemiProfiler, n pairs as representatives"
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def xlabel(st):
|
| 106 |
+
"""x-axis label; the inner-val range is read from the RUN.json files."""
|
| 107 |
+
return (f"LoRA training pairs per fold (each run +{rng_txt(st.n_inner_val)} inner-val pairs for early stopping; "
|
| 108 |
+
f"test fold never trained on)")
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def xticks(ds):
|
| 112 |
+
"""x tick labels of one cohort: the rightmost point is every training donor of the fold, shown as its count."""
|
| 113 |
+
return X_LAB[:-1] + [FZ.all_label(ds)]
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def close(a, b, tol=1e-6):
|
| 117 |
+
return abs(float(a) - float(b)) <= tol
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class Call:
|
| 121 |
+
"""One pooled score_ft.py scoring call."""
|
| 122 |
+
|
| 123 |
+
def __init__(self, path: Path):
|
| 124 |
+
self.path = path
|
| 125 |
+
self.summary = json.loads((path / "summary.json").read_text())
|
| 126 |
+
self.contrast = pd.read_csv(path / "contrast.csv") if (path / "contrast.csv").exists() else None
|
| 127 |
+
self.per_donor = pd.read_csv(path / "per_donor.csv")
|
| 128 |
+
self.src_summary = str(path / "summary.json")
|
| 129 |
+
self.src_contrast = str(path / "contrast.csv")
|
| 130 |
+
self.src_per_donor = str(path / "per_donor.csv")
|
| 131 |
+
|
| 132 |
+
def head(self, arm, key):
|
| 133 |
+
return float(self.summary["headline"][arm][key])
|
| 134 |
+
|
| 135 |
+
def contrast_r(self, arm, col="r_generated"):
|
| 136 |
+
c = self.contrast
|
| 137 |
+
c = c[(c.arm == arm) & (c.statistic == "mean_cp10k") & (c.celltype.isin(CELLTYPES))]
|
| 138 |
+
assert set(c.celltype) == set(CELLTYPES), (self.path, arm)
|
| 139 |
+
return float(c[col].mean())
|
| 140 |
+
|
| 141 |
+
def deg(self, arm, col="top50_overlap"):
|
| 142 |
+
d = self.contrast
|
| 143 |
+
d = d[(d.arm == arm) & (d.statistic == "welch_top50_deg")]
|
| 144 |
+
assert len(d) == 5, (self.path, arm, len(d)) # T/B/Mono/NK/DC
|
| 145 |
+
return float(d[col].sum())
|
| 146 |
+
|
| 147 |
+
def deg_type(self, arm, ct, col="top50_overlap"):
|
| 148 |
+
d = self.contrast
|
| 149 |
+
d = d[(d.arm == arm) & (d.statistic == "welch_top50_deg") & (d.celltype == ct)]
|
| 150 |
+
assert len(d) == 1, (self.path, arm, ct, len(d))
|
| 151 |
+
return float(d[col].iloc[0])
|
| 152 |
+
|
| 153 |
+
def frac_r(self, arm, ct):
|
| 154 |
+
d = self.per_donor[self.per_donor.arm == arm]
|
| 155 |
+
return float(np.corrcoef(d[f"gen_{ct}"].astype(float), d[f"obs_{ct}"].astype(float))[0, 1])
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def load():
|
| 159 |
+
calls = {ds: Call(PLAN / "scores" / ds / "pooled") for ds in DSETS}
|
| 160 |
+
deg_call = Call(PLAN / "scores" / "ye2026_sepsis" / "pooled_deg")
|
| 161 |
+
for ds, c in calls.items():
|
| 162 |
+
for a in LORA_ARMS + [ZS, ZS_CAL, "zs__pseudo"]:
|
| 163 |
+
assert a in c.summary["arms"], (ds, a)
|
| 164 |
+
assert c.summary["per_arm"][a].get("receipt_verified", True) is not False, (ds, a)
|
| 165 |
+
# headline composition L1 equals the donor mean of per_donor.csv
|
| 166 |
+
assert close(c.per_donor.loc[c.per_donor.arm == a, "comp_l1"].mean(), c.head(a, "comp_l1"), 1e-9), a
|
| 167 |
+
# headline contrast means equal the per-type mean of contrast.csv
|
| 168 |
+
se = calls["ye2026_sepsis"]
|
| 169 |
+
for a in LORA_ARMS + [ZS, ZS_CAL, "zs__pseudo"]:
|
| 170 |
+
assert close(se.contrast_r(a), se.head(a, "contrast_mean_cp10k_r_gen"), 1e-9), a
|
| 171 |
+
assert close(deg_call.deg(a), deg_call.head(a, "deg_top50_sum"), 1e-9), a
|
| 172 |
+
# broadcast is the same for every arm conditioned on raw real bulk
|
| 173 |
+
bc = {a: se.contrast_r(a, "r_broadcast") for a in RAW_ARMS}
|
| 174 |
+
assert max(bc.values()) - min(bc.values()) < 1e-12, bc
|
| 175 |
+
bcd = {a: deg_call.deg(a, "top50_overlap_broadcast") for a in RAW_ARMS}
|
| 176 |
+
assert len(set(bcd.values())) == 1, bcd
|
| 177 |
+
assert close(bcd["real_lora__raw"], deg_call.head("real_lora__raw", "deg_top50_sum_broadcast"), 1e-9)
|
| 178 |
+
# non-DEG metrics agree between the two sepsis scoring calls (k-NN ties allow 1e-3)
|
| 179 |
+
for a in LORA_ARMS + [ZS, ZS_CAL]:
|
| 180 |
+
for k in ("comp_l1", "coverage"):
|
| 181 |
+
assert abs(se.head(a, k) - deg_call.head(a, k)) <= 1e-3, (a, k)
|
| 182 |
+
lens = {ds: Call(PLAN / "scores" / ds / LEN_SUB) for ds in DSETS}
|
| 183 |
+
for ds, lc in lens.items():
|
| 184 |
+
c = calls[ds]
|
| 185 |
+
assert ZS_LEN in lc.summary["arms"] and ZS in lc.summary["arms"], (ds, lc.summary["arms"])
|
| 186 |
+
assert int(lc.summary["n_donors"]) == int(c.summary["n_donors"]), ds
|
| 187 |
+
assert lc.summary["reference"]["reference_sha256"] == c.summary["reference"]["reference_sha256"], ds
|
| 188 |
+
for k in ("comp_l1", "coverage", "precision"): # the raw arm reproduces in the new call (k-NN ties: 1e-3)
|
| 189 |
+
assert abs(lc.head(ZS, k) - c.head(ZS, k)) <= 1e-3, (ds, k, lc.head(ZS, k), c.head(ZS, k))
|
| 190 |
+
assert close(lens["ye2026_sepsis"].contrast_r(ZS), se.contrast_r(ZS), 1e-9)
|
| 191 |
+
assert close(lens["ye2026_sepsis"].deg(ZS), deg_call.deg(ZS), 1e-9), (lens["ye2026_sepsis"].deg(ZS), deg_call.deg(ZS))
|
| 192 |
+
return calls, deg_call, lens
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def find_cal_budget(calls, deg_call):
|
| 196 |
+
"""Scan the scores folder for equal-budget calibration arms (see module docstring).
|
| 197 |
+
|
| 198 |
+
Returns (budget, log): budget[ds][n] = dict(arm, calls=[Call, ...]) for drawable arms (pooled call first, then
|
| 199 |
+
other calls over the same donors; the sepsis DEG call first for DEG); log = one dict per matching arm found."""
|
| 200 |
+
budget, log = {ds: {} for ds in DSETS}, []
|
| 201 |
+
cache = {c.path: c for c in list(calls.values()) + [deg_call]}
|
| 202 |
+
for ds in DSETS:
|
| 203 |
+
root = PLAN / "scores" / ds
|
| 204 |
+
pooled = calls[ds]
|
| 205 |
+
donors = set(pooled.per_donor.donor)
|
| 206 |
+
cands = {}
|
| 207 |
+
for sp in sorted(root.rglob("summary.json")):
|
| 208 |
+
rel = sp.relative_to(root)
|
| 209 |
+
if "arms" in rel.parts:
|
| 210 |
+
continue
|
| 211 |
+
try:
|
| 212 |
+
arms = json.loads(sp.read_text()).get("arms") or []
|
| 213 |
+
except (OSError, ValueError):
|
| 214 |
+
continue
|
| 215 |
+
for a in arms:
|
| 216 |
+
m = CAL_N_RE.search(a)
|
| 217 |
+
if "cal" not in a.lower() or m is None or any(t in a.lower() for t in FT_TAGS):
|
| 218 |
+
continue
|
| 219 |
+
n = int(m.group(1))
|
| 220 |
+
if sp.parent not in cache:
|
| 221 |
+
try:
|
| 222 |
+
cache[sp.parent] = Call(sp.parent)
|
| 223 |
+
except (OSError, ValueError) as e:
|
| 224 |
+
log.append(dict(dataset=ds, call=str(rel.parent), arm=a, n=n, drawn=False,
|
| 225 |
+
note=f"not drawn: cannot read the call ({e.__class__.__name__})"))
|
| 226 |
+
continue
|
| 227 |
+
call = cache[sp.parent]
|
| 228 |
+
same = set(call.per_donor.loc[call.per_donor.arm == a, "donor"]) == donors
|
| 229 |
+
ok = same and n in LC_N
|
| 230 |
+
why = ("drawn" if ok else "not drawn: " + ("n not in " + str(LC_N) if same else
|
| 231 |
+
"call does not score the pooled donor set"))
|
| 232 |
+
log.append(dict(dataset=ds, call=str(rel.parent), arm=a, n=n, drawn=ok, note=why))
|
| 233 |
+
if ok:
|
| 234 |
+
cands.setdefault(n, []).append((a, call))
|
| 235 |
+
for n, lst in cands.items():
|
| 236 |
+
names = sorted({a for a, _ in lst})
|
| 237 |
+
if len(names) > 1:
|
| 238 |
+
pref = sorted({a for a, c in lst if c is pooled})
|
| 239 |
+
if len(pref) != 1:
|
| 240 |
+
sys.exit(f"{ds}: several equal-budget calibration arms for n = {n}: {names}; pick one")
|
| 241 |
+
names = pref
|
| 242 |
+
arm = names[0]
|
| 243 |
+
cl = [c for a, c in lst if a == arm]
|
| 244 |
+
cl.sort(key=lambda c: (c is not pooled, c is not deg_call, str(c.path)))
|
| 245 |
+
for c in cl: # a call other than the pooled one must reproduce shared arms (k-NN ties allow 1e-3)
|
| 246 |
+
if c is pooled:
|
| 247 |
+
continue
|
| 248 |
+
for shared in (ZS_CAL, "real_lora__raw"):
|
| 249 |
+
if shared in c.summary["arms"]:
|
| 250 |
+
for k in ("comp_l1", "coverage"):
|
| 251 |
+
assert abs(c.head(shared, k) - pooled.head(shared, k)) <= 1e-3, (c.path, shared, k)
|
| 252 |
+
budget[ds][n] = dict(arm=arm, calls=cl)
|
| 253 |
+
return budget, log
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def find_scsemi(calls):
|
| 257 |
+
"""scSemiProfiler at n = 5..40 (equal-budget arms) and "all" (5-fold CV arm), see module docstring.
|
| 258 |
+
|
| 259 |
+
Returns (scs, log): scs[ds][pairs label] = dict(arm, calls=[Call, ...]) for accepted calls; log = one dict per
|
| 260 |
+
arm found (accepted or not)."""
|
| 261 |
+
scs, log = {ds: {} for ds in DSETS}, []
|
| 262 |
+
for ds in DSETS:
|
| 263 |
+
ref = calls[ds].summary
|
| 264 |
+
found = [(str(n), a, d) for n, lst in sorted(SR.budget_calls(ds).items()) for a, d in lst]
|
| 265 |
+
found += [("all", SR.CV_ARM, d) for d in SR.cv_calls(ds)]
|
| 266 |
+
for lab, a, d in found:
|
| 267 |
+
try:
|
| 268 |
+
c = Call(d)
|
| 269 |
+
except (OSError, ValueError) as e:
|
| 270 |
+
log.append(dict(dataset=ds, call=str(d), arm=a, pairs=lab, drawn=False,
|
| 271 |
+
note=f"not drawn: cannot read the call ({e.__class__.__name__})"))
|
| 272 |
+
continue
|
| 273 |
+
why = SR.accept(c.summary, ref, a)
|
| 274 |
+
if lab not in X_LAB[1:]:
|
| 275 |
+
why.append(f"n {lab} not in {X_LAB[1:]}")
|
| 276 |
+
ent = scs[ds].get(lab)
|
| 277 |
+
if ent is not None and ent["arm"] != a:
|
| 278 |
+
why.append(f"a different arm ({ent['arm']}) already gives n = {lab}")
|
| 279 |
+
log.append(dict(dataset=ds, call=str(d), arm=a, pairs=lab, drawn=not why,
|
| 280 |
+
note="drawn" if not why else "not drawn: " + "; ".join(why)))
|
| 281 |
+
if not why:
|
| 282 |
+
scs[ds].setdefault(lab, dict(arm=a, calls=[]))["calls"].append(c)
|
| 283 |
+
return scs, log
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def scsemi_series(scs, ds, getter):
|
| 287 |
+
"""[(pairs label, value, source)] of the scSemiProfiler line for one panel ([] when nothing is found)."""
|
| 288 |
+
out = []
|
| 289 |
+
for lab in X_LAB[1:]:
|
| 290 |
+
if lab in scs[ds]:
|
| 291 |
+
v, c = budget_value(scs[ds][lab], getter)
|
| 292 |
+
if v is not None:
|
| 293 |
+
out.append((lab, v, f"{c.path} arm {scs[ds][lab]['arm']}"))
|
| 294 |
+
return out
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def budget_value(entry, getter):
|
| 298 |
+
"""First call of a budget entry that provides the metric (None if no call does)."""
|
| 299 |
+
for c in entry["calls"]:
|
| 300 |
+
try:
|
| 301 |
+
return getter(c, entry["arm"]), c
|
| 302 |
+
except (AssertionError, KeyError, TypeError, AttributeError):
|
| 303 |
+
continue
|
| 304 |
+
return None, None
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def load_steps():
|
| 308 |
+
rows = []
|
| 309 |
+
for ds in DSETS:
|
| 310 |
+
for k in range(5):
|
| 311 |
+
for arm in RUN_ARMS:
|
| 312 |
+
p = PLAN / "runs" / ds / f"fold{k}" / arm / "RUN.json"
|
| 313 |
+
r = json.loads(p.read_text())
|
| 314 |
+
assert r["source_checkpoint"] == FINAL_CKPT, (p, r["source_checkpoint"])
|
| 315 |
+
assert r["mode"] == "lora", p
|
| 316 |
+
assert r["inner_val_rows"], p # every LoRA run early-stops on paired inner-val donors
|
| 317 |
+
hist = json.loads((p.parent / "history.json").read_text())
|
| 318 |
+
h = {int(e["step"]): float(e["inner_val_loss"]) for e in hist}
|
| 319 |
+
# cap-limited = ran to max_steps without the patience window closing
|
| 320 |
+
cap_limited = (r["steps_run"] >= r["max_steps"]
|
| 321 |
+
and r["steps_run"] - r["selected_step"] < r["patience"] * r["eval_every"])
|
| 322 |
+
last = max(h)
|
| 323 |
+
win = r["patience"] * r["eval_every"] # last patience window (2,000 steps)
|
| 324 |
+
drop_total = h[0] - h[last]
|
| 325 |
+
drop_last = h[last - win] - h[last]
|
| 326 |
+
rows.append({"dataset": ds, "fold": k, "arm": arm, "n_train": len(r["train_rows"]),
|
| 327 |
+
"n_inner_val": len(r["inner_val_rows"]), "selected_step": r["selected_step"],
|
| 328 |
+
"max_steps": r["max_steps"], "steps_run": r["steps_run"],
|
| 329 |
+
"patience_steps": win, "cap_limited": bool(cap_limited),
|
| 330 |
+
"val_loss_step0": h[0], "val_loss_last": h[last],
|
| 331 |
+
"val_loss_last_window_drop_frac": drop_last / drop_total,
|
| 332 |
+
"wall_seconds": r.get("wall_seconds"), "source": str(p),
|
| 333 |
+
"history": str(p.parent / "history.json")})
|
| 334 |
+
st = pd.DataFrame(rows)
|
| 335 |
+
# nested subsets: n_train equals the arm size for lora_n*
|
| 336 |
+
for n in LC_N:
|
| 337 |
+
assert (st[st.arm == f"lora_n{n}"].n_train == n).all(), n
|
| 338 |
+
return st
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def load_fold_sizes():
|
| 342 |
+
"""Test donors per fold (PREPARE.json); their sum must equal the donors in the pooled scoring call.
|
| 343 |
+
alpha = paired donors the zs__cal alpha is fitted on per fold (train + inner-val)."""
|
| 344 |
+
out = {}
|
| 345 |
+
for ds in DSETS:
|
| 346 |
+
p = PLAN / "data" / ds / "PREPARE.json"
|
| 347 |
+
fs = json.loads(p.read_text())["fold_sizes"]
|
| 348 |
+
out[ds] = dict(test=[int(v["test"]) for v in fs.values()],
|
| 349 |
+
alpha=[int(v["train"]) + int(v["inner_val"]) for v in fs.values()], source=str(p))
|
| 350 |
+
return out
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
def load_fewshot():
|
| 354 |
+
"""Few-pair call (5 draws): zero-shot + calibration with alpha from the same 5 pairs vs LoRA on those 5 pairs
|
| 355 |
+
(fixed 3k steps, no inner-val). Its own donor set, so it is only quoted in the notes, never drawn."""
|
| 356 |
+
out = {}
|
| 357 |
+
for ds in DSETS:
|
| 358 |
+
p = PLAN / "scores" / ds / "fewshot_n5" / "aggregate.json"
|
| 359 |
+
a = json.loads(p.read_text())["arms"]
|
| 360 |
+
out[ds] = dict(zs_cal=float(a["zs_cal"]["coverage"][0]), lora5=float(a["lora5"]["coverage"][0]),
|
| 361 |
+
source=str(p))
|
| 362 |
+
return out
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
def rng_txt(v):
|
| 366 |
+
v = sorted(int(x) for x in v)
|
| 367 |
+
return f"{v[0]}" if v[0] == v[-1] else f"{v[0]}–{v[-1]}"
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
def break_axis(ax, v0, lo, hi, x_txt=X_RAW, extra=()):
|
| 371 |
+
"""Shrink ax to lo..hi and add a short segment above it that shows v0 at the same data scale.
|
| 372 |
+
extra: further break values (2026-10-02, two zero-shot points at x = 0). When they do not fit at the main scale,
|
| 373 |
+
the segment gets its own scale and a tick at each value."""
|
| 374 |
+
p = ax.get_position()
|
| 375 |
+
h_top, gap = 0.22 * p.height, 0.08 * p.height
|
| 376 |
+
h_main = p.height - h_top - gap
|
| 377 |
+
ax.set_position([p.x0, p.y0, p.width, h_main])
|
| 378 |
+
ax.set_ylim(lo, hi)
|
| 379 |
+
half = (hi - lo) * h_top / h_main / 2
|
| 380 |
+
top = ax.figure.add_axes([p.x0, p.y0 + h_main + gap, p.width, h_top], sharex=ax)
|
| 381 |
+
vals = [v0] + list(extra)
|
| 382 |
+
if max(vals) - min(vals) > 1.6 * half: # own scale: ticks at the values
|
| 383 |
+
spread = max(vals) - min(vals)
|
| 384 |
+
top.set_ylim(min(vals) - 0.35 * spread, max(vals) + 0.35 * spread)
|
| 385 |
+
top.set_yticks(sorted(round(v, 2) for v in vals))
|
| 386 |
+
top.spines["bottom"].set_visible(False)
|
| 387 |
+
top.tick_params(axis="x", bottom=False, labelbottom=False)
|
| 388 |
+
mk = dict(marker=[(-1, -0.5), (1, 0.5)], markersize=10, ls="none", color=style.INK, mec=style.INK, mew=1.2,
|
| 389 |
+
clip_on=False)
|
| 390 |
+
top.plot([0], [0], transform=top.transAxes, **mk)
|
| 391 |
+
ax.plot([0], [1], transform=ax.transAxes, **mk)
|
| 392 |
+
return top
|
| 393 |
+
v0 = (max(vals) + min(vals)) / 2
|
| 394 |
+
top.set_ylim(v0 - half, v0 + half)
|
| 395 |
+
# one tick in the short segment: the nearest value on the main axis' tick grid that fits inside it
|
| 396 |
+
step = float(np.diff(ax.get_yticks()[:2])[0]) / 2
|
| 397 |
+
tick = round(round(v0 / step) * step, 10)
|
| 398 |
+
top.set_yticks([tick] if abs(tick - v0) < half else [])
|
| 399 |
+
if not len(top.get_yticks()): # no grid value fits: print the value next to the point instead
|
| 400 |
+
top.text(x_txt + 0.3, v0, f"{v0:.2f}", va="center", ha="left", fontsize=12)
|
| 401 |
+
top.spines["bottom"].set_visible(False)
|
| 402 |
+
top.tick_params(axis="x", bottom=False, labelbottom=False)
|
| 403 |
+
mk = dict(marker=[(-1, -0.5), (1, 0.5)], markersize=10, ls="none", color=style.INK, mec=style.INK, mew=1.2,
|
| 404 |
+
clip_on=False)
|
| 405 |
+
top.plot([0], [0], transform=top.transAxes, **mk)
|
| 406 |
+
ax.plot([0], [1], transform=ax.transAxes, **mk)
|
| 407 |
+
return top
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def curve(ax, z0, vl, refs, rows, panel, ds, srcl, ylim0=None, vb=None, vs=None):
|
| 411 |
+
"""Zero-shot points at x = 0 (z0: [(series, value, source)] for raw and calibrated), LoRA curve at 5..all,
|
| 412 |
+
optional equal-budget calibration line (vb: [(pairs label, value, source)]), reference lines.
|
| 413 |
+
Returns the axis that carries the panel title."""
|
| 414 |
+
vb = vb or []
|
| 415 |
+
vs = vs or [] # scSemiProfiler line (n = 5..all)
|
| 416 |
+
lo, hi = min(vl), max(vl)
|
| 417 |
+
for _, val, _ in list(refs) + [(None, v, None) for _, v, _ in vb + vs]:
|
| 418 |
+
lo, hi = min(lo, val), max(hi, val)
|
| 419 |
+
span = hi - lo
|
| 420 |
+
# a zero-shot point goes to the break segment when it sits > BREAK_RATIO spans beyond everything else
|
| 421 |
+
out = {ser for ser, v, _ in z0
|
| 422 |
+
if ylim0 is None and span > 0 and (v - hi > BREAK_RATIO * span or lo - v > BREAK_RATIO * span)}
|
| 423 |
+
for ser, v, _ in z0:
|
| 424 |
+
if ser in out:
|
| 425 |
+
assert v > hi, (panel, ds, ser, "axis break below the curve is not implemented")
|
| 426 |
+
else:
|
| 427 |
+
lo, hi = min(lo, v), max(hi, v)
|
| 428 |
+
broken = bool(out)
|
| 429 |
+
pad = (hi - lo) * 0.15
|
| 430 |
+
axes = [ax]
|
| 431 |
+
xz = {"zero_shot": X_RAW, "zs_len": X_CAL}
|
| 432 |
+
if broken:
|
| 433 |
+
zb = [z for z in z0 if z[0] in out]
|
| 434 |
+
top = break_axis(ax, zb[0][1], lo - pad, hi + pad, xz[zb[0][0]], extra=[v for _, v, _ in zb[1:]])
|
| 435 |
+
axes.append(top)
|
| 436 |
+
else:
|
| 437 |
+
ax.set_ylim(ylim0 if ylim0 is not None else lo - pad, hi + pad)
|
| 438 |
+
for ser, v, src in z0:
|
| 439 |
+
a = axes[-1] if ser in out else ax
|
| 440 |
+
if ser == "zero_shot":
|
| 441 |
+
a.scatter([X_RAW], [v], s=70, color=COL_RAW, edgecolor=RAW_EDGE, lw=1.0, zorder=5, clip_on=False)
|
| 442 |
+
else:
|
| 443 |
+
a.scatter([X_CAL], [v], s=70, color=COL_LEN, edgecolor=style.INK, lw=0.6, zorder=5, clip_on=False)
|
| 444 |
+
rows.append(dict(panel=panel, dataset=ds, series=ser, pairs=X_LAB[0], value=v, source=src,
|
| 445 |
+
y_axis_break=bool(broken)))
|
| 446 |
+
if vb:
|
| 447 |
+
xb = [X_POS[X_LAB.index(lab)] for lab, _, _ in vb]
|
| 448 |
+
ax.plot(xb, [v for _, v, _ in vb], color=COL_CAL, lw=1.8, zorder=3)
|
| 449 |
+
ax.scatter(xb, [v for _, v, _ in vb], s=60, marker="s", color=COL_CAL, edgecolor=style.INK, lw=0.6,
|
| 450 |
+
zorder=5)
|
| 451 |
+
for lab, v, src in vb:
|
| 452 |
+
rows.append(dict(panel=panel, dataset=ds, series="zs_cal_budget", pairs=lab, value=v, source=src,
|
| 453 |
+
y_axis_break=bool(broken)))
|
| 454 |
+
if vs:
|
| 455 |
+
xs = [X_POS[X_LAB.index(lab)] for lab, _, _ in vs]
|
| 456 |
+
ax.plot(xs, [v for _, v, _ in vs], color=COL_SC, lw=1.8, zorder=3)
|
| 457 |
+
ax.scatter(xs, [v for _, v, _ in vs], s=55, marker="D", color=COL_SC, edgecolor=style.INK, lw=0.6, zorder=5)
|
| 458 |
+
for lab, v, src in vs:
|
| 459 |
+
rows.append(dict(panel=panel, dataset=ds, series="scsemi", pairs=lab, value=v, source=src,
|
| 460 |
+
y_axis_break=bool(broken)))
|
| 461 |
+
ax.plot(X_POS[1:], vl, color=style.ARM["lora"], lw=2.0, zorder=3)
|
| 462 |
+
ax.scatter(X_POS[1:], vl, s=70, color=style.ARM["lora"], edgecolor=style.INK, lw=0.6, zorder=5)
|
| 463 |
+
for lab, v, s in zip(X_LAB[1:], vl, srcl):
|
| 464 |
+
rows.append(dict(panel=panel, dataset=ds, series="lora", pairs=lab, value=v, source=s,
|
| 465 |
+
y_axis_break=bool(broken)))
|
| 466 |
+
for key, val, src in refs:
|
| 467 |
+
r = REF[key]
|
| 468 |
+
for a in axes:
|
| 469 |
+
a.axhline(val, ls=r["ls"], color=r["color"], lw=r["lw"], zorder=2)
|
| 470 |
+
rows.append(dict(panel=panel, dataset=ds, series=f"ref_{key}", pairs="", value=val, source=src,
|
| 471 |
+
y_axis_break=bool(broken)))
|
| 472 |
+
ax.set_xlim(*XLIM)
|
| 473 |
+
ax.set_xticks(X_POS)
|
| 474 |
+
ax.set_xticklabels(xticks(ds))
|
| 475 |
+
# nothing is clipped: every plotted value is inside the y range of the axis that draws it
|
| 476 |
+
for v in list(vl) + [val for _, val, _ in refs] + [v for _, v, _ in vb + vs] + [v for ser, v, _ in z0
|
| 477 |
+
if ser not in out]:
|
| 478 |
+
assert ax.get_ylim()[0] <= v <= ax.get_ylim()[1], (panel, ds, v, ax.get_ylim())
|
| 479 |
+
for ser, v, _ in z0:
|
| 480 |
+
if ser in out:
|
| 481 |
+
assert axes[-1].get_ylim()[0] <= v <= axes[-1].get_ylim()[1], (panel, ds, ser, v)
|
| 482 |
+
return axes[-1]
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
def budget_series(budget, ds, getter, cal_all, src_all):
|
| 486 |
+
"""Equal-budget calibration line for one panel: [(pairs label, value, source)] at n = 5..40 (where present)
|
| 487 |
+
plus "all" = zs__cal (alpha from the same train + inner-val pairs LoRA "all" saw). [] when nothing is found."""
|
| 488 |
+
out = []
|
| 489 |
+
for n in LC_N:
|
| 490 |
+
if n not in budget[ds]:
|
| 491 |
+
continue
|
| 492 |
+
v, c = budget_value(budget[ds][n], getter)
|
| 493 |
+
if v is not None:
|
| 494 |
+
out.append((str(n), v, f"{c.path} arm {budget[ds][n]['arm']}"))
|
| 495 |
+
if out:
|
| 496 |
+
out.append(("all", cal_all, src_all + " arm zs__cal (alpha from every training pair of the fold = the rightmost LoRA point's pairs)"))
|
| 497 |
+
return out
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
def fig_realism(calls, lens, st, fold_sizes, rows, steprows, budget, scs):
|
| 501 |
+
has_budget = any(budget[ds] for ds in DSETS)
|
| 502 |
+
has_sc = any(scs[ds] for ds in DSETS)
|
| 503 |
+
n_leg = 6 + has_budget + has_sc
|
| 504 |
+
fig, axs = plt.subplots(2, 3, figsize=style.FULL, # a third legend row when an optional line is drawn
|
| 505 |
+
gridspec_kw=dict(left=0.168, right=0.99, top=0.79 if n_leg > 6 else 0.83,
|
| 506 |
+
bottom=0.12, hspace=0.36, wspace=0.30))
|
| 507 |
+
heads = ["Composition L1 ↓", "Coverage ↑", "Selected step (×1,000)"]
|
| 508 |
+
pos0 = {ri: axs[ri, 2].get_position() for ri in range(len(DSETS))} # row extents before any y-axis break
|
| 509 |
+
title_ax = {ci: axs[0, ci] for ci in range(3)}
|
| 510 |
+
for ri, ds in enumerate(DSETS):
|
| 511 |
+
c = calls[ds]
|
| 512 |
+
for ci, key in enumerate(["comp_l1", "coverage"]):
|
| 513 |
+
ax = axs[ri, ci]
|
| 514 |
+
refs = [("pseudo", c.head("zs__pseudo", key), c.src_summary)]
|
| 515 |
+
if key == "comp_l1":
|
| 516 |
+
refs.append(("null", c.head("real_lora__raw", "comp_l1_obs_loo_null"), c.src_summary))
|
| 517 |
+
z0 = [("zero_shot", c.head(ZS, key), c.src_summary),
|
| 518 |
+
("zs_len", lens[ds].head(ZS_LEN, key), lens[ds].src_summary)]
|
| 519 |
+
vb = budget_series(budget, ds, lambda cc, a, k=key: cc.head(a, k), c.head(ZS_CAL, key), c.src_summary)
|
| 520 |
+
vs = scsemi_series(scs, ds, lambda cc, a, k=key: cc.head(a, k))
|
| 521 |
+
tax = curve(ax, z0, [c.head(a, key) for a in LORA_ARMS], refs, rows,
|
| 522 |
+
f"{key}", ds, [c.src_summary] * 5, vb=vb, vs=vs)
|
| 523 |
+
if ri == 0:
|
| 524 |
+
title_ax[ci] = tax
|
| 525 |
+
# selected early-stopping step per fold
|
| 526 |
+
ax = axs[ri, 2]
|
| 527 |
+
s = st[st.dataset == ds]
|
| 528 |
+
for xi, arm in zip(X_POS[1:], RUN_ARMS):
|
| 529 |
+
f = s[s.arm == arm].sort_values("fold")
|
| 530 |
+
v = f.selected_step.astype(float).values / 1000
|
| 531 |
+
jit = np.linspace(-0.22, 0.22, len(v))
|
| 532 |
+
ax.scatter(xi + jit, v, s=36, color=style.ARM["lora"], edgecolor=style.INK, lw=0.5, zorder=4)
|
| 533 |
+
med = float(np.median(v))
|
| 534 |
+
ax.plot([xi - 0.36, xi + 0.36], [med, med], color=style.INK, lw=2.0, zorder=5)
|
| 535 |
+
steprows.append(dict(dataset=ds, arm=arm, pairs=X_LAB[X_POS.index(xi)], median_step=med * 1000,
|
| 536 |
+
min_step=v.min() * 1000, max_step=v.max() * 1000,
|
| 537 |
+
n_cap_limited=int(f.cap_limited.sum()),
|
| 538 |
+
max_last_window_drop_frac=(float(f[f.cap_limited].val_loss_last_window_drop_frac.max())
|
| 539 |
+
if f.cap_limited.any() else np.nan),
|
| 540 |
+
n_train=rng_txt(f.n_train), n_inner_val=rng_txt(f.n_inner_val),
|
| 541 |
+
source=";".join(f.source)))
|
| 542 |
+
cap = float(s.max_steps.max()) / 1000
|
| 543 |
+
ax.axhline(cap, color=style.GREY, lw=1.0, ls=(0, (2, 2)), zorder=1)
|
| 544 |
+
ax.text(X_POS[0] - 0.4, cap + 0.6, f"cap {cap:g}k", color=style.GREY, fontsize=12, va="bottom")
|
| 545 |
+
ax.text(X_POS[0], cap * 0.45, "no training", color=style.GREY, fontsize=12, ha="center",
|
| 546 |
+
va="center", rotation=90)
|
| 547 |
+
ax.set_ylim(0, cap * 1.18)
|
| 548 |
+
ax.set_xlim(-0.5, X_POS[-1] + 0.5)
|
| 549 |
+
ax.set_xticks(X_POS)
|
| 550 |
+
ax.set_xticklabels(xticks(ds))
|
| 551 |
+
n_all = rng_txt(s[s.arm == "real_lora"].n_train)
|
| 552 |
+
n_iv = rng_txt(s.n_inner_val)
|
| 553 |
+
n_scored = int(c.summary["n_donors"])
|
| 554 |
+
assert n_scored == sum(fold_sizes[ds]["test"]), (ds, n_scored, fold_sizes[ds]["test"])
|
| 555 |
+
n_alpha = rng_txt(fold_sizes[ds]["alpha"])
|
| 556 |
+
# zs__cal alpha uses the same donors LoRA "all" trains and early-stops on (train + inner-val)
|
| 557 |
+
lora_all_seen = sorted(int(a) + int(b) for a, b in zip(s[s.arm == "real_lora"].sort_values("fold").n_train,
|
| 558 |
+
s[s.arm == "real_lora"].sort_values("fold").n_inner_val))
|
| 559 |
+
assert lora_all_seen == sorted(fold_sizes[ds]["alpha"]), (ds, lora_all_seen, fold_sizes[ds]["alpha"])
|
| 560 |
+
ymid = (pos0[ri].y0 + pos0[ri].y1) / 2
|
| 561 |
+
fig.text(0.005, ymid + 0.075, DS_LABEL[ds], fontsize=15, fontweight="bold", va="bottom", ha="left")
|
| 562 |
+
fig.text(0.005, ymid + 0.065,
|
| 563 |
+
f"{n_scored} donors\ninner-val = {n_iv}\ntest fold\nnever trained on",
|
| 564 |
+
fontsize=12.5, va="top", ha="left", linespacing=1.35)
|
| 565 |
+
rows.append(dict(panel="meta", dataset=ds, series="n_scored_donors", pairs="", value=n_scored,
|
| 566 |
+
source=c.src_summary))
|
| 567 |
+
rows.append(dict(panel="meta", dataset=ds, series="n_pairs_all", pairs="all", value=n_all,
|
| 568 |
+
source="RUN.json train_rows: " + ";".join(s[s.arm == "real_lora"].source)))
|
| 569 |
+
rows.append(dict(panel="meta", dataset=ds, series="n_inner_val", pairs="", value=n_iv,
|
| 570 |
+
source="RUN.json inner_val_rows (all LoRA arms, 5 folds)"))
|
| 571 |
+
rows.append(dict(panel="meta", dataset=ds, series="n_test_donors_per_fold", pairs="",
|
| 572 |
+
value="/".join(map(str, fold_sizes[ds]["test"])),
|
| 573 |
+
source=fold_sizes[ds]["source"] + " fold_sizes test"))
|
| 574 |
+
rows.append(dict(panel="meta", dataset=ds, series="n_alpha_fit_pairs", pairs="0", value=n_alpha,
|
| 575 |
+
source=fold_sizes[ds]["source"] + " fold_sizes train+inner_val; prepare_dataset.py "
|
| 576 |
+
"fit = fold != f"))
|
| 577 |
+
for ci, h in enumerate(heads):
|
| 578 |
+
title_ax[ci].set_title(h, fontsize=14, pad=8)
|
| 579 |
+
x0, x1 = axs[1, 0].get_position().x0, axs[1, 2].get_position().x1
|
| 580 |
+
fig.text((x0 + x1) / 2, 0.005, xlabel(st), ha="center", va="bottom", fontsize=14)
|
| 581 |
+
handles = [ # column-wise fill: [raw, cal, (equal-budget cal)] | [LoRA, (scSemi), median] | [pseudo, null]
|
| 582 |
+
h_raw(), h_len()] + ([h_budget()] if has_budget else []) + ([h_scsemi()] if has_sc else []) + [
|
| 583 |
+
Line2D([0], [0], marker="o", color=style.ARM["lora"], lw=2.0, markeredgecolor=style.INK, markersize=8,
|
| 584 |
+
label="LoRA fine-tune (dots in step panel = folds)"),
|
| 585 |
+
Line2D([0], [0], color=style.INK, lw=2.0, label="Median of 5 folds"),
|
| 586 |
+
Line2D([0], [0], ls=REF["pseudo"]["ls"], color=REF["pseudo"]["color"], lw=REF["pseudo"]["lw"],
|
| 587 |
+
label=REF["pseudo"]["label"]),
|
| 588 |
+
Line2D([0], [0], ls=REF["null"]["ls"], color=REF["null"]["color"], lw=REF["null"]["lw"],
|
| 589 |
+
label=REF["null"]["label"]),
|
| 590 |
+
]
|
| 591 |
+
fig.legend(handles=handles, loc="upper left", bbox_to_anchor=(0.005, 1.0), ncol=3, frameon=False,
|
| 592 |
+
fontsize=12, handlelength=2.4, columnspacing=1.6, labelspacing=0.4, borderaxespad=0.0)
|
| 593 |
+
style.save(fig, "sec08_pairs_realism", FIGDIR)
|
| 594 |
+
|
| 595 |
+
|
| 596 |
+
def h_raw():
|
| 597 |
+
return Line2D([0], [0], marker="o", color=COL_RAW, lw=0, markeredgecolor=RAW_EDGE, markersize=8, label=LEG_ZS)
|
| 598 |
+
|
| 599 |
+
|
| 600 |
+
def h_len():
|
| 601 |
+
return Line2D([0], [0], marker="o", color=COL_LEN, lw=0, markeredgecolor=style.INK, markersize=8, label=LEG_LEN)
|
| 602 |
+
|
| 603 |
+
|
| 604 |
+
def h_scsemi():
|
| 605 |
+
return Line2D([0], [0], marker="D", color=COL_SC, lw=1.8, markeredgecolor=style.INK, markersize=7, label=LEG_SC)
|
| 606 |
+
|
| 607 |
+
|
| 608 |
+
def h_budget():
|
| 609 |
+
return Line2D([0], [0], marker="s", color=COL_CAL, lw=1.8, markeredgecolor=style.INK, markersize=7,
|
| 610 |
+
label=LEG_CAL_N)
|
| 611 |
+
|
| 612 |
+
|
| 613 |
+
def fig_signal(calls, deg_call, lens, st, rows, budget, scs):
|
| 614 |
+
has_budget = any(budget[ds] for ds in DSETS)
|
| 615 |
+
has_sc = any(scs[ds] for ds in DSETS)
|
| 616 |
+
leg_rows = -(-(5 + has_budget + has_sc) // 2)
|
| 617 |
+
fig, axs = plt.subplots(1, 3, figsize=style.TALL,
|
| 618 |
+
gridspec_kw=dict(left=0.085, right=0.99, top=0.755 - 0.055 * (leg_rows - 3), bottom=0.115,
|
| 619 |
+
wspace=0.42)) # 3 legend rows (4 with both optional lines)
|
| 620 |
+
im, se = calls["immicro"], calls["ye2026_sepsis"]
|
| 621 |
+
iml, sel = lens["immicro"], lens["ye2026_sepsis"]
|
| 622 |
+
tax = [None] * 3
|
| 623 |
+
# a: ImMicro across-donor NK fraction r
|
| 624 |
+
tax[0] = curve(axs[0], [("zero_shot", im.frac_r(ZS, "NK cell"), im.src_per_donor),
|
| 625 |
+
("zs_len", iml.frac_r(ZS_LEN, "NK cell"), iml.src_per_donor)],
|
| 626 |
+
[im.frac_r(a, "NK cell") for a in LORA_ARMS],
|
| 627 |
+
[("pseudo", im.frac_r("zs__pseudo", "NK cell"), im.src_per_donor)], rows, "nk_fraction_r",
|
| 628 |
+
"immicro", [im.src_per_donor] * 5,
|
| 629 |
+
vb=budget_series(budget, "immicro", lambda cc, a: cc.frac_r(a, "NK cell"),
|
| 630 |
+
im.frac_r(ZS_CAL, "NK cell"), im.src_per_donor),
|
| 631 |
+
vs=scsemi_series(scs, "immicro", lambda cc, a: cc.frac_r(a, "NK cell")))
|
| 632 |
+
# other cell types, recorded for the footnote ("0+cal" = zero-shot + calibration)
|
| 633 |
+
for ct in ["T cell", "B cell", "Monocyte"]:
|
| 634 |
+
for a, lab in zip([ZS, ZS_CAL] + LORA_ARMS, ["0", "0+cal"] + X_LAB[1:]):
|
| 635 |
+
rows.append(dict(panel="other_fraction_r", dataset="immicro", series=ct, pairs=lab,
|
| 636 |
+
value=im.frac_r(a, ct), source=im.src_per_donor))
|
| 637 |
+
# b: sepsis disease logFC r (mean of T/B/Mono/NK, mean_cp10k)
|
| 638 |
+
tax[1] = curve(axs[1], [("zero_shot", se.contrast_r(ZS), se.src_contrast),
|
| 639 |
+
("zs_len", sel.contrast_r(ZS_LEN), sel.src_contrast)],
|
| 640 |
+
[se.contrast_r(a) for a in LORA_ARMS],
|
| 641 |
+
[("pseudo", se.contrast_r("zs__pseudo"), se.src_contrast),
|
| 642 |
+
("broadcast", se.contrast_r("real_lora__raw", "r_broadcast"), se.src_contrast)],
|
| 643 |
+
rows, "logfc_r", "ye2026_sepsis", [se.src_contrast] * 5,
|
| 644 |
+
vb=budget_series(budget, "ye2026_sepsis", lambda cc, a: cc.contrast_r(a),
|
| 645 |
+
se.contrast_r(ZS_CAL), se.src_contrast),
|
| 646 |
+
vs=scsemi_series(scs, "ye2026_sepsis", lambda cc, a: cc.contrast_r(a)))
|
| 647 |
+
# c: sepsis top-50 DEG (Welch, sum over T/B/Mono/NK/DC)
|
| 648 |
+
tax[2] = curve(axs[2], [("zero_shot", deg_call.deg(ZS), deg_call.src_contrast),
|
| 649 |
+
("zs_len", sel.deg(ZS_LEN), sel.src_contrast)],
|
| 650 |
+
[deg_call.deg(a) for a in LORA_ARMS],
|
| 651 |
+
[("pseudo", deg_call.deg("zs__pseudo"), deg_call.src_contrast),
|
| 652 |
+
("broadcast", deg_call.deg("real_lora__raw", "top50_overlap_broadcast"), deg_call.src_contrast)],
|
| 653 |
+
rows, "top50_deg", "ye2026_sepsis", [deg_call.src_contrast] * 5, ylim0=0,
|
| 654 |
+
vb=budget_series(budget, "ye2026_sepsis", lambda cc, a: cc.deg(a),
|
| 655 |
+
deg_call.deg(ZS_CAL), deg_call.src_contrast),
|
| 656 |
+
vs=scsemi_series(scs, "ye2026_sepsis", lambda cc, a: cc.deg(a)))
|
| 657 |
+
# top-50 DEG overlap per cell type (footnote: which types carry the gain), incl. broadcast
|
| 658 |
+
for ct in DEG_TYPES:
|
| 659 |
+
for a, lab in zip([ZS, ZS_CAL] + LORA_ARMS + ["zs__pseudo"], ["0", "0+cal"] + X_LAB[1:] + ["pseudo"]):
|
| 660 |
+
rows.append(dict(panel="top50_deg_by_type", dataset="ye2026_sepsis", series=ct, pairs=lab,
|
| 661 |
+
value=deg_call.deg_type(a, ct), source=deg_call.src_contrast))
|
| 662 |
+
rows.append(dict(panel="top50_deg_by_type", dataset="ye2026_sepsis", series=ct, pairs="broadcast",
|
| 663 |
+
value=deg_call.deg_type("real_lora__raw", ct, "top50_overlap_broadcast"),
|
| 664 |
+
source=deg_call.src_contrast))
|
| 665 |
+
cd = se.summary["contrast_definition"]
|
| 666 |
+
grp = f"Sepsis {cd['n_case_donors']} vs {cd['n_control_donors']}"
|
| 667 |
+
heads = [f"ImMicro, {int(im.summary['n_donors'])} donors\ndonor NK fraction r",
|
| 668 |
+
f"{grp}\ndisease logFC r", f"{grp}\ntop-50 DEG overlap"]
|
| 669 |
+
for ax, h in zip(tax, heads):
|
| 670 |
+
ax.set_title(h, fontsize=14, pad=8, linespacing=1.3)
|
| 671 |
+
x0, x1 = axs[0].get_position().x0, axs[2].get_position().x1
|
| 672 |
+
fig.text((x0 + x1) / 2, 0.005, xlabel(st), ha="center", va="bottom", fontsize=13)
|
| 673 |
+
rows.append(dict(panel="meta", dataset="ye2026_sepsis", series="n_case_vs_control", pairs="",
|
| 674 |
+
value=f"{se.summary['contrast_definition']['n_case_donors']} vs "
|
| 675 |
+
f"{se.summary['contrast_definition']['n_control_donors']}", source=se.src_summary))
|
| 676 |
+
handles = [ # column-wise fill: [raw, cal, pseudo, ...] | [LoRA, (equal-budget cal), (scSemi), broadcast]
|
| 677 |
+
h_raw(), h_len(),
|
| 678 |
+
Line2D([0], [0], ls=REF["pseudo"]["ls"], color=REF["pseudo"]["color"], lw=REF["pseudo"]["lw"],
|
| 679 |
+
label=REF["pseudo"]["label"]),
|
| 680 |
+
Line2D([0], [0], marker="o", color=style.ARM["lora"], lw=2.0, markeredgecolor=style.INK, markersize=8,
|
| 681 |
+
label="LoRA fine-tune"),
|
| 682 |
+
] + ([h_budget()] if has_budget else []) + ([h_scsemi()] if has_sc else []) + [
|
| 683 |
+
Line2D([0], [0], ls=REF["broadcast"]["ls"], color=REF["broadcast"]["color"], lw=REF["broadcast"]["lw"],
|
| 684 |
+
label=REF["broadcast"]["label"]),
|
| 685 |
+
]
|
| 686 |
+
fig.legend(handles=handles, loc="upper left", bbox_to_anchor=(0.005, 1.0), ncol=2, frameon=False,
|
| 687 |
+
fontsize=12, handlelength=2.4, columnspacing=1.2, labelspacing=0.4, borderaxespad=0.0)
|
| 688 |
+
style.save(fig, "sec08_pairs_signal", FIGDIR)
|
| 689 |
+
|
| 690 |
+
|
| 691 |
+
def slide_numbers(calls, deg_call, st, fold_sizes, fewshot, budget, budget_log, scs=None, sc_log=(), lens=None):
|
| 692 |
+
"""Numbers quoted in the slide keywords/footnote, each with its source file."""
|
| 693 |
+
im, se = calls["immicro"], calls["ye2026_sepsis"]
|
| 694 |
+
out = []
|
| 695 |
+
|
| 696 |
+
def add(key, value, src):
|
| 697 |
+
out.append(dict(key=key, value=value, source=src))
|
| 698 |
+
|
| 699 |
+
for ds, c in calls.items():
|
| 700 |
+
for key in ("coverage", "comp_l1"):
|
| 701 |
+
add(f"{ds}.{key}.zero_shot", round(c.head(ZS, key), 3), c.src_summary)
|
| 702 |
+
add(f"{ds}.{key}.zs_cal", round(c.head(ZS_CAL, key), 3), c.src_summary)
|
| 703 |
+
if lens:
|
| 704 |
+
add(f"{ds}.{key}.zs_len", round(lens[ds].head(ZS_LEN, key), 3), lens[ds].src_summary)
|
| 705 |
+
add(f"{ds}.{key}.lora_n5", round(c.head("lora_n5__raw", key), 3), c.src_summary)
|
| 706 |
+
add(f"{ds}.{key}.lora_all", round(c.head("real_lora__raw", key), 3), c.src_summary)
|
| 707 |
+
add(f"{ds}.{key}.zs_pseudo", round(c.head("zs__pseudo", key), 3), c.src_summary)
|
| 708 |
+
add(f"{ds}.comp_l1.null", round(c.head("real_lora__raw", "comp_l1_obs_loo_null"), 3), c.src_summary)
|
| 709 |
+
# donor-level composition L1, each LoRA size vs zero-shot (paired Wilcoxon, uncorrected)
|
| 710 |
+
piv = c.per_donor.pivot(index="donor", columns="arm", values="comp_l1")
|
| 711 |
+
for a, lab in zip(LORA_ARMS, X_LAB[1:]):
|
| 712 |
+
x = (piv[a] - piv[ZS]).dropna()
|
| 713 |
+
add(f"{ds}.comp_l1.lora_{lab}_minus_zero_shot.mean", round(float(x.mean()), 3), c.src_per_donor)
|
| 714 |
+
add(f"{ds}.comp_l1.lora_{lab}_minus_zero_shot.frac_donors_lower", round(float((x < 0).mean()), 2),
|
| 715 |
+
c.src_per_donor)
|
| 716 |
+
add(f"{ds}.comp_l1.lora_{lab}_vs_zero_shot.wilcoxon_p", float(f"{wilcoxon(x).pvalue:.2g}"),
|
| 717 |
+
c.src_per_donor)
|
| 718 |
+
# each LoRA size vs zero-shot + calibration (donor L1 and donor coverage; paired Wilcoxon, uncorrected)
|
| 719 |
+
for met in ("comp_l1", "coverage"):
|
| 720 |
+
pv = c.per_donor.pivot(index="donor", columns="arm", values=met)
|
| 721 |
+
for a, lab in zip(LORA_ARMS, X_LAB[1:]):
|
| 722 |
+
x = (pv[a] - pv[ZS_CAL]).dropna()
|
| 723 |
+
add(f"{ds}.{met}.lora_{lab}_minus_zs_cal.mean", round(float(x.mean()), 3), c.src_per_donor)
|
| 724 |
+
add(f"{ds}.{met}.lora_{lab}_minus_zs_cal.frac_donors_lower", round(float((x < 0).mean()), 2),
|
| 725 |
+
c.src_per_donor)
|
| 726 |
+
add(f"{ds}.{met}.lora_{lab}_vs_zs_cal.wilcoxon_p", float(f"{wilcoxon(x).pvalue:.2g}"),
|
| 727 |
+
c.src_per_donor)
|
| 728 |
+
# the raw -> calibrated zero-shot gap
|
| 729 |
+
x = (pv[ZS_CAL] - pv[ZS]).dropna()
|
| 730 |
+
add(f"{ds}.{met}.zs_cal_minus_zero_shot.mean", round(float(x.mean()), 3), c.src_per_donor)
|
| 731 |
+
add(f"{ds}.{met}.zs_cal_vs_zero_shot.wilcoxon_p", float(f"{wilcoxon(x).pvalue:.2g}"), c.src_per_donor)
|
| 732 |
+
add(f"{ds}.cal_alpha_fit_pairs", rng_txt(fold_sizes[ds]["alpha"]),
|
| 733 |
+
fold_sizes[ds]["source"] + " fold_sizes train+inner_val; tools/prepare_dataset.py fit = fold != f")
|
| 734 |
+
# few-pair call (its own donors): alpha from the same 5 pairs vs LoRA on them (fixed 3k steps, no inner-val)
|
| 735 |
+
add(f"{ds}.fewshot_n5.coverage.zs_cal_same5", round(fewshot[ds]["zs_cal"], 3), fewshot[ds]["source"])
|
| 736 |
+
add(f"{ds}.fewshot_n5.coverage.lora5_fixed3k", round(fewshot[ds]["lora5"], 3), fewshot[ds]["source"])
|
| 737 |
+
add(f"{ds}.n_scored_donors", int(c.summary["n_donors"]), c.src_summary)
|
| 738 |
+
s = st[st.dataset == ds]
|
| 739 |
+
add(f"{ds}.selected_step.lora_n5.range", rng_txt(s[s.arm == "lora_n5"].selected_step), "RUN.json: "
|
| 740 |
+
+ ";".join(s[s.arm == "lora_n5"].source))
|
| 741 |
+
add(f"{ds}.n_train.all", rng_txt(s[s.arm == "real_lora"].n_train), "RUN.json: "
|
| 742 |
+
+ ";".join(s[s.arm == "real_lora"].source))
|
| 743 |
+
add(f"{ds}.n_inner_val", rng_txt(s.n_inner_val), "RUN.json inner_val_rows (all LoRA arms, 5 folds)")
|
| 744 |
+
for arm in RUN_ARMS:
|
| 745 |
+
f = s[s.arm == arm]
|
| 746 |
+
add(f"{ds}.folds_cap_limited.{arm}", f"{int(f.cap_limited.sum())}/{len(f)}",
|
| 747 |
+
"RUN.json steps_run == max_steps and steps_run - selected_step < patience*eval_every: "
|
| 748 |
+
+ ";".join(f.source))
|
| 749 |
+
capped = s[s.cap_limited]
|
| 750 |
+
if len(capped):
|
| 751 |
+
add(f"{ds}.cap_limited.max_val_loss_drop_frac_last_2k_steps",
|
| 752 |
+
round(float(capped.val_loss_last_window_drop_frac.max()), 4),
|
| 753 |
+
"history.json inner_val_loss (drop over last patience window / drop from step 0): "
|
| 754 |
+
+ ";".join(capped.history))
|
| 755 |
+
for a, lab in zip([ZS, ZS_CAL] + LORA_ARMS + ["zs__pseudo"], KEY_LAB[:1] + ["zs_cal"] + KEY_LAB[1:] + ["pseudo"]):
|
| 756 |
+
add(f"immicro.nk_fraction_r.{lab}", round(im.frac_r(a, "NK cell"), 2), im.src_per_donor)
|
| 757 |
+
add(f"sepsis.logfc_r.{lab}", round(se.contrast_r(a), 2), se.src_contrast)
|
| 758 |
+
add(f"sepsis.top50_deg.{lab}", int(deg_call.deg(a)), deg_call.src_contrast)
|
| 759 |
+
add("sepsis.logfc_r.broadcast", round(se.contrast_r("real_lora__raw", "r_broadcast"), 2), se.src_contrast)
|
| 760 |
+
add("sepsis.top50_deg.broadcast", int(deg_call.deg("real_lora__raw", "top50_overlap_broadcast")),
|
| 761 |
+
deg_call.src_contrast)
|
| 762 |
+
|
| 763 |
+
def first_sustained(v, thr, strict=True):
|
| 764 |
+
"""First LoRA n from which every later n is above (or >=) thr."""
|
| 765 |
+
for i in range(len(v)):
|
| 766 |
+
if all((x > thr) if strict else (x >= thr) for x in v[i:]):
|
| 767 |
+
return X_LAB[1 + i]
|
| 768 |
+
return "never"
|
| 769 |
+
bc_r = se.contrast_r("real_lora__raw", "r_broadcast")
|
| 770 |
+
bc_d = deg_call.deg("real_lora__raw", "top50_overlap_broadcast")
|
| 771 |
+
vr = [se.contrast_r(a) for a in LORA_ARMS]
|
| 772 |
+
vd = [deg_call.deg(a) for a in LORA_ARMS]
|
| 773 |
+
add("sepsis.logfc_r.first_n_above_broadcast", first_sustained(vr, bc_r), se.src_contrast)
|
| 774 |
+
add("sepsis.logfc_r.first_n_above_zero_shot", first_sustained(vr, se.contrast_r(ZS)), se.src_contrast)
|
| 775 |
+
add("sepsis.top50_deg.first_n_at_or_above_broadcast", first_sustained(vd, bc_d, strict=False),
|
| 776 |
+
deg_call.src_contrast)
|
| 777 |
+
add("sepsis.top50_deg.first_n_above_zero_shot", first_sustained(vd, deg_call.deg(ZS)), deg_call.src_contrast)
|
| 778 |
+
add("sepsis.logfc_r.first_n_above_zs_cal", first_sustained(vr, se.contrast_r(ZS_CAL)), se.src_contrast)
|
| 779 |
+
add("sepsis.top50_deg.first_n_above_zs_cal", first_sustained(vd, deg_call.deg(ZS_CAL)), deg_call.src_contrast)
|
| 780 |
+
vn = [im.frac_r(a, "NK cell") for a in LORA_ARMS]
|
| 781 |
+
add("immicro.nk_fraction_r.first_n_above_zs_cal", first_sustained(vn, im.frac_r(ZS_CAL, "NK cell")),
|
| 782 |
+
im.src_per_donor)
|
| 783 |
+
for ds, c in calls.items():
|
| 784 |
+
for key in ("coverage", "comp_l1"):
|
| 785 |
+
v = [c.head(a, key) for a in LORA_ARMS]
|
| 786 |
+
thr = c.head(ZS_CAL, key)
|
| 787 |
+
first = first_sustained([-x for x in v], -thr) if key == "comp_l1" else first_sustained(v, thr)
|
| 788 |
+
add(f"{ds}.{key}.first_n_better_than_zs_cal", first, c.src_summary)
|
| 789 |
+
# across-donor fraction r per cell type: first n from which LoRA stays at/above zero-shot (footnote)
|
| 790 |
+
for ct, key in [("T cell", "T"), ("B cell", "B"), ("Monocyte", "Mono"), ("NK cell", "NK")]:
|
| 791 |
+
v = [im.frac_r(a, ct) for a in LORA_ARMS]
|
| 792 |
+
add(f"immicro.fraction_r.{key}.first_n_at_or_above_zero_shot",
|
| 793 |
+
first_sustained(v, im.frac_r(ZS, ct), strict=False), im.src_per_donor)
|
| 794 |
+
add(f"immicro.fraction_r.{key}.zero_shot", round(im.frac_r(ZS, ct), 2), im.src_per_donor)
|
| 795 |
+
add(f"immicro.fraction_r.{key}.zs_cal", round(im.frac_r(ZS_CAL, ct), 2), im.src_per_donor)
|
| 796 |
+
add(f"immicro.fraction_r.{key}.first_n_at_or_above_zs_cal",
|
| 797 |
+
first_sustained(v, im.frac_r(ZS_CAL, ct), strict=False), im.src_per_donor)
|
| 798 |
+
add(f"immicro.fraction_r.{key}.lora_5_10_20_40_all", "/".join(f"{x:.2f}" for x in v), im.src_per_donor)
|
| 799 |
+
# top-50 DEG overlap by cell type (which types carry the gain)
|
| 800 |
+
for ct, key in [("T cell", "T"), ("B cell", "B"), ("Monocyte", "Mono"), ("NK cell", "NK"), ("DC", "DC")]:
|
| 801 |
+
v = [deg_call.deg_type(a, ct) for a in [ZS] + LORA_ARMS]
|
| 802 |
+
add(f"sepsis.top50_deg.{key}.zero_shot_5_10_20_40_all", "/".join(f"{x:g}" for x in v),
|
| 803 |
+
deg_call.src_contrast)
|
| 804 |
+
add(f"sepsis.top50_deg.{key}.zs_cal", int(deg_call.deg_type(ZS_CAL, ct)), deg_call.src_contrast)
|
| 805 |
+
add(f"sepsis.top50_deg.{key}.broadcast", int(deg_call.deg_type("real_lora__raw", ct,
|
| 806 |
+
"top50_overlap_broadcast")),
|
| 807 |
+
deg_call.src_contrast)
|
| 808 |
+
add("sepsis.n_case", int(se.summary["contrast_definition"]["n_case_donors"]), se.src_summary)
|
| 809 |
+
add("sepsis.n_control", int(se.summary["contrast_definition"]["n_control_donors"]), se.src_summary)
|
| 810 |
+
add("final_checkpoint", FINAL_CKPT, "RUN.json source_checkpoint (all 50 LoRA runs)")
|
| 811 |
+
# equal-budget calibration scan (zero-shot + calibration with alpha from the n + inner-val pairs of lora_n*)
|
| 812 |
+
add("cal_budget.pattern", f"scores/<dataset>/**/summary.json arm names: 'cal' and regex {CAL_N_RE.pattern}, "
|
| 813 |
+
f"none of {list(FT_TAGS)}", str(PLAN / "scores"))
|
| 814 |
+
add("cal_budget.found", ";".join(f"{r['dataset']}:{r['call']}:{r['arm']}" for r in budget_log) or "none",
|
| 815 |
+
str(PLAN / "scores"))
|
| 816 |
+
for ds in DSETS:
|
| 817 |
+
add(f"{ds}.cal_budget.n_drawn", ",".join(str(n) for n in sorted(budget[ds])) or "none", str(PLAN / "scores"))
|
| 818 |
+
# scSemiProfiler line (equal-budget n + 5-fold CV "all")
|
| 819 |
+
add("scsemi.found", ";".join(f"{r['dataset']}:{r['call']}:{r['arm']}:{r['note']}" for r in sc_log) or "none",
|
| 820 |
+
f"{SR.plan_root()}/scores/<dataset>/{{{SR.BUDGET_EXP},{SR.CV_EXP}}}/pooled*")
|
| 821 |
+
for ds in DSETS:
|
| 822 |
+
sc = (scs or {}).get(ds, {})
|
| 823 |
+
add(f"{ds}.scsemi.pairs_drawn", ",".join(lab for lab in X_LAB[1:] if lab in sc) or "none",
|
| 824 |
+
f"{SR.plan_root()}/scores/{ds}")
|
| 825 |
+
for lab in X_LAB[1:]:
|
| 826 |
+
if lab in sc:
|
| 827 |
+
for key in ("coverage", "comp_l1"):
|
| 828 |
+
v, c = budget_value(sc[lab], lambda cc, a, k=key: cc.head(a, k))
|
| 829 |
+
if v is not None:
|
| 830 |
+
add(f"{ds}.{key}.scsemi_{lab}", round(v, 3), str(c.path / "summary.json"))
|
| 831 |
+
return pd.DataFrame(out)
|
| 832 |
+
|
| 833 |
+
|
| 834 |
+
def check_against_fig3(rows):
|
| 835 |
+
"""Cross-check the LoRA curve, the zero-shot + calibration point and the reference lines with the plan's own
|
| 836 |
+
fig3 source data (same numbers, independent code path; the plan's fig3 n=0 point is zs__cal). The zero-shot
|
| 837 |
+
real-bulk point is not in fig3; it is checked in load() instead (headline vs per_donor.csv / contrast.csv)."""
|
| 838 |
+
ref = pd.read_csv(PLAN / "figures" / "source_data" / "fig3_learning_curve.csv")
|
| 839 |
+
pmap = {("comp_l1", "immicro"): "3a", ("comp_l1", "ye2026_sepsis"): "3b",
|
| 840 |
+
("coverage", "immicro"): "3c", ("coverage", "ye2026_sepsis"): "3d",
|
| 841 |
+
("nk_fraction_r", "immicro"): "3e", ("logfc_r", "ye2026_sepsis"): "3f",
|
| 842 |
+
("top50_deg", "ye2026_sepsis"): "3h"}
|
| 843 |
+
n = 0
|
| 844 |
+
for r in rows:
|
| 845 |
+
p = pmap.get((r["panel"], r["dataset"]))
|
| 846 |
+
if p is None or r["series"] in ("zero_shot", "zs_cal_budget", "scsemi"):
|
| 847 |
+
continue
|
| 848 |
+
if r["series"] == "lora":
|
| 849 |
+
m = ref[(ref.panel == p) & (ref.series == r["series"]) & (ref.draw == f"n={r['pairs']}")]
|
| 850 |
+
elif r["series"] == "zs_cal":
|
| 851 |
+
m = ref[(ref.panel == p) & (ref.series == "zs_cal") & (ref.draw == "n=0")]
|
| 852 |
+
else:
|
| 853 |
+
m = ref[(ref.panel == p) & (ref.series == r["series"])]
|
| 854 |
+
assert len(m) == 1, (r, len(m))
|
| 855 |
+
assert abs(float(m.value.iloc[0]) - float(r["value"])) < 1e-5, (r, float(m.value.iloc[0]))
|
| 856 |
+
n += 1
|
| 857 |
+
return n
|
| 858 |
+
|
| 859 |
+
|
| 860 |
+
def main():
|
| 861 |
+
calls, deg_call, lens = load()
|
| 862 |
+
st = load_steps()
|
| 863 |
+
fold_sizes = load_fold_sizes()
|
| 864 |
+
fewshot = load_fewshot()
|
| 865 |
+
budget, budget_log = find_cal_budget(calls, deg_call)
|
| 866 |
+
scs, sc_log = find_scsemi(calls)
|
| 867 |
+
rows, steprows = [], []
|
| 868 |
+
fig_realism(calls, lens, st, fold_sizes, rows, steprows, budget, scs)
|
| 869 |
+
rows_sig = []
|
| 870 |
+
fig_signal(calls, deg_call, lens, st, rows_sig, budget, scs)
|
| 871 |
+
n_checked = check_against_fig3(rows + rows_sig)
|
| 872 |
+
pd.DataFrame(rows).to_csv(DATADIR / "sec08_pairs_realism.csv", index=False, float_format="%.6g")
|
| 873 |
+
pd.DataFrame(steprows).to_csv(DATADIR / "sec08_selected_steps.csv", index=False, float_format="%.6g")
|
| 874 |
+
st.to_csv(DATADIR / "sec08_selected_steps_per_fold.csv", index=False)
|
| 875 |
+
pd.DataFrame(rows_sig).to_csv(DATADIR / "sec08_pairs_signal.csv", index=False, float_format="%.6g")
|
| 876 |
+
nums = slide_numbers(calls, deg_call, st, fold_sizes, fewshot, budget, budget_log, scs, sc_log, lens)
|
| 877 |
+
nums.to_csv(DATADIR / "sec08_slide_numbers.csv", index=False)
|
| 878 |
+
print(nums.to_string(index=False, max_colwidth=70))
|
| 879 |
+
print(f"cross-checked {n_checked} plotted values against fig3_learning_curve.csv")
|
| 880 |
+
brk = [(r["panel"], r["dataset"]) for r in rows + rows_sig if r.get("series") == "zero_shot" and r["y_axis_break"]]
|
| 881 |
+
print(f"y-axis breaks: {brk}")
|
| 882 |
+
print(f"equal-budget calibration scan: arm names with 'cal' and regex {CAL_N_RE.pattern!r}, none of {FT_TAGS}, "
|
| 883 |
+
f"in {PLAN / 'scores'}/<dataset>/**/summary.json")
|
| 884 |
+
for r in budget_log:
|
| 885 |
+
print(f" found {r['dataset']} {r['call']} {r['arm']} (n {r['n']}): {r['note']}")
|
| 886 |
+
if not any(budget[ds] for ds in DSETS):
|
| 887 |
+
print(" NOTE: no equal-budget calibration arms found; only the two x = 0 zero-shot points are drawn.")
|
| 888 |
+
print(f"scSemiProfiler scan: {SR.plan_root()}/scores/<dataset>/{SR.BUDGET_EXP}/pooled* (scsemi_n<n>__raw) and "
|
| 889 |
+
f"{SR.CV_EXP}/pooled* ({SR.CV_ARM}, drawn at 'all')")
|
| 890 |
+
for r in sc_log:
|
| 891 |
+
print(f" found {r['dataset']} {r['call']} {r['arm']} (pairs {r['pairs']}): {r['note']}")
|
| 892 |
+
if not any(scs[ds] for ds in DSETS):
|
| 893 |
+
print(" NOTE: no scSemiProfiler equal-budget or 5-fold calls found; no scSemiProfiler line is drawn.")
|
| 894 |
+
|
| 895 |
+
|
| 896 |
+
if __name__ == "__main__":
|
| 897 |
+
main()
|
paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec09_cat_curves.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Section 9 of the 2026-09-30 paper-summary deck: CAT curves (correspondence at the top) of the disease genes
|
| 3 |
+
(added 2026-10-02, user request: a threshold-free DEG comparison with the random expectation drawn).
|
| 4 |
+
|
| 5 |
+
CPU only. Reads plans/paired_finetune_intradataset_20260927/scores_contrast/{fewshot,pooled}_cat.csv
|
| 6 |
+
(tools/contrast_extra.py): per cell type, all tested genes ranked by |limma moderated t| on the observed side and on the
|
| 7 |
+
predicted side; CAT(k) = fraction of the observed top-k genes that are also in the predicted top-k with the same logFC
|
| 8 |
+
sign (Irizarry et al. 2005); chance = k / (2 G) for G genes tested on both sides. Plotted: mean over T / B / Mono / NK;
|
| 9 |
+
5 donors = mean over the 5 draws of that per-draw mean; 5-fold = the pooled call. The broadcast is the raw real bulk of
|
| 10 |
+
the LoRA arm's condition (same ranking statistic on the input bulk).
|
| 11 |
+
|
| 12 |
+
Outputs (deck folder; DECK_FIGDIR / DECK_OUTDATA override the folders):
|
| 13 |
+
figures/sec09_cat_curves.{png,pdf}
|
| 14 |
+
data/sec09_cat_curves.csv every plotted value with its source
|
| 15 |
+
data/sec09_cat_curves_slide_text.json title, keywords, footnotes (synced through text_source)
|
| 16 |
+
"""
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import os
|
| 20 |
+
|
| 21 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = ""
|
| 22 |
+
|
| 23 |
+
import json
|
| 24 |
+
import sys
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
|
| 27 |
+
import numpy as np
|
| 28 |
+
import pandas as pd
|
| 29 |
+
|
| 30 |
+
DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/"
|
| 31 |
+
"2026-09-30--paper-summary--r00")
|
| 32 |
+
sys.path.insert(0, str(DECK / "tools"))
|
| 33 |
+
import sec09_paired_validation as S9 # noqa: E402 (names, colours, labels; sets the deck rcParams)
|
| 34 |
+
import style # noqa: E402
|
| 35 |
+
import matplotlib.pyplot as plt # noqa: E402
|
| 36 |
+
from matplotlib.lines import Line2D # noqa: E402
|
| 37 |
+
|
| 38 |
+
CX = S9.T / "scores_contrast"
|
| 39 |
+
FIGDIR = Path(os.environ.get("DECK_FIGDIR", str(DECK / "figures")))
|
| 40 |
+
OUTDATA = Path(os.environ.get("DECK_OUTDATA", str(DECK / "data")))
|
| 41 |
+
DIS = S9.DISEASE
|
| 42 |
+
NAME = S9.NAME
|
| 43 |
+
TYPES = ["T cell", "B cell", "Monocyte", "NK cell"]
|
| 44 |
+
FS = style.FS
|
| 45 |
+
FEW = [("zs_raw", "zs_raw"), ("zs_cal", "zs_cal"), ("scsemi5", "scsemi5"), ("lora", "lora5")]
|
| 46 |
+
POOL = [("zs_raw", "zs__raw"), ("zs_cal", "zs__cal"), ("sconly_cal", "pseudo_full__cal"), ("lora", "real_lora__raw")]
|
| 47 |
+
LORA_ARM = {"fewshot": "lora5", "pooled": "real_lora__raw"}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def curves(cat: pd.DataFrame, design: str):
|
| 51 |
+
"""{(dataset, key): Series over k} for generated arms, 'broadcast' and 'chance' (chance of the LoRA arm's lists)."""
|
| 52 |
+
c = cat[cat.celltype.isin(TYPES)].copy()
|
| 53 |
+
c["kind"] = np.where(c.predictor.str.startswith("generated:"), "gen", "bc")
|
| 54 |
+
out = {}
|
| 55 |
+
arms = FEW if design == "fewshot" else POOL
|
| 56 |
+
for ds in DIS:
|
| 57 |
+
d = c[c.dataset == ds]
|
| 58 |
+
for key, arm in arms:
|
| 59 |
+
g = d[(d.arm == arm) & (d.kind == "gen")]
|
| 60 |
+
if g.empty:
|
| 61 |
+
continue
|
| 62 |
+
out[(ds, key)] = g.groupby(["unit", "k"]).cat_same_sign.mean().groupby("k").mean()
|
| 63 |
+
lo = d[d.arm == LORA_ARM[design]]
|
| 64 |
+
out[(ds, "broadcast")] = lo[lo.kind == "bc"].groupby(["unit", "k"]).cat_same_sign.mean().groupby("k").mean()
|
| 65 |
+
out[(ds, "chance")] = lo[lo.kind == "gen"].groupby(["unit", "k"]).chance_same_sign.mean().groupby("k").mean()
|
| 66 |
+
return out
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def main() -> int:
|
| 70 |
+
few = curves(pd.read_csv(CX / "fewshot_cat.csv"), "fewshot")
|
| 71 |
+
poo = curves(pd.read_csv(CX / "pooled_cat.csv"), "pooled")
|
| 72 |
+
fig, axs = plt.subplots(2, len(DIS), figsize=(12.3, 5.2), sharex=True,
|
| 73 |
+
gridspec_kw=dict(left=0.105, right=0.995, top=0.90, bottom=0.215, hspace=0.32, wspace=0.28))
|
| 74 |
+
rows = []
|
| 75 |
+
for ri, (lab, cv, keys, src) in enumerate([("5 donors", few, FEW, "fewshot_cat.csv"),
|
| 76 |
+
("5-fold CV", poo, POOL, "pooled_cat.csv")]):
|
| 77 |
+
for ci, ds in enumerate(DIS):
|
| 78 |
+
ax = axs[ri, ci]
|
| 79 |
+
hi = 0.0
|
| 80 |
+
for key, _ in keys:
|
| 81 |
+
if (ds, key) not in cv:
|
| 82 |
+
continue
|
| 83 |
+
s = cv[(ds, key)]
|
| 84 |
+
ax.plot(s.index, s.values, color=S9.COL[key], lw=2.2 if key == "lora" else 1.6, marker="o", ms=4,
|
| 85 |
+
mec=S9.EDGE, mew=0.5, zorder=4 if key == "lora" else 3)
|
| 86 |
+
hi = max(hi, s.max())
|
| 87 |
+
rows += [dict(design=lab, dataset=ds, series=key, k=int(k), cat=float(v), source=str(CX / src))
|
| 88 |
+
for k, v in s.items()]
|
| 89 |
+
b, ch = cv[(ds, "broadcast")], cv[(ds, "chance")]
|
| 90 |
+
st = S9.REFSTYLE["broadcast"]
|
| 91 |
+
ax.plot(b.index, b.values, ls=st["ls"], color=st["color"], lw=st["lw"], zorder=2)
|
| 92 |
+
ax.plot(ch.index, ch.values, ls=(0, (3, 2)), color=style.INK, lw=1.0, zorder=2)
|
| 93 |
+
hi = max(hi, b.max())
|
| 94 |
+
rows += [dict(design=lab, dataset=ds, series=s_, k=int(k), cat=float(v), source=str(CX / src))
|
| 95 |
+
for s_, ser in (("broadcast", b), ("chance", ch)) for k, v in ser.items()]
|
| 96 |
+
ax.set_xscale("log")
|
| 97 |
+
ax.set_xticks([10, 50, 100, 500], ["10", "50", "100", "500"])
|
| 98 |
+
ax.set_ylim(0, max(0.12, hi * 1.15))
|
| 99 |
+
ax.yaxis.set_major_locator(plt.MaxNLocator(nbins=4))
|
| 100 |
+
ax.tick_params(labelsize=FS - 3)
|
| 101 |
+
if ri == 0:
|
| 102 |
+
ax.set_title(S9.ROWNAME[ds], fontsize=FS - 1, pad=6)
|
| 103 |
+
if ri == 1:
|
| 104 |
+
ax.set_xlabel("top-k genes (k)", fontsize=FS - 2)
|
| 105 |
+
axs[ri, 0].annotate(lab, xy=(0, 0.5), xycoords="axes fraction", xytext=(-58, 0), textcoords="offset points",
|
| 106 |
+
ha="right", va="center", fontsize=FS, fontweight="bold")
|
| 107 |
+
axs[ri, 0].set_ylabel("CAT, same sign", fontsize=FS - 3)
|
| 108 |
+
hk = [("zs_raw", S9.LAB["zs_raw"]), ("zs_cal", S9.LAB["zs_cal"]), ("scsemi5", "scSemiProfiler (5 donors)"),
|
| 109 |
+
("sconly_cal", "sc-only fine-tune (5-fold)"), ("lora", "LoRA")]
|
| 110 |
+
handles = [Line2D([0], [0], color=S9.COL[k], lw=2.0, marker="o", ms=5, mec=S9.EDGE, mew=0.5, label=l) for k, l in hk]
|
| 111 |
+
handles += [S9.refh("broadcast"), Line2D([0], [0], ls=(0, (3, 2)), color=style.INK, lw=1.0, label="Chance (k / 2G)")]
|
| 112 |
+
fig.legend(handles=handles, loc="lower center", ncol=4, bbox_to_anchor=(0.53, -0.01), fontsize=FS - 3,
|
| 113 |
+
frameon=False, columnspacing=1.4, handlelength=2.2)
|
| 114 |
+
style.save(fig, "sec09_cat_curves", FIGDIR)
|
| 115 |
+
d = pd.DataFrame(rows)
|
| 116 |
+
OUTDATA.mkdir(exist_ok=True)
|
| 117 |
+
d.to_csv(OUTDATA / "sec09_cat_curves.csv", index=False, float_format="%.6g")
|
| 118 |
+
|
| 119 |
+
# slide text, from the plotted values at k = 100
|
| 120 |
+
def at(cv, ds, key, k=100):
|
| 121 |
+
s = cv.get((ds, key))
|
| 122 |
+
return np.nan if s is None or k not in s.index else float(s.loc[k])
|
| 123 |
+
|
| 124 |
+
top_few = [ds for ds in DIS if at(few, ds, "lora") >= max(at(few, ds, k) for k, _ in FEW if k != "lora")]
|
| 125 |
+
top_poo = [ds for ds in DIS if at(poo, ds, "lora") >= max(at(poo, ds, k) for k, _ in POOL if k != "lora")]
|
| 126 |
+
bc_few = [ds for ds in DIS if at(few, ds, "broadcast") > at(few, ds, "lora")]
|
| 127 |
+
kw = [f"LoRA top model: {len(top_few)}/4 (5 donors), {len(top_poo)}/4 (5-fold)",
|
| 128 |
+
(f"Broadcast above LoRA: {S9.names(bc_few)}" if bc_few else "LoRA above broadcast in every cohort"),
|
| 129 |
+
f"Chance at k = 100: {min(at(few, ds, 'chance') for ds in DIS):.3f}–{max(at(few, ds, 'chance') for ds in DIS):.3f}"]
|
| 130 |
+
for k in kw:
|
| 131 |
+
if len(k) > 52:
|
| 132 |
+
raise ValueError(f"keyword too long: {k!r}")
|
| 133 |
+
vals = "; ".join(
|
| 134 |
+
f"{NAME[ds]} CAT100 5 donors LoRA {at(few, ds, 'lora'):.3f} / scSemi {at(few, ds, 'scsemi5'):.3f} / "
|
| 135 |
+
f"calibration {at(few, ds, 'zs_cal'):.3f} / raw {at(few, ds, 'zs_raw'):.3f} / broadcast {at(few, ds, 'broadcast'):.3f}"
|
| 136 |
+
f" / chance {at(few, ds, 'chance'):.3f}; 5-fold LoRA {at(poo, ds, 'lora'):.3f} / broadcast {at(poo, ds, 'broadcast'):.3f}"
|
| 137 |
+
for ds in DIS)
|
| 138 |
+
full = ("Correspondence at the top (Irizarry et al. 2005): per cell type, every gene tested on both sides is ranked by "
|
| 139 |
+
"|limma-voom moderated t| (case vs control, same donor x type pseudobulks as the DEG panels); CAT(k) = share of "
|
| 140 |
+
"the observed top-k genes that are also in the generated top-k with the same logFC sign. Mean over T / B / Mono "
|
| 141 |
+
"/ NK; 5 donors = mean over 5 draws (scSemiProfiler: its 25 draws); 5-fold = pooled call. Broadcast = the "
|
| 142 |
+
"input real bulk ranked the same way. Chance = k / (2G), G = genes tested on both sides ("
|
| 143 |
+
f"{min(at(few, ds, 'chance') for ds in DIS):.3f}–{max(at(few, ds, 'chance') for ds in DIS):.3f} at k = 100). "
|
| 144 |
+
"No significance threshold, so cohorts where few genes pass FDR (Giroux, Ji) still get a curve. "
|
| 145 |
+
"Rank-biased overlap (Webber et al. 2010, p = 0.98) gives the same order: scores_contrast/{fewshot,pooled}_rbo.csv. "
|
| 146 |
+
"Giroux: sex-linked genes excluded. " + vals + ".")
|
| 147 |
+
txt = {"title": "Disease genes at every list length (CAT)", "layout": "full",
|
| 148 |
+
"figures": [str(FIGDIR / "sec09_cat_curves.png")], "keywords": kw,
|
| 149 |
+
"footnote_short": "Same-sign overlap of observed and generated top-k genes per cell type; no FDR cut-off.",
|
| 150 |
+
"footnote": full,
|
| 151 |
+
"numbers": [{"value": vals, "source": str(CX / "fewshot_cat.csv") + "; " + str(CX / "pooled_cat.csv")}]}
|
| 152 |
+
(OUTDATA / "sec09_cat_curves_slide_text.json").write_text(json.dumps(
|
| 153 |
+
{"section": "09-cat", "scripts": [str(Path(__file__).resolve())],
|
| 154 |
+
"generated_from": "tools/sec09_cat_curves.py (rerun to refresh; do not edit by hand)", "slides": [txt]},
|
| 155 |
+
indent=1, ensure_ascii=False))
|
| 156 |
+
print("\n".join(kw))
|
| 157 |
+
return 0
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
if __name__ == "__main__":
|
| 161 |
+
sys.exit(main())
|
paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec09_extra_metrics.py
ADDED
|
@@ -0,0 +1,738 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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^2, scSemiProfiler's E_N, precision/coverage at k = 3 / 5 / 10).
|
| 4 |
+
|
| 5 |
+
CPU only: reads the per-unit outputs of plans/paired_finetune_intradataset_20260927/tools/extra_metrics.py
|
| 6 |
+
(scores_extra/<ds>/{fewshot_n5/draw<j>, pooled}/{metrics.csv, en.csv, manifest.json}) and draws slide figures.
|
| 7 |
+
No torch, no CUDA, no scoring. The headline definitions are the collector's (tools/collect_extra_metrics.py,
|
| 8 |
+
scores_extra/README.md) and every value is checked against scores_extra/{fewshot,pooled}_headline.csv:
|
| 9 |
+
classifier AUC (kNN, RF), 1-NN accuracy, MMD^2 real side R2 (held-out real cells), no depth matching;
|
| 10 |
+
control = real vs real, R2 vs R3
|
| 11 |
+
E_N all cells, squared L2 (their code); control = within-sample half
|
| 12 |
+
split; undefined (UB <= LB) -> left out of means, ranks last
|
| 13 |
+
precision / coverage at k = 3, 5, 10 the scorer's space (real side R1); control = R1 vs R2
|
| 14 |
+
|
| 15 |
+
Outputs (deck folder; DECK_FIGDIR / DECK_OUTDATA override the folders, used by the synthetic test):
|
| 16 |
+
figures/sec09_extra_fewpair.{png,pdf} main slide: 5 donors, kNN AUC / MMD^2 / E_N per cohort
|
| 17 |
+
figures/sec09_extra_fivefold.{png,pdf} section 9: the same for the 5-fold pooled design
|
| 18 |
+
figures/sec09_extra_ksens.{png,pdf} section 9: precision / coverage at k = 3, 5, 10 (5 donors)
|
| 19 |
+
data/sec09_extra_{fewpair,fivefold,ksens}.csv every plotted value with its source file
|
| 20 |
+
data/sec09_extra_scsemi_status.csv scSemiProfiler CV / equal-budget extra-metric units found or not
|
| 21 |
+
data/sec09_extra_quoted_numbers.csv quoted numbers (flat)
|
| 22 |
+
data/sec09_extra_slide_text.json titles, keywords, footnotes, quoted numbers (synced into
|
| 23 |
+
data/slides_spec.json by tools/sync_sec09_text.py)
|
| 24 |
+
|
| 25 |
+
scSemiProfiler with all training pairs (5-fold CV, arm scsemi__raw): drawn in the 5-fold figure as its own bar when an
|
| 26 |
+
extra-metric unit with that set exists (scores_extra/<ds>/pooled/ itself, or below scores_extra/<ds>/scsemi_cv_20261002/,
|
| 27 |
+
see tools/scsemi_results.py) for the same donors and reference cells; otherwise a note is printed and nothing is drawn.
|
| 28 |
+
Equal-budget units (scsemi_n<n>__raw) are only listed in the status CSV.
|
| 29 |
+
"""
|
| 30 |
+
from __future__ import annotations
|
| 31 |
+
|
| 32 |
+
import os
|
| 33 |
+
|
| 34 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = "" # plotting only
|
| 35 |
+
|
| 36 |
+
import json
|
| 37 |
+
import sys
|
| 38 |
+
from pathlib import Path
|
| 39 |
+
|
| 40 |
+
import numpy as np
|
| 41 |
+
import pandas as pd
|
| 42 |
+
|
| 43 |
+
DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/"
|
| 44 |
+
"2026-09-30--paper-summary--r00")
|
| 45 |
+
sys.path.insert(0, str(DECK / "tools"))
|
| 46 |
+
import sec09_paired_validation as S9 # noqa: E402 (shared section 9 drawing helpers; sets the deck rcParams)
|
| 47 |
+
import scsemi_results as SR # noqa: E402
|
| 48 |
+
import style # noqa: E402
|
| 49 |
+
import matplotlib.pyplot as plt # noqa: E402
|
| 50 |
+
from matplotlib.lines import Line2D # noqa: E402
|
| 51 |
+
from matplotlib.patches import Patch # noqa: E402
|
| 52 |
+
|
| 53 |
+
T = S9.T
|
| 54 |
+
X = T / "scores_extra"
|
| 55 |
+
FIGDIR = Path(os.environ.get("DECK_FIGDIR", str(DECK / "figures")))
|
| 56 |
+
OUTDATA = Path(os.environ.get("DECK_OUTDATA", str(DECK / "data")))
|
| 57 |
+
SCRIPT = DECK / "tools" / "sec09_extra_metrics.py"
|
| 58 |
+
ORDER, NAME, ROWNAME = S9.ORDER, S9.NAME, S9.ROWNAME
|
| 59 |
+
FS, SUB, EDGE = S9.FS, S9.SUB, S9.EDGE
|
| 60 |
+
|
| 61 |
+
# arm keys (deck colours / labels from sec09) -> set names in scores_extra
|
| 62 |
+
FEW_SETS = {"zs_raw": "zs_raw", "zs_cal": "zs_cal", "scsemi5": "scsemi5", "lora": "lora5", "pseudo": "zs_pseudo"}
|
| 63 |
+
POOL_SETS = {"zs_raw": "zs__raw", "zs_cal": "zs__cal", "sconly_cal": "pseudo_full__cal", "scsemi_all": SR.CV_ARM,
|
| 64 |
+
"lora": "real_lora__raw", "pseudo": "zs__pseudo"}
|
| 65 |
+
COL = {**S9.COL, "scsemi_all": style.ARM["scsemi"]}
|
| 66 |
+
LAB = {**S9.LAB, "scsemi_all": SR.LABEL_CV}
|
| 67 |
+
# headline metrics (collector's HEADLINE): column, short name, direction (0: closer to 0.5, -1 lower, +1 higher), space
|
| 68 |
+
TWO = [("c2st_knn_auc", "kNN AUC", 0), ("c2st_rf_auc", "RF AUC", 0), ("nn1_acc", "1-NN accuracy", 0),
|
| 69 |
+
("mmd2_bw1", "MMD² (σ = m)", -1), ("mmd2_sum", "MMD² (σ sum)", -1)]
|
| 70 |
+
EN = [("en_all_sq", "E_N (all cells)", -1)]
|
| 71 |
+
PC = [(f"{q}_k{k}", f"{q} k{k}", 1) for k in (3, 5, 10) for q in ("precision", "coverage")]
|
| 72 |
+
HEAD = TWO + EN + PC
|
| 73 |
+
DIRS = {c: s for c, _, s in HEAD}
|
| 74 |
+
SHORT = {c: n for c, n, _ in HEAD}
|
| 75 |
+
# drawn columns of the two realism figures
|
| 76 |
+
PANELS = [("c2st_knn_auc", "Classifier AUC (kNN) ↓"), ("mmd2_bw1", "MMD² ↓"), ("en_all_sq", "scSemiProfiler E_N ↓ (log)")]
|
| 77 |
+
CTRL = dict(ls=(0, (6, 2, 1.5, 2)), color="#7A7A7A", lw=1.8, label="Real vs real (same samples)")
|
| 78 |
+
KS = (3, 5, 10)
|
| 79 |
+
NUMS = {k: [] for k in "abc"}
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def num(slide, value, source):
|
| 83 |
+
NUMS[slide].append({"value": str(value), "source": str(source)})
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
# ------------------------------------------------------------------------------------------
|
| 87 |
+
# Loading
|
| 88 |
+
# ------------------------------------------------------------------------------------------
|
| 89 |
+
def unit_values(u: Path) -> dict:
|
| 90 |
+
"""set -> {metric: value} in the headline spaces of one extra-metric unit; 'control' = the real-vs-real rows."""
|
| 91 |
+
m = pd.read_csv(u / "metrics.csv")
|
| 92 |
+
e = pd.read_csv(u / "en.csv")
|
| 93 |
+
raw = m[m["mode"] == "raw"]
|
| 94 |
+
out = {}
|
| 95 |
+
for s in sorted(set(raw["set"])):
|
| 96 |
+
r2 = raw[(raw["set"] == s) & (raw.real_side == "R2")]
|
| 97 |
+
r1 = raw[(raw["set"] == s) & (raw.real_side == "R1")]
|
| 98 |
+
if len(r2) > 1 or len(r1) > 1:
|
| 99 |
+
raise ValueError(f"{u}: several raw rows for set {s}")
|
| 100 |
+
d = {c: (float(r2[c].iloc[0]) if len(r2) else np.nan) for c, _, _ in TWO}
|
| 101 |
+
d.update({c: (float(r1[c].iloc[0]) if len(r1) else np.nan) for c, _, _ in PC})
|
| 102 |
+
en = e[(e["set"] == s) & (e.cellset == "all") & (e.distance == "sq")]
|
| 103 |
+
if len(en) > 1:
|
| 104 |
+
raise ValueError(f"{u}: several E_N rows for set {s}")
|
| 105 |
+
ok = bool(len(en)) and float(en.ub.iloc[0]) > float(en.lb.iloc[0])
|
| 106 |
+
d["en_all_sq"] = float(en.en.iloc[0]) if ok else np.nan
|
| 107 |
+
d["en_all_sq_undefined"] = bool(len(en)) and not ok
|
| 108 |
+
out[s] = d
|
| 109 |
+
ctrl = {c: out["real_R3"][c] for c, _, _ in TWO}
|
| 110 |
+
ctrl.update({c: out["real_R2"][c] for c, _, _ in PC + EN})
|
| 111 |
+
ctrl["en_all_sq_undefined"] = False
|
| 112 |
+
out["control"] = ctrl
|
| 113 |
+
return out
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def manifest(u: Path) -> dict:
|
| 117 |
+
p = u / "manifest.json"
|
| 118 |
+
return json.loads(p.read_text()) if p.is_file() else {}
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def load_fewpair():
|
| 122 |
+
"""Long table: dataset, draw, arm (deck key or 'control'), metric, value, undefined, source."""
|
| 123 |
+
rows, info = [], {}
|
| 124 |
+
for ds in ORDER:
|
| 125 |
+
units = [d for d in sorted((X / ds / "fewshot_n5").glob("draw*")) if (d / "manifest.json").is_file()]
|
| 126 |
+
few_min = []
|
| 127 |
+
for u in units:
|
| 128 |
+
j = int(u.name.removeprefix("draw"))
|
| 129 |
+
mf_ = manifest(u)
|
| 130 |
+
sj = T / "scores" / ds / "fewshot_n5" / f"draw{j}" / "summary.json"
|
| 131 |
+
s = json.loads(sj.read_text())
|
| 132 |
+
if set(map(str, mf_["donors"])) != set(map(str, s["donors"])):
|
| 133 |
+
raise ValueError(f"{u}: scored donors differ from {sj}")
|
| 134 |
+
if mf_["reference_sha256"] != s["reference"]["reference_sha256"]:
|
| 135 |
+
raise ValueError(f"{u}: reference differs from {sj}")
|
| 136 |
+
few_min.append({"dataset": ds, "arm": "lora", "draw": j, "n_scored": int(s["n_donors"])})
|
| 137 |
+
vals = unit_values(u)
|
| 138 |
+
for key in list(FEW_SETS) + ["control"]:
|
| 139 |
+
sname = FEW_SETS.get(key, "control")
|
| 140 |
+
if sname not in vals:
|
| 141 |
+
continue
|
| 142 |
+
for c, _, _ in HEAD:
|
| 143 |
+
rows.append({"dataset": ds, "draw": j, "arm": key, "set": sname, "metric": c,
|
| 144 |
+
"value": vals[sname][c],
|
| 145 |
+
"undefined": bool(vals[sname].get(f"{c}_undefined", False)),
|
| 146 |
+
"source": str(u / ("en.csv" if c.startswith("en_") else "metrics.csv"))})
|
| 147 |
+
info[ds] = S9.draw_info(pd.DataFrame(few_min), ds)
|
| 148 |
+
return pd.DataFrame(rows), info
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def load_pooled():
|
| 152 |
+
"""dataset -> {arm key: {metric: value}}, plus the scSemiProfiler lookup log."""
|
| 153 |
+
out, log = {}, []
|
| 154 |
+
for ds in ORDER:
|
| 155 |
+
u = X / ds / "pooled"
|
| 156 |
+
vals = unit_values(u)
|
| 157 |
+
ref = manifest(u)
|
| 158 |
+
d = {}
|
| 159 |
+
for key, sname in POOL_SETS.items():
|
| 160 |
+
if sname in vals:
|
| 161 |
+
d[key] = {**vals[sname], "source": str(u)}
|
| 162 |
+
d["control"] = {**vals["control"], "source": str(u)}
|
| 163 |
+
# scSemiProfiler, all training pairs: in the pooled unit itself, else below scores_extra/<ds>/scsemi_cv_20261002/
|
| 164 |
+
if "scsemi_all" in d:
|
| 165 |
+
log.append(dict(dataset=ds, design="cv", unit=str(u), set=SR.CV_ARM, status="used", reason="in pooled unit"))
|
| 166 |
+
for cu in SR.extra_units(ds, SR.CV_EXP):
|
| 167 |
+
cv = unit_values(cu)
|
| 168 |
+
if SR.CV_ARM not in cv:
|
| 169 |
+
log.append(dict(dataset=ds, design="cv", unit=str(cu), set="", status="ignored",
|
| 170 |
+
reason=f"no set {SR.CV_ARM}"))
|
| 171 |
+
continue
|
| 172 |
+
cm = manifest(cu)
|
| 173 |
+
why = []
|
| 174 |
+
if cm.get("donors") is not None and set(map(str, cm["donors"])) != set(map(str, ref["donors"])):
|
| 175 |
+
why.append("donor set differs from the pooled unit")
|
| 176 |
+
if cm.get("reference_sha256") is not None and cm["reference_sha256"] != ref["reference_sha256"]:
|
| 177 |
+
why.append("reference differs from the pooled unit")
|
| 178 |
+
if "scsemi_all" in d:
|
| 179 |
+
why.append("already taken from an earlier unit")
|
| 180 |
+
if why:
|
| 181 |
+
log.append(dict(dataset=ds, design="cv", unit=str(cu), set=SR.CV_ARM, status="rejected",
|
| 182 |
+
reason="; ".join(why)))
|
| 183 |
+
continue
|
| 184 |
+
d["scsemi_all"] = {**cv[SR.CV_ARM], "source": str(cu)}
|
| 185 |
+
log.append(dict(dataset=ds, design="cv", unit=str(cu), set=SR.CV_ARM, status="used",
|
| 186 |
+
reason="no manifest: donors not checked" if not cm else ""))
|
| 187 |
+
for bu in SR.extra_units(ds, SR.BUDGET_EXP):
|
| 188 |
+
for s in sorted(unit_values(bu)):
|
| 189 |
+
if SR.BUDGET_RE.match(s):
|
| 190 |
+
log.append(dict(dataset=ds, design="budget", unit=str(bu), set=s, status="listed only",
|
| 191 |
+
reason="equal-budget units are not drawn"))
|
| 192 |
+
out[ds] = d
|
| 193 |
+
return out, pd.DataFrame(log, columns=["dataset", "design", "unit", "set", "status", "reason"])
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def check_headline(few: pd.DataFrame, pooled: dict):
|
| 197 |
+
"""Every value equals the collector's headline tables (few-pair: mean and n over draws; pooled: the value)."""
|
| 198 |
+
n = 0
|
| 199 |
+
hf = pd.read_csv(X / "fewshot_headline.csv")
|
| 200 |
+
for r in hf.itertuples():
|
| 201 |
+
key = "control" if r.set == "control" else {v: k for k, v in FEW_SETS.items()}[r.set]
|
| 202 |
+
for c, _, _ in HEAD:
|
| 203 |
+
x = few[(few.dataset == r.dataset) & (few.arm == key) & (few.metric == c) & ~few.undefined]["value"]
|
| 204 |
+
want = getattr(r, c)
|
| 205 |
+
if int(getattr(r, f"{c}_n")) != len(x) or abs(float(x.mean()) - want) > 1e-9:
|
| 206 |
+
raise ValueError(f"few-pair {r.dataset} {r.set} {c}: {x.mean()} (n {len(x)}) != headline {want}")
|
| 207 |
+
n += 1
|
| 208 |
+
hp = pd.read_csv(X / "pooled_headline.csv")
|
| 209 |
+
for r in hp.itertuples():
|
| 210 |
+
key = "control" if r.set == "control" else {v: k for k, v in POOL_SETS.items()}[r.set]
|
| 211 |
+
for c, _, _ in HEAD:
|
| 212 |
+
v, want = pooled[r.dataset][key][c], getattr(r, c)
|
| 213 |
+
if not (abs(v - want) <= 1e-9 or (np.isnan(v) and np.isnan(want))):
|
| 214 |
+
raise ValueError(f"pooled {r.dataset} {r.set} {c}: {v} != headline {want}")
|
| 215 |
+
n += 1
|
| 216 |
+
return n
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
# ------------------------------------------------------------------------------------------
|
| 220 |
+
# Drawing
|
| 221 |
+
# ------------------------------------------------------------------------------------------
|
| 222 |
+
def hbars_base(ax, arms, vals_of, base, seed=0, dots=True, na_text=None):
|
| 223 |
+
"""S9.hbars with bars starting at `base` (0.5 for AUC, the axis floor for a log axis)."""
|
| 224 |
+
out = {}
|
| 225 |
+
for i, arm in enumerate(arms):
|
| 226 |
+
vals = np.asarray([v for v in vals_of(arm) if not np.isnan(v)], float)
|
| 227 |
+
if len(vals) == 0:
|
| 228 |
+
ax.text(0.01, i, (na_text or {}).get(arm, "not run"), transform=ax.get_yaxis_transform(), va="center",
|
| 229 |
+
fontsize=FS - 3, color=SUB)
|
| 230 |
+
out[arm] = (np.nan, np.nan, 0)
|
| 231 |
+
continue
|
| 232 |
+
m = float(vals.mean())
|
| 233 |
+
sd = float(vals.std(ddof=1)) if len(vals) > 1 else 0.0
|
| 234 |
+
ax.barh(i, m - base, left=base, height=S9.BAR_H, color=COL[arm], edgecolor=EDGE, linewidth=0.6, zorder=2)
|
| 235 |
+
if dots and len(vals) > 1:
|
| 236 |
+
lo = max(m - sd, base) if ax.get_xscale() == "log" else m - sd
|
| 237 |
+
ax.errorbar(m, i, xerr=[[m - lo], [sd]], fmt="none", ecolor="#111111", elinewidth=1.0, capsize=3,
|
| 238 |
+
capthick=1.0, zorder=4)
|
| 239 |
+
ax.scatter(vals, i + S9.jitter(len(vals), seed + i), s=16, facecolor="white", edgecolor="#111111",
|
| 240 |
+
linewidth=0.7, zorder=5, clip_on=False)
|
| 241 |
+
out[arm] = (m, sd, len(vals))
|
| 242 |
+
ax.set_ylim(len(arms) - 0.5, -0.5)
|
| 243 |
+
ax.set_yticks([])
|
| 244 |
+
return out
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def vline(ax, x, style_, na):
|
| 248 |
+
if x is None or np.isnan(x):
|
| 249 |
+
return
|
| 250 |
+
ax.plot([x, x], [-0.5, na - 0.5], ls=style_["ls"], color=style_["color"], lw=style_["lw"], zorder=3,
|
| 251 |
+
solid_capstyle="butt")
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def ctrl_handle():
|
| 255 |
+
return Line2D([0], [0], ls=CTRL["ls"], color=CTRL["color"], lw=CTRL["lw"], label=CTRL["label"])
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def patch(key, label=None):
|
| 259 |
+
return Patch(facecolor=COL[key], edgecolor=EDGE, linewidth=0.6, label=label or LAB[key])
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def nice_log_limits(vals):
|
| 263 |
+
v = [x for x in vals if x > 0 and not np.isnan(x)]
|
| 264 |
+
lo = max([c for c in (0.01, 0.02, 0.03, 0.05, 0.1, 0.2, 0.5) if c <= min(v) / 1.3] or [0.005])
|
| 265 |
+
hi = min([c for c in (2, 5, 10, 20, 50, 100, 200, 500, 1000) if c >= max(v) * 1.3] or [max(v) * 2])
|
| 266 |
+
return lo, hi
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def axis_setup(axs_col, metric, allv, label):
|
| 270 |
+
"""Shared x scale of one metric column; returns the bar base."""
|
| 271 |
+
if metric.startswith("c2st") or metric.startswith("nn1"):
|
| 272 |
+
lo = min(0.45, np.floor(min(allv) * 20) / 20)
|
| 273 |
+
S9.shared_x(axs_col, lo, 1.0, label, [0.5, 0.75, 1.0])
|
| 274 |
+
for ax in axs_col: # bars start at 0.5 (chance); the real-vs-real line sits there, so no spine at lo
|
| 275 |
+
ax.spines["left"].set_visible(False)
|
| 276 |
+
return 0.5
|
| 277 |
+
if metric.startswith("mmd"):
|
| 278 |
+
hi = np.ceil(max(allv) * 1.08 / 0.05) * 0.05
|
| 279 |
+
lo = min(-0.02 * hi, min(allv) - 0.01 * hi)
|
| 280 |
+
S9.shared_x(axs_col, lo, hi, label, [round(t, 2) for t in np.arange(0, hi + 1e-9, 0.1)])
|
| 281 |
+
for ax in axs_col:
|
| 282 |
+
ax.spines["left"].set_visible(False)
|
| 283 |
+
ax.axvline(0, color="#555555", lw=0.8, zorder=1)
|
| 284 |
+
return 0.0
|
| 285 |
+
lo, hi = nice_log_limits(allv)
|
| 286 |
+
for ax in axs_col:
|
| 287 |
+
ax.set_xscale("log")
|
| 288 |
+
ticks = [t for t in (0.01, 0.1, 1, 10, 100, 1000) if lo <= t <= hi]
|
| 289 |
+
S9.shared_x(axs_col, lo, hi, label, ticks)
|
| 290 |
+
for ax in axs_col:
|
| 291 |
+
ax.set_xticklabels([f"{t:g}" for t in ticks])
|
| 292 |
+
ax.xaxis.set_minor_locator(plt.NullLocator())
|
| 293 |
+
return lo
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def realism_figure(name, arms, vals_of, ref_of, row_subs, legend_handles, dots, na_text=None, header=None):
|
| 297 |
+
"""rows = cohorts, columns = PANELS; vals_of(ds, arm, metric) -> list; ref_of(ds, kind, metric) -> float."""
|
| 298 |
+
leg_rows = -(-len(legend_handles) // 3)
|
| 299 |
+
fig, axs = S9.grid(len(ORDER), len(PANELS), style.FULL, left=S9.LEFT_IN, right=0.25, top=0.45,
|
| 300 |
+
bottom=0.65 + 0.30 * leg_rows, hspace=0.22, wspace=0.12)
|
| 301 |
+
rows = []
|
| 302 |
+
for j, (mk, lab) in enumerate(PANELS):
|
| 303 |
+
allv = [v for ds in ORDER for a in arms for v in vals_of(ds, a, mk) if not np.isnan(v)]
|
| 304 |
+
allv += [ref_of(ds, k, mk) for ds in ORDER for k in ("control", "pseudo")]
|
| 305 |
+
allv = [v for v in allv if not np.isnan(v)]
|
| 306 |
+
base = axis_setup(axs[:, j], mk, allv, lab)
|
| 307 |
+
for i, ds in enumerate(ORDER):
|
| 308 |
+
ax = axs[i, j]
|
| 309 |
+
hbars_base(ax, arms, lambda a: vals_of(ds, a, mk), base, seed=17 * i + j, dots=dots,
|
| 310 |
+
na_text=(na_text or {}).get(ds))
|
| 311 |
+
vline(ax, ref_of(ds, "control", mk), CTRL, len(arms))
|
| 312 |
+
vline(ax, ref_of(ds, "pseudo", mk), S9.REFSTYLE["pseudo"], len(arms))
|
| 313 |
+
for a in arms:
|
| 314 |
+
for v in vals_of(ds, a, mk):
|
| 315 |
+
rows.append({"figure": name, "dataset": ds, "metric": mk, "series": a, "value": v})
|
| 316 |
+
for k in ("control", "pseudo"):
|
| 317 |
+
rows.append({"figure": name, "dataset": ds, "metric": mk, "series": f"ref_{k}",
|
| 318 |
+
"value": ref_of(ds, k, mk)})
|
| 319 |
+
for i, ds in enumerate(ORDER):
|
| 320 |
+
S9.row_label(axs[i, 0], ROWNAME[ds], row_subs(ds))
|
| 321 |
+
if header:
|
| 322 |
+
S9.label_header(axs[0, 0], header)
|
| 323 |
+
S9.legend_bottom(fig, legend_handles, ncol=3)
|
| 324 |
+
S9.check_inside(fig, name)
|
| 325 |
+
style.save(fig, name, FIGDIR)
|
| 326 |
+
return rows
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
# ------------------------------------------------------------------------------------------
|
| 330 |
+
# Figures
|
| 331 |
+
# ------------------------------------------------------------------------------------------
|
| 332 |
+
FEW_ARMS = ["zs_raw", "zs_cal", "scsemi5", "lora"]
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
def few_vals(few, ds, arm, mk):
|
| 336 |
+
s = few[(few.dataset == ds) & (few.arm == arm) & (few.metric == mk)].sort_values("draw")
|
| 337 |
+
return [np.nan if u else v for v, u in zip(s.value, s.undefined)]
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
def few_mean(few, ds, arm, mk):
|
| 341 |
+
v = [x for x in few_vals(few, ds, arm, mk) if not np.isnan(x)]
|
| 342 |
+
return float(np.mean(v)) if v else np.nan
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def fig_fewpair(few, info):
|
| 346 |
+
nd = {info[d]["n_draws"] for d in ORDER}
|
| 347 |
+
per_row = len(nd) > 1
|
| 348 |
+
handles = [patch("zs_raw"), patch("zs_cal"), patch("scsemi5"), patch("lora"), ctrl_handle(), S9.refh("pseudo"),
|
| 349 |
+
S9.dot_handle(None if per_row else next(iter(nd)))]
|
| 350 |
+
return realism_figure(
|
| 351 |
+
"sec09_extra_fewpair", FEW_ARMS, lambda ds, a, mk: few_vals(few, ds, a, mk),
|
| 352 |
+
lambda ds, k, mk: few_mean(few, ds, k, mk), lambda ds: S9.row_subs(info[ds], per_row), handles, dots=True,
|
| 353 |
+
header="pairs per draw")
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
def fig_fivefold(pooled, arms, tab):
|
| 357 |
+
def vals(ds, a, mk):
|
| 358 |
+
d = pooled[ds].get(a)
|
| 359 |
+
return [np.nan] if d is None else [d[mk]]
|
| 360 |
+
|
| 361 |
+
def ref(ds, k, mk):
|
| 362 |
+
return pooled[ds][k][mk]
|
| 363 |
+
|
| 364 |
+
def subs(ds):
|
| 365 |
+
n, nd = tab[ds]
|
| 366 |
+
return [f"n={n}" + (f" ({nd} donors)" if nd != n else "")]
|
| 367 |
+
|
| 368 |
+
handles = [patch(a, LAB["lora_all"] if a == "lora" else None) for a in arms] + [ctrl_handle(), S9.refh("pseudo")]
|
| 369 |
+
na = {ds: {"scsemi_all": "pending"} for ds in ORDER}
|
| 370 |
+
return realism_figure("sec09_extra_fivefold", arms, vals, ref, subs, handles, dots=False, na_text=na)
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
def fig_ksens(few):
|
| 374 |
+
fig, axs = plt.subplots(2, len(ORDER), figsize=style.FULL, sharey=True,
|
| 375 |
+
gridspec_kw=dict(left=0.075, right=0.995, top=0.93, bottom=0.25, hspace=0.18,
|
| 376 |
+
wspace=0.10))
|
| 377 |
+
xs = np.arange(len(KS))
|
| 378 |
+
rows = []
|
| 379 |
+
mk_style = {"zs_raw": "o", "zs_cal": "o", "scsemi5": "D", "lora": "o"}
|
| 380 |
+
off = {"zs_raw": -0.09, "zs_cal": -0.03, "scsemi5": 0.03, "lora": 0.09}
|
| 381 |
+
for i, q in enumerate(("coverage", "precision")):
|
| 382 |
+
for j, ds in enumerate(ORDER):
|
| 383 |
+
ax = axs[i, j]
|
| 384 |
+
cv = [few_mean(few, ds, "control", f"{q}_k{k}") for k in KS]
|
| 385 |
+
ax.plot(xs, cv, ls=CTRL["ls"], color=CTRL["color"], lw=CTRL["lw"], marker="s", ms=4, zorder=2)
|
| 386 |
+
for k, v in zip(KS, cv):
|
| 387 |
+
rows.append({"figure": "sec09_extra_ksens", "dataset": ds, "metric": f"{q}_k{k}",
|
| 388 |
+
"series": "control", "value": v, "sd": np.nan})
|
| 389 |
+
for a in FEW_ARMS:
|
| 390 |
+
m = [few_mean(few, ds, a, f"{q}_k{k}") for k in KS]
|
| 391 |
+
sd = [float(np.std([x for x in few_vals(few, ds, a, f"{q}_k{k}") if not np.isnan(x)], ddof=1))
|
| 392 |
+
for k in KS]
|
| 393 |
+
ax.errorbar(xs + off[a], m, yerr=sd, color=COL[a], lw=2.0, marker=mk_style[a], ms=6,
|
| 394 |
+
mec=EDGE, mew=0.6, capsize=2.5, elinewidth=1.0, zorder=4 if a == "lora" else 3)
|
| 395 |
+
for k, v, s in zip(KS, m, sd):
|
| 396 |
+
rows.append({"figure": "sec09_extra_ksens", "dataset": ds, "metric": f"{q}_k{k}",
|
| 397 |
+
"series": a, "value": v, "sd": s})
|
| 398 |
+
ax.set_xticks(xs)
|
| 399 |
+
ax.set_xticklabels([str(k) for k in KS])
|
| 400 |
+
ax.set_xlim(-0.4, len(KS) - 0.6)
|
| 401 |
+
ax.set_ylim(0, 1.05)
|
| 402 |
+
ax.set_yticks([0, 0.5, 1.0])
|
| 403 |
+
if i == 0:
|
| 404 |
+
ax.set_title(ROWNAME[ds], fontsize=FS, pad=6)
|
| 405 |
+
ax.tick_params(axis="x", labelbottom=False)
|
| 406 |
+
if j == 0:
|
| 407 |
+
ax.set_ylabel(f"{q.capitalize()} ↑")
|
| 408 |
+
fig.text(0.535, 0.155, "k (nearest neighbours per ball)", ha="center", va="center", fontsize=FS)
|
| 409 |
+
handles = [Line2D([0], [0], color=COL[a], lw=2.0, marker=mk_style[a], ms=6, mec=EDGE, mew=0.6, label=LAB[a])
|
| 410 |
+
for a in FEW_ARMS] + [Line2D([0], [0], ls=CTRL["ls"], color=CTRL["color"], lw=CTRL["lw"], marker="s",
|
| 411 |
+
ms=4, label="Real vs real (held-out cells)")]
|
| 412 |
+
S9.legend_bottom(fig, handles, ncol=3)
|
| 413 |
+
style.save(fig, "sec09_extra_ksens", FIGDIR)
|
| 414 |
+
return rows
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
# ------------------------------------------------------------------------------------------
|
| 418 |
+
# Comparisons for the slide text
|
| 419 |
+
# ------------------------------------------------------------------------------------------
|
| 420 |
+
def better(a, b, sign):
|
| 421 |
+
"""a better than b (NaN = undefined E_N ranks last)."""
|
| 422 |
+
if np.isnan(a):
|
| 423 |
+
return False
|
| 424 |
+
if np.isnan(b):
|
| 425 |
+
return True
|
| 426 |
+
return (abs(a - 0.5) < abs(b - 0.5)) if sign == 0 else (a > b if sign > 0 else a < b)
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
def few_wide(few, mk):
|
| 430 |
+
s = few[few.metric == mk].copy()
|
| 431 |
+
s.loc[s.undefined, "value"] = np.nan
|
| 432 |
+
return s.pivot_table(index=["dataset", "draw"], columns="arm", values="value", dropna=False)
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
def few_compare(few, comps=("scsemi5", "zs_raw", "zs_cal")):
|
| 436 |
+
"""Per cohort x comparator x metric: draws where LoRA-5 is better / worse / tied."""
|
| 437 |
+
out = []
|
| 438 |
+
for c, _, sign in HEAD:
|
| 439 |
+
w = few_wide(few, c)
|
| 440 |
+
for ds in ORDER:
|
| 441 |
+
x = w.loc[ds]
|
| 442 |
+
for comp in comps:
|
| 443 |
+
xx = x[["lora", comp]].dropna(how="all")
|
| 444 |
+
nb = sum(better(a, b, sign) for a, b in zip(xx.lora, xx[comp]))
|
| 445 |
+
nw = sum(better(b, a, sign) for a, b in zip(xx.lora, xx[comp]))
|
| 446 |
+
out.append(dict(dataset=ds, comp=comp, metric=c, n=len(xx), n_better=nb, n_worse=nw,
|
| 447 |
+
lora=float(np.nanmean(xx.lora)), other=float(np.nanmean(xx[comp]))))
|
| 448 |
+
return pd.DataFrame(out)
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
def best_draws(few, mk, arms=FEW_ARMS):
|
| 452 |
+
"""Draws where LoRA-5 is best of the arms on one metric."""
|
| 453 |
+
sign = DIRS[mk]
|
| 454 |
+
w = few_wide(few, mk)
|
| 455 |
+
n = 0
|
| 456 |
+
for _, r in w.iterrows():
|
| 457 |
+
n += all(better(r["lora"], r[a], sign) for a in arms if a != "lora")
|
| 458 |
+
return n, len(w)
|
| 459 |
+
|
| 460 |
+
|
| 461 |
+
def fmt_metric(c, v):
|
| 462 |
+
return f"{v:.4f}" if c.startswith("mmd") else (f"{v:.2f}" if c.startswith("en_") else f"{v:.3f}")
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
def exceptions_text(exc):
|
| 466 |
+
"""'vs zero-shot + calibration: Imperial E_N (all cells) 3/5 (1.28 vs 1.22), ...' grouped by comparator / cohort."""
|
| 467 |
+
parts = []
|
| 468 |
+
for comp, g in exc.groupby("comp", sort=True):
|
| 469 |
+
items = []
|
| 470 |
+
for ds in ORDER:
|
| 471 |
+
h = g[g.dataset == ds]
|
| 472 |
+
if len(h):
|
| 473 |
+
items.append(f"{NAME[ds]} " + ", ".join(
|
| 474 |
+
f"{SHORT[r.metric]} {r.n_worse}/{r.n} ({fmt_metric(r.metric, r.lora)} vs "
|
| 475 |
+
f"{fmt_metric(r.metric, r.other)})" for r in h.itertuples()))
|
| 476 |
+
parts.append(f"vs {S9.LAB[comp].lower()}: " + "; ".join(items))
|
| 477 |
+
return " | ".join(parts)
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
def rng2(v, nd=2):
|
| 481 |
+
v = [x for x in v if not np.isnan(x)]
|
| 482 |
+
a, b = f"{min(v):.{nd}f}", f"{max(v):.{nd}f}"
|
| 483 |
+
return a if a == b else f"{a}–{b}"
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
# ------------------------------------------------------------------------------------------
|
| 487 |
+
def main():
|
| 488 |
+
FIGDIR.mkdir(parents=True, exist_ok=True)
|
| 489 |
+
OUTDATA.mkdir(parents=True, exist_ok=True)
|
| 490 |
+
few, info = load_fewpair()
|
| 491 |
+
pooled, sclog = load_pooled()
|
| 492 |
+
n_checked = check_headline(few, pooled)
|
| 493 |
+
sclog.to_csv(OUTDATA / "sec09_extra_scsemi_status.csv", index=False)
|
| 494 |
+
tab = {}
|
| 495 |
+
for ds in ORDER:
|
| 496 |
+
dj = json.loads((T / "data" / ds / "fewshot_n5" / "DRAWS.json").read_text())
|
| 497 |
+
n = int(json.loads((T / "scores" / ds / "pooled" / "summary.json").read_text())["n_donors"])
|
| 498 |
+
if n != int(dj["n_usable_rows"]):
|
| 499 |
+
raise ValueError(f"{ds}: pooled n {n} != usable rows")
|
| 500 |
+
tab[ds] = (n, int(dj["n_usable_donors"]))
|
| 501 |
+
has_sc = [ds for ds in ORDER if "scsemi_all" in pooled[ds]]
|
| 502 |
+
arms5 = ["zs_raw", "zs_cal", "sconly_cal"] + (["scsemi_all"] if has_sc else []) + ["lora"]
|
| 503 |
+
|
| 504 |
+
rows_a = fig_fewpair(few, info)
|
| 505 |
+
rows_b = fig_fivefold(pooled, arms5, tab)
|
| 506 |
+
rows_c = fig_ksens(few)
|
| 507 |
+
srcf = f"{X}/<cohort>/fewshot_n5/draw<j>/{{metrics,en}}.csv"
|
| 508 |
+
srcp = f"{X}/<cohort>/pooled/{{metrics,en}}.csv"
|
| 509 |
+
pd.DataFrame(rows_a).assign(source=srcf).to_csv(OUTDATA / "sec09_extra_fewpair.csv", index=False,
|
| 510 |
+
float_format="%.6g")
|
| 511 |
+
pd.DataFrame(rows_b).assign(source=srcp).to_csv(OUTDATA / "sec09_extra_fivefold.csv", index=False,
|
| 512 |
+
float_format="%.6g")
|
| 513 |
+
pd.DataFrame(rows_c).assign(source=srcf).to_csv(OUTDATA / "sec09_extra_ksens.csv", index=False,
|
| 514 |
+
float_format="%.6g")
|
| 515 |
+
slides = []
|
| 516 |
+
|
| 517 |
+
# ---------------- slide a: 5 donors, realism beyond P/C ----------------
|
| 518 |
+
cmp = few_compare(few)
|
| 519 |
+
nb_knn, ntot = best_draws(few, "c2st_knn_auc")
|
| 520 |
+
nb_rf, _ = best_draws(few, "c2st_rf_auc")
|
| 521 |
+
nb_nn1, _ = best_draws(few, "nn1_acc")
|
| 522 |
+
nb_mmd, _ = best_draws(few, "mmd2_bw1")
|
| 523 |
+
nb_en, _ = best_draws(few, "en_all_sq")
|
| 524 |
+
en_sc = cmp[(cmp.comp == "scsemi5") & (cmp.metric == "en_all_sq")]
|
| 525 |
+
en_sc_better, en_sc_n = int(en_sc.n_better.sum()), int(en_sc.n.sum())
|
| 526 |
+
auc_l = [few_mean(few, d, "lora", "c2st_knn_auc") for d in ORDER]
|
| 527 |
+
auc_draws = few[(few.arm == "lora") & (few.metric == "c2st_knn_auc")].value
|
| 528 |
+
kw1 = S9.keyword_or_short(f"Classifier AUC: LoRA-5 best in {nb_knn}/{ntot} draws",
|
| 529 |
+
f"AUC: LoRA-5 best in {nb_knn}/{ntot} draws")
|
| 530 |
+
kw2 = f"E_N: LoRA-5 below scSemi-5 in {en_sc_better}/{en_sc_n} draws"
|
| 531 |
+
kw3 = f"Still separable: LoRA-5 AUC {rng2(auc_l)}"
|
| 532 |
+
kw_a = S9.check_keywords([kw1, kw2, kw3])
|
| 533 |
+
# exceptions over every headline metric (LoRA-5 worse in >= 1 draw)
|
| 534 |
+
exc = cmp[cmp.n_worse > 0].copy()
|
| 535 |
+
exc_comps = sorted(set(exc.comp))
|
| 536 |
+
drawn = {m for m, _ in PANELS}
|
| 537 |
+
exc_drawn = exc[exc.metric.isin(drawn)].sort_values(["n_worse", "dataset"], ascending=[False, True])
|
| 538 |
+
if exc.empty:
|
| 539 |
+
fs_a = "E_N: scSemiProfiler's own error metric. LoRA-5 best of the 4 arms on every metric in every draw."
|
| 540 |
+
elif exc_comps == ["zs_cal"]:
|
| 541 |
+
e0 = exc_drawn.iloc[0] if len(exc_drawn) else exc.sort_values("n_worse", ascending=False).iloc[0]
|
| 542 |
+
nd = 2 if e0.metric.startswith("en_") else 3
|
| 543 |
+
fs_a = (f"E_N: scSemiProfiler's own error metric. Misses only vs calibration, e.g. {NAME[e0.dataset]} "
|
| 544 |
+
f"{SHORT[e0.metric].split(' (')[0]} {e0.lora:.{nd}f} vs {e0.other:.{nd}f}.")
|
| 545 |
+
else:
|
| 546 |
+
fs_a = (f"E_N: scSemiProfiler's own error metric. LoRA-5 behind in {len(exc)} cohort × arm × metric cases; "
|
| 547 |
+
f"see notes.")
|
| 548 |
+
fs_a = S9.check_foot_short(fs_a)
|
| 549 |
+
rf_l = [few_mean(few, d, "lora", "c2st_rf_auc") for d in ORDER]
|
| 550 |
+
ctrl_auc = [few_mean(few, d, "control", "c2st_knn_auc") for d in ORDER]
|
| 551 |
+
ctrl_en = [few_mean(few, d, "control", "en_all_sq") for d in ORDER]
|
| 552 |
+
nn_c = cmp[cmp.metric.isin(["c2st_knn_auc", "c2st_rf_auc", "nn1_acc"] + [f"coverage_k{k}" for k in KS])]
|
| 553 |
+
wins_all = (nn_c.n_better == nn_c.n).all()
|
| 554 |
+
exc_txt = exceptions_text(exc)
|
| 555 |
+
en_means = "; ".join(f"{NAME[d]} {few_mean(few, d, 'scsemi5', 'en_all_sq'):.2f} vs "
|
| 556 |
+
f"{few_mean(few, d, 'lora', 'en_all_sq'):.2f}" for d in ORDER)
|
| 557 |
+
foot_a = (f"Same 5-donor draws as the previous slides; every metric on exactly the scored cells (scores_extra/, "
|
| 558 |
+
f"tools/extra_metrics.py). Real side for AUC and MMD² = held-out real cells of the same samples (R2), "
|
| 559 |
+
f"projected like the generated cells; real vs real = R2 vs R3 (AUC {rng2(ctrl_auc)}). Classifier AUC: "
|
| 560 |
+
f"5-fold CV ROC AUC of a kNN classifier (k = 5) separating real from generated cells, 0.5 = "
|
| 561 |
+
f"indistinguishable; bars start at 0.5. MMD²: unbiased, Gaussian kernel, bandwidth = median distance "
|
| 562 |
+
f"among real cells. E_N: scSemiProfiler's normalized error (Wang et al. 2024, eq. 17–18), their code's "
|
| 563 |
+
f"squared L2 on all cells, per-arm PCA-100; real vs real = within-sample half split "
|
| 564 |
+
f"({rng2(ctrl_en)}); every generated arm is above 1. LoRA-5 best of the 4 arms in {nb_knn}/{ntot} "
|
| 565 |
+
f"draws on kNN AUC, {nb_rf}/{ntot} on RF AUC, {nb_nn1}/{ntot} on 1-NN accuracy, {nb_mmd}/{ntot} on MMD², "
|
| 566 |
+
f"{nb_en}/{ntot} on E_N. "
|
| 567 |
+
+ ("LoRA-5 better than scSemi-5, zero-shot and zero-shot + calibration on both AUCs, 1-NN accuracy and "
|
| 568 |
+
"coverage at k = 3, 5, 10 in every draw. " if wins_all else "")
|
| 569 |
+
+ f"E_N scSemi-5 vs LoRA-5 (cohort means): {en_means}; LoRA-5 lower in {en_sc_better}/{en_sc_n} draws. "
|
| 570 |
+
f"Draws where LoRA-5 is worse (cohort means in brackets): {exc_txt if len(exc) else 'none'}. "
|
| 571 |
+
f"LoRA-5 AUC per draw "
|
| 572 |
+
f"{auc_draws.min():.2f}–{auc_draws.max():.2f} (kNN), RF cohort means {rng2(rf_l)}: a classifier still "
|
| 573 |
+
f"tells generated from real cells. Scores: scores_extra/<cohort>/fewshot_n5/draw<j>/.")
|
| 574 |
+
S9.check_text(foot_a, "footnote")
|
| 575 |
+
num("a", f"LoRA-5 best of 4 arms (draws): kNN AUC {nb_knn}/{ntot}, RF AUC {nb_rf}/{ntot}, 1-NN {nb_nn1}/{ntot}, "
|
| 576 |
+
f"MMD² {nb_mmd}/{ntot}, E_N {nb_en}/{ntot}", srcf)
|
| 577 |
+
num("a", f"E_N LoRA-5 < scSemi-5 in {en_sc_better}/{en_sc_n} draws; cohort means scSemi-5 vs LoRA-5: {en_means}",
|
| 578 |
+
f"{X}/<cohort>/fewshot_n5/draw<j>/en.csv (cellset all, distance sq)")
|
| 579 |
+
num("a", "LoRA-5 kNN AUC cohort means: " + ", ".join(f"{NAME[d]} {v:.3f}" for d, v in zip(ORDER, auc_l)) +
|
| 580 |
+
f"; per draw {auc_draws.min():.3f}–{auc_draws.max():.3f}", srcf)
|
| 581 |
+
num("a", "real vs real: kNN AUC " + ", ".join(f"{NAME[d]} {v:.3f}" for d, v in zip(ORDER, ctrl_auc)) +
|
| 582 |
+
"; E_N " + ", ".join(f"{NAME[d]} {v:.3f}" for d, v in zip(ORDER, ctrl_en)), srcf)
|
| 583 |
+
num("a", f"LoRA-5 worse than a comparator (draws): {exc_txt if len(exc) else 'none'}", srcf)
|
| 584 |
+
num("a", f"cross-check: {n_checked} cohort × arm × metric values equal scores_extra/{{fewshot,pooled}}_headline.csv",
|
| 585 |
+
f"{X}/fewshot_headline.csv; {X}/pooled_headline.csv")
|
| 586 |
+
slides.append({"title": "5 donors: realism beyond precision/coverage", "layout": "full",
|
| 587 |
+
"figures": [str(FIGDIR / "sec09_extra_fewpair.png")], "keywords": kw_a, "footnote": foot_a,
|
| 588 |
+
"footnote_short": fs_a, "numbers": NUMS["a"]})
|
| 589 |
+
|
| 590 |
+
# ---------------- slide b: 5-fold pooled ----------------
|
| 591 |
+
comps = [a for a in arms5 if a != "lora"]
|
| 592 |
+
first = {}
|
| 593 |
+
for c, _, sign in HEAD:
|
| 594 |
+
first[c] = [ds for ds in ORDER if all(better(pooled[ds]["lora"][c], pooled[ds][a][c], sign)
|
| 595 |
+
for a in comps if a in pooled[ds])]
|
| 596 |
+
n_all = sum(len(v) == len(ORDER) for v in first.values())
|
| 597 |
+
if n_all == len(HEAD):
|
| 598 |
+
kwb1 = f"Every metric: LoRA first in {len(ORDER)}/{len(ORDER)} cohorts"
|
| 599 |
+
else:
|
| 600 |
+
kwb1 = f"LoRA first everywhere on {n_all}/{len(HEAD)} metrics"
|
| 601 |
+
ji = pooled["ji2025_chili"]
|
| 602 |
+
oth = [ji[a]["en_all_sq"] for a in comps if a in ji]
|
| 603 |
+
kwb2 = S9.keyword_or_short(f"Ji whole blood: E_N {ji['lora']['en_all_sq']:.1f} vs {rng2(oth, 1)}",
|
| 604 |
+
f"Ji: E_N {ji['lora']['en_all_sq']:.1f} vs {rng2(oth, 1)}")
|
| 605 |
+
auc_p = [pooled[d]["lora"]["c2st_knn_auc"] for d in ORDER]
|
| 606 |
+
kwb3 = f"Still separable: LoRA AUC {rng2(auc_p)}"
|
| 607 |
+
kw_b = S9.check_keywords([kwb1, kwb2, kwb3])
|
| 608 |
+
fs_b = S9.check_foot_short("Donor-level 5-fold CV, one pooled call per cohort. E_N: scSemiProfiler's own error "
|
| 609 |
+
"metric.")
|
| 610 |
+
lost = {SHORT[c]: [NAME[d] for d in ORDER if d not in v] for c, v in first.items() if len(v) < len(ORDER)}
|
| 611 |
+
sc_txt = (f"scSemiProfiler, 5-fold CV (every training donor of the fold, inner-val included, as "
|
| 612 |
+
f"representatives; arm {SR.CV_ARM}) drawn for {', '.join(NAME[d] for d in has_sc)}; sources: "
|
| 613 |
+
+ "; ".join(f"{NAME[d]} {pooled[d]['scsemi_all']['source']}" for d in has_sc) + ". "
|
| 614 |
+
if has_sc else "scSemiProfiler 5-fold CV not available yet (no extra-metric unit with set "
|
| 615 |
+
f"{SR.CV_ARM}). ")
|
| 616 |
+
foot_b = (f"Donor-level 5-fold CV; each pair scored once by the fold model that never trained on its donor (one "
|
| 617 |
+
f"pooled call per cohort, all cross-fitted pairs). Arms as on the 5-fold slide. Metric definitions as on "
|
| 618 |
+
f"the 5-donor realism slide. LoRA first among the {len(comps) + 1} arms in all {len(ORDER)} cohorts on "
|
| 619 |
+
f"{n_all}/{len(HEAD)} headline metrics (kNN and RF AUC, 1-NN accuracy, MMD² at σ = m and summed, E_N all "
|
| 620 |
+
f"cells, precision and coverage at k = 3, 5, 10)"
|
| 621 |
+
+ (f"; exceptions: " + "; ".join(f"{k}: {', '.join(v)}" for k, v in lost.items()) if lost else "")
|
| 622 |
+
+ f". LoRA kNN AUC " + ", ".join(f"{NAME[d]} {v:.3f}" for d, v in zip(ORDER, auc_p))
|
| 623 |
+
+ f"; real vs real " + ", ".join(f"{NAME[d]} {pooled[d]['control']['c2st_knn_auc']:.3f}" for d in ORDER)
|
| 624 |
+
+ ". E_N LoRA vs other arms: " + "; ".join(
|
| 625 |
+
f"{NAME[d]} {pooled[d]['lora']['en_all_sq']:.2f} vs {rng2([pooled[d][a]['en_all_sq'] for a in comps if a in pooled[d]])}"
|
| 626 |
+
for d in ORDER)
|
| 627 |
+
+ f". {sc_txt}Scores: scores_extra/<cohort>/pooled/.")
|
| 628 |
+
S9.check_text(foot_b, "footnote")
|
| 629 |
+
num("b", f"LoRA first among {len(comps) + 1} arms in all {len(ORDER)} cohorts on {n_all}/{len(HEAD)} metrics", srcp)
|
| 630 |
+
num("b", f"Ji E_N: LoRA {ji['lora']['en_all_sq']:.3f}; " +
|
| 631 |
+
", ".join(f"{LAB[a]} {ji[a]['en_all_sq']:.3f}" for a in comps if a in ji), srcp)
|
| 632 |
+
num("b", "LoRA kNN AUC (pooled): " + ", ".join(f"{NAME[d]} {v:.3f}" for d, v in zip(ORDER, auc_p)), srcp)
|
| 633 |
+
num("b", "scSemiProfiler, 5-fold CV: " + (", ".join(NAME[d] for d in has_sc) if has_sc else "not available"),
|
| 634 |
+
OUTDATA / "sec09_extra_scsemi_status.csv")
|
| 635 |
+
slides.append({"title": "5-fold: realism beyond precision/coverage", "layout": "full",
|
| 636 |
+
"figures": [str(FIGDIR / "sec09_extra_fivefold.png")], "keywords": kw_b, "footnote": foot_b,
|
| 637 |
+
"footnote_short": fs_b, "numbers": NUMS["b"]})
|
| 638 |
+
|
| 639 |
+
# ---------------- slide c: k sensitivity ----------------
|
| 640 |
+
sets_k = FEW_ARMS + ["control"]
|
| 641 |
+
mono = all(few_mean(few, d, a, f"{q}_k3") <= few_mean(few, d, a, f"{q}_k5") <= few_mean(few, d, a, f"{q}_k10")
|
| 642 |
+
for d in ORDER for a in sets_k for q in ("coverage", "precision"))
|
| 643 |
+
ctrl_c3 = [few_mean(few, d, "control", "coverage_k3") for d in ORDER]
|
| 644 |
+
kwc1 = ("Smaller k lowers every set, real included" if mono else
|
| 645 |
+
f"Real vs real coverage at k = 3: {rng2(ctrl_c3)}")
|
| 646 |
+
cov_all_k = 0
|
| 647 |
+
wc = {k: few_wide(few, f"coverage_k{k}") for k in KS}
|
| 648 |
+
for idx in wc[10].index:
|
| 649 |
+
cov_all_k += all(all(better(wc[k].loc[idx, "lora"], wc[k].loc[idx, a], 1) for a in FEW_ARMS if a != "lora")
|
| 650 |
+
for k in KS)
|
| 651 |
+
kwc2 = f"Coverage: LoRA-5 first at all k, {cov_all_k}/{len(wc[10])}"
|
| 652 |
+
pb = [best_draws(few, f"precision_k{k}")[0] for k in KS]
|
| 653 |
+
kwc3 = f"Precision: LoRA-5 first in {min(pb)}–{max(pb)}/{ntot} draws" if min(pb) != max(pb) else \
|
| 654 |
+
f"Precision: LoRA-5 first in {pb[0]}/{ntot} draws"
|
| 655 |
+
kw_c = S9.check_keywords([kwc1, kwc2, kwc3])
|
| 656 |
+
fs_c = S9.check_foot_short("5 donors, 5 draws per cohort; error bars = SD over draws. k = 10 is the value on the main "
|
| 657 |
+
"slides.")
|
| 658 |
+
# who beats LoRA-5 on precision, per k
|
| 659 |
+
who_n, who_arms = {}, set()
|
| 660 |
+
for k in KS:
|
| 661 |
+
w = few_wide(few, f"precision_k{k}")
|
| 662 |
+
for (d, j), r in w.iterrows():
|
| 663 |
+
b = [a for a in FEW_ARMS if a != "lora" and not better(r["lora"], r[a], 1)]
|
| 664 |
+
if b:
|
| 665 |
+
who_n.setdefault(d, {kk: 0 for kk in KS})[k] += 1
|
| 666 |
+
who_arms.update(b)
|
| 667 |
+
who = ", ".join(f"{NAME[d]} {'/'.join(str(who_n[d][k]) for k in KS)}" for d in ORDER if d in who_n)
|
| 668 |
+
who = (f"{who} draws at k = 3/5/10, beaten by {' or '.join(S9.LAB[a].lower() for a in sorted(who_arms))}"
|
| 669 |
+
if who else "none")
|
| 670 |
+
exp_cov = {}
|
| 671 |
+
for d in ORDER:
|
| 672 |
+
mt = pd.concat([pd.read_csv(u / "metrics.csv") for u in sorted((X / d / "fewshot_n5").glob("draw*"))])
|
| 673 |
+
mt = mt[(mt["set"] == "lora5") & (mt.real_side == "R1") & (mt["mode"] == "raw")]
|
| 674 |
+
exp_cov[d] = "/".join(f"{mt[f'expected_coverage_identical_k{k}'].mean():.2f}" for k in KS)
|
| 675 |
+
exp_cov = (f"{next(iter(exp_cov.values()))} in every cohort" if len(set(exp_cov.values())) == 1
|
| 676 |
+
else "; ".join(f"{NAME[d]} {v}" for d, v in exp_cov.items()))
|
| 677 |
+
same_rank, lora_top = [], []
|
| 678 |
+
for d in ORDER:
|
| 679 |
+
r = {k: sorted([a for a in arms5 if a in pooled[d]], key=lambda a: -pooled[d][a][f"coverage_k{k}"]) for k in KS}
|
| 680 |
+
same_rank.append(r[3] == r[5] == r[10])
|
| 681 |
+
lora_top.append(all(r[k][0] == "lora" for k in KS))
|
| 682 |
+
pooled_rank = (f"{'unchanged' if all(same_rank) else 'changes in ' + ', '.join(NAME[d] for d, x in zip(ORDER, same_rank) if not x)}"
|
| 683 |
+
f"; LoRA first at every k in {sum(lora_top)}/{len(ORDER)} cohorts")
|
| 684 |
+
foot_c = (f"Precision and coverage recomputed with k = 3, 5, 10 nearest-neighbour balls in the scorer's PCA-50 "
|
| 685 |
+
f"(k = 10 reproduces the main-slide values exactly). Means over the 5 draws per cohort; error bars = SD; "
|
| 686 |
+
f"grey = real vs real (R1 vs R2, same samples). Both metrics fall with smaller k for every set "
|
| 687 |
+
f"{'including' if mono else 'but not always'} the real control (real coverage at k = 3: {rng2(ctrl_c3)}), "
|
| 688 |
+
f"so compare arms with the real row, not with 1. Expected coverage of a perfect generator (Naeem et al. "
|
| 689 |
+
f"2020, eq. 9) at k = 3/5/10: {exp_cov}. LoRA-5 first on coverage at every k in "
|
| 690 |
+
f"{cov_all_k}/{len(wc[10])} draws; on precision in {'/'.join(map(str, pb))} of {ntot} draws "
|
| 691 |
+
f"(k = 3/5/10); not first: {who}. 5-fold pooled design (not drawn): "
|
| 692 |
+
f"coverage ranking of the {len(arms5)} arms across k {pooled_rank}. Scores: "
|
| 693 |
+
f"scores_extra/<cohort>/fewshot_n5/draw<j>/metrics.csv.")
|
| 694 |
+
S9.check_text(foot_c, "footnote")
|
| 695 |
+
num("c", f"LoRA-5 first on coverage at k = 3, 5 and 10: {cov_all_k}/{len(wc[10])} draws", srcf)
|
| 696 |
+
num("c", f"LoRA-5 first on precision (draws) at k = 3/5/10: {'/'.join(map(str, pb))} of {ntot}", srcf)
|
| 697 |
+
num("c", "real vs real coverage at k = 3: " + ", ".join(f"{NAME[d]} {v:.3f}" for d, v in zip(ORDER, ctrl_c3)), srcf)
|
| 698 |
+
num("c", f"every set falls with smaller k (cohort means): {mono}", srcf)
|
| 699 |
+
slides.append({"title": "5 donors: precision/coverage at k = 3, 5, 10", "layout": "full",
|
| 700 |
+
"figures": [str(FIGDIR / "sec09_extra_ksens.png")], "keywords": kw_c, "footnote": foot_c,
|
| 701 |
+
"footnote_short": fs_c, "numbers": NUMS["c"]})
|
| 702 |
+
|
| 703 |
+
for s in slides:
|
| 704 |
+
for k in ("title", "footnote", "footnote_short"):
|
| 705 |
+
S9.check_text(s[k], k)
|
| 706 |
+
for n in s["numbers"]:
|
| 707 |
+
S9.check_text(n["value"], "quoted number")
|
| 708 |
+
spec = {"section": "09-extra", "slides": slides, "scripts": [str(SCRIPT)],
|
| 709 |
+
"generated_from": "tools/sec09_extra_metrics.py (rerun to refresh; do not edit by hand)",
|
| 710 |
+
"scsemi_cv_cohorts": [NAME[d] for d in has_sc]}
|
| 711 |
+
(OUTDATA / "sec09_extra_slide_text.json").write_text(json.dumps(spec, indent=1, ensure_ascii=False))
|
| 712 |
+
pd.DataFrame([{"slide": k, "value": n["value"], "source": n["source"]} for k in "abc" for n in NUMS[k]]).to_csv(
|
| 713 |
+
OUTDATA / "sec09_extra_quoted_numbers.csv", index=False)
|
| 714 |
+
for p in [OUTDATA / "sec09_extra_slide_text.json"] + sorted(OUTDATA.glob("sec09_extra_*.csv")):
|
| 715 |
+
m = S9.OFF_STORY.search(p.read_text(encoding="utf-8"))
|
| 716 |
+
if m:
|
| 717 |
+
raise ValueError(f"{p}: off-story text {m.group(0)!r}")
|
| 718 |
+
|
| 719 |
+
print(f"cross-checked {n_checked} values against the collector's headline tables")
|
| 720 |
+
if not has_sc:
|
| 721 |
+
print(f"NOTE: no scSemiProfiler 5-fold extra-metric unit (set {SR.CV_ARM}) under "
|
| 722 |
+
f"{SR.plan_root()}/scores_extra/<ds>/{SR.CV_EXP}/ or in the pooled units; the 5-fold figure has no "
|
| 723 |
+
f"scSemiProfiler row.")
|
| 724 |
+
else:
|
| 725 |
+
print(f"scSemiProfiler, 5-fold CV drawn for: {[NAME[d] for d in has_sc]}")
|
| 726 |
+
for r in sclog.itertuples():
|
| 727 |
+
print(f" scSemiProfiler extra unit {r.dataset} {r.design} {r.set}: {r.status} {r.reason} ({r.unit})")
|
| 728 |
+
for s in slides:
|
| 729 |
+
print(f"\n== {s['title']}")
|
| 730 |
+
for k in s["keywords"]:
|
| 731 |
+
print(" *", k, f"({S9.n_words(k)} words, {len(k)} chars)")
|
| 732 |
+
print(" footnote_short:", s["footnote_short"], f"({len(s['footnote_short'])} chars)")
|
| 733 |
+
print(" footnote:", s["footnote"])
|
| 734 |
+
return 0
|
| 735 |
+
|
| 736 |
+
|
| 737 |
+
if __name__ == "__main__":
|
| 738 |
+
sys.exit(main())
|
paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec09_paired_validation.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|