diff --git a/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 b/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 new file mode 100644 index 0000000000000000000000000000000000000000..b4a9509c2ec275371ee4bc36208870272d60176d --- /dev/null +++ b/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 @@ -0,0 +1,897 @@ +"""Section 8 of the 2026-09-30 paper-summary deck: how many bulk-sc pairs LoRA needs (learning curve). + +CPU only. Reads the pooled 5-fold scoring calls of the paired fine-tune plan and the per-fold RUN.json files, +then draws two slide figures: + figures/sec08_pairs_realism.{png,pdf} FULL: composition L1, coverage, selected step x (ImMicro, sepsis) + figures/sec08_pairs_signal.{png,pdf} TALL: ImMicro NK fraction r, sepsis logFC r, sepsis top-50 DEG +Every plotted/quoted number is read from a score file here and written with its source to data/sec08_*.csv. +Model: final f01 6k 1x epoch-16 checkpoint + LoRA (checked against every RUN.json). +x axis: "0" = no LoRA training. Two zero-shot points sit there, side by side: the pretrained model fed the real bulk +as measured (score arm zs__raw; uses no pair) and fed gene-wise calibrated bulk (zs__cal). Calibration (back as a +comparator, user decision 2026-10-01): alpha_g = mean CPM(pseudobulk_g) / mean CPM(bulk_g) over ALL paired training +donors of the fold (train + inner-val; tools/prepare_dataset.py `fit = fold != f`), applied as bulk CPM x alpha, then +renormalised. So zs__cal is not pair-free: its alpha uses the same 85-86 / 65-66 donors that LoRA "all" trains and +early-stops on. LoRA n = training pairs, and every LoRA run also early-stops on 7-8 paired inner-val donors +(RUN.json inner_val_rows). The LoRA arms are conditioned on the real bulk (*__raw) and share one real-bulk broadcast. +Cap-limited = ran to max_steps before the patience window closed; its late inner-val loss drop is read from +history.json. +When a zero-shot point lies far outside every other value of a panel (BREAK_RATIO), that panel gets a y-axis +break with a short segment at the same data scale, instead of squeezing the LoRA curve. + +Equal-budget calibration (optional, drawn only if present): zero-shot + calibration with alpha fitted on exactly the +pairs a lora_n{5,10,20,40} run saw (n training + its inner-val pairs), per fold. The scores folder is scanned for +summary.json files (scores//**/summary.json, outside arms/) whose arm names match CAL_N_RE (contain "cal" +and an n token) and carry no fine-tune tag (FT_TAGS). An arm is drawn only from a scoring call over the +same donors as the pooled call (same reference cells, so metrics are comparable). If found, it is drawn as a second +line across n, ending at "all" with zs__cal (alpha from the same pairs LoRA "all" saw). If none is found, only the +two x = 0 points are drawn and a note is printed. + +scSemiProfiler line (optional, drawn only if present; added 2026-10-02): scSemiProfiler trained with n pairs as +representatives (arms scsemi_n{5,10,20,40}__raw in scores//scsemi_budget_20261002/pooled*/) and with all +training pairs ("all" = arm scsemi__raw of the 5-fold CV run in scores//scsemi_cv_20261002/pooled*/), looked up +by tools/scsemi_results.py and drawn only for calls over the same donors and reference cells as the pooled call. If +nothing is found, a note is printed and the figures are unchanged. DECK_FIGDIR / DECK_OUTDATA redirect the outputs and +DECK_SCSEMI_PLAN_ROOT the scSemiProfiler lookup (synthetic presence test). +""" +import os +import json +import re +import sys +from pathlib import Path + +import numpy as np +import pandas as pd +from scipy.stats import wilcoxon + +DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/" + "2026-09-30--paper-summary--r00") +sys.path.insert(0, str(DECK / "tools")) +import style # noqa: E402 +import scsemi_results as SR # noqa: E402 +import fold_sizes as FZ # noqa: E402 (2026-10-02: the "all" point is labelled with its training-pair count) +import matplotlib.pyplot as plt # noqa: E402 +from matplotlib.lines import Line2D # noqa: E402 + +PLAN = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/" + "paired_finetune_intradataset_20260927") +FINAL_CKPT = ("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/runs/" + "f01_6k_1x_seed20260627/checkpoint_epoch_016.pt") +FIGDIR = Path(os.environ.get("DECK_FIGDIR", str(DECK / "figures"))) +DATADIR = Path(os.environ.get("DECK_OUTDATA", str(DECK / "data"))) +FIGDIR.mkdir(exist_ok=True) +DATADIR.mkdir(exist_ok=True) + +DSETS = ["immicro", "ye2026_sepsis"] +DS_LABEL = {"immicro": "ImMicro", "ye2026_sepsis": "Sepsis"} +LC_N = [5, 10, 20, 40] +LORA_ARMS = [f"lora_n{n}__raw" for n in LC_N] + ["real_lora__raw"] +RUN_ARMS = [f"lora_n{n}" for n in LC_N] + ["real_lora"] +ZS = "zs__raw" # zero-shot on the real bulk as measured: 0 pairs +ZS_CAL = "zs__cal" # zero-shot + calibration, alpha from all fold pairs (train + inner-val) +# 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 +# after exon-length correction (no pairs); zs__cal (alpha from every training pair of the fold) is only drawn where it +# belongs, as the right end of the equal-budget calibration line (same pairs as the rightmost LoRA point). +ZS_LEN = "zs__len" # zero-shot, exon-length-corrected real bulk (tools/build_tpm_zeroshot.py) +LEN_SUB = "zeroshot_tpm_20261002/pooled" # its scoring call (same donors and reference cells as scores//pooled) +X_LAB = ["0", "5", "10", "20", "40", "all"] +KEY_LAB = ["zero_shot", "5", "10", "20", "40", "all"] # the same points, as keys in sec08_slide_numbers.csv +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 +DX0 = 0.2 # raw zero-shot left of x = 0, calibrated right of it +X_RAW, X_CAL = X_POS[0] - DX0, X_POS[0] + DX0 # X_CAL: position of the second zero-shot point +XLIM = (-0.5, X_POS[-1] + 0.5) # same x range as the selected-step panel +COL_RAW, COL_CAL = style.ARM["zs_raw"], style.ARM["zs_cal"] # archived pair: pale = raw, #0072B2 = calibrated +RAW_EDGE = "#5E8FB5" # edge of the pale raw marker (same as sec05 RAW_EDGE) +COL_LEN = style.ARM["tpm"] # zero-shot, length-corrected bulk (sand) +# equal-budget calibration arms: "cal" and an n token, and no fine-tune tag +CAL_N_RE = re.compile(r"(?:^|[^a-z0-9])n(\d+)(?![0-9])", re.I) +FT_TAGS = ("lora", "real", "pseudo", "full", "condenc", "multik", "recipe") +BREAK_RATIO = 1.5 # y-axis break when the zero-shot point sits > 1.5 spans of the other values beyond them +CELLTYPES = ["T cell", "B cell", "Monocyte", "NK cell"] +DEG_TYPES = ["T cell", "B cell", "Monocyte", "NK cell", "DC"] +RAW_ARMS = LORA_ARMS + ["zs__raw", "real_full__raw", "pseudo_full__raw"] # all conditioned on raw real bulk + +REF = { # reference-line styles; pseudo/broadcast copied from sec09 REFSTYLE so the deck is consistent + "pseudo": dict(ls=(0, (4, 2)), color=style.ARM["pseudo"], lw=1.6, label="Zero-shot from sc pseudobulk"), + "broadcast": dict(ls=(0, (1, 1.2)), color=style.ARM["broadcast"], lw=2.4, label="Real-bulk broadcast"), + "null": dict(ls=(0, (6, 2, 1.5, 2)), color=style.GREY, lw=1.4, label="Cohort-mean null"), +} +LEG_ZS = "Zero-shot, real bulk as measured (no pairs)" +LEG_LEN = "Zero-shot, exon-length-corrected bulk (no pairs)" +LEG_CAL_N = "Zero-shot + calibration, α from the same pairs" +COL_SC = style.ARM["scsemi"] +LEG_SC = "scSemiProfiler, n pairs as representatives" + + +def xlabel(st): + """x-axis label; the inner-val range is read from the RUN.json files.""" + return (f"LoRA training pairs per fold (each run +{rng_txt(st.n_inner_val)} inner-val pairs for early stopping; " + f"test fold never trained on)") + + +def xticks(ds): + """x tick labels of one cohort: the rightmost point is every training donor of the fold, shown as its count.""" + return X_LAB[:-1] + [FZ.all_label(ds)] + + +def close(a, b, tol=1e-6): + return abs(float(a) - float(b)) <= tol + + +class Call: + """One pooled score_ft.py scoring call.""" + + def __init__(self, path: Path): + self.path = path + self.summary = json.loads((path / "summary.json").read_text()) + self.contrast = pd.read_csv(path / "contrast.csv") if (path / "contrast.csv").exists() else None + self.per_donor = pd.read_csv(path / "per_donor.csv") + self.src_summary = str(path / "summary.json") + self.src_contrast = str(path / "contrast.csv") + self.src_per_donor = str(path / "per_donor.csv") + + def head(self, arm, key): + return float(self.summary["headline"][arm][key]) + + def contrast_r(self, arm, col="r_generated"): + c = self.contrast + c = c[(c.arm == arm) & (c.statistic == "mean_cp10k") & (c.celltype.isin(CELLTYPES))] + assert set(c.celltype) == set(CELLTYPES), (self.path, arm) + return float(c[col].mean()) + + def deg(self, arm, col="top50_overlap"): + d = self.contrast + d = d[(d.arm == arm) & (d.statistic == "welch_top50_deg")] + assert len(d) == 5, (self.path, arm, len(d)) # T/B/Mono/NK/DC + return float(d[col].sum()) + + def deg_type(self, arm, ct, col="top50_overlap"): + d = self.contrast + d = d[(d.arm == arm) & (d.statistic == "welch_top50_deg") & (d.celltype == ct)] + assert len(d) == 1, (self.path, arm, ct, len(d)) + return float(d[col].iloc[0]) + + def frac_r(self, arm, ct): + d = self.per_donor[self.per_donor.arm == arm] + return float(np.corrcoef(d[f"gen_{ct}"].astype(float), d[f"obs_{ct}"].astype(float))[0, 1]) + + +def load(): + calls = {ds: Call(PLAN / "scores" / ds / "pooled") for ds in DSETS} + deg_call = Call(PLAN / "scores" / "ye2026_sepsis" / "pooled_deg") + for ds, c in calls.items(): + for a in LORA_ARMS + [ZS, ZS_CAL, "zs__pseudo"]: + assert a in c.summary["arms"], (ds, a) + assert c.summary["per_arm"][a].get("receipt_verified", True) is not False, (ds, a) + # headline composition L1 equals the donor mean of per_donor.csv + assert close(c.per_donor.loc[c.per_donor.arm == a, "comp_l1"].mean(), c.head(a, "comp_l1"), 1e-9), a + # headline contrast means equal the per-type mean of contrast.csv + se = calls["ye2026_sepsis"] + for a in LORA_ARMS + [ZS, ZS_CAL, "zs__pseudo"]: + assert close(se.contrast_r(a), se.head(a, "contrast_mean_cp10k_r_gen"), 1e-9), a + assert close(deg_call.deg(a), deg_call.head(a, "deg_top50_sum"), 1e-9), a + # broadcast is the same for every arm conditioned on raw real bulk + bc = {a: se.contrast_r(a, "r_broadcast") for a in RAW_ARMS} + assert max(bc.values()) - min(bc.values()) < 1e-12, bc + bcd = {a: deg_call.deg(a, "top50_overlap_broadcast") for a in RAW_ARMS} + assert len(set(bcd.values())) == 1, bcd + assert close(bcd["real_lora__raw"], deg_call.head("real_lora__raw", "deg_top50_sum_broadcast"), 1e-9) + # non-DEG metrics agree between the two sepsis scoring calls (k-NN ties allow 1e-3) + for a in LORA_ARMS + [ZS, ZS_CAL]: + for k in ("comp_l1", "coverage"): + assert abs(se.head(a, k) - deg_call.head(a, k)) <= 1e-3, (a, k) + lens = {ds: Call(PLAN / "scores" / ds / LEN_SUB) for ds in DSETS} + for ds, lc in lens.items(): + c = calls[ds] + assert ZS_LEN in lc.summary["arms"] and ZS in lc.summary["arms"], (ds, lc.summary["arms"]) + assert int(lc.summary["n_donors"]) == int(c.summary["n_donors"]), ds + assert lc.summary["reference"]["reference_sha256"] == c.summary["reference"]["reference_sha256"], ds + for k in ("comp_l1", "coverage", "precision"): # the raw arm reproduces in the new call (k-NN ties: 1e-3) + assert abs(lc.head(ZS, k) - c.head(ZS, k)) <= 1e-3, (ds, k, lc.head(ZS, k), c.head(ZS, k)) + assert close(lens["ye2026_sepsis"].contrast_r(ZS), se.contrast_r(ZS), 1e-9) + assert close(lens["ye2026_sepsis"].deg(ZS), deg_call.deg(ZS), 1e-9), (lens["ye2026_sepsis"].deg(ZS), deg_call.deg(ZS)) + return calls, deg_call, lens + + +def find_cal_budget(calls, deg_call): + """Scan the scores folder for equal-budget calibration arms (see module docstring). + + Returns (budget, log): budget[ds][n] = dict(arm, calls=[Call, ...]) for drawable arms (pooled call first, then + other calls over the same donors; the sepsis DEG call first for DEG); log = one dict per matching arm found.""" + budget, log = {ds: {} for ds in DSETS}, [] + cache = {c.path: c for c in list(calls.values()) + [deg_call]} + for ds in DSETS: + root = PLAN / "scores" / ds + pooled = calls[ds] + donors = set(pooled.per_donor.donor) + cands = {} + for sp in sorted(root.rglob("summary.json")): + rel = sp.relative_to(root) + if "arms" in rel.parts: + continue + try: + arms = json.loads(sp.read_text()).get("arms") or [] + except (OSError, ValueError): + continue + for a in arms: + m = CAL_N_RE.search(a) + if "cal" not in a.lower() or m is None or any(t in a.lower() for t in FT_TAGS): + continue + n = int(m.group(1)) + if sp.parent not in cache: + try: + cache[sp.parent] = Call(sp.parent) + except (OSError, ValueError) as e: + log.append(dict(dataset=ds, call=str(rel.parent), arm=a, n=n, drawn=False, + note=f"not drawn: cannot read the call ({e.__class__.__name__})")) + continue + call = cache[sp.parent] + same = set(call.per_donor.loc[call.per_donor.arm == a, "donor"]) == donors + ok = same and n in LC_N + why = ("drawn" if ok else "not drawn: " + ("n not in " + str(LC_N) if same else + "call does not score the pooled donor set")) + log.append(dict(dataset=ds, call=str(rel.parent), arm=a, n=n, drawn=ok, note=why)) + if ok: + cands.setdefault(n, []).append((a, call)) + for n, lst in cands.items(): + names = sorted({a for a, _ in lst}) + if len(names) > 1: + pref = sorted({a for a, c in lst if c is pooled}) + if len(pref) != 1: + sys.exit(f"{ds}: several equal-budget calibration arms for n = {n}: {names}; pick one") + names = pref + arm = names[0] + cl = [c for a, c in lst if a == arm] + cl.sort(key=lambda c: (c is not pooled, c is not deg_call, str(c.path))) + for c in cl: # a call other than the pooled one must reproduce shared arms (k-NN ties allow 1e-3) + if c is pooled: + continue + for shared in (ZS_CAL, "real_lora__raw"): + if shared in c.summary["arms"]: + for k in ("comp_l1", "coverage"): + assert abs(c.head(shared, k) - pooled.head(shared, k)) <= 1e-3, (c.path, shared, k) + budget[ds][n] = dict(arm=arm, calls=cl) + return budget, log + + +def find_scsemi(calls): + """scSemiProfiler at n = 5..40 (equal-budget arms) and "all" (5-fold CV arm), see module docstring. + + Returns (scs, log): scs[ds][pairs label] = dict(arm, calls=[Call, ...]) for accepted calls; log = one dict per + arm found (accepted or not).""" + scs, log = {ds: {} for ds in DSETS}, [] + for ds in DSETS: + ref = calls[ds].summary + found = [(str(n), a, d) for n, lst in sorted(SR.budget_calls(ds).items()) for a, d in lst] + found += [("all", SR.CV_ARM, d) for d in SR.cv_calls(ds)] + for lab, a, d in found: + try: + c = Call(d) + except (OSError, ValueError) as e: + log.append(dict(dataset=ds, call=str(d), arm=a, pairs=lab, drawn=False, + note=f"not drawn: cannot read the call ({e.__class__.__name__})")) + continue + why = SR.accept(c.summary, ref, a) + if lab not in X_LAB[1:]: + why.append(f"n {lab} not in {X_LAB[1:]}") + ent = scs[ds].get(lab) + if ent is not None and ent["arm"] != a: + why.append(f"a different arm ({ent['arm']}) already gives n = {lab}") + log.append(dict(dataset=ds, call=str(d), arm=a, pairs=lab, drawn=not why, + note="drawn" if not why else "not drawn: " + "; ".join(why))) + if not why: + scs[ds].setdefault(lab, dict(arm=a, calls=[]))["calls"].append(c) + return scs, log + + +def scsemi_series(scs, ds, getter): + """[(pairs label, value, source)] of the scSemiProfiler line for one panel ([] when nothing is found).""" + out = [] + for lab in X_LAB[1:]: + if lab in scs[ds]: + v, c = budget_value(scs[ds][lab], getter) + if v is not None: + out.append((lab, v, f"{c.path} arm {scs[ds][lab]['arm']}")) + return out + + +def budget_value(entry, getter): + """First call of a budget entry that provides the metric (None if no call does).""" + for c in entry["calls"]: + try: + return getter(c, entry["arm"]), c + except (AssertionError, KeyError, TypeError, AttributeError): + continue + return None, None + + +def load_steps(): + rows = [] + for ds in DSETS: + for k in range(5): + for arm in RUN_ARMS: + p = PLAN / "runs" / ds / f"fold{k}" / arm / "RUN.json" + r = json.loads(p.read_text()) + assert r["source_checkpoint"] == FINAL_CKPT, (p, r["source_checkpoint"]) + assert r["mode"] == "lora", p + assert r["inner_val_rows"], p # every LoRA run early-stops on paired inner-val donors + hist = json.loads((p.parent / "history.json").read_text()) + h = {int(e["step"]): float(e["inner_val_loss"]) for e in hist} + # cap-limited = ran to max_steps without the patience window closing + cap_limited = (r["steps_run"] >= r["max_steps"] + and r["steps_run"] - r["selected_step"] < r["patience"] * r["eval_every"]) + last = max(h) + win = r["patience"] * r["eval_every"] # last patience window (2,000 steps) + drop_total = h[0] - h[last] + drop_last = h[last - win] - h[last] + rows.append({"dataset": ds, "fold": k, "arm": arm, "n_train": len(r["train_rows"]), + "n_inner_val": len(r["inner_val_rows"]), "selected_step": r["selected_step"], + "max_steps": r["max_steps"], "steps_run": r["steps_run"], + "patience_steps": win, "cap_limited": bool(cap_limited), + "val_loss_step0": h[0], "val_loss_last": h[last], + "val_loss_last_window_drop_frac": drop_last / drop_total, + "wall_seconds": r.get("wall_seconds"), "source": str(p), + "history": str(p.parent / "history.json")}) + st = pd.DataFrame(rows) + # nested subsets: n_train equals the arm size for lora_n* + for n in LC_N: + assert (st[st.arm == f"lora_n{n}"].n_train == n).all(), n + return st + + +def load_fold_sizes(): + """Test donors per fold (PREPARE.json); their sum must equal the donors in the pooled scoring call. + alpha = paired donors the zs__cal alpha is fitted on per fold (train + inner-val).""" + out = {} + for ds in DSETS: + p = PLAN / "data" / ds / "PREPARE.json" + fs = json.loads(p.read_text())["fold_sizes"] + out[ds] = dict(test=[int(v["test"]) for v in fs.values()], + alpha=[int(v["train"]) + int(v["inner_val"]) for v in fs.values()], source=str(p)) + return out + + +def load_fewshot(): + """Few-pair call (5 draws): zero-shot + calibration with alpha from the same 5 pairs vs LoRA on those 5 pairs + (fixed 3k steps, no inner-val). Its own donor set, so it is only quoted in the notes, never drawn.""" + out = {} + for ds in DSETS: + p = PLAN / "scores" / ds / "fewshot_n5" / "aggregate.json" + a = json.loads(p.read_text())["arms"] + out[ds] = dict(zs_cal=float(a["zs_cal"]["coverage"][0]), lora5=float(a["lora5"]["coverage"][0]), + source=str(p)) + return out + + +def rng_txt(v): + v = sorted(int(x) for x in v) + return f"{v[0]}" if v[0] == v[-1] else f"{v[0]}–{v[-1]}" + + +def break_axis(ax, v0, lo, hi, x_txt=X_RAW, extra=()): + """Shrink ax to lo..hi and add a short segment above it that shows v0 at the same data scale. + extra: further break values (2026-10-02, two zero-shot points at x = 0). When they do not fit at the main scale, + the segment gets its own scale and a tick at each value.""" + p = ax.get_position() + h_top, gap = 0.22 * p.height, 0.08 * p.height + h_main = p.height - h_top - gap + ax.set_position([p.x0, p.y0, p.width, h_main]) + ax.set_ylim(lo, hi) + half = (hi - lo) * h_top / h_main / 2 + top = ax.figure.add_axes([p.x0, p.y0 + h_main + gap, p.width, h_top], sharex=ax) + vals = [v0] + list(extra) + if max(vals) - min(vals) > 1.6 * half: # own scale: ticks at the values + spread = max(vals) - min(vals) + top.set_ylim(min(vals) - 0.35 * spread, max(vals) + 0.35 * spread) + top.set_yticks(sorted(round(v, 2) for v in vals)) + top.spines["bottom"].set_visible(False) + top.tick_params(axis="x", bottom=False, labelbottom=False) + mk = dict(marker=[(-1, -0.5), (1, 0.5)], markersize=10, ls="none", color=style.INK, mec=style.INK, mew=1.2, + clip_on=False) + top.plot([0], [0], transform=top.transAxes, **mk) + ax.plot([0], [1], transform=ax.transAxes, **mk) + return top + v0 = (max(vals) + min(vals)) / 2 + top.set_ylim(v0 - half, v0 + half) + # one tick in the short segment: the nearest value on the main axis' tick grid that fits inside it + step = float(np.diff(ax.get_yticks()[:2])[0]) / 2 + tick = round(round(v0 / step) * step, 10) + top.set_yticks([tick] if abs(tick - v0) < half else []) + if not len(top.get_yticks()): # no grid value fits: print the value next to the point instead + top.text(x_txt + 0.3, v0, f"{v0:.2f}", va="center", ha="left", fontsize=12) + top.spines["bottom"].set_visible(False) + top.tick_params(axis="x", bottom=False, labelbottom=False) + mk = dict(marker=[(-1, -0.5), (1, 0.5)], markersize=10, ls="none", color=style.INK, mec=style.INK, mew=1.2, + clip_on=False) + top.plot([0], [0], transform=top.transAxes, **mk) + ax.plot([0], [1], transform=ax.transAxes, **mk) + return top + + +def curve(ax, z0, vl, refs, rows, panel, ds, srcl, ylim0=None, vb=None, vs=None): + """Zero-shot points at x = 0 (z0: [(series, value, source)] for raw and calibrated), LoRA curve at 5..all, + optional equal-budget calibration line (vb: [(pairs label, value, source)]), reference lines. + Returns the axis that carries the panel title.""" + vb = vb or [] + vs = vs or [] # scSemiProfiler line (n = 5..all) + lo, hi = min(vl), max(vl) + for _, val, _ in list(refs) + [(None, v, None) for _, v, _ in vb + vs]: + lo, hi = min(lo, val), max(hi, val) + span = hi - lo + # a zero-shot point goes to the break segment when it sits > BREAK_RATIO spans beyond everything else + out = {ser for ser, v, _ in z0 + if ylim0 is None and span > 0 and (v - hi > BREAK_RATIO * span or lo - v > BREAK_RATIO * span)} + for ser, v, _ in z0: + if ser in out: + assert v > hi, (panel, ds, ser, "axis break below the curve is not implemented") + else: + lo, hi = min(lo, v), max(hi, v) + broken = bool(out) + pad = (hi - lo) * 0.15 + axes = [ax] + xz = {"zero_shot": X_RAW, "zs_len": X_CAL} + if broken: + zb = [z for z in z0 if z[0] in out] + top = break_axis(ax, zb[0][1], lo - pad, hi + pad, xz[zb[0][0]], extra=[v for _, v, _ in zb[1:]]) + axes.append(top) + else: + ax.set_ylim(ylim0 if ylim0 is not None else lo - pad, hi + pad) + for ser, v, src in z0: + a = axes[-1] if ser in out else ax + if ser == "zero_shot": + a.scatter([X_RAW], [v], s=70, color=COL_RAW, edgecolor=RAW_EDGE, lw=1.0, zorder=5, clip_on=False) + else: + a.scatter([X_CAL], [v], s=70, color=COL_LEN, edgecolor=style.INK, lw=0.6, zorder=5, clip_on=False) + rows.append(dict(panel=panel, dataset=ds, series=ser, pairs=X_LAB[0], value=v, source=src, + y_axis_break=bool(broken))) + if vb: + xb = [X_POS[X_LAB.index(lab)] for lab, _, _ in vb] + ax.plot(xb, [v for _, v, _ in vb], color=COL_CAL, lw=1.8, zorder=3) + ax.scatter(xb, [v for _, v, _ in vb], s=60, marker="s", color=COL_CAL, edgecolor=style.INK, lw=0.6, + zorder=5) + for lab, v, src in vb: + rows.append(dict(panel=panel, dataset=ds, series="zs_cal_budget", pairs=lab, value=v, source=src, + y_axis_break=bool(broken))) + if vs: + xs = [X_POS[X_LAB.index(lab)] for lab, _, _ in vs] + ax.plot(xs, [v for _, v, _ in vs], color=COL_SC, lw=1.8, zorder=3) + ax.scatter(xs, [v for _, v, _ in vs], s=55, marker="D", color=COL_SC, edgecolor=style.INK, lw=0.6, zorder=5) + for lab, v, src in vs: + rows.append(dict(panel=panel, dataset=ds, series="scsemi", pairs=lab, value=v, source=src, + y_axis_break=bool(broken))) + ax.plot(X_POS[1:], vl, color=style.ARM["lora"], lw=2.0, zorder=3) + ax.scatter(X_POS[1:], vl, s=70, color=style.ARM["lora"], edgecolor=style.INK, lw=0.6, zorder=5) + for lab, v, s in zip(X_LAB[1:], vl, srcl): + rows.append(dict(panel=panel, dataset=ds, series="lora", pairs=lab, value=v, source=s, + y_axis_break=bool(broken))) + for key, val, src in refs: + r = REF[key] + for a in axes: + a.axhline(val, ls=r["ls"], color=r["color"], lw=r["lw"], zorder=2) + rows.append(dict(panel=panel, dataset=ds, series=f"ref_{key}", pairs="", value=val, source=src, + y_axis_break=bool(broken))) + ax.set_xlim(*XLIM) + ax.set_xticks(X_POS) + ax.set_xticklabels(xticks(ds)) + # nothing is clipped: every plotted value is inside the y range of the axis that draws it + for v in list(vl) + [val for _, val, _ in refs] + [v for _, v, _ in vb + vs] + [v for ser, v, _ in z0 + if ser not in out]: + assert ax.get_ylim()[0] <= v <= ax.get_ylim()[1], (panel, ds, v, ax.get_ylim()) + for ser, v, _ in z0: + if ser in out: + assert axes[-1].get_ylim()[0] <= v <= axes[-1].get_ylim()[1], (panel, ds, ser, v) + return axes[-1] + + +def budget_series(budget, ds, getter, cal_all, src_all): + """Equal-budget calibration line for one panel: [(pairs label, value, source)] at n = 5..40 (where present) + plus "all" = zs__cal (alpha from the same train + inner-val pairs LoRA "all" saw). [] when nothing is found.""" + out = [] + for n in LC_N: + if n not in budget[ds]: + continue + v, c = budget_value(budget[ds][n], getter) + if v is not None: + out.append((str(n), v, f"{c.path} arm {budget[ds][n]['arm']}")) + if out: + out.append(("all", cal_all, src_all + " arm zs__cal (alpha from every training pair of the fold = the rightmost LoRA point's pairs)")) + return out + + +def fig_realism(calls, lens, st, fold_sizes, rows, steprows, budget, scs): + has_budget = any(budget[ds] for ds in DSETS) + has_sc = any(scs[ds] for ds in DSETS) + n_leg = 6 + has_budget + has_sc + fig, axs = plt.subplots(2, 3, figsize=style.FULL, # a third legend row when an optional line is drawn + gridspec_kw=dict(left=0.168, right=0.99, top=0.79 if n_leg > 6 else 0.83, + bottom=0.12, hspace=0.36, wspace=0.30)) + heads = ["Composition L1 ↓", "Coverage ↑", "Selected step (×1,000)"] + pos0 = {ri: axs[ri, 2].get_position() for ri in range(len(DSETS))} # row extents before any y-axis break + title_ax = {ci: axs[0, ci] for ci in range(3)} + for ri, ds in enumerate(DSETS): + c = calls[ds] + for ci, key in enumerate(["comp_l1", "coverage"]): + ax = axs[ri, ci] + refs = [("pseudo", c.head("zs__pseudo", key), c.src_summary)] + if key == "comp_l1": + refs.append(("null", c.head("real_lora__raw", "comp_l1_obs_loo_null"), c.src_summary)) + z0 = [("zero_shot", c.head(ZS, key), c.src_summary), + ("zs_len", lens[ds].head(ZS_LEN, key), lens[ds].src_summary)] + vb = budget_series(budget, ds, lambda cc, a, k=key: cc.head(a, k), c.head(ZS_CAL, key), c.src_summary) + vs = scsemi_series(scs, ds, lambda cc, a, k=key: cc.head(a, k)) + tax = curve(ax, z0, [c.head(a, key) for a in LORA_ARMS], refs, rows, + f"{key}", ds, [c.src_summary] * 5, vb=vb, vs=vs) + if ri == 0: + title_ax[ci] = tax + # selected early-stopping step per fold + ax = axs[ri, 2] + s = st[st.dataset == ds] + for xi, arm in zip(X_POS[1:], RUN_ARMS): + f = s[s.arm == arm].sort_values("fold") + v = f.selected_step.astype(float).values / 1000 + jit = np.linspace(-0.22, 0.22, len(v)) + ax.scatter(xi + jit, v, s=36, color=style.ARM["lora"], edgecolor=style.INK, lw=0.5, zorder=4) + med = float(np.median(v)) + ax.plot([xi - 0.36, xi + 0.36], [med, med], color=style.INK, lw=2.0, zorder=5) + steprows.append(dict(dataset=ds, arm=arm, pairs=X_LAB[X_POS.index(xi)], median_step=med * 1000, + min_step=v.min() * 1000, max_step=v.max() * 1000, + n_cap_limited=int(f.cap_limited.sum()), + max_last_window_drop_frac=(float(f[f.cap_limited].val_loss_last_window_drop_frac.max()) + if f.cap_limited.any() else np.nan), + n_train=rng_txt(f.n_train), n_inner_val=rng_txt(f.n_inner_val), + source=";".join(f.source))) + cap = float(s.max_steps.max()) / 1000 + ax.axhline(cap, color=style.GREY, lw=1.0, ls=(0, (2, 2)), zorder=1) + ax.text(X_POS[0] - 0.4, cap + 0.6, f"cap {cap:g}k", color=style.GREY, fontsize=12, va="bottom") + ax.text(X_POS[0], cap * 0.45, "no training", color=style.GREY, fontsize=12, ha="center", + va="center", rotation=90) + ax.set_ylim(0, cap * 1.18) + ax.set_xlim(-0.5, X_POS[-1] + 0.5) + ax.set_xticks(X_POS) + ax.set_xticklabels(xticks(ds)) + n_all = rng_txt(s[s.arm == "real_lora"].n_train) + n_iv = rng_txt(s.n_inner_val) + n_scored = int(c.summary["n_donors"]) + assert n_scored == sum(fold_sizes[ds]["test"]), (ds, n_scored, fold_sizes[ds]["test"]) + n_alpha = rng_txt(fold_sizes[ds]["alpha"]) + # zs__cal alpha uses the same donors LoRA "all" trains and early-stops on (train + inner-val) + lora_all_seen = sorted(int(a) + int(b) for a, b in zip(s[s.arm == "real_lora"].sort_values("fold").n_train, + s[s.arm == "real_lora"].sort_values("fold").n_inner_val)) + assert lora_all_seen == sorted(fold_sizes[ds]["alpha"]), (ds, lora_all_seen, fold_sizes[ds]["alpha"]) + ymid = (pos0[ri].y0 + pos0[ri].y1) / 2 + fig.text(0.005, ymid + 0.075, DS_LABEL[ds], fontsize=15, fontweight="bold", va="bottom", ha="left") + fig.text(0.005, ymid + 0.065, + f"{n_scored} donors\ninner-val = {n_iv}\ntest fold\nnever trained on", + fontsize=12.5, va="top", ha="left", linespacing=1.35) + rows.append(dict(panel="meta", dataset=ds, series="n_scored_donors", pairs="", value=n_scored, + source=c.src_summary)) + rows.append(dict(panel="meta", dataset=ds, series="n_pairs_all", pairs="all", value=n_all, + source="RUN.json train_rows: " + ";".join(s[s.arm == "real_lora"].source))) + rows.append(dict(panel="meta", dataset=ds, series="n_inner_val", pairs="", value=n_iv, + source="RUN.json inner_val_rows (all LoRA arms, 5 folds)")) + rows.append(dict(panel="meta", dataset=ds, series="n_test_donors_per_fold", pairs="", + value="/".join(map(str, fold_sizes[ds]["test"])), + source=fold_sizes[ds]["source"] + " fold_sizes test")) + rows.append(dict(panel="meta", dataset=ds, series="n_alpha_fit_pairs", pairs="0", value=n_alpha, + source=fold_sizes[ds]["source"] + " fold_sizes train+inner_val; prepare_dataset.py " + "fit = fold != f")) + for ci, h in enumerate(heads): + title_ax[ci].set_title(h, fontsize=14, pad=8) + x0, x1 = axs[1, 0].get_position().x0, axs[1, 2].get_position().x1 + fig.text((x0 + x1) / 2, 0.005, xlabel(st), ha="center", va="bottom", fontsize=14) + handles = [ # column-wise fill: [raw, cal, (equal-budget cal)] | [LoRA, (scSemi), median] | [pseudo, null] + h_raw(), h_len()] + ([h_budget()] if has_budget else []) + ([h_scsemi()] if has_sc else []) + [ + Line2D([0], [0], marker="o", color=style.ARM["lora"], lw=2.0, markeredgecolor=style.INK, markersize=8, + label="LoRA fine-tune (dots in step panel = folds)"), + Line2D([0], [0], color=style.INK, lw=2.0, label="Median of 5 folds"), + Line2D([0], [0], ls=REF["pseudo"]["ls"], color=REF["pseudo"]["color"], lw=REF["pseudo"]["lw"], + label=REF["pseudo"]["label"]), + Line2D([0], [0], ls=REF["null"]["ls"], color=REF["null"]["color"], lw=REF["null"]["lw"], + label=REF["null"]["label"]), + ] + fig.legend(handles=handles, loc="upper left", bbox_to_anchor=(0.005, 1.0), ncol=3, frameon=False, + fontsize=12, handlelength=2.4, columnspacing=1.6, labelspacing=0.4, borderaxespad=0.0) + style.save(fig, "sec08_pairs_realism", FIGDIR) + + +def h_raw(): + return Line2D([0], [0], marker="o", color=COL_RAW, lw=0, markeredgecolor=RAW_EDGE, markersize=8, label=LEG_ZS) + + +def h_len(): + return Line2D([0], [0], marker="o", color=COL_LEN, lw=0, markeredgecolor=style.INK, markersize=8, label=LEG_LEN) + + +def h_scsemi(): + return Line2D([0], [0], marker="D", color=COL_SC, lw=1.8, markeredgecolor=style.INK, markersize=7, label=LEG_SC) + + +def h_budget(): + return Line2D([0], [0], marker="s", color=COL_CAL, lw=1.8, markeredgecolor=style.INK, markersize=7, + label=LEG_CAL_N) + + +def fig_signal(calls, deg_call, lens, st, rows, budget, scs): + has_budget = any(budget[ds] for ds in DSETS) + has_sc = any(scs[ds] for ds in DSETS) + leg_rows = -(-(5 + has_budget + has_sc) // 2) + fig, axs = plt.subplots(1, 3, figsize=style.TALL, + gridspec_kw=dict(left=0.085, right=0.99, top=0.755 - 0.055 * (leg_rows - 3), bottom=0.115, + wspace=0.42)) # 3 legend rows (4 with both optional lines) + im, se = calls["immicro"], calls["ye2026_sepsis"] + iml, sel = lens["immicro"], lens["ye2026_sepsis"] + tax = [None] * 3 + # a: ImMicro across-donor NK fraction r + tax[0] = curve(axs[0], [("zero_shot", im.frac_r(ZS, "NK cell"), im.src_per_donor), + ("zs_len", iml.frac_r(ZS_LEN, "NK cell"), iml.src_per_donor)], + [im.frac_r(a, "NK cell") for a in LORA_ARMS], + [("pseudo", im.frac_r("zs__pseudo", "NK cell"), im.src_per_donor)], rows, "nk_fraction_r", + "immicro", [im.src_per_donor] * 5, + vb=budget_series(budget, "immicro", lambda cc, a: cc.frac_r(a, "NK cell"), + im.frac_r(ZS_CAL, "NK cell"), im.src_per_donor), + vs=scsemi_series(scs, "immicro", lambda cc, a: cc.frac_r(a, "NK cell"))) + # other cell types, recorded for the footnote ("0+cal" = zero-shot + calibration) + for ct in ["T cell", "B cell", "Monocyte"]: + for a, lab in zip([ZS, ZS_CAL] + LORA_ARMS, ["0", "0+cal"] + X_LAB[1:]): + rows.append(dict(panel="other_fraction_r", dataset="immicro", series=ct, pairs=lab, + value=im.frac_r(a, ct), source=im.src_per_donor)) + # b: sepsis disease logFC r (mean of T/B/Mono/NK, mean_cp10k) + tax[1] = curve(axs[1], [("zero_shot", se.contrast_r(ZS), se.src_contrast), + ("zs_len", sel.contrast_r(ZS_LEN), sel.src_contrast)], + [se.contrast_r(a) for a in LORA_ARMS], + [("pseudo", se.contrast_r("zs__pseudo"), se.src_contrast), + ("broadcast", se.contrast_r("real_lora__raw", "r_broadcast"), se.src_contrast)], + rows, "logfc_r", "ye2026_sepsis", [se.src_contrast] * 5, + vb=budget_series(budget, "ye2026_sepsis", lambda cc, a: cc.contrast_r(a), + se.contrast_r(ZS_CAL), se.src_contrast), + vs=scsemi_series(scs, "ye2026_sepsis", lambda cc, a: cc.contrast_r(a))) + # c: sepsis top-50 DEG (Welch, sum over T/B/Mono/NK/DC) + tax[2] = curve(axs[2], [("zero_shot", deg_call.deg(ZS), deg_call.src_contrast), + ("zs_len", sel.deg(ZS_LEN), sel.src_contrast)], + [deg_call.deg(a) for a in LORA_ARMS], + [("pseudo", deg_call.deg("zs__pseudo"), deg_call.src_contrast), + ("broadcast", deg_call.deg("real_lora__raw", "top50_overlap_broadcast"), deg_call.src_contrast)], + rows, "top50_deg", "ye2026_sepsis", [deg_call.src_contrast] * 5, ylim0=0, + vb=budget_series(budget, "ye2026_sepsis", lambda cc, a: cc.deg(a), + deg_call.deg(ZS_CAL), deg_call.src_contrast), + vs=scsemi_series(scs, "ye2026_sepsis", lambda cc, a: cc.deg(a))) + # top-50 DEG overlap per cell type (footnote: which types carry the gain), incl. broadcast + for ct in DEG_TYPES: + for a, lab in zip([ZS, ZS_CAL] + LORA_ARMS + ["zs__pseudo"], ["0", "0+cal"] + X_LAB[1:] + ["pseudo"]): + rows.append(dict(panel="top50_deg_by_type", dataset="ye2026_sepsis", series=ct, pairs=lab, + value=deg_call.deg_type(a, ct), source=deg_call.src_contrast)) + rows.append(dict(panel="top50_deg_by_type", dataset="ye2026_sepsis", series=ct, pairs="broadcast", + value=deg_call.deg_type("real_lora__raw", ct, "top50_overlap_broadcast"), + source=deg_call.src_contrast)) + cd = se.summary["contrast_definition"] + grp = f"Sepsis {cd['n_case_donors']} vs {cd['n_control_donors']}" + heads = [f"ImMicro, {int(im.summary['n_donors'])} donors\ndonor NK fraction r", + f"{grp}\ndisease logFC r", f"{grp}\ntop-50 DEG overlap"] + for ax, h in zip(tax, heads): + ax.set_title(h, fontsize=14, pad=8, linespacing=1.3) + x0, x1 = axs[0].get_position().x0, axs[2].get_position().x1 + fig.text((x0 + x1) / 2, 0.005, xlabel(st), ha="center", va="bottom", fontsize=13) + rows.append(dict(panel="meta", dataset="ye2026_sepsis", series="n_case_vs_control", pairs="", + value=f"{se.summary['contrast_definition']['n_case_donors']} vs " + f"{se.summary['contrast_definition']['n_control_donors']}", source=se.src_summary)) + handles = [ # column-wise fill: [raw, cal, pseudo, ...] | [LoRA, (equal-budget cal), (scSemi), broadcast] + h_raw(), h_len(), + Line2D([0], [0], ls=REF["pseudo"]["ls"], color=REF["pseudo"]["color"], lw=REF["pseudo"]["lw"], + label=REF["pseudo"]["label"]), + Line2D([0], [0], marker="o", color=style.ARM["lora"], lw=2.0, markeredgecolor=style.INK, markersize=8, + label="LoRA fine-tune"), + ] + ([h_budget()] if has_budget else []) + ([h_scsemi()] if has_sc else []) + [ + Line2D([0], [0], ls=REF["broadcast"]["ls"], color=REF["broadcast"]["color"], lw=REF["broadcast"]["lw"], + label=REF["broadcast"]["label"]), + ] + fig.legend(handles=handles, loc="upper left", bbox_to_anchor=(0.005, 1.0), ncol=2, frameon=False, + fontsize=12, handlelength=2.4, columnspacing=1.2, labelspacing=0.4, borderaxespad=0.0) + style.save(fig, "sec08_pairs_signal", FIGDIR) + + +def slide_numbers(calls, deg_call, st, fold_sizes, fewshot, budget, budget_log, scs=None, sc_log=(), lens=None): + """Numbers quoted in the slide keywords/footnote, each with its source file.""" + im, se = calls["immicro"], calls["ye2026_sepsis"] + out = [] + + def add(key, value, src): + out.append(dict(key=key, value=value, source=src)) + + for ds, c in calls.items(): + for key in ("coverage", "comp_l1"): + add(f"{ds}.{key}.zero_shot", round(c.head(ZS, key), 3), c.src_summary) + add(f"{ds}.{key}.zs_cal", round(c.head(ZS_CAL, key), 3), c.src_summary) + if lens: + add(f"{ds}.{key}.zs_len", round(lens[ds].head(ZS_LEN, key), 3), lens[ds].src_summary) + add(f"{ds}.{key}.lora_n5", round(c.head("lora_n5__raw", key), 3), c.src_summary) + add(f"{ds}.{key}.lora_all", round(c.head("real_lora__raw", key), 3), c.src_summary) + add(f"{ds}.{key}.zs_pseudo", round(c.head("zs__pseudo", key), 3), c.src_summary) + add(f"{ds}.comp_l1.null", round(c.head("real_lora__raw", "comp_l1_obs_loo_null"), 3), c.src_summary) + # donor-level composition L1, each LoRA size vs zero-shot (paired Wilcoxon, uncorrected) + piv = c.per_donor.pivot(index="donor", columns="arm", values="comp_l1") + for a, lab in zip(LORA_ARMS, X_LAB[1:]): + x = (piv[a] - piv[ZS]).dropna() + add(f"{ds}.comp_l1.lora_{lab}_minus_zero_shot.mean", round(float(x.mean()), 3), c.src_per_donor) + add(f"{ds}.comp_l1.lora_{lab}_minus_zero_shot.frac_donors_lower", round(float((x < 0).mean()), 2), + c.src_per_donor) + add(f"{ds}.comp_l1.lora_{lab}_vs_zero_shot.wilcoxon_p", float(f"{wilcoxon(x).pvalue:.2g}"), + c.src_per_donor) + # each LoRA size vs zero-shot + calibration (donor L1 and donor coverage; paired Wilcoxon, uncorrected) + for met in ("comp_l1", "coverage"): + pv = c.per_donor.pivot(index="donor", columns="arm", values=met) + for a, lab in zip(LORA_ARMS, X_LAB[1:]): + x = (pv[a] - pv[ZS_CAL]).dropna() + add(f"{ds}.{met}.lora_{lab}_minus_zs_cal.mean", round(float(x.mean()), 3), c.src_per_donor) + add(f"{ds}.{met}.lora_{lab}_minus_zs_cal.frac_donors_lower", round(float((x < 0).mean()), 2), + c.src_per_donor) + add(f"{ds}.{met}.lora_{lab}_vs_zs_cal.wilcoxon_p", float(f"{wilcoxon(x).pvalue:.2g}"), + c.src_per_donor) + # the raw -> calibrated zero-shot gap + x = (pv[ZS_CAL] - pv[ZS]).dropna() + add(f"{ds}.{met}.zs_cal_minus_zero_shot.mean", round(float(x.mean()), 3), c.src_per_donor) + add(f"{ds}.{met}.zs_cal_vs_zero_shot.wilcoxon_p", float(f"{wilcoxon(x).pvalue:.2g}"), c.src_per_donor) + add(f"{ds}.cal_alpha_fit_pairs", rng_txt(fold_sizes[ds]["alpha"]), + fold_sizes[ds]["source"] + " fold_sizes train+inner_val; tools/prepare_dataset.py fit = fold != f") + # few-pair call (its own donors): alpha from the same 5 pairs vs LoRA on them (fixed 3k steps, no inner-val) + add(f"{ds}.fewshot_n5.coverage.zs_cal_same5", round(fewshot[ds]["zs_cal"], 3), fewshot[ds]["source"]) + add(f"{ds}.fewshot_n5.coverage.lora5_fixed3k", round(fewshot[ds]["lora5"], 3), fewshot[ds]["source"]) + add(f"{ds}.n_scored_donors", int(c.summary["n_donors"]), c.src_summary) + s = st[st.dataset == ds] + add(f"{ds}.selected_step.lora_n5.range", rng_txt(s[s.arm == "lora_n5"].selected_step), "RUN.json: " + + ";".join(s[s.arm == "lora_n5"].source)) + add(f"{ds}.n_train.all", rng_txt(s[s.arm == "real_lora"].n_train), "RUN.json: " + + ";".join(s[s.arm == "real_lora"].source)) + add(f"{ds}.n_inner_val", rng_txt(s.n_inner_val), "RUN.json inner_val_rows (all LoRA arms, 5 folds)") + for arm in RUN_ARMS: + f = s[s.arm == arm] + add(f"{ds}.folds_cap_limited.{arm}", f"{int(f.cap_limited.sum())}/{len(f)}", + "RUN.json steps_run == max_steps and steps_run - selected_step < patience*eval_every: " + + ";".join(f.source)) + capped = s[s.cap_limited] + if len(capped): + add(f"{ds}.cap_limited.max_val_loss_drop_frac_last_2k_steps", + round(float(capped.val_loss_last_window_drop_frac.max()), 4), + "history.json inner_val_loss (drop over last patience window / drop from step 0): " + + ";".join(capped.history)) + for a, lab in zip([ZS, ZS_CAL] + LORA_ARMS + ["zs__pseudo"], KEY_LAB[:1] + ["zs_cal"] + KEY_LAB[1:] + ["pseudo"]): + add(f"immicro.nk_fraction_r.{lab}", round(im.frac_r(a, "NK cell"), 2), im.src_per_donor) + add(f"sepsis.logfc_r.{lab}", round(se.contrast_r(a), 2), se.src_contrast) + add(f"sepsis.top50_deg.{lab}", int(deg_call.deg(a)), deg_call.src_contrast) + add("sepsis.logfc_r.broadcast", round(se.contrast_r("real_lora__raw", "r_broadcast"), 2), se.src_contrast) + add("sepsis.top50_deg.broadcast", int(deg_call.deg("real_lora__raw", "top50_overlap_broadcast")), + deg_call.src_contrast) + + def first_sustained(v, thr, strict=True): + """First LoRA n from which every later n is above (or >=) thr.""" + for i in range(len(v)): + if all((x > thr) if strict else (x >= thr) for x in v[i:]): + return X_LAB[1 + i] + return "never" + bc_r = se.contrast_r("real_lora__raw", "r_broadcast") + bc_d = deg_call.deg("real_lora__raw", "top50_overlap_broadcast") + vr = [se.contrast_r(a) for a in LORA_ARMS] + vd = [deg_call.deg(a) for a in LORA_ARMS] + add("sepsis.logfc_r.first_n_above_broadcast", first_sustained(vr, bc_r), se.src_contrast) + add("sepsis.logfc_r.first_n_above_zero_shot", first_sustained(vr, se.contrast_r(ZS)), se.src_contrast) + add("sepsis.top50_deg.first_n_at_or_above_broadcast", first_sustained(vd, bc_d, strict=False), + deg_call.src_contrast) + add("sepsis.top50_deg.first_n_above_zero_shot", first_sustained(vd, deg_call.deg(ZS)), deg_call.src_contrast) + add("sepsis.logfc_r.first_n_above_zs_cal", first_sustained(vr, se.contrast_r(ZS_CAL)), se.src_contrast) + add("sepsis.top50_deg.first_n_above_zs_cal", first_sustained(vd, deg_call.deg(ZS_CAL)), deg_call.src_contrast) + vn = [im.frac_r(a, "NK cell") for a in LORA_ARMS] + add("immicro.nk_fraction_r.first_n_above_zs_cal", first_sustained(vn, im.frac_r(ZS_CAL, "NK cell")), + im.src_per_donor) + for ds, c in calls.items(): + for key in ("coverage", "comp_l1"): + v = [c.head(a, key) for a in LORA_ARMS] + thr = c.head(ZS_CAL, key) + first = first_sustained([-x for x in v], -thr) if key == "comp_l1" else first_sustained(v, thr) + add(f"{ds}.{key}.first_n_better_than_zs_cal", first, c.src_summary) + # across-donor fraction r per cell type: first n from which LoRA stays at/above zero-shot (footnote) + for ct, key in [("T cell", "T"), ("B cell", "B"), ("Monocyte", "Mono"), ("NK cell", "NK")]: + v = [im.frac_r(a, ct) for a in LORA_ARMS] + add(f"immicro.fraction_r.{key}.first_n_at_or_above_zero_shot", + first_sustained(v, im.frac_r(ZS, ct), strict=False), im.src_per_donor) + add(f"immicro.fraction_r.{key}.zero_shot", round(im.frac_r(ZS, ct), 2), im.src_per_donor) + add(f"immicro.fraction_r.{key}.zs_cal", round(im.frac_r(ZS_CAL, ct), 2), im.src_per_donor) + add(f"immicro.fraction_r.{key}.first_n_at_or_above_zs_cal", + first_sustained(v, im.frac_r(ZS_CAL, ct), strict=False), im.src_per_donor) + add(f"immicro.fraction_r.{key}.lora_5_10_20_40_all", "/".join(f"{x:.2f}" for x in v), im.src_per_donor) + # top-50 DEG overlap by cell type (which types carry the gain) + for ct, key in [("T cell", "T"), ("B cell", "B"), ("Monocyte", "Mono"), ("NK cell", "NK"), ("DC", "DC")]: + v = [deg_call.deg_type(a, ct) for a in [ZS] + LORA_ARMS] + add(f"sepsis.top50_deg.{key}.zero_shot_5_10_20_40_all", "/".join(f"{x:g}" for x in v), + deg_call.src_contrast) + add(f"sepsis.top50_deg.{key}.zs_cal", int(deg_call.deg_type(ZS_CAL, ct)), deg_call.src_contrast) + add(f"sepsis.top50_deg.{key}.broadcast", int(deg_call.deg_type("real_lora__raw", ct, + "top50_overlap_broadcast")), + deg_call.src_contrast) + add("sepsis.n_case", int(se.summary["contrast_definition"]["n_case_donors"]), se.src_summary) + add("sepsis.n_control", int(se.summary["contrast_definition"]["n_control_donors"]), se.src_summary) + add("final_checkpoint", FINAL_CKPT, "RUN.json source_checkpoint (all 50 LoRA runs)") + # equal-budget calibration scan (zero-shot + calibration with alpha from the n + inner-val pairs of lora_n*) + add("cal_budget.pattern", f"scores//**/summary.json arm names: 'cal' and regex {CAL_N_RE.pattern}, " + f"none of {list(FT_TAGS)}", str(PLAN / "scores")) + add("cal_budget.found", ";".join(f"{r['dataset']}:{r['call']}:{r['arm']}" for r in budget_log) or "none", + str(PLAN / "scores")) + for ds in DSETS: + add(f"{ds}.cal_budget.n_drawn", ",".join(str(n) for n in sorted(budget[ds])) or "none", str(PLAN / "scores")) + # scSemiProfiler line (equal-budget n + 5-fold CV "all") + add("scsemi.found", ";".join(f"{r['dataset']}:{r['call']}:{r['arm']}:{r['note']}" for r in sc_log) or "none", + f"{SR.plan_root()}/scores//{{{SR.BUDGET_EXP},{SR.CV_EXP}}}/pooled*") + for ds in DSETS: + sc = (scs or {}).get(ds, {}) + add(f"{ds}.scsemi.pairs_drawn", ",".join(lab for lab in X_LAB[1:] if lab in sc) or "none", + f"{SR.plan_root()}/scores/{ds}") + for lab in X_LAB[1:]: + if lab in sc: + for key in ("coverage", "comp_l1"): + v, c = budget_value(sc[lab], lambda cc, a, k=key: cc.head(a, k)) + if v is not None: + add(f"{ds}.{key}.scsemi_{lab}", round(v, 3), str(c.path / "summary.json")) + return pd.DataFrame(out) + + +def check_against_fig3(rows): + """Cross-check the LoRA curve, the zero-shot + calibration point and the reference lines with the plan's own + fig3 source data (same numbers, independent code path; the plan's fig3 n=0 point is zs__cal). The zero-shot + real-bulk point is not in fig3; it is checked in load() instead (headline vs per_donor.csv / contrast.csv).""" + ref = pd.read_csv(PLAN / "figures" / "source_data" / "fig3_learning_curve.csv") + pmap = {("comp_l1", "immicro"): "3a", ("comp_l1", "ye2026_sepsis"): "3b", + ("coverage", "immicro"): "3c", ("coverage", "ye2026_sepsis"): "3d", + ("nk_fraction_r", "immicro"): "3e", ("logfc_r", "ye2026_sepsis"): "3f", + ("top50_deg", "ye2026_sepsis"): "3h"} + n = 0 + for r in rows: + p = pmap.get((r["panel"], r["dataset"])) + if p is None or r["series"] in ("zero_shot", "zs_cal_budget", "scsemi"): + continue + if r["series"] == "lora": + m = ref[(ref.panel == p) & (ref.series == r["series"]) & (ref.draw == f"n={r['pairs']}")] + elif r["series"] == "zs_cal": + m = ref[(ref.panel == p) & (ref.series == "zs_cal") & (ref.draw == "n=0")] + else: + m = ref[(ref.panel == p) & (ref.series == r["series"])] + assert len(m) == 1, (r, len(m)) + assert abs(float(m.value.iloc[0]) - float(r["value"])) < 1e-5, (r, float(m.value.iloc[0])) + n += 1 + return n + + +def main(): + calls, deg_call, lens = load() + st = load_steps() + fold_sizes = load_fold_sizes() + fewshot = load_fewshot() + budget, budget_log = find_cal_budget(calls, deg_call) + scs, sc_log = find_scsemi(calls) + rows, steprows = [], [] + fig_realism(calls, lens, st, fold_sizes, rows, steprows, budget, scs) + rows_sig = [] + fig_signal(calls, deg_call, lens, st, rows_sig, budget, scs) + n_checked = check_against_fig3(rows + rows_sig) + pd.DataFrame(rows).to_csv(DATADIR / "sec08_pairs_realism.csv", index=False, float_format="%.6g") + pd.DataFrame(steprows).to_csv(DATADIR / "sec08_selected_steps.csv", index=False, float_format="%.6g") + st.to_csv(DATADIR / "sec08_selected_steps_per_fold.csv", index=False) + pd.DataFrame(rows_sig).to_csv(DATADIR / "sec08_pairs_signal.csv", index=False, float_format="%.6g") + nums = slide_numbers(calls, deg_call, st, fold_sizes, fewshot, budget, budget_log, scs, sc_log, lens) + nums.to_csv(DATADIR / "sec08_slide_numbers.csv", index=False) + print(nums.to_string(index=False, max_colwidth=70)) + print(f"cross-checked {n_checked} plotted values against fig3_learning_curve.csv") + brk = [(r["panel"], r["dataset"]) for r in rows + rows_sig if r.get("series") == "zero_shot" and r["y_axis_break"]] + print(f"y-axis breaks: {brk}") + print(f"equal-budget calibration scan: arm names with 'cal' and regex {CAL_N_RE.pattern!r}, none of {FT_TAGS}, " + f"in {PLAN / 'scores'}//**/summary.json") + for r in budget_log: + print(f" found {r['dataset']} {r['call']} {r['arm']} (n {r['n']}): {r['note']}") + if not any(budget[ds] for ds in DSETS): + print(" NOTE: no equal-budget calibration arms found; only the two x = 0 zero-shot points are drawn.") + print(f"scSemiProfiler scan: {SR.plan_root()}/scores//{SR.BUDGET_EXP}/pooled* (scsemi_n__raw) and " + f"{SR.CV_EXP}/pooled* ({SR.CV_ARM}, drawn at 'all')") + for r in sc_log: + print(f" found {r['dataset']} {r['call']} {r['arm']} (pairs {r['pairs']}): {r['note']}") + if not any(scs[ds] for ds in DSETS): + print(" NOTE: no scSemiProfiler equal-budget or 5-fold calls found; no scSemiProfiler line is drawn.") + + +if __name__ == "__main__": + main() diff --git a/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 b/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 new file mode 100644 index 0000000000000000000000000000000000000000..477fb240f5a7e13ac0fb021ae3330fb3e74d4856 --- /dev/null +++ b/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 @@ -0,0 +1,161 @@ +#!/usr/bin/env python3 +"""Section 9 of the 2026-09-30 paper-summary deck: CAT curves (correspondence at the top) of the disease genes +(added 2026-10-02, user request: a threshold-free DEG comparison with the random expectation drawn). + +CPU only. Reads plans/paired_finetune_intradataset_20260927/scores_contrast/{fewshot,pooled}_cat.csv +(tools/contrast_extra.py): per cell type, all tested genes ranked by |limma moderated t| on the observed side and on the +predicted side; CAT(k) = fraction of the observed top-k genes that are also in the predicted top-k with the same logFC +sign (Irizarry et al. 2005); chance = k / (2 G) for G genes tested on both sides. Plotted: mean over T / B / Mono / NK; +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 +the LoRA arm's condition (same ranking statistic on the input bulk). + +Outputs (deck folder; DECK_FIGDIR / DECK_OUTDATA override the folders): + figures/sec09_cat_curves.{png,pdf} + data/sec09_cat_curves.csv every plotted value with its source + data/sec09_cat_curves_slide_text.json title, keywords, footnotes (synced through text_source) +""" +from __future__ import annotations + +import os + +os.environ["CUDA_VISIBLE_DEVICES"] = "" + +import json +import sys +from pathlib import Path + +import numpy as np +import pandas as pd + +DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/" + "2026-09-30--paper-summary--r00") +sys.path.insert(0, str(DECK / "tools")) +import sec09_paired_validation as S9 # noqa: E402 (names, colours, labels; sets the deck rcParams) +import style # noqa: E402 +import matplotlib.pyplot as plt # noqa: E402 +from matplotlib.lines import Line2D # noqa: E402 + +CX = S9.T / "scores_contrast" +FIGDIR = Path(os.environ.get("DECK_FIGDIR", str(DECK / "figures"))) +OUTDATA = Path(os.environ.get("DECK_OUTDATA", str(DECK / "data"))) +DIS = S9.DISEASE +NAME = S9.NAME +TYPES = ["T cell", "B cell", "Monocyte", "NK cell"] +FS = style.FS +FEW = [("zs_raw", "zs_raw"), ("zs_cal", "zs_cal"), ("scsemi5", "scsemi5"), ("lora", "lora5")] +POOL = [("zs_raw", "zs__raw"), ("zs_cal", "zs__cal"), ("sconly_cal", "pseudo_full__cal"), ("lora", "real_lora__raw")] +LORA_ARM = {"fewshot": "lora5", "pooled": "real_lora__raw"} + + +def curves(cat: pd.DataFrame, design: str): + """{(dataset, key): Series over k} for generated arms, 'broadcast' and 'chance' (chance of the LoRA arm's lists).""" + c = cat[cat.celltype.isin(TYPES)].copy() + c["kind"] = np.where(c.predictor.str.startswith("generated:"), "gen", "bc") + out = {} + arms = FEW if design == "fewshot" else POOL + for ds in DIS: + d = c[c.dataset == ds] + for key, arm in arms: + g = d[(d.arm == arm) & (d.kind == "gen")] + if g.empty: + continue + out[(ds, key)] = g.groupby(["unit", "k"]).cat_same_sign.mean().groupby("k").mean() + lo = d[d.arm == LORA_ARM[design]] + out[(ds, "broadcast")] = lo[lo.kind == "bc"].groupby(["unit", "k"]).cat_same_sign.mean().groupby("k").mean() + out[(ds, "chance")] = lo[lo.kind == "gen"].groupby(["unit", "k"]).chance_same_sign.mean().groupby("k").mean() + return out + + +def main() -> int: + few = curves(pd.read_csv(CX / "fewshot_cat.csv"), "fewshot") + poo = curves(pd.read_csv(CX / "pooled_cat.csv"), "pooled") + fig, axs = plt.subplots(2, len(DIS), figsize=(12.3, 5.2), sharex=True, + gridspec_kw=dict(left=0.105, right=0.995, top=0.90, bottom=0.215, hspace=0.32, wspace=0.28)) + rows = [] + for ri, (lab, cv, keys, src) in enumerate([("5 donors", few, FEW, "fewshot_cat.csv"), + ("5-fold CV", poo, POOL, "pooled_cat.csv")]): + for ci, ds in enumerate(DIS): + ax = axs[ri, ci] + hi = 0.0 + for key, _ in keys: + if (ds, key) not in cv: + continue + s = cv[(ds, key)] + ax.plot(s.index, s.values, color=S9.COL[key], lw=2.2 if key == "lora" else 1.6, marker="o", ms=4, + mec=S9.EDGE, mew=0.5, zorder=4 if key == "lora" else 3) + hi = max(hi, s.max()) + rows += [dict(design=lab, dataset=ds, series=key, k=int(k), cat=float(v), source=str(CX / src)) + for k, v in s.items()] + b, ch = cv[(ds, "broadcast")], cv[(ds, "chance")] + st = S9.REFSTYLE["broadcast"] + ax.plot(b.index, b.values, ls=st["ls"], color=st["color"], lw=st["lw"], zorder=2) + ax.plot(ch.index, ch.values, ls=(0, (3, 2)), color=style.INK, lw=1.0, zorder=2) + hi = max(hi, b.max()) + rows += [dict(design=lab, dataset=ds, series=s_, k=int(k), cat=float(v), source=str(CX / src)) + for s_, ser in (("broadcast", b), ("chance", ch)) for k, v in ser.items()] + ax.set_xscale("log") + ax.set_xticks([10, 50, 100, 500], ["10", "50", "100", "500"]) + ax.set_ylim(0, max(0.12, hi * 1.15)) + ax.yaxis.set_major_locator(plt.MaxNLocator(nbins=4)) + ax.tick_params(labelsize=FS - 3) + if ri == 0: + ax.set_title(S9.ROWNAME[ds], fontsize=FS - 1, pad=6) + if ri == 1: + ax.set_xlabel("top-k genes (k)", fontsize=FS - 2) + axs[ri, 0].annotate(lab, xy=(0, 0.5), xycoords="axes fraction", xytext=(-58, 0), textcoords="offset points", + ha="right", va="center", fontsize=FS, fontweight="bold") + axs[ri, 0].set_ylabel("CAT, same sign", fontsize=FS - 3) + hk = [("zs_raw", S9.LAB["zs_raw"]), ("zs_cal", S9.LAB["zs_cal"]), ("scsemi5", "scSemiProfiler (5 donors)"), + ("sconly_cal", "sc-only fine-tune (5-fold)"), ("lora", "LoRA")] + 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] + handles += [S9.refh("broadcast"), Line2D([0], [0], ls=(0, (3, 2)), color=style.INK, lw=1.0, label="Chance (k / 2G)")] + fig.legend(handles=handles, loc="lower center", ncol=4, bbox_to_anchor=(0.53, -0.01), fontsize=FS - 3, + frameon=False, columnspacing=1.4, handlelength=2.2) + style.save(fig, "sec09_cat_curves", FIGDIR) + d = pd.DataFrame(rows) + OUTDATA.mkdir(exist_ok=True) + d.to_csv(OUTDATA / "sec09_cat_curves.csv", index=False, float_format="%.6g") + + # slide text, from the plotted values at k = 100 + def at(cv, ds, key, k=100): + s = cv.get((ds, key)) + return np.nan if s is None or k not in s.index else float(s.loc[k]) + + top_few = [ds for ds in DIS if at(few, ds, "lora") >= max(at(few, ds, k) for k, _ in FEW if k != "lora")] + top_poo = [ds for ds in DIS if at(poo, ds, "lora") >= max(at(poo, ds, k) for k, _ in POOL if k != "lora")] + bc_few = [ds for ds in DIS if at(few, ds, "broadcast") > at(few, ds, "lora")] + kw = [f"LoRA top model: {len(top_few)}/4 (5 donors), {len(top_poo)}/4 (5-fold)", + (f"Broadcast above LoRA: {S9.names(bc_few)}" if bc_few else "LoRA above broadcast in every cohort"), + 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}"] + for k in kw: + if len(k) > 52: + raise ValueError(f"keyword too long: {k!r}") + vals = "; ".join( + f"{NAME[ds]} CAT100 5 donors LoRA {at(few, ds, 'lora'):.3f} / scSemi {at(few, ds, 'scsemi5'):.3f} / " + f"calibration {at(few, ds, 'zs_cal'):.3f} / raw {at(few, ds, 'zs_raw'):.3f} / broadcast {at(few, ds, 'broadcast'):.3f}" + f" / chance {at(few, ds, 'chance'):.3f}; 5-fold LoRA {at(poo, ds, 'lora'):.3f} / broadcast {at(poo, ds, 'broadcast'):.3f}" + for ds in DIS) + full = ("Correspondence at the top (Irizarry et al. 2005): per cell type, every gene tested on both sides is ranked by " + "|limma-voom moderated t| (case vs control, same donor x type pseudobulks as the DEG panels); CAT(k) = share of " + "the observed top-k genes that are also in the generated top-k with the same logFC sign. Mean over T / B / Mono " + "/ NK; 5 donors = mean over 5 draws (scSemiProfiler: its 25 draws); 5-fold = pooled call. Broadcast = the " + "input real bulk ranked the same way. Chance = k / (2G), G = genes tested on both sides (" + f"{min(at(few, ds, 'chance') for ds in DIS):.3f}–{max(at(few, ds, 'chance') for ds in DIS):.3f} at k = 100). " + "No significance threshold, so cohorts where few genes pass FDR (Giroux, Ji) still get a curve. " + "Rank-biased overlap (Webber et al. 2010, p = 0.98) gives the same order: scores_contrast/{fewshot,pooled}_rbo.csv. " + "Giroux: sex-linked genes excluded. " + vals + ".") + txt = {"title": "Disease genes at every list length (CAT)", "layout": "full", + "figures": [str(FIGDIR / "sec09_cat_curves.png")], "keywords": kw, + "footnote_short": "Same-sign overlap of observed and generated top-k genes per cell type; no FDR cut-off.", + "footnote": full, + "numbers": [{"value": vals, "source": str(CX / "fewshot_cat.csv") + "; " + str(CX / "pooled_cat.csv")}]} + (OUTDATA / "sec09_cat_curves_slide_text.json").write_text(json.dumps( + {"section": "09-cat", "scripts": [str(Path(__file__).resolve())], + "generated_from": "tools/sec09_cat_curves.py (rerun to refresh; do not edit by hand)", "slides": [txt]}, + indent=1, ensure_ascii=False)) + print("\n".join(kw)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/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 b/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 new file mode 100644 index 0000000000000000000000000000000000000000..4dfec8d2dbe9ccfecdda1442ce21eedbf77b7631 --- /dev/null +++ b/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 @@ -0,0 +1,738 @@ +#!/usr/bin/env python3 +"""Section 9 extras of the 2026-09-30 paper-summary deck: realism / diversity metrics beyond precision and coverage +(classifier AUC, MMD^2, scSemiProfiler's E_N, precision/coverage at k = 3 / 5 / 10). + +CPU only: reads the per-unit outputs of plans/paired_finetune_intradataset_20260927/tools/extra_metrics.py +(scores_extra//{fewshot_n5/draw, pooled}/{metrics.csv, en.csv, manifest.json}) and draws slide figures. +No torch, no CUDA, no scoring. The headline definitions are the collector's (tools/collect_extra_metrics.py, +scores_extra/README.md) and every value is checked against scores_extra/{fewshot,pooled}_headline.csv: + classifier AUC (kNN, RF), 1-NN accuracy, MMD^2 real side R2 (held-out real cells), no depth matching; + control = real vs real, R2 vs R3 + E_N all cells, squared L2 (their code); control = within-sample half + split; undefined (UB <= LB) -> left out of means, ranks last + precision / coverage at k = 3, 5, 10 the scorer's space (real side R1); control = R1 vs R2 + +Outputs (deck folder; DECK_FIGDIR / DECK_OUTDATA override the folders, used by the synthetic test): + figures/sec09_extra_fewpair.{png,pdf} main slide: 5 donors, kNN AUC / MMD^2 / E_N per cohort + figures/sec09_extra_fivefold.{png,pdf} section 9: the same for the 5-fold pooled design + figures/sec09_extra_ksens.{png,pdf} section 9: precision / coverage at k = 3, 5, 10 (5 donors) + data/sec09_extra_{fewpair,fivefold,ksens}.csv every plotted value with its source file + data/sec09_extra_scsemi_status.csv scSemiProfiler CV / equal-budget extra-metric units found or not + data/sec09_extra_quoted_numbers.csv quoted numbers (flat) + data/sec09_extra_slide_text.json titles, keywords, footnotes, quoted numbers (synced into + data/slides_spec.json by tools/sync_sec09_text.py) + +scSemiProfiler with all training pairs (5-fold CV, arm scsemi__raw): drawn in the 5-fold figure as its own bar when an +extra-metric unit with that set exists (scores_extra//pooled/ itself, or below scores_extra//scsemi_cv_20261002/, +see tools/scsemi_results.py) for the same donors and reference cells; otherwise a note is printed and nothing is drawn. +Equal-budget units (scsemi_n__raw) are only listed in the status CSV. +""" +from __future__ import annotations + +import os + +os.environ["CUDA_VISIBLE_DEVICES"] = "" # plotting only + +import json +import sys +from pathlib import Path + +import numpy as np +import pandas as pd + +DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/" + "2026-09-30--paper-summary--r00") +sys.path.insert(0, str(DECK / "tools")) +import sec09_paired_validation as S9 # noqa: E402 (shared section 9 drawing helpers; sets the deck rcParams) +import scsemi_results as SR # noqa: E402 +import style # noqa: E402 +import matplotlib.pyplot as plt # noqa: E402 +from matplotlib.lines import Line2D # noqa: E402 +from matplotlib.patches import Patch # noqa: E402 + +T = S9.T +X = T / "scores_extra" +FIGDIR = Path(os.environ.get("DECK_FIGDIR", str(DECK / "figures"))) +OUTDATA = Path(os.environ.get("DECK_OUTDATA", str(DECK / "data"))) +SCRIPT = DECK / "tools" / "sec09_extra_metrics.py" +ORDER, NAME, ROWNAME = S9.ORDER, S9.NAME, S9.ROWNAME +FS, SUB, EDGE = S9.FS, S9.SUB, S9.EDGE + +# arm keys (deck colours / labels from sec09) -> set names in scores_extra +FEW_SETS = {"zs_raw": "zs_raw", "zs_cal": "zs_cal", "scsemi5": "scsemi5", "lora": "lora5", "pseudo": "zs_pseudo"} +POOL_SETS = {"zs_raw": "zs__raw", "zs_cal": "zs__cal", "sconly_cal": "pseudo_full__cal", "scsemi_all": SR.CV_ARM, + "lora": "real_lora__raw", "pseudo": "zs__pseudo"} +COL = {**S9.COL, "scsemi_all": style.ARM["scsemi"]} +LAB = {**S9.LAB, "scsemi_all": SR.LABEL_CV} +# headline metrics (collector's HEADLINE): column, short name, direction (0: closer to 0.5, -1 lower, +1 higher), space +TWO = [("c2st_knn_auc", "kNN AUC", 0), ("c2st_rf_auc", "RF AUC", 0), ("nn1_acc", "1-NN accuracy", 0), + ("mmd2_bw1", "MMD² (σ = m)", -1), ("mmd2_sum", "MMD² (σ sum)", -1)] +EN = [("en_all_sq", "E_N (all cells)", -1)] +PC = [(f"{q}_k{k}", f"{q} k{k}", 1) for k in (3, 5, 10) for q in ("precision", "coverage")] +HEAD = TWO + EN + PC +DIRS = {c: s for c, _, s in HEAD} +SHORT = {c: n for c, n, _ in HEAD} +# drawn columns of the two realism figures +PANELS = [("c2st_knn_auc", "Classifier AUC (kNN) ↓"), ("mmd2_bw1", "MMD² ↓"), ("en_all_sq", "scSemiProfiler E_N ↓ (log)")] +CTRL = dict(ls=(0, (6, 2, 1.5, 2)), color="#7A7A7A", lw=1.8, label="Real vs real (same samples)") +KS = (3, 5, 10) +NUMS = {k: [] for k in "abc"} + + +def num(slide, value, source): + NUMS[slide].append({"value": str(value), "source": str(source)}) + + +# ------------------------------------------------------------------------------------------ +# Loading +# ------------------------------------------------------------------------------------------ +def unit_values(u: Path) -> dict: + """set -> {metric: value} in the headline spaces of one extra-metric unit; 'control' = the real-vs-real rows.""" + m = pd.read_csv(u / "metrics.csv") + e = pd.read_csv(u / "en.csv") + raw = m[m["mode"] == "raw"] + out = {} + for s in sorted(set(raw["set"])): + r2 = raw[(raw["set"] == s) & (raw.real_side == "R2")] + r1 = raw[(raw["set"] == s) & (raw.real_side == "R1")] + if len(r2) > 1 or len(r1) > 1: + raise ValueError(f"{u}: several raw rows for set {s}") + d = {c: (float(r2[c].iloc[0]) if len(r2) else np.nan) for c, _, _ in TWO} + d.update({c: (float(r1[c].iloc[0]) if len(r1) else np.nan) for c, _, _ in PC}) + en = e[(e["set"] == s) & (e.cellset == "all") & (e.distance == "sq")] + if len(en) > 1: + raise ValueError(f"{u}: several E_N rows for set {s}") + ok = bool(len(en)) and float(en.ub.iloc[0]) > float(en.lb.iloc[0]) + d["en_all_sq"] = float(en.en.iloc[0]) if ok else np.nan + d["en_all_sq_undefined"] = bool(len(en)) and not ok + out[s] = d + ctrl = {c: out["real_R3"][c] for c, _, _ in TWO} + ctrl.update({c: out["real_R2"][c] for c, _, _ in PC + EN}) + ctrl["en_all_sq_undefined"] = False + out["control"] = ctrl + return out + + +def manifest(u: Path) -> dict: + p = u / "manifest.json" + return json.loads(p.read_text()) if p.is_file() else {} + + +def load_fewpair(): + """Long table: dataset, draw, arm (deck key or 'control'), metric, value, undefined, source.""" + rows, info = [], {} + for ds in ORDER: + units = [d for d in sorted((X / ds / "fewshot_n5").glob("draw*")) if (d / "manifest.json").is_file()] + few_min = [] + for u in units: + j = int(u.name.removeprefix("draw")) + mf_ = manifest(u) + sj = T / "scores" / ds / "fewshot_n5" / f"draw{j}" / "summary.json" + s = json.loads(sj.read_text()) + if set(map(str, mf_["donors"])) != set(map(str, s["donors"])): + raise ValueError(f"{u}: scored donors differ from {sj}") + if mf_["reference_sha256"] != s["reference"]["reference_sha256"]: + raise ValueError(f"{u}: reference differs from {sj}") + few_min.append({"dataset": ds, "arm": "lora", "draw": j, "n_scored": int(s["n_donors"])}) + vals = unit_values(u) + for key in list(FEW_SETS) + ["control"]: + sname = FEW_SETS.get(key, "control") + if sname not in vals: + continue + for c, _, _ in HEAD: + rows.append({"dataset": ds, "draw": j, "arm": key, "set": sname, "metric": c, + "value": vals[sname][c], + "undefined": bool(vals[sname].get(f"{c}_undefined", False)), + "source": str(u / ("en.csv" if c.startswith("en_") else "metrics.csv"))}) + info[ds] = S9.draw_info(pd.DataFrame(few_min), ds) + return pd.DataFrame(rows), info + + +def load_pooled(): + """dataset -> {arm key: {metric: value}}, plus the scSemiProfiler lookup log.""" + out, log = {}, [] + for ds in ORDER: + u = X / ds / "pooled" + vals = unit_values(u) + ref = manifest(u) + d = {} + for key, sname in POOL_SETS.items(): + if sname in vals: + d[key] = {**vals[sname], "source": str(u)} + d["control"] = {**vals["control"], "source": str(u)} + # scSemiProfiler, all training pairs: in the pooled unit itself, else below scores_extra//scsemi_cv_20261002/ + if "scsemi_all" in d: + log.append(dict(dataset=ds, design="cv", unit=str(u), set=SR.CV_ARM, status="used", reason="in pooled unit")) + for cu in SR.extra_units(ds, SR.CV_EXP): + cv = unit_values(cu) + if SR.CV_ARM not in cv: + log.append(dict(dataset=ds, design="cv", unit=str(cu), set="", status="ignored", + reason=f"no set {SR.CV_ARM}")) + continue + cm = manifest(cu) + why = [] + if cm.get("donors") is not None and set(map(str, cm["donors"])) != set(map(str, ref["donors"])): + why.append("donor set differs from the pooled unit") + if cm.get("reference_sha256") is not None and cm["reference_sha256"] != ref["reference_sha256"]: + why.append("reference differs from the pooled unit") + if "scsemi_all" in d: + why.append("already taken from an earlier unit") + if why: + log.append(dict(dataset=ds, design="cv", unit=str(cu), set=SR.CV_ARM, status="rejected", + reason="; ".join(why))) + continue + d["scsemi_all"] = {**cv[SR.CV_ARM], "source": str(cu)} + log.append(dict(dataset=ds, design="cv", unit=str(cu), set=SR.CV_ARM, status="used", + reason="no manifest: donors not checked" if not cm else "")) + for bu in SR.extra_units(ds, SR.BUDGET_EXP): + for s in sorted(unit_values(bu)): + if SR.BUDGET_RE.match(s): + log.append(dict(dataset=ds, design="budget", unit=str(bu), set=s, status="listed only", + reason="equal-budget units are not drawn")) + out[ds] = d + return out, pd.DataFrame(log, columns=["dataset", "design", "unit", "set", "status", "reason"]) + + +def check_headline(few: pd.DataFrame, pooled: dict): + """Every value equals the collector's headline tables (few-pair: mean and n over draws; pooled: the value).""" + n = 0 + hf = pd.read_csv(X / "fewshot_headline.csv") + for r in hf.itertuples(): + key = "control" if r.set == "control" else {v: k for k, v in FEW_SETS.items()}[r.set] + for c, _, _ in HEAD: + x = few[(few.dataset == r.dataset) & (few.arm == key) & (few.metric == c) & ~few.undefined]["value"] + want = getattr(r, c) + if int(getattr(r, f"{c}_n")) != len(x) or abs(float(x.mean()) - want) > 1e-9: + raise ValueError(f"few-pair {r.dataset} {r.set} {c}: {x.mean()} (n {len(x)}) != headline {want}") + n += 1 + hp = pd.read_csv(X / "pooled_headline.csv") + for r in hp.itertuples(): + key = "control" if r.set == "control" else {v: k for k, v in POOL_SETS.items()}[r.set] + for c, _, _ in HEAD: + v, want = pooled[r.dataset][key][c], getattr(r, c) + if not (abs(v - want) <= 1e-9 or (np.isnan(v) and np.isnan(want))): + raise ValueError(f"pooled {r.dataset} {r.set} {c}: {v} != headline {want}") + n += 1 + return n + + +# ------------------------------------------------------------------------------------------ +# Drawing +# ------------------------------------------------------------------------------------------ +def hbars_base(ax, arms, vals_of, base, seed=0, dots=True, na_text=None): + """S9.hbars with bars starting at `base` (0.5 for AUC, the axis floor for a log axis).""" + out = {} + for i, arm in enumerate(arms): + vals = np.asarray([v for v in vals_of(arm) if not np.isnan(v)], float) + if len(vals) == 0: + ax.text(0.01, i, (na_text or {}).get(arm, "not run"), transform=ax.get_yaxis_transform(), va="center", + fontsize=FS - 3, color=SUB) + out[arm] = (np.nan, np.nan, 0) + continue + m = float(vals.mean()) + sd = float(vals.std(ddof=1)) if len(vals) > 1 else 0.0 + ax.barh(i, m - base, left=base, height=S9.BAR_H, color=COL[arm], edgecolor=EDGE, linewidth=0.6, zorder=2) + if dots and len(vals) > 1: + lo = max(m - sd, base) if ax.get_xscale() == "log" else m - sd + ax.errorbar(m, i, xerr=[[m - lo], [sd]], fmt="none", ecolor="#111111", elinewidth=1.0, capsize=3, + capthick=1.0, zorder=4) + ax.scatter(vals, i + S9.jitter(len(vals), seed + i), s=16, facecolor="white", edgecolor="#111111", + linewidth=0.7, zorder=5, clip_on=False) + out[arm] = (m, sd, len(vals)) + ax.set_ylim(len(arms) - 0.5, -0.5) + ax.set_yticks([]) + return out + + +def vline(ax, x, style_, na): + if x is None or np.isnan(x): + return + ax.plot([x, x], [-0.5, na - 0.5], ls=style_["ls"], color=style_["color"], lw=style_["lw"], zorder=3, + solid_capstyle="butt") + + +def ctrl_handle(): + return Line2D([0], [0], ls=CTRL["ls"], color=CTRL["color"], lw=CTRL["lw"], label=CTRL["label"]) + + +def patch(key, label=None): + return Patch(facecolor=COL[key], edgecolor=EDGE, linewidth=0.6, label=label or LAB[key]) + + +def nice_log_limits(vals): + v = [x for x in vals if x > 0 and not np.isnan(x)] + 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]) + 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]) + return lo, hi + + +def axis_setup(axs_col, metric, allv, label): + """Shared x scale of one metric column; returns the bar base.""" + if metric.startswith("c2st") or metric.startswith("nn1"): + lo = min(0.45, np.floor(min(allv) * 20) / 20) + S9.shared_x(axs_col, lo, 1.0, label, [0.5, 0.75, 1.0]) + for ax in axs_col: # bars start at 0.5 (chance); the real-vs-real line sits there, so no spine at lo + ax.spines["left"].set_visible(False) + return 0.5 + if metric.startswith("mmd"): + hi = np.ceil(max(allv) * 1.08 / 0.05) * 0.05 + lo = min(-0.02 * hi, min(allv) - 0.01 * hi) + S9.shared_x(axs_col, lo, hi, label, [round(t, 2) for t in np.arange(0, hi + 1e-9, 0.1)]) + for ax in axs_col: + ax.spines["left"].set_visible(False) + ax.axvline(0, color="#555555", lw=0.8, zorder=1) + return 0.0 + lo, hi = nice_log_limits(allv) + for ax in axs_col: + ax.set_xscale("log") + ticks = [t for t in (0.01, 0.1, 1, 10, 100, 1000) if lo <= t <= hi] + S9.shared_x(axs_col, lo, hi, label, ticks) + for ax in axs_col: + ax.set_xticklabels([f"{t:g}" for t in ticks]) + ax.xaxis.set_minor_locator(plt.NullLocator()) + return lo + + +def realism_figure(name, arms, vals_of, ref_of, row_subs, legend_handles, dots, na_text=None, header=None): + """rows = cohorts, columns = PANELS; vals_of(ds, arm, metric) -> list; ref_of(ds, kind, metric) -> float.""" + leg_rows = -(-len(legend_handles) // 3) + fig, axs = S9.grid(len(ORDER), len(PANELS), style.FULL, left=S9.LEFT_IN, right=0.25, top=0.45, + bottom=0.65 + 0.30 * leg_rows, hspace=0.22, wspace=0.12) + rows = [] + for j, (mk, lab) in enumerate(PANELS): + allv = [v for ds in ORDER for a in arms for v in vals_of(ds, a, mk) if not np.isnan(v)] + allv += [ref_of(ds, k, mk) for ds in ORDER for k in ("control", "pseudo")] + allv = [v for v in allv if not np.isnan(v)] + base = axis_setup(axs[:, j], mk, allv, lab) + for i, ds in enumerate(ORDER): + ax = axs[i, j] + hbars_base(ax, arms, lambda a: vals_of(ds, a, mk), base, seed=17 * i + j, dots=dots, + na_text=(na_text or {}).get(ds)) + vline(ax, ref_of(ds, "control", mk), CTRL, len(arms)) + vline(ax, ref_of(ds, "pseudo", mk), S9.REFSTYLE["pseudo"], len(arms)) + for a in arms: + for v in vals_of(ds, a, mk): + rows.append({"figure": name, "dataset": ds, "metric": mk, "series": a, "value": v}) + for k in ("control", "pseudo"): + rows.append({"figure": name, "dataset": ds, "metric": mk, "series": f"ref_{k}", + "value": ref_of(ds, k, mk)}) + for i, ds in enumerate(ORDER): + S9.row_label(axs[i, 0], ROWNAME[ds], row_subs(ds)) + if header: + S9.label_header(axs[0, 0], header) + S9.legend_bottom(fig, legend_handles, ncol=3) + S9.check_inside(fig, name) + style.save(fig, name, FIGDIR) + return rows + + +# ------------------------------------------------------------------------------------------ +# Figures +# ------------------------------------------------------------------------------------------ +FEW_ARMS = ["zs_raw", "zs_cal", "scsemi5", "lora"] + + +def few_vals(few, ds, arm, mk): + s = few[(few.dataset == ds) & (few.arm == arm) & (few.metric == mk)].sort_values("draw") + return [np.nan if u else v for v, u in zip(s.value, s.undefined)] + + +def few_mean(few, ds, arm, mk): + v = [x for x in few_vals(few, ds, arm, mk) if not np.isnan(x)] + return float(np.mean(v)) if v else np.nan + + +def fig_fewpair(few, info): + nd = {info[d]["n_draws"] for d in ORDER} + per_row = len(nd) > 1 + handles = [patch("zs_raw"), patch("zs_cal"), patch("scsemi5"), patch("lora"), ctrl_handle(), S9.refh("pseudo"), + S9.dot_handle(None if per_row else next(iter(nd)))] + return realism_figure( + "sec09_extra_fewpair", FEW_ARMS, lambda ds, a, mk: few_vals(few, ds, a, mk), + lambda ds, k, mk: few_mean(few, ds, k, mk), lambda ds: S9.row_subs(info[ds], per_row), handles, dots=True, + header="pairs per draw") + + +def fig_fivefold(pooled, arms, tab): + def vals(ds, a, mk): + d = pooled[ds].get(a) + return [np.nan] if d is None else [d[mk]] + + def ref(ds, k, mk): + return pooled[ds][k][mk] + + def subs(ds): + n, nd = tab[ds] + return [f"n={n}" + (f" ({nd} donors)" if nd != n else "")] + + handles = [patch(a, LAB["lora_all"] if a == "lora" else None) for a in arms] + [ctrl_handle(), S9.refh("pseudo")] + na = {ds: {"scsemi_all": "pending"} for ds in ORDER} + return realism_figure("sec09_extra_fivefold", arms, vals, ref, subs, handles, dots=False, na_text=na) + + +def fig_ksens(few): + fig, axs = plt.subplots(2, len(ORDER), figsize=style.FULL, sharey=True, + gridspec_kw=dict(left=0.075, right=0.995, top=0.93, bottom=0.25, hspace=0.18, + wspace=0.10)) + xs = np.arange(len(KS)) + rows = [] + mk_style = {"zs_raw": "o", "zs_cal": "o", "scsemi5": "D", "lora": "o"} + off = {"zs_raw": -0.09, "zs_cal": -0.03, "scsemi5": 0.03, "lora": 0.09} + for i, q in enumerate(("coverage", "precision")): + for j, ds in enumerate(ORDER): + ax = axs[i, j] + cv = [few_mean(few, ds, "control", f"{q}_k{k}") for k in KS] + ax.plot(xs, cv, ls=CTRL["ls"], color=CTRL["color"], lw=CTRL["lw"], marker="s", ms=4, zorder=2) + for k, v in zip(KS, cv): + rows.append({"figure": "sec09_extra_ksens", "dataset": ds, "metric": f"{q}_k{k}", + "series": "control", "value": v, "sd": np.nan}) + for a in FEW_ARMS: + m = [few_mean(few, ds, a, f"{q}_k{k}") for k in KS] + sd = [float(np.std([x for x in few_vals(few, ds, a, f"{q}_k{k}") if not np.isnan(x)], ddof=1)) + for k in KS] + ax.errorbar(xs + off[a], m, yerr=sd, color=COL[a], lw=2.0, marker=mk_style[a], ms=6, + mec=EDGE, mew=0.6, capsize=2.5, elinewidth=1.0, zorder=4 if a == "lora" else 3) + for k, v, s in zip(KS, m, sd): + rows.append({"figure": "sec09_extra_ksens", "dataset": ds, "metric": f"{q}_k{k}", + "series": a, "value": v, "sd": s}) + ax.set_xticks(xs) + ax.set_xticklabels([str(k) for k in KS]) + ax.set_xlim(-0.4, len(KS) - 0.6) + ax.set_ylim(0, 1.05) + ax.set_yticks([0, 0.5, 1.0]) + if i == 0: + ax.set_title(ROWNAME[ds], fontsize=FS, pad=6) + ax.tick_params(axis="x", labelbottom=False) + if j == 0: + ax.set_ylabel(f"{q.capitalize()} ↑") + fig.text(0.535, 0.155, "k (nearest neighbours per ball)", ha="center", va="center", fontsize=FS) + handles = [Line2D([0], [0], color=COL[a], lw=2.0, marker=mk_style[a], ms=6, mec=EDGE, mew=0.6, label=LAB[a]) + for a in FEW_ARMS] + [Line2D([0], [0], ls=CTRL["ls"], color=CTRL["color"], lw=CTRL["lw"], marker="s", + ms=4, label="Real vs real (held-out cells)")] + S9.legend_bottom(fig, handles, ncol=3) + style.save(fig, "sec09_extra_ksens", FIGDIR) + return rows + + +# ------------------------------------------------------------------------------------------ +# Comparisons for the slide text +# ------------------------------------------------------------------------------------------ +def better(a, b, sign): + """a better than b (NaN = undefined E_N ranks last).""" + if np.isnan(a): + return False + if np.isnan(b): + return True + return (abs(a - 0.5) < abs(b - 0.5)) if sign == 0 else (a > b if sign > 0 else a < b) + + +def few_wide(few, mk): + s = few[few.metric == mk].copy() + s.loc[s.undefined, "value"] = np.nan + return s.pivot_table(index=["dataset", "draw"], columns="arm", values="value", dropna=False) + + +def few_compare(few, comps=("scsemi5", "zs_raw", "zs_cal")): + """Per cohort x comparator x metric: draws where LoRA-5 is better / worse / tied.""" + out = [] + for c, _, sign in HEAD: + w = few_wide(few, c) + for ds in ORDER: + x = w.loc[ds] + for comp in comps: + xx = x[["lora", comp]].dropna(how="all") + nb = sum(better(a, b, sign) for a, b in zip(xx.lora, xx[comp])) + nw = sum(better(b, a, sign) for a, b in zip(xx.lora, xx[comp])) + out.append(dict(dataset=ds, comp=comp, metric=c, n=len(xx), n_better=nb, n_worse=nw, + lora=float(np.nanmean(xx.lora)), other=float(np.nanmean(xx[comp])))) + return pd.DataFrame(out) + + +def best_draws(few, mk, arms=FEW_ARMS): + """Draws where LoRA-5 is best of the arms on one metric.""" + sign = DIRS[mk] + w = few_wide(few, mk) + n = 0 + for _, r in w.iterrows(): + n += all(better(r["lora"], r[a], sign) for a in arms if a != "lora") + return n, len(w) + + +def fmt_metric(c, v): + return f"{v:.4f}" if c.startswith("mmd") else (f"{v:.2f}" if c.startswith("en_") else f"{v:.3f}") + + +def exceptions_text(exc): + """'vs zero-shot + calibration: Imperial E_N (all cells) 3/5 (1.28 vs 1.22), ...' grouped by comparator / cohort.""" + parts = [] + for comp, g in exc.groupby("comp", sort=True): + items = [] + for ds in ORDER: + h = g[g.dataset == ds] + if len(h): + items.append(f"{NAME[ds]} " + ", ".join( + f"{SHORT[r.metric]} {r.n_worse}/{r.n} ({fmt_metric(r.metric, r.lora)} vs " + f"{fmt_metric(r.metric, r.other)})" for r in h.itertuples())) + parts.append(f"vs {S9.LAB[comp].lower()}: " + "; ".join(items)) + return " | ".join(parts) + + +def rng2(v, nd=2): + v = [x for x in v if not np.isnan(x)] + a, b = f"{min(v):.{nd}f}", f"{max(v):.{nd}f}" + return a if a == b else f"{a}–{b}" + + +# ------------------------------------------------------------------------------------------ +def main(): + FIGDIR.mkdir(parents=True, exist_ok=True) + OUTDATA.mkdir(parents=True, exist_ok=True) + few, info = load_fewpair() + pooled, sclog = load_pooled() + n_checked = check_headline(few, pooled) + sclog.to_csv(OUTDATA / "sec09_extra_scsemi_status.csv", index=False) + tab = {} + for ds in ORDER: + dj = json.loads((T / "data" / ds / "fewshot_n5" / "DRAWS.json").read_text()) + n = int(json.loads((T / "scores" / ds / "pooled" / "summary.json").read_text())["n_donors"]) + if n != int(dj["n_usable_rows"]): + raise ValueError(f"{ds}: pooled n {n} != usable rows") + tab[ds] = (n, int(dj["n_usable_donors"])) + has_sc = [ds for ds in ORDER if "scsemi_all" in pooled[ds]] + arms5 = ["zs_raw", "zs_cal", "sconly_cal"] + (["scsemi_all"] if has_sc else []) + ["lora"] + + rows_a = fig_fewpair(few, info) + rows_b = fig_fivefold(pooled, arms5, tab) + rows_c = fig_ksens(few) + srcf = f"{X}//fewshot_n5/draw/{{metrics,en}}.csv" + srcp = f"{X}//pooled/{{metrics,en}}.csv" + pd.DataFrame(rows_a).assign(source=srcf).to_csv(OUTDATA / "sec09_extra_fewpair.csv", index=False, + float_format="%.6g") + pd.DataFrame(rows_b).assign(source=srcp).to_csv(OUTDATA / "sec09_extra_fivefold.csv", index=False, + float_format="%.6g") + pd.DataFrame(rows_c).assign(source=srcf).to_csv(OUTDATA / "sec09_extra_ksens.csv", index=False, + float_format="%.6g") + slides = [] + + # ---------------- slide a: 5 donors, realism beyond P/C ---------------- + cmp = few_compare(few) + nb_knn, ntot = best_draws(few, "c2st_knn_auc") + nb_rf, _ = best_draws(few, "c2st_rf_auc") + nb_nn1, _ = best_draws(few, "nn1_acc") + nb_mmd, _ = best_draws(few, "mmd2_bw1") + nb_en, _ = best_draws(few, "en_all_sq") + en_sc = cmp[(cmp.comp == "scsemi5") & (cmp.metric == "en_all_sq")] + en_sc_better, en_sc_n = int(en_sc.n_better.sum()), int(en_sc.n.sum()) + auc_l = [few_mean(few, d, "lora", "c2st_knn_auc") for d in ORDER] + auc_draws = few[(few.arm == "lora") & (few.metric == "c2st_knn_auc")].value + kw1 = S9.keyword_or_short(f"Classifier AUC: LoRA-5 best in {nb_knn}/{ntot} draws", + f"AUC: LoRA-5 best in {nb_knn}/{ntot} draws") + kw2 = f"E_N: LoRA-5 below scSemi-5 in {en_sc_better}/{en_sc_n} draws" + kw3 = f"Still separable: LoRA-5 AUC {rng2(auc_l)}" + kw_a = S9.check_keywords([kw1, kw2, kw3]) + # exceptions over every headline metric (LoRA-5 worse in >= 1 draw) + exc = cmp[cmp.n_worse > 0].copy() + exc_comps = sorted(set(exc.comp)) + drawn = {m for m, _ in PANELS} + exc_drawn = exc[exc.metric.isin(drawn)].sort_values(["n_worse", "dataset"], ascending=[False, True]) + if exc.empty: + fs_a = "E_N: scSemiProfiler's own error metric. LoRA-5 best of the 4 arms on every metric in every draw." + elif exc_comps == ["zs_cal"]: + e0 = exc_drawn.iloc[0] if len(exc_drawn) else exc.sort_values("n_worse", ascending=False).iloc[0] + nd = 2 if e0.metric.startswith("en_") else 3 + fs_a = (f"E_N: scSemiProfiler's own error metric. Misses only vs calibration, e.g. {NAME[e0.dataset]} " + f"{SHORT[e0.metric].split(' (')[0]} {e0.lora:.{nd}f} vs {e0.other:.{nd}f}.") + else: + fs_a = (f"E_N: scSemiProfiler's own error metric. LoRA-5 behind in {len(exc)} cohort × arm × metric cases; " + f"see notes.") + fs_a = S9.check_foot_short(fs_a) + rf_l = [few_mean(few, d, "lora", "c2st_rf_auc") for d in ORDER] + ctrl_auc = [few_mean(few, d, "control", "c2st_knn_auc") for d in ORDER] + ctrl_en = [few_mean(few, d, "control", "en_all_sq") for d in ORDER] + nn_c = cmp[cmp.metric.isin(["c2st_knn_auc", "c2st_rf_auc", "nn1_acc"] + [f"coverage_k{k}" for k in KS])] + wins_all = (nn_c.n_better == nn_c.n).all() + exc_txt = exceptions_text(exc) + en_means = "; ".join(f"{NAME[d]} {few_mean(few, d, 'scsemi5', 'en_all_sq'):.2f} vs " + f"{few_mean(few, d, 'lora', 'en_all_sq'):.2f}" for d in ORDER) + foot_a = (f"Same 5-donor draws as the previous slides; every metric on exactly the scored cells (scores_extra/, " + f"tools/extra_metrics.py). Real side for AUC and MMD² = held-out real cells of the same samples (R2), " + f"projected like the generated cells; real vs real = R2 vs R3 (AUC {rng2(ctrl_auc)}). Classifier AUC: " + f"5-fold CV ROC AUC of a kNN classifier (k = 5) separating real from generated cells, 0.5 = " + f"indistinguishable; bars start at 0.5. MMD²: unbiased, Gaussian kernel, bandwidth = median distance " + f"among real cells. E_N: scSemiProfiler's normalized error (Wang et al. 2024, eq. 17–18), their code's " + f"squared L2 on all cells, per-arm PCA-100; real vs real = within-sample half split " + f"({rng2(ctrl_en)}); every generated arm is above 1. LoRA-5 best of the 4 arms in {nb_knn}/{ntot} " + f"draws on kNN AUC, {nb_rf}/{ntot} on RF AUC, {nb_nn1}/{ntot} on 1-NN accuracy, {nb_mmd}/{ntot} on MMD², " + f"{nb_en}/{ntot} on E_N. " + + ("LoRA-5 better than scSemi-5, zero-shot and zero-shot + calibration on both AUCs, 1-NN accuracy and " + "coverage at k = 3, 5, 10 in every draw. " if wins_all else "") + + f"E_N scSemi-5 vs LoRA-5 (cohort means): {en_means}; LoRA-5 lower in {en_sc_better}/{en_sc_n} draws. " + f"Draws where LoRA-5 is worse (cohort means in brackets): {exc_txt if len(exc) else 'none'}. " + f"LoRA-5 AUC per draw " + f"{auc_draws.min():.2f}–{auc_draws.max():.2f} (kNN), RF cohort means {rng2(rf_l)}: a classifier still " + f"tells generated from real cells. Scores: scores_extra//fewshot_n5/draw/.") + S9.check_text(foot_a, "footnote") + 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}, " + f"MMD² {nb_mmd}/{ntot}, E_N {nb_en}/{ntot}", srcf) + 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}", + f"{X}//fewshot_n5/draw/en.csv (cellset all, distance sq)") + num("a", "LoRA-5 kNN AUC cohort means: " + ", ".join(f"{NAME[d]} {v:.3f}" for d, v in zip(ORDER, auc_l)) + + f"; per draw {auc_draws.min():.3f}–{auc_draws.max():.3f}", srcf) + num("a", "real vs real: kNN AUC " + ", ".join(f"{NAME[d]} {v:.3f}" for d, v in zip(ORDER, ctrl_auc)) + + "; E_N " + ", ".join(f"{NAME[d]} {v:.3f}" for d, v in zip(ORDER, ctrl_en)), srcf) + num("a", f"LoRA-5 worse than a comparator (draws): {exc_txt if len(exc) else 'none'}", srcf) + num("a", f"cross-check: {n_checked} cohort × arm × metric values equal scores_extra/{{fewshot,pooled}}_headline.csv", + f"{X}/fewshot_headline.csv; {X}/pooled_headline.csv") + slides.append({"title": "5 donors: realism beyond precision/coverage", "layout": "full", + "figures": [str(FIGDIR / "sec09_extra_fewpair.png")], "keywords": kw_a, "footnote": foot_a, + "footnote_short": fs_a, "numbers": NUMS["a"]}) + + # ---------------- slide b: 5-fold pooled ---------------- + comps = [a for a in arms5 if a != "lora"] + first = {} + for c, _, sign in HEAD: + first[c] = [ds for ds in ORDER if all(better(pooled[ds]["lora"][c], pooled[ds][a][c], sign) + for a in comps if a in pooled[ds])] + n_all = sum(len(v) == len(ORDER) for v in first.values()) + if n_all == len(HEAD): + kwb1 = f"Every metric: LoRA first in {len(ORDER)}/{len(ORDER)} cohorts" + else: + kwb1 = f"LoRA first everywhere on {n_all}/{len(HEAD)} metrics" + ji = pooled["ji2025_chili"] + oth = [ji[a]["en_all_sq"] for a in comps if a in ji] + kwb2 = S9.keyword_or_short(f"Ji whole blood: E_N {ji['lora']['en_all_sq']:.1f} vs {rng2(oth, 1)}", + f"Ji: E_N {ji['lora']['en_all_sq']:.1f} vs {rng2(oth, 1)}") + auc_p = [pooled[d]["lora"]["c2st_knn_auc"] for d in ORDER] + kwb3 = f"Still separable: LoRA AUC {rng2(auc_p)}" + kw_b = S9.check_keywords([kwb1, kwb2, kwb3]) + fs_b = S9.check_foot_short("Donor-level 5-fold CV, one pooled call per cohort. E_N: scSemiProfiler's own error " + "metric.") + 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)} + sc_txt = (f"scSemiProfiler, 5-fold CV (every training donor of the fold, inner-val included, as " + f"representatives; arm {SR.CV_ARM}) drawn for {', '.join(NAME[d] for d in has_sc)}; sources: " + + "; ".join(f"{NAME[d]} {pooled[d]['scsemi_all']['source']}" for d in has_sc) + ". " + if has_sc else "scSemiProfiler 5-fold CV not available yet (no extra-metric unit with set " + f"{SR.CV_ARM}). ") + foot_b = (f"Donor-level 5-fold CV; each pair scored once by the fold model that never trained on its donor (one " + f"pooled call per cohort, all cross-fitted pairs). Arms as on the 5-fold slide. Metric definitions as on " + f"the 5-donor realism slide. LoRA first among the {len(comps) + 1} arms in all {len(ORDER)} cohorts on " + f"{n_all}/{len(HEAD)} headline metrics (kNN and RF AUC, 1-NN accuracy, MMD² at σ = m and summed, E_N all " + f"cells, precision and coverage at k = 3, 5, 10)" + + (f"; exceptions: " + "; ".join(f"{k}: {', '.join(v)}" for k, v in lost.items()) if lost else "") + + f". LoRA kNN AUC " + ", ".join(f"{NAME[d]} {v:.3f}" for d, v in zip(ORDER, auc_p)) + + f"; real vs real " + ", ".join(f"{NAME[d]} {pooled[d]['control']['c2st_knn_auc']:.3f}" for d in ORDER) + + ". E_N LoRA vs other arms: " + "; ".join( + 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]])}" + for d in ORDER) + + f". {sc_txt}Scores: scores_extra//pooled/.") + S9.check_text(foot_b, "footnote") + num("b", f"LoRA first among {len(comps) + 1} arms in all {len(ORDER)} cohorts on {n_all}/{len(HEAD)} metrics", srcp) + num("b", f"Ji E_N: LoRA {ji['lora']['en_all_sq']:.3f}; " + + ", ".join(f"{LAB[a]} {ji[a]['en_all_sq']:.3f}" for a in comps if a in ji), srcp) + num("b", "LoRA kNN AUC (pooled): " + ", ".join(f"{NAME[d]} {v:.3f}" for d, v in zip(ORDER, auc_p)), srcp) + num("b", "scSemiProfiler, 5-fold CV: " + (", ".join(NAME[d] for d in has_sc) if has_sc else "not available"), + OUTDATA / "sec09_extra_scsemi_status.csv") + slides.append({"title": "5-fold: realism beyond precision/coverage", "layout": "full", + "figures": [str(FIGDIR / "sec09_extra_fivefold.png")], "keywords": kw_b, "footnote": foot_b, + "footnote_short": fs_b, "numbers": NUMS["b"]}) + + # ---------------- slide c: k sensitivity ---------------- + sets_k = FEW_ARMS + ["control"] + 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") + for d in ORDER for a in sets_k for q in ("coverage", "precision")) + ctrl_c3 = [few_mean(few, d, "control", "coverage_k3") for d in ORDER] + kwc1 = ("Smaller k lowers every set, real included" if mono else + f"Real vs real coverage at k = 3: {rng2(ctrl_c3)}") + cov_all_k = 0 + wc = {k: few_wide(few, f"coverage_k{k}") for k in KS} + for idx in wc[10].index: + 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") + for k in KS) + kwc2 = f"Coverage: LoRA-5 first at all k, {cov_all_k}/{len(wc[10])}" + pb = [best_draws(few, f"precision_k{k}")[0] for k in KS] + kwc3 = f"Precision: LoRA-5 first in {min(pb)}–{max(pb)}/{ntot} draws" if min(pb) != max(pb) else \ + f"Precision: LoRA-5 first in {pb[0]}/{ntot} draws" + kw_c = S9.check_keywords([kwc1, kwc2, kwc3]) + 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 " + "slides.") + # who beats LoRA-5 on precision, per k + who_n, who_arms = {}, set() + for k in KS: + w = few_wide(few, f"precision_k{k}") + for (d, j), r in w.iterrows(): + b = [a for a in FEW_ARMS if a != "lora" and not better(r["lora"], r[a], 1)] + if b: + who_n.setdefault(d, {kk: 0 for kk in KS})[k] += 1 + who_arms.update(b) + who = ", ".join(f"{NAME[d]} {'/'.join(str(who_n[d][k]) for k in KS)}" for d in ORDER if d in who_n) + who = (f"{who} draws at k = 3/5/10, beaten by {' or '.join(S9.LAB[a].lower() for a in sorted(who_arms))}" + if who else "none") + exp_cov = {} + for d in ORDER: + mt = pd.concat([pd.read_csv(u / "metrics.csv") for u in sorted((X / d / "fewshot_n5").glob("draw*"))]) + mt = mt[(mt["set"] == "lora5") & (mt.real_side == "R1") & (mt["mode"] == "raw")] + exp_cov[d] = "/".join(f"{mt[f'expected_coverage_identical_k{k}'].mean():.2f}" for k in KS) + exp_cov = (f"{next(iter(exp_cov.values()))} in every cohort" if len(set(exp_cov.values())) == 1 + else "; ".join(f"{NAME[d]} {v}" for d, v in exp_cov.items())) + same_rank, lora_top = [], [] + for d in ORDER: + 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} + same_rank.append(r[3] == r[5] == r[10]) + lora_top.append(all(r[k][0] == "lora" for k in KS)) + 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)}" + f"; LoRA first at every k in {sum(lora_top)}/{len(ORDER)} cohorts") + foot_c = (f"Precision and coverage recomputed with k = 3, 5, 10 nearest-neighbour balls in the scorer's PCA-50 " + f"(k = 10 reproduces the main-slide values exactly). Means over the 5 draws per cohort; error bars = SD; " + f"grey = real vs real (R1 vs R2, same samples). Both metrics fall with smaller k for every set " + f"{'including' if mono else 'but not always'} the real control (real coverage at k = 3: {rng2(ctrl_c3)}), " + f"so compare arms with the real row, not with 1. Expected coverage of a perfect generator (Naeem et al. " + f"2020, eq. 9) at k = 3/5/10: {exp_cov}. LoRA-5 first on coverage at every k in " + f"{cov_all_k}/{len(wc[10])} draws; on precision in {'/'.join(map(str, pb))} of {ntot} draws " + f"(k = 3/5/10); not first: {who}. 5-fold pooled design (not drawn): " + f"coverage ranking of the {len(arms5)} arms across k {pooled_rank}. Scores: " + f"scores_extra//fewshot_n5/draw/metrics.csv.") + S9.check_text(foot_c, "footnote") + num("c", f"LoRA-5 first on coverage at k = 3, 5 and 10: {cov_all_k}/{len(wc[10])} draws", srcf) + num("c", f"LoRA-5 first on precision (draws) at k = 3/5/10: {'/'.join(map(str, pb))} of {ntot}", srcf) + num("c", "real vs real coverage at k = 3: " + ", ".join(f"{NAME[d]} {v:.3f}" for d, v in zip(ORDER, ctrl_c3)), srcf) + num("c", f"every set falls with smaller k (cohort means): {mono}", srcf) + slides.append({"title": "5 donors: precision/coverage at k = 3, 5, 10", "layout": "full", + "figures": [str(FIGDIR / "sec09_extra_ksens.png")], "keywords": kw_c, "footnote": foot_c, + "footnote_short": fs_c, "numbers": NUMS["c"]}) + + for s in slides: + for k in ("title", "footnote", "footnote_short"): + S9.check_text(s[k], k) + for n in s["numbers"]: + S9.check_text(n["value"], "quoted number") + spec = {"section": "09-extra", "slides": slides, "scripts": [str(SCRIPT)], + "generated_from": "tools/sec09_extra_metrics.py (rerun to refresh; do not edit by hand)", + "scsemi_cv_cohorts": [NAME[d] for d in has_sc]} + (OUTDATA / "sec09_extra_slide_text.json").write_text(json.dumps(spec, indent=1, ensure_ascii=False)) + pd.DataFrame([{"slide": k, "value": n["value"], "source": n["source"]} for k in "abc" for n in NUMS[k]]).to_csv( + OUTDATA / "sec09_extra_quoted_numbers.csv", index=False) + for p in [OUTDATA / "sec09_extra_slide_text.json"] + sorted(OUTDATA.glob("sec09_extra_*.csv")): + m = S9.OFF_STORY.search(p.read_text(encoding="utf-8")) + if m: + raise ValueError(f"{p}: off-story text {m.group(0)!r}") + + print(f"cross-checked {n_checked} values against the collector's headline tables") + if not has_sc: + print(f"NOTE: no scSemiProfiler 5-fold extra-metric unit (set {SR.CV_ARM}) under " + f"{SR.plan_root()}/scores_extra//{SR.CV_EXP}/ or in the pooled units; the 5-fold figure has no " + f"scSemiProfiler row.") + else: + print(f"scSemiProfiler, 5-fold CV drawn for: {[NAME[d] for d in has_sc]}") + for r in sclog.itertuples(): + print(f" scSemiProfiler extra unit {r.dataset} {r.design} {r.set}: {r.status} {r.reason} ({r.unit})") + for s in slides: + print(f"\n== {s['title']}") + for k in s["keywords"]: + print(" *", k, f"({S9.n_words(k)} words, {len(k)} chars)") + print(" footnote_short:", s["footnote_short"], f"({len(s['footnote_short'])} chars)") + print(" footnote:", s["footnote"]) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/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 b/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 new file mode 100644 index 0000000000000000000000000000000000000000..7a58b7b0ee1cc3b76a9b6948a1e17e2c544d7d27 --- /dev/null +++ b/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 +1,1654 @@ +#!/usr/bin/env python3 +"""Section 9 of the 2026-09-30 paper-summary deck: the final method in five paired cohorts, +and scSemiProfiler trained on the same 5 donors. + +CPU only: reads score files, draws slide-sized figures. No torch, no CUDA, no generation, no scANVI. + +Data loading is imported unchanged from the benchmark's own figure script +(plans/paired_finetune_intradataset_20260927/figures/make_figures.py: load_fewpair, load_pooled), +so every plotted number and every scSemiProfiler acceptance check (same donor set, same reference +sha, receipt verified) is the same as in the paper figures. Only the drawing is new. + +Outputs (deck folder): + figures/sec09_cohorts.{png,pdf} slide a: five paired cohorts (table) + figures/sec09_fewpair_cells.{png,pdf} slide b: 5 donors, cell-level metrics + figures/sec09_fewpair_disease.{png,pdf} slide c: 5 donors, disease signal + figures/sec09_fivefold.{png,pdf} slide d: all pairs, 5-fold pooled + data/sec09_*.csv every plotted number with its source file + data/sec09_slide_text.json slide titles, keywords, footnotes (long "footnote" for the speaker + notes + one-line "footnote_short") and quoted numbers (+ sources), + all built by this script from the same data as the figures + data/sec09_quoted_numbers.csv the quoted numbers as a flat table + +Baselines (user decisions 2026-09-30 and 2026-10-01): the no-fine-tune baseline is zero-shot on the real bulk as +measured (few-pair arm zs_raw, pooled arm zs__raw). The gene-wise calibration comparator is back (2026-10-01) and is +called "Zero-shot + calibration" (few-pair arm zs_cal, alpha fitted on the same 5 training donors; pooled arm zs__cal, +alpha from each fold's training donors). The sc-only control is the sc-only fine-tune fed calibrated bulk (pooled arm +pseudo_full__cal, "sc-only fine-tune (+ calibration)"). OFF_STORY still bans refcal / reference calibration, VAE, +TPM, AIFI and AIDA wording in every output. + +Giroux (user decision 2026-10-01): severity is confounded with sex, so its disease-signal metrics (logFC r, partial r, +top-50 DEG, broadcast) are read from scores_nosex/giroux2022/ (tools/rescore_excluding_genes.py: the same calls with +data/sex_linked_genes/sex_linked_genes_exclude.csv excluded and the same frozen labels). Every other Giroux metric is +asserted equal to the original scores/ files. The other cohorts use scores/ unchanged. + +scSemiProfiler with all training pairs (5-fold CV, arm scsemi__raw; added 2026-10-02): drawn as its own bar on the 5-fold +slide when an accepted pooled call exists at scores//scsemi_cv_20261002/pooled*/ (tools/scsemi_results.py: same donors, +same reference cells, receipt not unverified). Giroux's disease metrics for it are read from +scores_nosex/giroux2022/scsemi_cv_20261002/ when that rescore exists, else left blank ("rescore pending"). Without any +accepted call a note is printed and the slide is unchanged. DECK_FIGDIR / DECK_OUTDATA redirect the outputs and +DECK_SCSEMI_PLAN_ROOT the scSemiProfiler lookup (synthetic presence test). + +RERUN CHECKLIST (all 25 scSemiProfiler draws are scored; rerun whenever a score file changes): + 1. /home/sj_server_1/miniforge3/bin/python3 tools/sec09_paired_validation.py (no edits needed; must exit 0) + 2. Rebuild the four slides from data/sec09_slide_text.json: every title, keyword line, footnote and quoted + number there is regenerated. Do not keep hand-copied slide text. + 3. Look at the four PNGs again. +""" +from __future__ import annotations + +import os + +os.environ["CUDA_VISIBLE_DEVICES"] = "" # plotting only + +import gzip +import importlib +import importlib.util +import json +import re +import sys +from pathlib import Path + +import numpy as np +import pandas as pd +from scipy.stats import wilcoxon + +DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/" + "2026-09-30--paper-summary--r00") +T = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/" + "paired_finetune_intradataset_20260927") +SCORES = T / "scores" +DATA = T / "data" +FIGDIR = Path(os.environ.get("DECK_FIGDIR", str(DECK / "figures"))) +OUTDATA = Path(os.environ.get("DECK_OUTDATA", str(DECK / "data"))) +SCRIPT = DECK / "tools" / "sec09_paired_validation.py" +DATALAKE = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc") + +# 1) the benchmark's loaders (this import sets print-size rcParams) ... +_spec = importlib.util.spec_from_file_location("pf_make_figures", T / "figures" / "make_figures.py") +mf = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(mf) +# 2) ... then the deck style, which must win the rcParams +sys.path.insert(0, str(DECK / "tools")) +import style # noqa: E402 +import scsemi_results as SR # noqa: E402 + +importlib.reload(style) +import matplotlib.pyplot as plt # noqa: E402 +from matplotlib.lines import Line2D # noqa: E402 +from matplotlib.patches import Patch # noqa: E402 +from matplotlib.ticker import MaxNLocator # noqa: E402 + +# deck order: healthy first, whole-blood cohort last +ORDER = ["immicro", "ye2026_sepsis", "imperial_eskd", "giroux2022", "ji2025_chili"] +DISEASE = [d for d in ORDER if d != "immicro"] +NAME = {"immicro": "ImMicro", "ye2026_sepsis": "Sepsis", "imperial_eskd": "Imperial", + "giroux2022": "Giroux", "ji2025_chili": "Ji"} +ROWNAME = {**NAME, "ji2025_chili": "Ji (whole blood)"} +# pale = raw real bulk, #0072B2 = calibrated (the pair used by sections 7 and 8 and the paper figures) +COL = {"zs_raw": style.ARM["zs_raw"], "zs_cal": style.ARM["zs_cal"], "scsemi5": style.ARM["scsemi"], + "lora": style.ARM["lora"], "sconly_cal": style.ARM["sconly"], "scsemi_all": style.ARM["scsemi"]} +LAB = {"zs_raw": "Zero-shot, real bulk", "zs_cal": "Zero-shot + calibration", "scsemi5": "scSemiProfiler, 5 donors", + "lora": "LoRA, 5 donors", "sconly_cal": "sc-only fine-tune (+ calibration)", + "lora_all": "LoRA, 5-fold CV (other 4 folds)", "scsemi_all": SR.LABEL_CV} +# few-pair arms kept from load_fewpair (canonical key -> arm name in summary.json); everything else is dropped +ARM_FILE = {"lora": "lora5", "scsemi5": "scsemi5", "zs_raw": "zs_raw", "zs_cal": "zs_cal", "pseudo": "zs_pseudo"} +# pooled 5-fold arms (plot key -> arm name in scores//pooled/summary.json) +POOLED_ARMS = {"zs_raw": "zs__raw", "zs_cal": "zs__cal", "sconly_cal": "pseudo_full__cal", "lora": "real_lora__raw"} +SC_ALL = "scsemi_all" # plot key of scSemiProfiler with all training pairs (pooled arm SR.CV_ARM), drawn when present +POOLED_FILE = {**POOLED_ARMS, SC_ALL: SR.CV_ARM} +# text that must not appear in any figure, CSV label or slide text of this section ("calibration" itself is allowed) +OFF_STORY = re.compile(r"refcal|reference[ -]calibrat|\bVAE\b|\bTPM\b|\bAIFI\b|\bAIDA\b", re.I) +# Giroux: disease-signal metrics without sex-linked genes (see module docstring) +SCORES_NOSEX = T / "scores_nosex" +NOSEX = ("giroux2022",) +SEXLIST = DATA / "sex_linked_genes" / "sex_linked_genes_exclude.csv" +DISEASE_KEYS = ("contrast_r", "broadcast_r", "deg", "deg_broadcast", "deg_max", "r_type", "bc_type") +KW_MAX_CHARS = 45 # keyword line length on the slide +FOOT_SHORT_MAX = 110 # one-line on-slide footnote +REFSTYLE = {"pseudo": dict(ls=(0, (4, 2)), color=style.ARM["pseudo"], lw=1.6, label="Zero-shot, sc pseudobulk input"), + "broadcast": dict(ls=(0, (1, 1.2)), color=style.ARM["broadcast"], lw=2.4, label="Real-bulk broadcast"), + "ceiling": dict(ls="-", color="#1A1A1A", lw=1.8, label="Split-half ceiling (observed vs observed)")} +# 2026-10-02: rank / threshold-free disease metrics from plans/.../scores_contrast (tools/contrast_extra.py): +# Spearman r, split-half ceiling (noise-free, Spearman-Brown), limma-voom top-50 DEG and the chance overlap of both DEG +# tests (hypergeometric mean). Pearson r and Welch top-50 there must equal the scorer's values used below. +CX = T / "scores_contrast" +CX_ARM = {"zs_raw": "zs_raw", "zs_cal": "zs_cal", "scsemi5": "scsemi5", "lora": "lora5"} +CHANCE_COL = "#7A7A7A" +EDGE = "#333333" +SUB = "#595959" +FS = style.FS +HILITE = "#FFF3D1" +LEFT_IN = 2.25 # room for the row labels (cohort + train/test pairs) +WIN_FRAC = 0.8 # a cohort verdict needs one method better in >= 80 % of the shared draws +QC = {d: DATA / d / "QC_REPORT.md" for d in DISEASE} +ARGS = T / "tools" / "contrast_args.sh" +README = T / "README.md" +SCORE_FT = T / "tools" / "score_ft.py" +PREPARE = T / "tools" / "prepare_dataset.py" +INV = DATALAKE / "docs" / "dataset_inventory.csv" +SOFT_SC = DATALAKE / "datasets" / "GSE314416" / "metadata" / "GSE314416_family.soft.gz" +SOFT_BULK = DATALAKE / "datasets" / "GSE314922" / "metadata" / "GSE314922_family.soft.gz" + +CKPT = "runs/f01_6k_1x_seed20260627/checkpoint_epoch_016.pt" +NUMS = {k: [] for k in "abcd"} # slide -> [{"value", "source"}] quoted on the slide +EXTRA = [] # further numbers written to the CSV only + + +def num(slide, value, source): + NUMS[slide].append({"value": str(value), "source": str(source)}) + + +def extra(slide, item, value, source): + EXTRA.append({"slide": slide, "item": item, "value": str(value), "source": str(source)}) + + +def rng(vals, fmt="{:d}"): + vals = sorted(set(vals)) + return fmt.format(vals[0]) if len(vals) == 1 else f"{fmt.format(vals[0])}–{fmt.format(vals[-1])}" + + +# ------------------------------------------------------------------------------------------ +# Evidence: every label on the cohort table must match ONE line of its source file +# ------------------------------------------------------------------------------------------ +_TEXT_CACHE: dict = {} + + +def _read_text(p: Path) -> str: + if p not in _TEXT_CACHE: + if p.suffix == ".gz": + with gzip.open(p, "rt", encoding="utf-8", errors="replace") as fh: + _TEXT_CACHE[p] = fh.read() + else: + _TEXT_CACHE[p] = p.read_text(encoding="utf-8", errors="replace") + return _TEXT_CACHE[p] + + +def evidence(p: Path, pattern: str) -> str: + """The full source line (with its number) that contains a match of `pattern`; the match may not span lines.""" + text = _read_text(p) + m = re.search(pattern, text, flags=re.M) + if not m: + raise ValueError(f"evidence not found: /{pattern}/ in {p}") + if "\n" in m.group(0): + raise ValueError(f"evidence /{pattern}/ spans lines in {p}") + a = text.rfind("\n", 0, m.start()) + 1 + b = text.find("\n", m.end()) + line = text[a:(len(text) if b < 0 else b)].strip() + return f"L{text.count(chr(10), 0, m.start()) + 1}: {line[:240]}" + + +def match_text(p: Path, pattern: str) -> str: + """Only the matched text (one line) of `pattern` in p, after the same checks as evidence().""" + evidence(p, pattern) + return re.search(pattern, _read_text(p), flags=re.M).group(0) + + +def evidences(pairs) -> tuple[str, str]: + ev = [evidence(p, pat) for p, pat in pairs] + return " || ".join(ev), " ; ".join(sorted({str(p) for p, _ in pairs})) + + +# display text -> [(file, one-line regex), ...]; each regex must match a single line of its file +COHORT_TEXT = { + "immicro": { + "study": ("ImMicro 2026", [(INV, r"Babdor et al\., Cell 2026 ImMicro")]), + "disease": ("healthy", [(INV, r'Babdor et al\., Cell 2026 ImMicro",Healthy humans')]), + "bulk": ("PBMC, mRNA-Seq", [(SOFT_BULK, r"^!Sample_source_name_ch1 = PBMC *$"), + (SOFT_BULK, r"Universal Plus mRNA-Seq with NuQuant kit")]), + "sc": ("10x 5′ v1.1 CITE-seq", [(SOFT_SC, r"Chromium Next GEM Single Cell 5.{1,2} v1\.1 Library Kit"), + (SOFT_SC, r"Library strategy: CITE-seq")]), + }, + "ye2026_sepsis": { + "study": ("Ye 2026", [(QC["ye2026_sepsis"], r"Ye Q et al\., Nat Immunol 2026")]), + "disease": ("sepsis", [(QC["ye2026_sepsis"], r"^# Ye 2026 sepsis")]), + # extraction is total RNA (Trizol) but the library (polyA vs rRNA depletion) is not stated -> show PBMC only + "bulk": ("PBMC", [(QC["ye2026_sepsis"], r"GEO protocol: PBMC total RNA \(Trizol\).*polyA vs rRNA depletion not stated")]), + "sc": ("10x 5′", [(QC["ye2026_sepsis"], r"Chemistry: GEO says .*but the data show 5'")]), + }, + "imperial_eskd": { + "study": ("Imperial ESKD", [(QC["imperial_eskd"], r"patients with COVID-19, Imperial cohort")]), + "disease": ("COVID-19, dialysis", [(QC["imperial_eskd"], r"haemodialysis \(end-stage kidney disease\) patients with COVID-19")]), + "bulk": ("PBMC", [(QC["imperial_eskd"], r"^- Bulk: .*PBMC RNA-seq")]), + "sc": ("10x 5′ v2 CITE-seq", [(QC["imperial_eskd"], r"^- scRNA: .*PBMC CITE-seq"), + (QC["imperial_eskd"], r"Chemistry: 10x 5′ v2")]), + }, + "giroux2022": { + "study": ("Giroux 2022", [(QC["giroux2022"], r"Giroux NS et al\., Sci Rep 2022")]), + "disease": ("COVID-19, outpatient", [(QC["giroux2022"], r"Duke outpatients, early COVID-19")]), + "bulk": ("PBMC, total RNA (SoLo)", [(QC["giroux2022"], r"^# Giroux 2022 COVID-19: paired PBMC bulk and scRNA"), + (QC["giroux2022"], r"GEO protocol: Zymo Direct-zol total RNA, NuGEN Ovation SoLo")]), + "sc": ("10x 5′ v1", [(QC["giroux2022"], r"10x library per subject-day \(5' v1")]), + }, + "ji2025_chili": { + "study": ("Ji 2025", [(QC["ji2025_chili"], r"Ji C et al\., Cancer Immunol Immunother 2025")]), + "disease": ("ICI liver injury", [(QC["ji2025_chili"], r"liver injury on checkpoint inhibitors \(ChILI\)")]), + "bulk": ("whole blood, 3′ QuantSeq", [(QC["ji2025_chili"], r"\*\*PAXgene whole-blood tubes\*\*"), + (QC["ji2025_chili"], r"Protocol: Lexogen QuantSeq 3′ FWD")]), + "sc": ("10x 5′", [(QC["ji2025_chili"], r"Chemistry: 10x 5′ GEX")]), + }, +} +# display labels of the scorer's case / control groups; the group lists are asserted against summary.json and +# contrast_args.sh; `neither` = groups scored in neither arm of the contrast +CONTRAST = { + "ye2026_sepsis": dict(case="sepsis", control="control", case_groups=["adult_sepsis", "ped_sepsis"], + control_groups=["adult_HC", "adult_ICU_ctrl", "ped_HC", "ped_ICU_ctrl"], neither=[], + ev=[(ARGS, r'ye2026_sepsis\) echo "--case-groups adult_sepsis,ped_sepsis ' + r'--control-groups adult_HC,adult_ICU_ctrl,ped_HC,ped_ICU_ctrl"')]), + "imperial_eskd": dict(case="COVID+", control="COVID−", case_groups=["covid_positive"], + control_groups=["covid_negative"], neither=["recovery"], + ev=[(ARGS, r"COVID-positive vs COVID-negative haemodialysis patients \(recovery samples in neither group\)"), + (ARGS, r'imperial_eskd\) echo "--case-groups covid_positive --control-groups covid_negative"')]), + # the GEO label is "severe"; the paper and the author sheet call this group "moderate" (all are outpatients) + "giroux2022": dict(case="moderate", control="mild", case_groups=["severe"], control_groups=["mild"], neither=[], + ev=[(QC["giroux2022"], r'The paper and the author sheet call the "severe" group "moderate"'), + (ARGS, r'giroux2022\) echo "--case-groups severe --control-groups mild"')]), + "ji2025_chili": dict(case="ChILI", control="ICI control", case_groups=["TOL", "FU1"], control_groups=["BC", "AC"], + neither=[], + ev=[(ARGS, r"ChILI patients \(liver injury and its follow-up\) vs checkpoint-inhibitor controls"), + (ARGS, r'ji2025_chili\) echo "--case-groups TOL,FU1 --control-groups BC,AC"')]), +} + + +def usable_folds(ds): + f = pd.read_csv(DATA / ds / "folds.csv") + f["donor_id"] = f["donor_id"].astype(str) + f["sample_id"] = f["sample_id"].astype(str) + return f[f.fold >= 0].copy() + + +def min_cells() -> int: + return int(re.search(r"^MIN_CELLS = (\d+)", _read_text(PREPARE), flags=re.M).group(1)) + + +def cohort_rows(): + mc = min_cells() + rows = [] + for ds in ORDER: + r = {"dataset": ds} + for key, (txt, pairs) in COHORT_TEXT[ds].items(): + r[key] = txt + r[f"{key}_evidence"], r[f"{key}_source"] = evidences(pairs) + dj = DATA / ds / "fewshot_n5" / "DRAWS.json" + draws = json.loads(dj.read_text()) + used = usable_folds(ds) + if len(used) != draws["n_usable_rows"] or used.donor_id.nunique() != draws["n_usable_donors"]: + raise ValueError(f"{ds}: folds.csv and DRAWS.json disagree on usable rows/donors") + # exclusion tally, re-derived with prepare_dataset.py's rule: identity_pass & n_cells >= MIN_CELLS + feats = np.load(DATA / ds / "features.npz", allow_pickle=False) + samples = pd.read_csv(DATA / ds / "samples.csv") + n_all = int(feats["bulk_raw"].shape[0]) + idp = feats["identity_pass"].astype(bool) if "identity_pass" in feats.files else np.ones(n_all, bool) + chk = (pd.Series(feats["identity_check"].astype(str)).str.split(":").str[0].str.strip() + if "identity_check" in feats.files else pd.Series(["(no flag)"] * n_all)) + low = (samples["n_cells"].to_numpy() < mc) + n_fail, n_border = int((chk == "fail").sum()), int((chk == "borderline").sum()) + if int((~idp).sum()) != n_fail + n_border: + raise ValueError(f"{ds}: identity_pass False rows != fail + borderline") + n_low = int((idp & low).sum()) + if n_all - n_fail - n_border - n_low != draws["n_usable_rows"]: + raise ValueError(f"{ds}: exclusion tally does not reproduce the usable rows") + pooled_sum = json.loads((SCORES / ds / "pooled" / "summary.json").read_text()) + if pooled_sum["n_donors"] != draws["n_usable_rows"]: + raise ValueError(f"{ds}: pooled scored n {pooled_sum['n_donors']} != usable rows {draws['n_usable_rows']}") + r.update(n_pairs_all=n_all, n_identity_fail=n_fail, n_identity_borderline=n_border, + n_low_cells=n_low, min_cells=mc, identity_flag=("identity_pass" in feats.files), + n_rows=draws["n_usable_rows"], n_donors=draws["n_usable_donors"], n_rows_source=str(dj), + exclusion_source=f"{DATA / ds / 'features.npz'} (identity_pass, identity_check); " + f"{DATA / ds / 'samples.csv'} (n_cells); {PREPARE} (MIN_CELLS)") + cd = pooled_sum["contrast_definition"] + psrc = str(SCORES / ds / "pooled" / "summary.json") + if ds in CONTRAST: + C = CONTRAST[ds] + if list(cd["case_groups"]) != C["case_groups"] or list(cd["control_groups"]) != C["control_groups"]: + raise ValueError(f"{ds}: contrast groups changed: {cd['case_groups']} / {cd['control_groups']}") + neither = sorted({g for g, a, b in zip(cd["groups"], cd["case"], cd["ctrl"]) if not a and not b}) + if neither != sorted(C["neither"]) or (int(cd.get("n_donors_in_neither", 0)) > 0) != bool(neither): + raise ValueError(f"{ds}: groups in neither arm {neither} != expected {C['neither']}") + ev, evsrc = evidences(C["ev"]) + r.update(case_label=C["case"], control_label=C["control"], n_case=int(cd["n_case_donors"]), + n_control=int(cd["n_control_donors"]), n_neither=int(cd.get("n_donors_in_neither", 0)), + neither_label=",".join(neither), contrast_source=psrc, contrast_label_evidence=ev, + contrast_label_source=evsrc) + else: + if cd.get("enabled"): + raise ValueError(f"{ds}: expected no contrast") + r.update(case_label="", control_label="", n_case=np.nan, n_control=np.nan, n_neither=0, + neither_label="", contrast_source=psrc) + rows.append(r) + return pd.DataFrame(rows) + + +def fig_cohorts(tab: pd.DataFrame): + """Plain table: columns are placed by measuring the rendered text, so nothing overlaps.""" + headers = ["Cohort", "Condition", "Bulk", "scRNA-seq", "Pairs (donors)", "Case vs control"] + center = {4} + body = [] + for r in tab.itertuples(): + pd_txt = f"{r.n_rows}" if r.n_rows == r.n_donors else f"{r.n_rows} ({r.n_donors})" + ctxt = (f"{r.case_label} {int(r.n_case)} vs {r.control_label} {int(r.n_control)}" if r.case_label + else "none (healthy)") + csub = f"+{r.n_neither} {r.neither_label} (neither)" if r.n_neither else None + body.append([(r.study, {}, None), (r.disease, {}, None), + (r.bulk, {"fontweight": "bold"} if r.dataset == "ji2025_chili" else {}, None), + (r.sc, {}, None), (pd_txt, {}, None), (ctxt, {} if r.case_label else {"color": SUB}, csub)]) + W, H = style.FULL[0], 3.7 + fig = plt.figure(figsize=(W, H)) + ax = fig.add_axes([0.0, 0.0, 1.0, 1.0]) + ax.set_axis_off() + ax.set_xlim(0, 1) + ax.set_ylim(0, 1) + n = len(body) + top, rowh = 0.87, 0.84 / n + texts = [[] for _ in headers] + for j, h in enumerate(headers): + texts[j].append(ax.text(0, top + 0.055, h, ha="left", va="center", fontsize=FS, fontweight="bold", + color=style.INK)) + for i, row in enumerate(body): + y = top - rowh * (i + 0.5) + for j, (txt, kw, sub) in enumerate(row): + if sub: + texts[j].append(ax.text(0, y + 0.03, txt, ha="left", va="center", fontsize=FS, + **{"color": style.INK, **kw})) + texts[j].append(ax.text(0, y - 0.035, sub, ha="left", va="center", fontsize=FS - 3, color=SUB)) + else: + texts[j].append(ax.text(0, y, txt, ha="left", va="center", fontsize=FS, + **{"color": style.INK, **kw})) + fig.canvas.draw() + rend = fig.canvas.get_renderer() + widths = [max(t.get_window_extent(rend).width for t in col) / (fig.dpi * W) for col in texts] + gap = (1.0 - sum(widths)) / (len(headers) - 1) + if gap < 0.012: + raise ValueError(f"cohort table too wide for the slide (gap {gap:.3f})") + x = 0.0 + for j, col in enumerate(texts): + for t in col: + if j in center: + t.set_x(x + widths[j] / 2) + t.set_ha("center") + else: + t.set_x(x) + x += widths[j] + gap + ax.plot([0, 1], [top + 0.005] * 2, color=style.INK, lw=1.2) + for i in range(1, n): + ax.plot([0, 1], [top - rowh * i] * 2, color="#C8C8C8", lw=0.7) + ax.plot([0, 1], [top - rowh * n] * 2, color=style.INK, lw=1.2) + style.save(fig, "sec09_cohorts", FIGDIR) + + +# ------------------------------------------------------------------------------------------ +# Shared drawing helpers: rows = cohorts, columns = metrics, horizontal bars +# ------------------------------------------------------------------------------------------ +BAR_H = 0.72 + + +def jitter(n, seed): + r = np.random.default_rng(seed) + return (r.random(n) - 0.5) * BAR_H * 0.6 + + +def hbars(ax, arms, vals_of, seed=0, dots=True, na_text=None): + """arms drawn top to bottom at y = 0..na-1. vals_of(arm) -> list of floats. Returns stats. + na_text: {arm: text} shown instead of "not run" when an arm has no value.""" + out = {} + for i, arm in enumerate(arms): + vals = np.asarray([v for v in vals_of(arm) if not np.isnan(v)], float) + if len(vals) == 0: + ax.text(0.01, i, (na_text or {}).get(arm, "not run"), transform=ax.get_yaxis_transform(), va="center", + fontsize=FS - 3, color=SUB) + out[arm] = (np.nan, np.nan, 0) + continue + m = float(vals.mean()) + sd = float(vals.std(ddof=1)) if len(vals) > 1 else 0.0 + ax.barh(i, m, height=BAR_H, color=COL[arm], edgecolor=EDGE, linewidth=0.6, zorder=2) + if dots and len(vals) > 1: + ax.errorbar(m, i, xerr=sd, fmt="none", ecolor="#111111", elinewidth=1.0, capsize=3, capthick=1.0, + zorder=4) + # dots unclipped so a draw at an axis end (precision 1.0) stays whole; check_inside() asserts that every + # dot and bar lies within the final x-limits. SD whiskers stay clipped (a count's SD can reach below 0). + ax.scatter(vals, i + jitter(len(vals), seed + i), s=16, facecolor="white", edgecolor="#111111", + linewidth=0.7, zorder=5, clip_on=False) + out[arm] = (m, sd, len(vals)) + ax.set_ylim(len(arms) - 0.5, -0.5) + ax.set_yticks([]) + return out + + +def check_inside(fig, name): + """Every draw dot, bar end and reference line lies within its panel's final x-limits (nothing cut off).""" + from matplotlib.collections import PathCollection + from matplotlib.patches import Rectangle + for ax in fig.axes: + lo, hi = sorted(ax.get_xlim()) + eps = 1e-9 * max(1.0, abs(hi - lo)) + xs = [float(x) for c in ax.collections if isinstance(c, PathCollection) for x in c.get_offsets()[:, 0]] + xs += [x for p in ax.patches if isinstance(p, Rectangle) for x in (p.get_x(), p.get_x() + p.get_width())] + xs += [float(x) for ln in ax.lines for x in np.atleast_1d(ln.get_xdata()) if ln.get_linestyle() != "None"] + bad = [x for x in xs if not (lo - eps <= x <= hi + eps)] + if bad: + raise ValueError(f"{name}: value(s) {bad[:3]} outside the x-limits ({lo:.3g}, {hi:.3g})") + + +def ref_line(ax, x, kind, na): + """Reference line above the bars (zorder 2) but below error bars (4) and draw dots (5).""" + if x is None or np.isnan(x): + return + s = REFSTYLE[kind] + ax.plot([x, x], [-0.5, na - 0.5], ls=s["ls"], color=s["color"], lw=s["lw"], zorder=3, + solid_capstyle="butt") + + +def row_label(ax, name, subs): + """Cohort name (FS) with grey sub-lines (FS-3) stacked below it, the block centred on the row.""" + lines = [(name, FS, style.INK)] + [(s, FS - 3, SUB) for s in subs] + y = sum(fs * 1.3 for _, fs, _ in lines) / 2 + for txt, fs, col in lines: + h = fs * 1.3 + ax.annotate(txt, xy=(0, 0.5), xycoords="axes fraction", xytext=(-12, y - h / 2), textcoords="offset points", + ha="right", va="center", fontsize=fs, color=col) + y -= h + + +def label_header(ax, text): + ax.annotate(text, xy=(0, 1), xycoords="axes fraction", xytext=(-12, 10), textcoords="offset points", + ha="right", va="bottom", fontsize=FS - 3, color=SUB, style="italic") + + +def blank(ax, text): + for sp in ax.spines.values(): + sp.set_visible(False) + ax.set_xticks([]) + ax.set_yticks([]) + ax.text(0.5, 0.5, text, transform=ax.transAxes, ha="center", va="center", fontsize=FS - 3, color=SUB, + style="italic") + + +def grid(nrows, ncols, figsize, left, right, top, bottom, hspace, wspace): + fig = plt.figure(figsize=figsize) + gs = fig.add_gridspec(nrows, ncols, left=left / figsize[0], right=1 - right / figsize[0], + top=1 - top / figsize[1], bottom=bottom / figsize[1], hspace=hspace, wspace=wspace) + axs = np.empty((nrows, ncols), dtype=object) + for i in range(nrows): + for j in range(ncols): + axs[i, j] = fig.add_subplot(gs[i, j]) + return fig, axs + + +def shared_x(axs_col, lo, hi, xlabel, ticks=None): + for k, ax in enumerate(axs_col): + ax.set_xlim(lo, hi) + if ticks is not None: + ax.set_xticks(ticks) + if k < len(axs_col) - 1: + ax.tick_params(axis="x", labelbottom=False, length=0) + ax.spines["bottom"].set_visible(False) + axs_col[-1].set_xlabel(xlabel) + + +def legend_bottom(fig, handles, ncol, y=0.0): + fig.legend(handles=handles, loc="lower center", bbox_to_anchor=(0.5, y), ncol=ncol, frameon=False, + fontsize=FS - 2, handlelength=2.2, columnspacing=1.6, borderaxespad=0.0) + + +def patch(key, label=None): + return Patch(facecolor=COL[key], edgecolor=EDGE, linewidth=0.6, label=label or LAB[key]) + + +def refh(kind): + s = REFSTYLE[kind] + return Line2D([0], [0], ls=s["ls"], color=s["color"], lw=s["lw"], label=s["label"]) + + +def dot_handle(n_draws): + lab = "one draw; bar = mean ± SD" + (f" of {n_draws}" if n_draws else "") + return Line2D([0], [0], marker="o", lw=0, markerfacecolor="white", markeredgecolor="#111111", + markersize=5, label=lab) + + +# ------------------------------------------------------------------------------------------ +# Few-pair (5 donors) data +# ------------------------------------------------------------------------------------------ +_JSON: dict = {} + + +def jload(p: Path): + if p not in _JSON: + _JSON[p] = json.loads(Path(p).read_text()) + return _JSON[p] + + +def load_nosex(loader): + """A make_figures loader (load_fewpair / load_pooled, unchanged) run on SCORES_NOSEX for the NOSEX cohorts only.""" + saved = mf.DATASETS + mf.DATASETS = list(NOSEX) + try: + return loader(SCORES_NOSEX) + finally: + mf.DATASETS = saved + + +def nosex_calls(ds): + """Every sex-gene-excluded score dir of a cohort: same exclusion file (the current one), labels reused from the + original call of the same relative path.""" + out = [] + for p in sorted((SCORES_NOSEX / ds).rglob("summary.json")): + s = jload(p) + ge = s.get("gene_exclusion") + if ge is None or Path(ge["file"]) != SEXLIST or ge["sha256"] != mf_sha(SEXLIST): + raise ValueError(f"{p}: not scored with the current {SEXLIST}") + rel = p.parent.relative_to(SCORES_NOSEX) + if Path(s["labels_reused_from"]) != SCORES / rel: + raise ValueError(f"{p}: labels not reused from {SCORES / rel}") + out.append(p) + return out + + +_SHA: dict = {} + + +def mf_sha(p: Path) -> str: + if p not in _SHA: + import hashlib + _SHA[p] = hashlib.sha256(Path(p).read_bytes()).hexdigest() + return _SHA[p] + + +def same_non_disease(a: dict, b: dict, what: str): + """Every metric except the disease-signal ones must be identical between original and sex-gene-excluded scores.""" + for k in ("comp_l1", "null", "precision", "coverage", "n_scored"): + if not (a[k] == b[k] or (np.isnan(a[k]) and np.isnan(b[k]))): + raise ValueError(f"{what}: {k} differs between scores/ and scores_nosex/ ({a[k]} vs {b[k]})") + + +def fewpair(): + few, status = mf.load_fewpair(SCORES) + fn, sn = load_nosex(mf.load_fewpair) + for ds in NOSEX: # Giroux: disease metrics without sex-linked genes; everything else must be unchanged + nosex_calls(ds) + o = few[few.dataset == ds].set_index(["draw", "arm"]).sort_index() + n = fn[fn.dataset == ds].set_index(["draw", "arm"]).sort_index() + if list(o.index) != list(n.index): + raise ValueError(f"{ds}: few-pair draws/arms differ between scores/ and scores_nosex/") + for key in o.index: + same_non_disease(o.loc[key], n.loc[key], f"{ds} few-pair {key}") + so = status[status.dataset == ds][["draw", "status"]].reset_index(drop=True) + if not so.equals(sn[["draw", "status"]].reset_index(drop=True)): + raise ValueError(f"{ds}: scSemiProfiler acceptance differs between scores/ and scores_nosex/") + few = pd.concat([few[few.dataset != ds], fn], ignore_index=True) + status = pd.concat([status[status.dataset != ds], sn], ignore_index=True) + few = few[few.arm.isin(ARM_FILE)].reset_index(drop=True) + status = status.sort_values(["dataset", "draw"], key=lambda c: c.map(mf.DATASETS.index) if c.name == "dataset" else c, + kind="stable").reset_index(drop=True) + status.to_csv(OUTDATA / "sec09_scsemi_status.csv", index=False) + # depth-matched precision / coverage are in each call's summary.json headline (not in load_fewpair's metrics) + for k in ("precision_dm", "coverage_dm"): + few[k] = [float(jload(T / s)["headline"][ARM_FILE[a]][k]) for s, a in zip(few.source, few.arm)] + return few, status + + +def pooled_scores(): + """mf.load_pooled on scores/, with the NOSEX cohorts read from scores_nosex/ (non-disease metrics asserted equal).""" + pooled, calls = mf.load_pooled(SCORES) + pn, _ = load_nosex(mf.load_pooled) + for ds in NOSEX: + for a in POOLED_ARMS.values(): + same_non_disease(pooled[ds][a], pn[ds][a], f"{ds} pooled {a}") + pooled[ds] = pn[ds] + add_scsemi_cv(pooled, calls) + return pooled, calls + + +def add_contrast_extra(few, pooled): + """Join Spearman r, the split-half ceiling, limma-voom top-50 DEG and chance overlaps (scores_contrast/) into the + few-pair rows and the pooled arms of the disease cohorts. Pearson r and Welch top-50 must match exactly.""" + h = pd.read_csv(CX / "fewshot_headline.csv") + h["draw"] = h.unit.str.extract(r"draw(\d+)", expand=False).astype(int) + ce = pd.read_csv(CX / "fewshot_ceiling.csv") + ce = ce[(ce.predictor == "split_half_A_vs_B") & (ce.celltype == "mean4")].copy() + ce["draw"] = ce.unit.str.extract(r"draw(\d+)", expand=False).astype(int) + new = ["spearman_r", "limma_deg", "deg_chance", "limma_chance", "broadcast_spearman", "limma_deg_broadcast", + "ceiling_r", "ceiling_spearman", "cat50", "cat50_chance", "rbo", "broadcast_cat50", "broadcast_rbo"] + for c in new: + few[c] = np.nan + for i, r in few.iterrows(): + if r.dataset not in DISEASE or r.arm not in CX_ARM: + continue + m = h[(h.dataset == r.dataset) & (h.draw == int(r.draw)) & (h.arm == CX_ARM[r.arm])] + if len(m) != 1: + raise ValueError(f"scores_contrast: {len(m)} rows for {r.dataset} draw {r.draw} {r.arm}") + m = m.iloc[0] + if abs(m.pearson_r - r.contrast_r) > 1e-9 or abs(m.welch_top50 - r.deg) > 1e-9: + raise ValueError(f"scores_contrast disagrees with the scorer: {r.dataset} draw {r.draw} {r.arm}") + c = ce[(ce.dataset == r.dataset) & (ce.draw == int(r.draw))].iloc[0] + vals = dict(spearman_r=m.spearman_r, limma_deg=m.limma_top50, deg_chance=m.welch_top50_chance, + limma_chance=m.limma_top50_chance, broadcast_spearman=m.broadcast_spearman_r, + limma_deg_broadcast=m.limma_top50_broadcast, ceiling_r=c.noise_free_ceiling_pearson, + ceiling_spearman=c.noise_free_ceiling_spearman, cat50=m.cat50, cat50_chance=m.cat50_chance, + rbo=m.rbo, broadcast_cat50=m.broadcast_cat50, broadcast_rbo=m.broadcast_rbo) + for k, v in vals.items(): + few.at[i, k] = float(v) + ph = pd.read_csv(CX / "pooled_headline.csv") + pc = pd.read_csv(CX / "pooled_ceiling.csv") + pc = pc[(pc.predictor == "split_half_A_vs_B") & (pc.celltype == "mean4") & (pc.unit == "pooled")] + for ds in DISEASE: + c = pc[pc.dataset == ds].iloc[0] + for a in POOLED_ARMS.values(): + m = ph[(ph.dataset == ds) & (ph.unit == "pooled") & (ph.arm == a)] + if len(m) != 1: + raise ValueError(f"scores_contrast pooled: {len(m)} rows for {ds} {a}") + m = m.iloc[0] + P = pooled[ds][a] + if abs(m.pearson_r - P["contrast_r"]) > 1e-9 or abs(m.welch_top50 - P["deg"]) > 1e-9: + raise ValueError(f"scores_contrast pooled disagrees with the scorer: {ds} {a}") + P.update(spearman_r=float(m.spearman_r), limma_deg=float(m.limma_top50), + deg_chance=float(m.welch_top50_chance), limma_chance=float(m.limma_top50_chance), + broadcast_spearman=float(m.broadcast_spearman_r), limma_deg_broadcast=float(m.limma_top50_broadcast), + ceiling_r=float(c.noise_free_ceiling_pearson), ceiling_spearman=float(c.noise_free_ceiling_spearman), + cx_source=str(CX / ds / "pooled")) + return few, pooled + + +SC_LOG: list = [] # scSemiProfiler 5-fold lookup: one dict per cohort (status, reason, source) + + +def add_scsemi_cv(pooled, calls): + """scSemiProfiler with all training pairs (SR.CV_ARM) from scores//scsemi_cv_20261002/pooled*/, when present. + Accepted only for the main pooled call's donors and reference (SR.accept). Metrics from the first accepted call; + DEG from the first accepted call with DEG enabled; Giroux's disease metrics from the scores_nosex rescore of the + same call (non-disease metrics asserted equal), else blank.""" + for ds in ORDER: + dirs = SR.cv_calls(ds) + ok, why_all = [], [] + for d in dirs: + c = mf.Call(d) + why = SR.accept(c.summary, calls[ds].summary, SR.CV_ARM) + (ok if not why else why_all).append(c if not why else f"{d}: {'; '.join(why)}") + if not ok: + SC_LOG.append(dict(dataset=ds, status="missing" if not dirs else "rejected", reason=" | ".join(why_all), + source=str(SR.plan_root() / "scores" / ds / SR.CV_EXP))) + continue + m = mf.arm_metrics(ok[0], SR.CV_ARM) + m["source"] = str(ok[0].path / "summary.json") + degc = [c for c in ok if c.deg_enabled and c.summary["headline"][SR.CV_ARM].get("deg_top50_sum") is not None] + if degc and degc[0] is not ok[0]: + md = mf.arm_metrics(degc[0], SR.CV_ARM) + for k in ("deg", "deg_broadcast", "deg_max"): + m[k] = md[k] + m["deg_source"] = str(degc[0].path / "summary.json") + note = "" + if ds in NOSEX: + ns = [mf.Call(d) for d in SR.cv_calls(ds, tree="scores_nosex")] + ns = [c for c in ns if not SR.accept(c.summary, calls[ds].summary, SR.CV_ARM)] + if ns: + mn = mf.arm_metrics(ns[0], SR.CV_ARM) + same_non_disease(m, mn, f"{ds} pooled {SR.CV_ARM}") + for k in DISEASE_KEYS: + m[k] = mn[k] + m["source"] = m["deg_source"] = str(ns[0].path / "summary.json") + else: + for k in ("contrast_r", "broadcast_r", "deg", "deg_broadcast", "deg_max"): + m[k] = np.nan + m["r_type"], m["bc_type"] = {}, {} + note = "disease metrics blank: no sex-gene-excluded rescore (scores_nosex) yet" + pooled[ds][SR.CV_ARM] = m + SC_LOG.append(dict(dataset=ds, status="used", reason=note, source=m["source"])) + + +def sex_split(ds): + """Subjects of the scorer's case / control groups by sex, for the scored (usable) rows and for all paired rows. + Sex = features.npz sex_bulk_expr (bulk chrY expression call), checked against sex_sc_expr and sex_geo.""" + f = np.load(DATA / ds / "features.npz", allow_pickle=False) + t = pd.DataFrame({k: f[k].astype(str) for k in ("sample_ids", "donor_ids", "groups", "sex_bulk_expr", "sex_sc_expr", + "sex_geo")}) + if (t.sex_bulk_expr.str.lower() != t.sex_sc_expr.str.lower()).any() or \ + (t.sex_bulk_expr.str.lower() != t.sex_geo.str.lower()).any(): + raise ValueError(f"{ds}: bulk, sc and GEO sex calls disagree") + used = set(usable_folds(ds).sample_id) + C = CONTRAST[ds] + out = {} + for scope, rows in (("scored", t[t.sample_ids.isin(used)]), ("all", t)): + d = rows.drop_duplicates("donor_ids") + out[scope] = {arm: {sx: int(((d.groups.isin(C[f"{arm}_groups"])) & (d.sex_bulk_expr.str.lower() == sx)).sum()) + for sx in ("female", "male")} for arm in ("case", "control")} + out["source"] = f"{DATA / ds / 'features.npz'} (sex_bulk_expr = sex_sc_expr = sex_geo); {DATA / ds / 'folds.csv'}" + return out + + +def fm(x): + """'4F/0M' from a {'female': n, 'male': m} count.""" + return f"{x['female']}F/{x['male']}M" + + +def few_vals(few, ds, arm, metric): + s = few[(few.dataset == ds) & (few.arm == arm)].sort_values("draw") + return s[metric].astype(float).tolist(), s["draw"].tolist(), s["source"].tolist() + + +def few_ref(few, ds, kind, metric): + """pseudo = zero-shot from sc pseudobulk (zs_pseudo arm); broadcast = raw real bulk logFC/DEG; mean over draws.""" + if kind == "pseudo": + s = few[(few.dataset == ds) & (few.arm == "pseudo")] + v = s[metric] + elif kind == "ceiling": + s = few[(few.dataset == ds) & (few.arm == "lora")] + v = s["ceiling_spearman" if metric == "spearman_r" else "ceiling_r"] + else: + s = few[(few.dataset == ds) & (few.arm == "lora")] + v = s[{"contrast_r": "broadcast_r", "deg": "deg_broadcast", "spearman_r": "broadcast_spearman", + "limma_deg": "limma_deg_broadcast"}[metric]] + v = v.dropna() + return (float(v.mean()) if len(v) else np.nan), ";".join(sorted(set(s["source"]))) + + +def n_draws(few, ds, arm): + return int(few[(few.dataset == ds) & (few.arm == arm)]["draw"].nunique()) + + +def draw_info(few, ds): + """Training / test pairs of the scored LoRA draws (DRAWS.json), and test subjects per contrast arm.""" + dj = DATA / ds / "fewshot_n5" / "DRAWS.json" + D = jload(dj)["draw"] + u = usable_folds(ds) + lora = few[(few.dataset == ds) & (few.arm == "lora")].sort_values("draw") + tr, te, n_sub, sub_cc = [], [], [], [] + for r in lora.itertuples(): + v = D[str(int(r.draw))] if str(int(r.draw)) in D else D[int(r.draw)] + if int(r.n_scored) != int(v["n_test_rows"]): + raise ValueError(f"{ds} draw {r.draw}: scored n {r.n_scored} != DRAWS n_test_rows {v['n_test_rows']}") + train = {str(x) for x in v["train_donors"]} + if int(u[u.donor_id.isin(train)].shape[0]) != int(v["n_train_rows"]): + raise ValueError(f"{ds} draw {r.draw}: train rows in folds.csv != DRAWS n_train_rows") + tr.append(int(v["n_train_rows"])) + te.append(int(r.n_scored)) + test = u[~u.donor_id.isin(train)] + n_sub.append(int(test.donor_id.nunique())) + if ds in CONTRAST: + C = CONTRAST[ds] + cs = set(test[test.group.isin(C["case_groups"])].donor_id) + ct = set(test[test.group.isin(C["control_groups"])].donor_id) + sub_cc.append((len(cs), len(ct))) + return {"train": rng(tr), "test": rng(te), "n_train": tr, "n_test": te, "n_test_subjects": n_sub, + "subjects_cc": sub_cc, "n_draws": len(tr), "source": str(dj)} + + +def subjects_text(info): + """'2 vs 2' when a cohort's test set holds few subjects (< 10) per draw; else ''.""" + if not info["subjects_cc"] or max(info["n_test_subjects"]) >= 10: + return "" + a = rng([c for c, _ in info["subjects_cc"]]) + b = rng([t for _, t in info["subjects_cc"]]) + return f"{a} vs {b}" + + +def row_subs(info, per_row_draws): + subs = [f"train {info['train']} / test {info['test']}"] + st = subjects_text(info) + if st: + subs.append(f"test = {st} subjects") + if per_row_draws: + subs.append(f"{info['n_draws']} draws") + return subs + + +def long_rows(fig, few, datasets, arms, metrics, refs): + rows = [] + for ds in datasets: + for metric in metrics: + for arm in arms: + vals, draws, srcs = few_vals(few, ds, arm, metric) + for v, d, s in zip(vals, draws, srcs): + rows.append({"figure": fig, "dataset": ds, "metric": metric, "series": arm, "kind": "draw", + "draw": d, "value": v, "source": s}) + vv = [v for v in vals if not np.isnan(v)] + if vv: + rows.append({"figure": fig, "dataset": ds, "metric": metric, "series": arm, "kind": "mean", + "draw": "", "value": float(np.mean(vv)), + "sd": float(np.std(vv, ddof=1)) if len(vv) > 1 else 0.0, "n_draws": len(vv), + "source": "derived: mean/SD of the draw rows"}) + for kind in refs.get(metric, []): + v, s = few_ref(few, ds, kind, metric) + rows.append({"figure": fig, "dataset": ds, "metric": metric, "series": f"ref_{kind}", + "kind": "reference (mean over draws)", "draw": "", "value": v, "source": s}) + return rows + + +def same_draw_compare(few, status, datasets, metric, lower_better=False, min_margin=0.0, other="scsemi5"): + """LoRA-5 vs another arm (scSemi-5 by default, or zero-shot zs_raw) draw by draw, on the draws where both + exist (same test pairs; scSemi-5 draws only when load_fewpair accepted them). + + Per draw: LoRA better / other better / tie (equal values). Cohort verdict: + 'tie' if at least half the shared draws tie, or |mean difference| < min_margin; + 'lora' if LoRA is better in >= WIN_FRAC of the shared draws; + 'other' if the other arm is better in >= WIN_FRAC of the shared draws; + 'split' otherwise. + """ + used = status[status.status == "used"] + res = {} + for ds in datasets: + a = few[(few.dataset == ds) & (few.arm == "lora")].set_index("draw")[metric].astype(float) + b = few[(few.dataset == ds) & (few.arm == other)].set_index("draw")[metric].astype(float) + cand = sorted(used[used.dataset == ds]["draw"]) if other == "scsemi5" else sorted(a.index) + dr = [d for d in cand if d in a.index and d in b.index and not (np.isnan(a[d]) or np.isnan(b[d]))] + if not dr: + continue + d = (a[dr] - b[dr]) * (-1.0 if lower_better else 1.0) # > 0: LoRA better + nL, nO = int((d > 0).sum()), int((d < 0).sum()) + nT = len(dr) - nL - nO + mdiff = float(a[dr].mean() - b[dr].mean()) + if 2 * nT >= len(dr) or abs(mdiff) < min_margin: + verdict = "tie" + elif nL >= WIN_FRAC * len(dr): + verdict = "lora" + elif nO >= WIN_FRAC * len(dr): + verdict = "other" + else: + verdict = "split" + res[ds] = dict(lora=float(a[dr].mean()), other=float(b[dr].mean()), n=len(dr), n_lora=nL, n_other=nO, + n_tie=nT, verdict=verdict, draws=dr) + return res + + +def l1_vs_zeroshot_per_donor(ds, other="zs_raw"): + """LoRA-5 minus zero-shot (raw real bulk zs_raw, or zero-shot + calibration zs_cal) composition L1, averaged per + donor over every draw the donor was tested in, then a Wilcoxon signed-rank test over donors (units repeat across + draws, so donor-draw rows are not independent). The donor-draw row test is returned too, for the CSV only. + Composition does not depend on the gene set, so the original scores/ files are read for every cohort.""" + s2d = dict(zip(usable_folds(ds).sample_id, usable_folds(ds).donor_id)) + parts = [] + for j, p in mf.draw_dirs(SCORES / ds / "fewshot_n5"): + pdn = pd.read_csv(p / "per_donor.csv", usecols=["arm", "donor", "comp_l1"]) + w = pdn[pdn.arm.isin(["lora5", other])].pivot(index="donor", columns="arm", values="comp_l1") + if w[["lora5", other]].isna().any().any(): + raise ValueError(f"{p}: per_donor.csv lacks lora5 or {other} rows for some donors") + x = (w["lora5"] - w[other]).rename("diff").reset_index() + x["draw"] = j + parts.append(x) + x = pd.concat(parts) + x["donor_id"] = x["donor"].astype(str).map(s2d) + if x["donor_id"].isna().any(): + raise ValueError(f"{ds}: per_donor units missing from folds.csv") + per = x.groupby("donor_id")["diff"].mean() + return dict(n_donors=int(len(per)), n_rows=int(len(x)), mean_diff=float(per.mean()), + frac_better=float((per < 0).mean()), p=float(wilcoxon(per).pvalue), + row_mean_diff=float(x["diff"].mean()), row_p=float(wilcoxon(x["diff"]).pvalue), + source=f"{SCORES / ds / 'fewshot_n5'}/draw/per_donor.csv (comp_l1, arms lora5 / {other}); " + f"{DATA / ds / 'folds.csv'} (sample -> donor)") + + +# ------------------------------------------------------------------------------------------ +# Slide b: 5 donors, cells +# ------------------------------------------------------------------------------------------ +def fig_fewpair_cells(few, info): + arms = ["zs_raw", "zs_cal", "scsemi5", "lora"] + metrics = [("coverage", "Coverage ↑", (0, 1.0), [0, 0.5, 1.0]), + ("precision", "Precision ↑", (0, 1.0), [0, 0.5, 1.0]), + ("comp_l1", "Composition L1 ↓", None, None)] + nd_all = {info[d]["n_draws"] for d in ORDER} + per_row = len(nd_all) > 1 + fig, axs = grid(len(ORDER), len(metrics), style.FULL, left=LEFT_IN, right=0.15, top=0.45, bottom=1.25, + hspace=0.22, wspace=0.10) + l1max = 0.0 + for i, ds in enumerate(ORDER): + nl = n_draws(few, ds, "lora") + ns = n_draws(few, ds, "scsemi5") + for j, (mk, _, _, _) in enumerate(metrics): + ax = axs[i, j] + st = hbars(ax, arms, lambda a: few_vals(few, ds, a, mk)[0], seed=17 * i + j) + ref = few_ref(few, ds, "pseudo", mk)[0] + ref_line(ax, ref, "pseudo", len(arms)) + if mk == "comp_l1": + allv = [v for a in arms for v in few_vals(few, ds, a, mk)[0] if not np.isnan(v)] + [ref] + l1max = max([l1max, np.nanmax(allv)] + [m + sd for m, sd, n in st.values() if n]) + elif max([v for a in arms for v in few_vals(few, ds, a, mk)[0] if not np.isnan(v)] + [ref]) > 1.0: + raise ValueError(f"{ds} {mk}: value above the fixed 0-1 axis") + if j == 0 and 0 < ns < nl: + m, sd, n = st["scsemi5"] + ax.text(max(m + sd, max(few_vals(few, ds, "scsemi5", mk)[0])) + 0.03, arms.index("scsemi5"), + f"{ns} of {nl} draws", + va="center", ha="left", fontsize=FS - 3, color="#8A5A00") + row_label(axs[i, 0], ROWNAME[ds], row_subs(info[ds], per_row)) + label_header(axs[0, 0], "pairs per draw") + for j, (mk, lab, lim, ticks) in enumerate(metrics): + if lim is None: # raw zero-shot L1 reaches ~0.8: the axis follows the data (every draw dot and SD bar) + lim = (0, np.ceil(l1max * 1.08 * 10) / 10) + ticks = [round(t, 1) for t in np.arange(0, lim[1] + 1e-9, 0.2)] + shared_x(axs[:, j], lim[0], lim[1], lab, ticks) + handles = [patch("zs_raw"), patch("zs_cal"), patch("scsemi5"), patch("lora"), refh("pseudo"), + dot_handle(None if per_row else nd_all.pop())] + legend_bottom(fig, handles, ncol=3) + check_inside(fig, "sec09_fewpair_cells") + style.save(fig, "sec09_fewpair_cells", FIGDIR) + rows = long_rows("sec09_fewpair_cells", few, ORDER, arms, [m[0] for m in metrics] + ["precision_dm", "coverage_dm"], + {"coverage": ["pseudo"], "precision": ["pseudo"], "comp_l1": ["pseudo"]}) + pd.DataFrame(rows).to_csv(OUTDATA / "sec09_fewpair_cells.csv", index=False, float_format="%.6g") + + +# ------------------------------------------------------------------------------------------ +# Slide c: 5 donors, disease signal +# ------------------------------------------------------------------------------------------ +def fmt_deg(v): + return f"{v:.1f}" if v < 10 else f"{v:.0f}" + + +def chance_ticks(ax, arms, vals_of, n_arms): + """Chance overlap of each arm's top-50 lists (hypergeometric mean), a short grey tick on its bar row.""" + for k, a in enumerate(arms): + v = [x for x in vals_of(a) if not np.isnan(x)] + if v: + c = float(np.mean(v)) + ax.plot([c, c], [k - 0.42, k + 0.42], color=CHANCE_COL, lw=1.6, zorder=6, solid_capstyle="butt") + + +def fig_fewpair_disease(few, info): + """2026-10-02: Pearson and Spearman logFC r with the split-half ceiling; top-50 DEG by Welch and by limma-voom with + each arm's chance overlap (grey tick).""" + arms = ["zs_raw", "zs_cal", "scsemi5", "lora"] + cols = [("contrast_r", "logFC r, Pearson ↑"), ("spearman_r", "logFC r, Spearman ↑"), + ("deg", "Top-50 DEG, Welch ↑"), ("limma_deg", "Top-50 DEG, limma ↑")] + nd_all = {info[d]["n_draws"] for d in DISEASE} + per_row = len(nd_all) > 1 + fig, axs = grid(len(DISEASE), len(cols), (12.3, 5.4), left=LEFT_IN, right=0.25, top=0.45, bottom=1.25, + hspace=0.45, wspace=0.14) + rows = [] + for i, ds in enumerate(DISEASE): + nl = n_draws(few, ds, "lora") + ns = n_draws(few, ds, "scsemi5") + for j, (mk, _) in enumerate(cols): + ax = axs[i, j] + st = hbars(ax, arms, lambda a: few_vals(few, ds, a, mk)[0], seed=31 * i + 7 * j) + bc = few_ref(few, ds, "broadcast", mk)[0] + ref_line(ax, bc, "broadcast", len(arms)) + for a in arms: + for v, dr, src in zip(*few_vals(few, ds, a, mk)): + rows.append({"figure": "sec09_fewpair_disease", "dataset": ds, "metric": mk, "series": a, + "draw": dr, "value": v, "source": src if mk in ("contrast_r", "deg") else str(CX)}) + rows.append({"figure": "sec09_fewpair_disease", "dataset": ds, "metric": mk, "series": "ref_broadcast", + "draw": "mean", "value": bc, "source": few_ref(few, ds, "broadcast", mk)[1]}) + if mk in ("contrast_r", "spearman_r"): + ce = few_ref(few, ds, "ceiling", mk)[0] + ref_line(ax, ce, "ceiling", len(arms)) + rows.append({"figure": "sec09_fewpair_disease", "dataset": ds, "metric": mk, "series": "ref_ceiling", + "draw": "mean", "value": ce, "source": str(CX / "fewshot_ceiling.csv")}) + ax.axvline(0, color="#555555", lw=0.8, zorder=1) + ax.spines["left"].set_visible(False) + if ns < nl and j == 0: + ax.text(1.0, arms.index("scsemi5"), f"{ns} of {nl} draws", transform=ax.get_yaxis_transform(), + va="center", ha="right", fontsize=FS - 3, color="#8A5A00") + else: + chk = "deg_chance" if mk == "deg" else "limma_chance" + chance_ticks(ax, arms, lambda a: few_vals(few, ds, a, chk)[0], len(arms)) + for a in arms: + for v, dr, _ in zip(*few_vals(few, ds, a, chk)): + rows.append({"figure": "sec09_fewpair_disease", "dataset": ds, "metric": chk, "series": a, + "draw": dr, "value": v, "source": str(CX)}) + hi = max([bc] + [v for a in arms for v in few_vals(few, ds, a, mk)[0] if not np.isnan(v)] + [4.0]) + ax.set_xlim(0, hi * 1.40) + ax.xaxis.set_major_locator(MaxNLocator(nbins=3, integer=True)) + ax.tick_params(axis="x", labelsize=FS - 3) + for k, a in enumerate(arms): + m, sd, n = st[a] + if n: + ax.text(0.995, k, fmt_deg(m), transform=ax.get_yaxis_transform(), va="center", ha="right", + fontsize=FS - 3, color=SUB) + row_label(axs[i, 0], ROWNAME[ds], row_subs(info[ds], per_row)) + label_header(axs[0, 0], "pairs per draw") + for j in (0, 1): + shared_x(axs[:, j], -0.2, 1.0, cols[j][1], [0, 0.5, 1.0]) + for j in (2, 3): + axs[-1, j].set_xlabel(cols[j][1]) + handles = [patch("zs_raw"), patch("zs_cal"), patch("scsemi5"), patch("lora"), refh("broadcast"), refh("ceiling"), + Line2D([0], [0], color=CHANCE_COL, lw=1.6, label="Chance overlap (per arm)"), + dot_handle(None if per_row else nd_all.pop())] + legend_bottom(fig, handles, ncol=4) + check_inside(fig, "sec09_fewpair_disease") + style.save(fig, "sec09_fewpair_disease", FIGDIR) + pd.DataFrame(rows).to_csv(OUTDATA / "sec09_fewpair_disease.csv", index=False, float_format="%.6g") + + +# ------------------------------------------------------------------------------------------ +# Slide d: all pairs, 5-fold pooled +# ------------------------------------------------------------------------------------------ +def baselines_text(vals): + """'0.11' when every baseline rounds to the same 2 decimals, else '0.10–0.12' (lowest–highest).""" + s = sorted({f"{v:.2f}" for v in vals}) + return s[0] if len(s) == 1 else f"{s[0]}–{s[-1]}" + + +def sc_cohorts(pooled): + """Cohorts with an accepted scSemiProfiler 5-fold (all training pairs) call.""" + return [d for d in ORDER if SR.CV_ARM in pooled[d]] + + +def pooled_val(P, a, mk): + m = P.get(POOLED_FILE[a]) + return np.nan if m is None else m.get(mk, np.nan) + + +def fivefold_arms(pooled): + return ["zs_raw", "zs_cal", "sconly_cal"] + ([SC_ALL] if sc_cohorts(pooled) else []) + ["lora"] + + +def fig_fivefold(pooled, tab): + arms = fivefold_arms(pooled) + base = ["zs_raw", "zs_cal", "sconly_cal"] # the Ji note sits next to these three bars + metrics = [("coverage", "Coverage ↑"), ("contrast_r", "logFC r, Pearson ↑"), ("spearman_r", "logFC r, Spearman ↑"), + ("deg", "Top-50 DEG, Welch ↑"), ("limma_deg", "Top-50 DEG, limma ↑")] + leg_rows = -(-(len(arms) + 4) // 4) # arm patches + 4 reference marks, 4 per legend row + fig, axs = grid(len(ORDER), len(metrics), style.FULL, left=LEFT_IN, right=0.35, top=0.45, + bottom=0.65 + 0.30 * leg_rows, hspace=0.40, wspace=0.12) + rows = [] + ji_note = None + tabi = tab.set_index("dataset") + + def src(m, mk): + return m.get("deg_source", m["source"]) if mk == "deg" else m["source"] + + for i, ds in enumerate(ORDER): + P = pooled[ds] + for j, (mk, _) in enumerate(metrics): + ax = axs[i, j] + if ds == "ji2025_chili": + ax.set_facecolor(HILITE) + if mk != "coverage" and ds == "immicro": + blank(ax, "healthy cohort: no contrast") + continue + sc_na = {SC_ALL: ("rescore pending" if POOLED_FILE[SC_ALL] in P else "not run")} + hbars(ax, arms, lambda a: [pooled_val(P, a, mk)], dots=False, na_text=sc_na) + for a in arms: + if POOLED_FILE[a] not in P: + continue + rows.append({"figure": "sec09_fivefold", "dataset": ds, "metric": mk, "series": a, + "arm_file": POOLED_FILE[a], "value": P[POOLED_FILE[a]][mk], + "n_scored": P[POOLED_FILE[a]]["n_scored"], "source": src(P[POOLED_FILE[a]], mk)}) + if mk == "coverage": + ref = P["zs__pseudo"]["coverage"] + ref_line(ax, ref, "pseudo", len(arms)) + rows.append({"figure": "sec09_fivefold", "dataset": ds, "metric": mk, "series": "ref_pseudo", + "arm_file": "zs__pseudo", "value": ref, "source": P["zs__pseudo"]["source"]}) + else: + m = P["real_lora__raw"] + ref = m[{"contrast_r": "broadcast_r", "deg": "deg_broadcast", "spearman_r": "broadcast_spearman", + "limma_deg": "limma_deg_broadcast"}[mk]] + ref_line(ax, ref, "broadcast", len(arms)) + rows.append({"figure": "sec09_fivefold", "dataset": ds, "metric": mk, "series": "ref_broadcast", + "arm_file": "real_lora__raw (raw real bulk)", "value": ref, + "source": src(m, mk) if mk in ("contrast_r", "deg") else m["cx_source"]}) + if mk in ("contrast_r", "spearman_r"): + ce = P["real_lora__raw"]["ceiling_spearman" if mk == "spearman_r" else "ceiling_r"] + ref_line(ax, ce, "ceiling", len(arms)) + rows.append({"figure": "sec09_fivefold", "dataset": ds, "metric": mk, "series": "ref_ceiling", + "arm_file": "observed split halves", "value": ce, "source": P["real_lora__raw"]["cx_source"]}) + if mk in ("deg", "limma_deg"): + chance_ticks(ax, arms, lambda a: [pooled_val(P, a, "deg_chance" if mk == "deg" else "limma_chance")], + len(arms)) + hi = float(np.nanmax([ref] + [pooled_val(P, a, mk) for a in arms] + [4.0])) + ax.set_xlim(0, hi * 1.25) + ax.xaxis.set_major_locator(MaxNLocator(nbins=3, integer=True)) + ax.tick_params(axis="x", labelsize=FS - 3) + for k, a in enumerate(arms): + v = pooled_val(P, a, mk) + if not np.isnan(v): + ax.text(v + hi * 0.03, k, f"{v:.0f}", va="center", ha="left", fontsize=FS - 3, color=SUB) + if mk in ("contrast_r", "spearman_r"): + ax.axvline(0, color="#555555", lw=0.8, zorder=1) + ax.spines["left"].set_visible(False) + if ds == "ji2025_chili" and mk == "coverage": + vb = [P[POOLED_ARMS[a]]["coverage"] for a in base] + v_lo = P[POOLED_ARMS["lora"]]["coverage"] + txt = ax.text(max(vb) + 0.03, (len(base) - 1) / 2, baselines_text(vb), + va="center", ha="left", fontsize=FS - 3, color="#5A5A5A") + ji_note = (txt, ax, P["zs__pseudo"]["coverage"]) + ax.text(v_lo + 0.02, arms.index("lora"), f"{v_lo:.2f}", va="center", ha="left", fontsize=FS - 3, + color=SUB) + n = P["real_lora__raw"]["n_scored"] + nd = int(tabi.loc[ds, "n_donors"]) + if int(tabi.loc[ds, "n_rows"]) != int(n): + raise ValueError(f"{ds}: pooled n {n} != usable rows") + row_label(axs[i, 0], ROWNAME[ds], [f"n={n}" + (f" ({nd} donors)" if nd != n else "")]) + shared_x(axs[:, 0], 0, 1.0, metrics[0][1], [0, 0.5, 1.0]) + # the Ji annotation must end left of the pseudobulk reference line (checked on the final x scale) + txt, ax, ref = ji_note + fig.canvas.draw() + x1 = ax.transData.inverted().transform(txt.get_window_extent(fig.canvas.get_renderer()))[1, 0] + if x1 >= ref - 0.01: + raise ValueError(f"Ji annotation ends at {x1:.2f}, over the pseudobulk reference line at {ref:.2f}") + rvals = [r["value"] for r in rows if r["metric"] in ("contrast_r", "spearman_r") and not np.isnan(r["value"])] + for j in (1, 2): + shared_x(axs[1:, j], min(-0.2, np.floor(min(rvals) * 10) / 10), 1.0, metrics[j][1], [0, 0.5, 1.0]) + for j in (3, 4): + axs[-1, j].set_xlabel(metrics[j][1]) + handles = [patch(a, LAB["lora_all"] if a == "lora" else None) for a in arms] + [ + refh("pseudo"), refh("broadcast"), refh("ceiling"), + Line2D([0], [0], color=CHANCE_COL, lw=1.6, label="Chance overlap (per arm)")] + legend_bottom(fig, handles, ncol=4) + check_inside(fig, "sec09_fivefold") + style.save(fig, "sec09_fivefold", FIGDIR) + pd.DataFrame(rows).to_csv(OUTDATA / "sec09_fivefold.csv", index=False, float_format="%.6g") + return rows + + +# ------------------------------------------------------------------------------------------ +# Slide text: every keyword / footnote / quoted number is built here from the same data +# ------------------------------------------------------------------------------------------ +BANNED = ("novel", "powerful", "robust", "state-of-the-art", "seamless", "leverage") + + +def n_words(s): + return sum(1 for t in s.split() if re.search(r"[A-Za-z0-9]", t)) + + +def check_text(s, what): + if any(b in s.lower() for b in BANNED) or re.search(r"[가-힣]", s): + raise ValueError(f"banned word / Korean in {what}: {s!r}") + if OFF_STORY.search(s): + raise ValueError(f"off-story wording (refcal / VAE / TPM / AIFI / AIDA) in {what}: {s!r}") + return s + + +def check_keywords(kws): + if len(kws) > 3: + raise ValueError(f"more than 3 keyword lines: {kws}") + for k in kws: + if n_words(k) > 7: + raise ValueError(f"keyword over 7 words: {k!r}") + if len(k) > KW_MAX_CHARS: + raise ValueError(f"keyword over {KW_MAX_CHARS} characters ({len(k)}): {k!r}") + check_text(k, "keyword") + return kws + + +def check_foot_short(s): + """One on-slide line: <= FOOT_SHORT_MAX characters, no file paths.""" + if len(s) > FOOT_SHORT_MAX or "\n" in s: + raise ValueError(f"footnote_short over {FOOT_SHORT_MAX} characters ({len(s)}): {s!r}") + if re.search(r"/home|\b(scores|data|runs|tools|figures)/|\.(json|csv|npz|md|py|pt)\b", s): + raise ValueError(f"file path in footnote_short: {s!r}") + return check_text(s, "footnote_short") + + +def keyword_or_short(long, short): + """The long wording when it fits a keyword line, else the short one (both computed from the same numbers).""" + return long if len(long) <= KW_MAX_CHARS else short + + +def names(dss): + return ", ".join(NAME[d] for d in dss) + + +def fmt_p(p): + return f"{p:.0e}" if p < 0.01 else f"{p:.2f}" + + +def main(): + FIGDIR.mkdir(parents=True, exist_ok=True) + OUTDATA.mkdir(parents=True, exist_ok=True) + + tab = cohort_rows() + tab.to_csv(OUTDATA / "sec09_cohorts.csv", index=False) + fig_cohorts(tab) + + few, status = fewpair() + info = {ds: draw_info(few, ds) for ds in ORDER} + pooled, calls = pooled_scores() + few, pooled = add_contrast_extra(few, pooled) + fig_fewpair_cells(few, info) + fig_fewpair_disease(few, info) + fig_fivefold(pooled, tab) + + used = status[status.status == "used"] + run_json = T / "runs" / "immicro" / "fewshot_n5" / "draw0" / "lora" / "RUN.json" + evidence(run_json, re.escape(CKPT)) # the few-pair LoRA runs start from the final checkpoint + steps = int(re.search(r'"fixed_steps": (\d+)', evidence(run_json, r'"fixed_steps": \d+')).group(1)) + lora_r = re.search(r"LoRA r = (\d+)", evidence(README, r"LoRA r = \d+ \(1\.3 M")).group(1) + sampling = match_text(README, r"test donors only, 1,500 cells each, seed \d+, DDIM 50, EMA, Bernoulli read-out") + early = match_text(README, r"About 10 % of each fold's training donors are inner-validation, used only for early stopping") + pc_def = match_text(SCORE_FT, r"precision/coverage/density \(PCA-50 \+ k = 10 balls fitted on the scored donors' observed R1 cells\)") + pca_n = {int(jload(SCORES / ds / "fewshot_n5" / "draw0" / "summary.json")["reference"]["pca"]["n_components"]) + for ds in ORDER} + if pca_n != {50}: + raise ValueError(f"PCA components differ from the footnote: {pca_n}") + ddef = jload(SCORES / "ji2025_chili" / "fewshot_n5" / "draw0" / "summary.json")["deg_definition"] + if not ("welch_bh_deg" in ddef["functions"] and ddef["top_n"] == 50 and len(ddef["types"]) == 5): + raise ValueError("DEG definition differs from the footnote") + n_types = len(ddef["types"]) + base_src = f"{run_json}; {README}" + slides = [] + + # ---------------- slide a ---------------- + tot_rows, tot_donors = int(tab.n_rows.sum()), int(tab.n_donors.sum()) + n_all = int(tab.n_pairs_all.sum()) + n_fail, n_bord, n_low = int(tab.n_identity_fail.sum()), int(tab.n_identity_borderline.sum()), int(tab.n_low_cells.sum()) + ji = tab.set_index("dataset").loc["ji2025_chili"] + if not ji.bulk.startswith("whole blood"): + raise ValueError("Ji bulk label changed") + noflag = [NAME[d] for d in tab[~tab.identity_flag].dataset] + multi = [NAME[d] for d in tab[tab.n_rows != tab.n_donors].dataset] + sxa = sex_split("giroux2022") + kw_a = check_keywords([f"{tot_rows} paired samples, {tot_donors} donors", + "Only identity-pass pairs; donor-level splits", + "Ji bulk: whole blood, not PBMC"]) + foot_a = (f"Usable pair = passed the pairing identity check and >= {int(tab.min_cells.iloc[0])} cells " + f"(fold >= 0 in data//folds.csv); dropped {n_fail} identity-fail, {n_bord} borderline and " + f"{n_low} low-cell pairs of {n_all}. {', '.join(noflag)}: no identity flag, all used. " + f"{', '.join(multi)}: several pairs per donor. Case vs control = samples in " + f"scores//pooled/summary.json. Giroux 'moderate' = GEO 'severe' (paper term); its moderate vs mild " + f"subjects are {fm(sxa['scored']['case'])} vs {fm(sxa['scored']['control'])} (scored), so its disease " + f"metrics exclude sex-linked genes. Labels: data//QC_REPORT.md; ImMicro: GEO GSE314922/GSE314416.") + num("a", f"{tot_rows} paired samples (sum of usable rows)", f"{DATA}//fewshot_n5/DRAWS.json (n_usable_rows)") + num("a", f"{tot_donors} donors (sum of usable donors)", f"{DATA}//fewshot_n5/DRAWS.json (n_usable_donors)") + num("a", f"dropped {n_fail} identity-fail, {n_bord} borderline, {n_low} < {int(tab.min_cells.iloc[0])} cells, of {n_all}", + f"{DATA}//features.npz (identity_pass, identity_check); samples.csv (n_cells); {PREPARE} (MIN_CELLS)") + for r in tab.itertuples(): + v = f"{NAME[r.dataset]} {r.n_rows} pairs / {r.n_donors} donors" + s = r.n_rows_source + if r.case_label: + v += f"; {r.case_label} {int(r.n_case)} vs {r.control_label} {int(r.n_control)}" + if r.n_neither: + v += f" (+{r.n_neither} {r.neither_label}, neither)" + s += f"; {r.contrast_source}" + num("a", v, s) + fs_a = check_foot_short(f"Usable pair = passed identity check and ≥ {int(tab.min_cells.iloc[0])} cells: " + f"{tot_rows} of {n_all} pairs; donor-level splits.") + slides.append({"title": "Five paired cohorts", "layout": "full", + "figures": [str(FIGDIR / "sec09_cohorts.png")], "keywords": kw_a, "footnote": foot_a, + "footnote_short": fs_a, "numbers": NUMS["a"]}) + + # ---------------- slide b ---------------- + mk_b = (("coverage", False), ("precision", False), ("comp_l1", True), ("coverage_dm", False), + ("precision_dm", False)) + cmp_b = {mk: same_draw_compare(few, status, ORDER, mk, lower) for mk, lower in mk_b} + cmp_bz = {mk: same_draw_compare(few, status, ORDER, mk, lower, other="zs_raw") for mk, lower in mk_b} + cmp_bc = {mk: same_draw_compare(few, status, ORDER, mk, lower, other="zs_cal") for mk, lower in mk_b} + wins = {mk: sum(v["verdict"] == "lora" for v in c.values()) for mk, c in cmp_b.items()} + wins_z = {mk: sum(v["verdict"] == "lora" for v in c.values()) for mk, c in cmp_bz.items()} + wins_c = {mk: sum(v["verdict"] == "lora" for v in c.values()) for mk, c in cmp_bc.items()} + ncoh = {mk: len(c) for mk, c in cmp_b.items()} + if ncoh["coverage"] != len(ORDER): + raise ValueError("a cohort has no shared scSemiProfiler draw") + if any(len(c) != len(ORDER) for cc in (cmp_bz, cmp_bc) for c in cc.values()): + raise ValueError("a cohort has no zero-shot draw") + nb = len(ORDER) + if wins["coverage"] == wins["precision"]: + kw_b1 = f"LoRA-5 > scSemi-5: coverage, precision {wins['coverage']}/{nb}" + else: + kw_b1 = f"Beats scSemi-5: coverage {wins['coverage']}/{nb}, precision {wins['precision']}/{nb}" + + def span(v): + return f"{min(v):.2f}–{max(v):.2f}" + + cov_mean = {a: [float(np.mean(few_vals(few, d, a, "coverage")[0])) for d in ORDER] + for a in ("lora", "scsemi5", "zs_raw", "zs_cal")} + kw_b2 = keyword_or_short(f"Beats zero-shot + calibration: coverage {wins_c['coverage']}/{nb}", + f"Coverage > calibration: {wins_c['coverage']}/{nb}") + l1t = {ds: l1_vs_zeroshot_per_donor(ds) for ds in ORDER} + l1c = {ds: l1_vs_zeroshot_per_donor(ds, "zs_cal") for ds in ORDER} + gain = [d for d in ORDER if l1t[d]["p"] < 0.05 and l1t[d]["mean_diff"] < 0] + gain_c = [d for d in ORDER if l1c[d]["p"] < 0.05 and l1c[d]["mean_diff"] < 0] + worse_c = [d for d in ORDER if l1c[d]["p"] < 0.05 and l1c[d]["mean_diff"] > 0] + if not gain_c: + kw_b3 = "Composition: no gain over calibration" + elif len(gain_c) == nb: + kw_b3 = "Lower L1 than calibration: all cohorts" + else: + kw_b3 = keyword_or_short(f"Lower L1 than calibration: {names(gain_c)} only", + f"Lower L1 than calibration: {len(gain_c)}/{nb}") + kw_b = check_keywords([kw_b1, kw_b2, kw_b3]) + l1_split = [d for d, v in cmp_b["comp_l1"].items() if v["verdict"] != "lora"] + dm_c = {a: [cmp_b["coverage_dm"][d][k] for d in ORDER] for a, k in (("lora", "lora"), ("scsemi5", "other"))} + if wins["coverage_dm"] != wins["coverage"] or wins["precision_dm"] != wins["precision"]: + raise ValueError("depth-matched ranking differs from raw P/C: rewrite the 'same ranking' footnote") + tr_all = [x for d in ORDER for x in info[d]["n_train"]] + missing = status[status.status != "used"] + miss_txt = ", ".join(f"{NAME[r.dataset]} draw{r.draw}" for r in missing.itertuples()) + ns_used, ns_all = len(used), len(status) + + def pc_wins(w): + return (f"coverage {w['coverage']}/{nb}, precision {w['precision']}/{nb}, " + f"depth-matched {w['coverage_dm']}/{nb} and {w['precision_dm']}/{nb}") + + def l1_list(t): + return ", ".join(f"{NAME[d]} {t[d]['mean_diff']:+.2f} (p {fmt_p(t[d]['p'])})" for d in ORDER) + + foot_b = (f"Base f01 6k·1x·E16 (EMA, DDIM 50) + LoRA r={lora_r}, {steps:,} steps. LoRA-5 / scSemi-5 = LoRA / " + f"scSemiProfiler trained on the same 5 donors ({min(tr_all)}–{max(tr_all)} pairs); test = all other usable " + f"pairs. Zero-shot = base model without fine-tuning, fed each test pair's real bulk as measured; zero-shot + " + f"calibration = the same model fed that bulk after gene-wise calibration, alpha fitted on the same 5 " + f"training donors' pairs (both in the same call as LoRA-5). scSemi-5 scored in a separate call, same test " + f"set and reference (sha-checked); {ns_used}/{ns_all} draws" + (f" (missing: {miss_txt})" if len(missing) else "") + + ". Verdict = better in >= 80% of shared draws. LoRA-5 lower L1 than scSemi-5 in " + f"{wins['comp_l1']}/{nb}" + + (f" ({', '.join(f'{NAME[d]} {cmp_b['comp_l1'][d]['verdict']} {cmp_b['comp_l1'][d]['n_lora']}/{cmp_b['comp_l1'][d]['n']}' for d in l1_split)})" + if l1_split else "") + + f". LoRA-5 > zero-shot + calibration: {pc_wins(wins_c)} cohorts; > zero-shot (real bulk): " + f"{pc_wins(wins_z)}. Depth-matched P/C vs scSemi-5: same ranking, coverage LoRA-5 {span(dm_c['lora'])} vs " + f"scSemi-5 {span(dm_c['scsemi5'])}. Composition L1, LoRA-5 minus zero-shot + calibration, per-donor Wilcoxon " + f"(gain = p < 0.05): {l1_list(l1c)}; minus zero-shot (real bulk): {l1_list(l1t)}. scANVI labels; P/C = " + f"PCA-50, k=10 balls. Scores: scores//fewshot_n5/.") + nd_b = sorted({info[d]["n_draws"] for d in ORDER}) + fs_b = check_foot_short(f"{rng(nd_b)} draws per cohort; test = all other usable pairs. Calibration α from the same " + f"5 donors. scANVI labels.") + scs = f"{SCORES}//fewshot_n5/draw/summary.json and draw_scsemi5/summary.json" + for mk in ("coverage", "precision", "comp_l1", "coverage_dm", "precision_dm"): + c = cmp_b[mk] + num("b", f"LoRA-5 vs scSemi-5 {mk} (shared-draw means; LoRA-better draws/n; verdict): " + + "; ".join(f"{NAME[d]} {v['lora']:.3f} vs {v['other']:.3f} ({v['n_lora']}/{v['n']}, {v['verdict']})" + for d, v in c.items()) + f" -> LoRA verdicts {wins[mk]}/{ncoh[mk]}", scs) + for cmpx, w, lab, arm in ((cmp_bc, wins_c, "zero-shot + calibration", "zs_cal"), + (cmp_bz, wins_z, "zero-shot (real bulk)", "zs_raw")): + for mk in ("coverage", "precision", "comp_l1", "coverage_dm", "precision_dm"): + c = cmpx[mk] + num("b", f"LoRA-5 vs {lab} {mk} (same-draw means; LoRA-better draws/n; verdict): " + + "; ".join(f"{NAME[d]} {v['lora']:.3f} vs {v['other']:.3f} ({v['n_lora']}/{v['n']}, {v['verdict']})" + for d, v in c.items()) + f" -> LoRA verdicts {w[mk]}/{len(c)}", + f"{SCORES}//fewshot_n5/draw/summary.json (arms lora5, {arm})") + num("b", "coverage cohort means over all draws: " + "; ".join( + f"{lab} " + ", ".join(f"{NAME[d]} {v:.3f}" for d, v in zip(ORDER, cov_mean[a])) + for a, lab in (("lora", "LoRA-5"), ("scsemi5", "scSemi-5"), ("zs_cal", "zero-shot + calibration"), + ("zs_raw", "zero-shot"))), scs) + for t, lab, g in ((l1c, "zero-shot + calibration", gain_c), (l1t, "zero-shot (real bulk)", gain)): + num("b", f"LoRA-5 minus {lab} composition L1, per-donor Wilcoxon (draw-averaged): " + + "; ".join(f"{NAME[d]} {v['mean_diff']:+.3f}, n={v['n_donors']}, p={v['p']:.2g}" for d, v in t.items()) + + f" -> gain in {len(g)}/{nb}", f"{SCORES}//fewshot_n5/draw/per_donor.csv; {DATA}//folds.csv") + if worse_c: + num("b", "LoRA-5 L1 significantly higher than zero-shot + calibration: " + names(worse_c), + f"{SCORES}//fewshot_n5/draw/per_donor.csv") + num("b", "scSemiProfiler draws used / LoRA draws: " + + ", ".join(f"{NAME[d]} {int((used.dataset == d).sum())}/{n_draws(few, d, 'lora')}" for d in ORDER), + OUTDATA / "sec09_scsemi_status.csv") + num("b", "training pairs per draw: " + ", ".join(f"{NAME[d]} {info[d]['train']}" for d in ORDER) + + "; test pairs: " + ", ".join(f"{NAME[d]} {info[d]['test']}" for d in ORDER), + f"{DATA}//fewshot_n5/DRAWS.json (n_train_rows, n_test_rows)") + num("b", f"LoRA r = {lora_r}; {steps} fixed steps; base {CKPT}; sampling: {sampling}", base_src) + num("b", f"P/C definition: {pc_def}; PCA components in every summary.json = 50", SCORE_FT) + for ds in ORDER: + for t, lab in ((l1c, "zero-shot + calibration"), (l1t, "zero-shot (real bulk)")): + extra("b", f"{ds} LoRA-5 minus {lab} L1, Wilcoxon over donor-draw rows (pseudo-replicated; not quoted, " + f"replaced by the per-donor test)", + f"{t[ds]['row_mean_diff']:+.3f}, n={t[ds]['n_rows']}, p {t[ds]['row_p']:.2g}", t[ds]["source"]) + slides.append({"title": "5 donors: LoRA vs scSemiProfiler — cells", "layout": "full", + "figures": [str(FIGDIR / "sec09_fewpair_cells.png")], "keywords": kw_b, "footnote": foot_b, + "footnote_short": fs_b, "numbers": NUMS["b"]}) + + # ---------------- Giroux: sex-linked genes excluded from the disease metrics ---------------- + sx = {d: sex_split(d) for d in NOSEX} + gex = jload(SCORES_NOSEX / "giroux2022" / "pooled" / "summary.json")["gene_exclusion"] + sexbuild = jload(SEXLIST.parent / "BUILD.json")["counts"] + sx_txt = {d: f"{fm(sx[d]['scored']['case'])} vs {fm(sx[d]['scored']['control'])}" for d in NOSEX} + sx_all = {d: f"{fm(sx[d]['all']['case'])} vs {fm(sx[d]['all']['control'])}" for d in NOSEX} + nosex_short = " ".join(f"{NAME[d]}: sex-linked genes excluded (severity confounded with sex: {sx_txt[d]})." + for d in NOSEX) + nosex_long = " ".join( + f"{NAME[d]}: {CONTRAST[d]['case']} vs {CONTRAST[d]['control']} subjects are {sx_txt[d]} (scored; all paired " + f"subjects {sx_all[d]}; sex from bulk chrY expression = sc = GEO), so its disease metrics (logFC r, partial r, " + f"top-50 DEG, broadcast) exclude {gex['n_listed']} sex-linked genes ({sexbuild['chrY_nonPAR_excluded']} chrY " + f"non-PAR + {sexbuild['chrX_escape_excluded']} X-inactivation escape / variable-escape genes of Tukiainen et al. " + f"2017; PAR genes kept), {gex['n_dropped_from_scoring_genes']} of them scoring genes; same labels and cells as " + f"before (scores_nosex/{d}/)." for d in NOSEX) + for d in NOSEX: + num("c", f"{NAME[d]} sex by contrast arm (subjects, F/M): scored {CONTRAST[d]['case']} {fm(sx[d]['scored']['case'])}" + f" vs {CONTRAST[d]['control']} {fm(sx[d]['scored']['control'])}; all paired {fm(sx[d]['all']['case'])} " + f"vs {fm(sx[d]['all']['control'])}", sx[d]["source"]) + num("c", f"{NAME[d]} sex-linked genes excluded from the disease metrics: {gex['n_listed']} listed " + f"({sexbuild['chrY_nonPAR_excluded']} chrY non-PAR + {sexbuild['chrX_escape_excluded']} X escape), " + f"{gex['n_dropped_from_scoring_genes']} of {gex['n_scoring_genes']} scoring genes", + f"{SEXLIST}; {SEXLIST.parent / 'BUILD.json'}; {SCORES_NOSEX / d / 'pooled' / 'summary.json'} (gene_exclusion)") + + # ---------------- slide c ---------------- + cmp_r = same_draw_compare(few, status, DISEASE, "contrast_r") + cmp_d = same_draw_compare(few, status, DISEASE, "deg", min_margin=1.0) + cmp_rz = same_draw_compare(few, status, DISEASE, "contrast_r", other="zs_raw") + cmp_dz = same_draw_compare(few, status, DISEASE, "deg", min_margin=1.0, other="zs_raw") + cmp_rc = same_draw_compare(few, status, DISEASE, "contrast_r", other="zs_cal") + cmp_dc = same_draw_compare(few, status, DISEASE, "deg", min_margin=1.0, other="zs_cal") + nd = len(DISEASE) + deg_l = [d for d, v in cmp_d.items() if v["verdict"] == "lora"] + r_l = [d for d, v in cmp_r.items() if v["verdict"] == "lora"] + kw_c1 = f"LoRA-5 > scSemi-5: DEG {len(deg_l)}/{len(cmp_d)}, logFC r {len(r_l)}/{len(cmp_r)}" + rc_l = [d for d, v in cmp_rc.items() if v["verdict"] == "lora"] + kw_c2 = keyword_or_short(f"logFC r: LoRA-5 > calibrated zero-shot {len(rc_l)}/{len(cmp_rc)}", + f"logFC r > calibration: {len(rc_l)}/{len(cmp_rc)}") + arms4 = ("zs_raw", "zs_cal", "scsemi5", "lora") + + def arm_mean(ds, a, mk): + v = [x for x in few_vals(few, ds, a, mk)[0] if not np.isnan(x)] + return float(np.mean(v)) if v else np.nan + + def best_arm(d, mk): + return float(np.nanmax([arm_mean(d, a, mk) for a in arms4])) + + bc_r = [d for d in DISEASE if few_ref(few, d, "broadcast", "contrast_r")[0] > best_arm(d, "contrast_r")] + bc_d = [d for d in DISEASE if few_ref(few, d, "broadcast", "deg")[0] > best_arm(d, "deg")] + bc_both = [d for d in bc_r if d in bc_d] + if bc_both and bc_both == bc_r: + kw_c3 = keyword_or_short(f"{names(bc_both)}: real-bulk broadcast beats all arms", + f"Broadcast beats all arms: {len(bc_both)}/{nd}") + elif bc_r: + kw_c3 = keyword_or_short(f"{names(bc_r)}: broadcast r beats all arms", + f"Broadcast r beats all arms: {len(bc_r)}/{nd}") + else: + kw_c3 = "Every cohort: some arm beats broadcast" + kw_c_old = [kw_c2, kw_c3] # 2026-10-02: kept in the footnote; the slide lines now cover the rank metrics + bc_rank = [d for d in DISEASE if few_ref(few, d, "broadcast", "spearman_r")[0] > arm_mean(d, "lora", "spearman_r") + or few_ref(few, d, "broadcast", "limma_deg")[0] > arm_mean(d, "lora", "limma_deg")] + kw_c2 = keyword_or_short(f"Spearman / limma: broadcast ahead in {names(bc_rank)}", + f"Spearman or limma: broadcast ahead {len(bc_rank)}/{nd}") + ceil = [few_ref(few, d, "ceiling", "contrast_r")[0] for d in DISEASE] + kw_c3 = f"Split-half ceiling {min(ceil):.2f}–{max(ceil):.2f}: not limiting" + kw_c = check_keywords([kw_c1, kw_c2, kw_c3]) + rank_txt = "; ".join( + f"{NAME[d]}: Spearman LoRA-5 {arm_mean(d, 'lora', 'spearman_r'):.2f} / scSemi-5 {arm_mean(d, 'scsemi5', 'spearman_r'):.2f}" + f" / broadcast {few_ref(few, d, 'broadcast', 'spearman_r')[0]:.2f}, limma top-50 LoRA-5 " + f"{arm_mean(d, 'lora', 'limma_deg'):.1f} / scSemi-5 {arm_mean(d, 'scsemi5', 'limma_deg'):.1f} / broadcast " + f"{few_ref(few, d, 'broadcast', 'limma_deg')[0]:.1f} (chance {arm_mean(d, 'lora', 'limma_chance'):.1f}), " + f"ceiling {few_ref(few, d, 'ceiling', 'contrast_r')[0]:.2f}" for d in DISEASE) + dmax = {d: sorted({int(x) for x in few[(few.dataset == d) & (few.arm == "lora")]["deg_max"].dropna()}) for d in DISEASE} + small = [d for d in DISEASE if subjects_text(info[d])] + + def vz(c, other): + return ", ".join(f"{NAME[d]} {v['verdict'].replace('other', other)} {v['n_lora']}/{v['n']}" for d, v in c.items()) + + foot_c = (f"Same draws and verdict rule as the previous slide; DEG tie = half the draws equal or mean gap < 1 gene. " + f"Rank and threshold-free checks (scores_contrast/, tools/contrast_extra.py): Spearman r of the same logFC " + f"vectors; split-half ceiling = observed cells of each scored sample split in two halves (5 seeds), r of " + f"half-A vs half-B logFC, Spearman-Brown corrected to full data (noise-free ceiling); limma-voom top-50 = " + f"edgeR TMM + voom + limma eBayes on the same donor x type pseudobulks, BH FDR < 0.05, top 50 by |logFC|; " + f"grey tick = chance overlap (hypergeometric mean) of that arm's lists. Repeated samples of one patient " + f"(Imperial, Giroux, Ji) enter both tests as separate samples, as in the scorer. {rank_txt}. " + f"Earlier slide lines: {kw_c_old[0]}; {kw_c_old[1]}. " + f"logFC r = mean over T/B/Mono/NK of case-vs-control log2FC r (generated vs observed); top-50 DEG = " + f"Welch+BH overlap summed over {n_types} types (max 250; " + + ", ".join(f"{NAME[d]} {rng(dmax[d])}" for d in DISEASE if dmax[d] != [250]) + " per draw). " + + "".join(f"{NAME[d]} test = {subjects_text(info[d])} subjects per draw. " for d in small) + + f"LoRA-5-better draws (verdict): vs scSemi-5 logFC r {vz(cmp_r, 'scSemi-5')}; DEG {vz(cmp_d, 'scSemi-5')}. " + f"Vs zero-shot + calibration: logFC r {vz(cmp_rc, 'calibration')}; DEG {vz(cmp_dc, 'calibration')}. " + f"Vs zero-shot (real bulk): logFC r {vz(cmp_rz, 'zero-shot')}; DEG {vz(cmp_dz, 'zero-shot')}. " + + f"Broadcast = the input real bulk's own logFC. {nosex_long} " + + "Scores: scores//fewshot_n5/draw{,_scsemi5}/.") + fs_c = check_foot_short(f"{nosex_short} Top-50 DEG over {n_types} types.") + srcc = f"{SCORES}//fewshot_n5/draw{{,_scsemi5}}/summary.json and contrast.csv (Giroux: {SCORES_NOSEX}/giroux2022/)" + for cmpx, lab, arm in ((cmp_d, "scSemi-5", "scsemi5"), (cmp_dc, "zero-shot + calibration", "zs_cal"), + (cmp_dz, "zero-shot (real bulk)", "zs_raw")): + num("c", f"Top-50 DEG LoRA-5 vs {lab} (shared-draw means; LoRA-better / tied draws; verdict): " + + "; ".join(f"{NAME[d]} {v['lora']:.1f} vs {v['other']:.1f} ({v['n_lora']}/{v['n']}, {v['n_tie']} tied, {v['verdict']})" + for d, v in cmpx.items()), srcc) + for cmpx, lab, arm in ((cmp_r, "scSemi-5", "scsemi5"), (cmp_rc, "zero-shot + calibration", "zs_cal"), + (cmp_rz, "zero-shot (real bulk)", "zs_raw")): + num("c", f"logFC r LoRA-5 vs {lab} (shared-draw means; LoRA-better draws; verdict): " + + "; ".join(f"{NAME[d]} {v['lora']:.3f} vs {v['other']:.3f} ({v['n_lora']}/{v['n']}, {v['verdict']})" + for d, v in cmpx.items()), srcc) + for d in DISEASE: + num("c", f"{NAME[d]} broadcast logFC r {few_ref(few, d, 'broadcast', 'contrast_r')[0]:.3f} vs best arm " + f"{best_arm(d, 'contrast_r'):.3f}; broadcast DEG {few_ref(few, d, 'broadcast', 'deg')[0]:.1f} vs best arm " + f"{best_arm(d, 'deg'):.1f} (means over all draws; arms: zero-shot, zero-shot + calibration, scSemi-5, " + f"LoRA-5)", f"{SCORES if d not in NOSEX else SCORES_NOSEX}/{d}/fewshot_n5/draw{{,_scsemi5}}/summary.json") + num("c", "DEG maximum per draw: " + ", ".join(f"{NAME[d]} {rng(dmax[d])}" for d in DISEASE), + f"{SCORES}//fewshot_n5/draw/summary.json (deg_top50_max; Giroux: {SCORES_NOSEX})") + for d in small: + num("c", f"{NAME[d]} test subjects per draw: {subjects_text(info[d])} ({CONTRAST[d]['case']} vs " + f"{CONTRAST[d]['control']}); test pairs {info[d]['test']}", + f"{info[d]['source']} (train_donors); {DATA / d / 'folds.csv'} (group)") + # Giroux before / after the exclusion (CSV only) + for d in NOSEX: + saved = mf.DATASETS + mf.DATASETS = [d] + try: + fo, _ = mf.load_fewpair(SCORES) + finally: + mf.DATASETS = saved + for a in arms4: + o = fo[fo.arm == ARM_FILE[a]] + n = few[(few.dataset == d) & (few.arm == a)] + extra("c", f"{d} few-pair {a}: logFC r / DEG mean over draws, all genes -> sex-linked genes excluded", + f"{o.contrast_r.mean():.3f} / {o.deg.mean():.1f} -> {n.contrast_r.mean():.3f} / {n.deg.mean():.1f}", + f"{SCORES}/{d}/fewshot_n5 -> {SCORES_NOSEX}/{d}/fewshot_n5") + o = fo[fo.arm == "lora5"] + n = few[(few.dataset == d) & (few.arm == "lora")] + extra("c", f"{d} few-pair broadcast: logFC r / DEG mean over draws, all genes -> sex-linked genes excluded", + f"{o.broadcast_r.mean():.3f} / {o.deg_broadcast.mean():.1f} -> {n.broadcast_r.mean():.3f} / " + f"{n.deg_broadcast.mean():.1f}", f"{SCORES}/{d}/fewshot_n5 -> {SCORES_NOSEX}/{d}/fewshot_n5") + slides.append({"title": "5 donors: LoRA vs scSemiProfiler — disease signal", "layout": "figure_keywords", + "figures": [str(FIGDIR / "sec09_fewpair_disease.png")], "keywords": kw_c, "footnote": foot_c, + "footnote_short": fs_c, "numbers": NUMS["c"]}) + + # ---------------- slide d ---------------- + L = {d: pooled[d][POOLED_ARMS["lora"]] for d in ORDER} + Z = {d: pooled[d][POOLED_ARMS["zs_raw"]] for d in ORDER} + ZC = {d: pooled[d][POOLED_ARMS["zs_cal"]] for d in ORDER} + S = {d: pooled[d][POOLED_ARMS["sconly_cal"]] for d in ORDER} + has_sc = sc_cohorts(pooled) + B = {d: [Z[d], ZC[d], S[d]] + ([pooled[d][SR.CV_ARM]] if d in has_sc else []) for d in ORDER} + n_arms = len(fivefold_arms(pooled)) + best = {mk: [d for d in (ORDER if mk == "coverage" else DISEASE) if L[d][mk] >= np.nanmax([b[mk] for b in B[d]])] + for mk in ("coverage", "contrast_r", "deg")} + kw_d1 = f"LoRA tops coverage {len(best['coverage'])}/{len(ORDER)}, logFC r {len(best['contrast_r'])}/{len(DISEASE)}" + jb = baselines_text([b["coverage"] for b in B["ji2025_chili"] if not np.isnan(b["coverage"])]) + jl = f"{L['ji2025_chili']['coverage']:.2f}" + kw_d2 = keyword_or_short(f"Ji whole blood: baselines {jb}, LoRA {jl}", f"Ji whole blood: LoRA {jl}, others {jb}") + bc_win = [d for d in DISEASE if L[d]["broadcast_r"] > L[d]["contrast_r"]] + kw_d3 = ("; ".join(f"{NAME[d]}: broadcast r {L[d]['broadcast_r']:.2f} > LoRA {L[d]['contrast_r']:.2f}" for d in bc_win) + if bc_win else "LoRA above broadcast in every cohort") + kw_d3 = keyword_or_short(kw_d3, f"Broadcast r above LoRA: {names(bc_win)}") + sym = {"contrast_r": "r", "spearman_r": "ρ", "deg": "DEG", "limma_deg": "limma"} + bc_key = {"contrast_r": "broadcast_r", "spearman_r": "broadcast_spearman", "deg": "deg_broadcast", + "limma_deg": "limma_deg_broadcast"} + bc_lose = {d: [sym[mk] for mk in sym if L[d][bc_key[mk]] > L[d][mk]] for d in DISEASE} + bc_lose = {d: v for d, v in bc_lose.items() if v} + kw_d3 = keyword_or_short("Broadcast ahead: " + "; ".join(f"{NAME[d]} {', '.join(v)}" for d, v in bc_lose.items()), + f"Broadcast ahead: {names(bc_lose)}" if bc_lose else "LoRA above broadcast everywhere") + kw_d = check_keywords([kw_d1, kw_d2, kw_d3]) + foot_d = (f"Donor-level 5-fold CV; each pair scored once, by the fold model that never trained on its donor " + f"(one pooled call per cohort). LoRA r={lora_r} on the real bulk of the other 4 folds' training donors, early stop on " + f"inner-val donors. Zero-shot = base model without fine-tuning, fed the test pair's real bulk as measured; " + f"zero-shot + calibration = the same model fed gene-wise calibrated bulk (alpha fitted on the fold's " + f"training donors); sc-only fine-tune (+ calibration) = full fine-tune on training donors' sc pseudobulk, " + f"fed calibrated bulk. " + ( + f"scSemiProfiler, 5-fold CV = scSemiProfiler with every training donor of the fold " + f"(inner-val included) as representatives, scored for the same pairs and reference cells " + f"({names(has_sc)}" + + "".join(f"; {NAME[r['dataset']]}: {r['reason']}" for r in SC_LOG if r["status"] == "used" and r["reason"]) + + "). " if has_sc else "") + + f"Base f01 6k·1x·E16. LoRA best of {n_arms} arms: coverage {len(best['coverage'])}/{len(ORDER)}, " + f"logFC r {len(best['contrast_r'])}/{len(DISEASE)}, top-50 DEG {len(best['deg'])}/{len(DISEASE)}. " + f"Broadcast = raw real bulk. Sepsis DEG from pooled_deg. {nosex_long} " + f"Scores: scores//pooled/summary.json.") + fs_d = check_foot_short(f"Donor-level 5-fold CV. {nosex_short}") + psrc = (f"{SCORES}//pooled/summary.json (Sepsis DEG: {SCORES}/ye2026_sepsis/pooled_deg/summary.json; " + f"Giroux: {SCORES_NOSEX}/giroux2022/pooled/summary.json)") + num("d", f"LoRA best of {n_arms} arms: coverage {len(best['coverage'])}/{len(ORDER)}, logFC r " + f"{len(best['contrast_r'])}/{len(DISEASE)}, top-50 DEG {len(best['deg'])}/{len(DISEASE)}", psrc) + num("d", f"Ji coverage: zero-shot {Z['ji2025_chili']['coverage']:.3f}, zero-shot + calibration " + f"{ZC['ji2025_chili']['coverage']:.3f}, sc-only (+ calibration) {S['ji2025_chili']['coverage']:.3f}, " + f"LoRA {L['ji2025_chili']['coverage']:.3f}", SCORES / "ji2025_chili" / "pooled" / "summary.json") + for d in bc_win: + num("d", f"{NAME[d]} logFC r: broadcast {L[d]['broadcast_r']:.3f} vs LoRA {L[d]['contrast_r']:.3f}; " + f"DEG broadcast {L[d]['deg_broadcast']:.0f} vs LoRA {L[d]['deg']:.0f}", + (SCORES_NOSEX if d in NOSEX else SCORES) / d / "pooled" / "summary.json") + num("d", "LoRA logFC r vs broadcast: " + ", ".join(f"{NAME[d]} {L[d]['contrast_r']:.3f} vs {L[d]['broadcast_r']:.3f}" + for d in DISEASE), psrc) + for mk, lab in (("coverage", "coverage"), ("contrast_r", "logFC r"), ("deg", "top-50 DEG")): + dd = ORDER if mk == "coverage" else DISEASE + f = "{:.3f}" if mk != "deg" else "{:.0f}" + num("d", f"{lab} LoRA / zero-shot + calibration / zero-shot / sc-only (+ calibration): " + + ", ".join(f"{NAME[d]} {f.format(L[d][mk])} / {f.format(ZC[d][mk])} / {f.format(Z[d][mk])} / " + f"{f.format(S[d][mk])}" for d in dd), psrc) + if has_sc: + def _f(x, nd): + return "n/a" if np.isnan(x) else f"{x:.{nd}f}" + num("d", "scSemiProfiler, 5-fold CV: coverage / logFC r / top-50 DEG (n/a = no contrast or rescore " + "pending): " + ", ".join( + f"{NAME[d]} {_f(pooled[d][SR.CV_ARM]['coverage'], 3)} / {_f(pooled[d][SR.CV_ARM]['contrast_r'], 3)} / " + f"{_f(pooled[d][SR.CV_ARM]['deg'], 0)}" for d in has_sc), + "; ".join(pooled[d][SR.CV_ARM]["source"] for d in has_sc)) + num("d", "Pooled n (pairs / donors): " + ", ".join(f"{NAME[r.dataset]} {r.n_rows}/{r.n_donors}" for r in tab.itertuples()), + f"{SCORES}//pooled/summary.json (n_donors); {DATA}//fewshot_n5/DRAWS.json") + num("d", f"early stopping: {early}", README) + po, _ = mf.load_pooled(SCORES) + for d in ORDER: + for a, f in POOLED_ARMS.items(): + extra("d", f"{d} pooled {a} ({f}) coverage / precision / L1 / r / DEG", + f"{pooled[d][f]['coverage']:.3f} / {pooled[d][f]['precision']:.3f} / {pooled[d][f]['comp_l1']:.3f} / " + f"{pooled[d][f]['contrast_r']:.3f} / {pooled[d][f]['deg']:.0f}", + pooled[d][f]["source"] + (f"; DEG: {pooled[d][f]['deg_source']}" if "deg_source" in pooled[d][f] else "")) + if d in NOSEX: + extra("d", f"{d} pooled {a} ({f}) logFC r / broadcast r / DEG / DEG broadcast, all genes -> " + f"sex-linked genes excluded", + f"{po[d][f]['contrast_r']:.3f} / {po[d][f]['broadcast_r']:.3f} / {po[d][f]['deg']:.0f} / " + f"{po[d][f]['deg_broadcast']:.0f} -> {pooled[d][f]['contrast_r']:.3f} / " + f"{pooled[d][f]['broadcast_r']:.3f} / {pooled[d][f]['deg']:.0f} / {pooled[d][f]['deg_broadcast']:.0f}", + f"{po[d][f]['source']} -> {pooled[d][f]['source']}") + for r in SC_LOG: + extra("d", f"{r['dataset']} scSemiProfiler 5-fold ({SR.CV_ARM}) lookup", f"{r['status']} {r['reason']}".strip(), + r["source"]) + slides.append({"title": "5-fold CV: train on the other 4 folds", "layout": "full", "figures": [str(FIGDIR / "sec09_fivefold.png")], + "keywords": kw_d, "footnote": foot_d, "footnote_short": fs_d, "numbers": NUMS["d"]}) + + for s in slides: + for k in ("title", "footnote"): + check_text(s[k], k) + for n in s["numbers"]: + check_text(n["value"], "quoted number") + spec = {"section": "09", "slides": slides, "scripts": [str(SCRIPT)], + "generated_from": "tools/sec09_paired_validation.py (rerun to refresh; do not edit by hand)", + "scsemi_draws_used": f"{ns_used}/{ns_all}"} + (OUTDATA / "sec09_slide_text.json").write_text(json.dumps(spec, indent=1, ensure_ascii=False)) + flat = [{"slide": k, "item": "quoted on slide", "value": n["value"], "source": n["source"]} + for k in "abcd" for n in NUMS[k]] + EXTRA + pd.DataFrame(flat).to_csv(OUTDATA / "sec09_quoted_numbers.csv", index=False) + # nothing written by this script may carry refcal / VAE / TPM / AIFI / AIDA wording + for p in [OUTDATA / "sec09_slide_text.json"] + sorted(OUTDATA.glob("sec09_*.csv")): + m = OFF_STORY.search(p.read_text(encoding="utf-8")) + if m: + raise ValueError(f"{p}: off-story text {m.group(0)!r}") + + if not any(r["status"] == "used" for r in SC_LOG): + print(f"NOTE: no scSemiProfiler 5-fold call ({SR.CV_ARM}) under {SR.plan_root()}/scores//{SR.CV_EXP}/pooled*; " + f"the 5-fold slide has no scSemiProfiler bar.") + for r in SC_LOG: + print(f" scSemiProfiler 5-fold {r['dataset']}: {r['status']} {r['reason']} ({r['source']})") + print("scSemiProfiler draws used per dataset:", + {NAME[d]: f"{int((used.dataset == d).sum())}/{n_draws(few, d, 'lora')}" for d in ORDER}) + for s in slides: + print(f"\n== {s['title']} [{s['layout']}]") + for k in s["keywords"]: + print(" *", k, f"({n_words(k)} words, {len(k)} chars)") + print(" footnote_short:", s["footnote_short"], f"({len(s['footnote_short'])} chars)") + print(" footnote:", s["footnote"]) + for n in s["numbers"]: + print(" #", n["value"]) + for p in sorted(FIGDIR.glob("sec09_*.png")): + print("wrote", p) + return 0 + + +if __name__ == "__main__": + sys.exit(main())