diff --git a/paper-releases/pbisc-diffusion/updates/20261005T133325Z-deck-scratch-samepairs-tracking/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec07_no_pretraining.py b/paper-releases/pbisc-diffusion/updates/20261005T133325Z-deck-scratch-samepairs-tracking/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec07_no_pretraining.py new file mode 100644 index 0000000000000000000000000000000000000000..a5207c4d8dba0c617e91575e2382216e5a5b17f0 --- /dev/null +++ b/paper-releases/pbisc-diffusion/updates/20261005T133325Z-deck-scratch-samepairs-tracking/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec07_no_pretraining.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python3 +"""Section 7 slide of the 2026-09-30 paper-summary deck: no pretraining, same cohort (sepsis fold 0 pilot, 2026-10-05). + +CPU only. The same denoiser trained from random initialisation on the cohort's own pairs (tools/ft_sdd_aug.py +--init random, full training, lr 2e-4, inner-val selection, cap 100k steps) vs the pretrained model + LoRA r16, on the +same training pairs, real-bulk conditions (K = 1,000), test donors (fold 0: 12 sepsis, 5 controls) and sampling seed. +Reads one score_ft.py call over every arm (plans/paired_finetune_intradataset_20260927/scores/ye2026_sepsis/ +fold0_scratch_20261005/{summary.json, per_donor.csv, contrast.csv}) and the runs' RUN.json: + composition L1, coverage, disease logFC r (mean over T/B/Mono/NK of the mean-CP10K contrast r) = summary.json headline + across-donor composition r = per cell type (T, B, Mono, NK), Pearson r over the 17 test donors of generated vs + observed fraction (per_donor.csv), mean of the four types (reproduces ablation_extra_donor.csv comp_r_mean4) + training time = RUN.json wall_seconds (GB10; selected step and steps run in the slide data) +Outputs (deck folder; DECK_FIGDIR / DECK_OUTDATA override the folders): + figures/sec07_no_pretraining.{png,pdf}, data/sec07_no_pretraining.csv, data/sec07_no_pretraining_slide_text.json +""" +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 (deck rcParams and shared names) +import style # noqa: E402 +from grouped_bars import grouped_bars # 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 +SC = T / "scores" / "ye2026_sepsis" / "fold0_scratch_20261005" +RUNS = T / "runs" / "ye2026_sepsis" / "fold0" +FIGDIR = Path(os.environ.get("DECK_FIGDIR", str(DECK / "figures"))) +OUTDATA = Path(os.environ.get("DECK_OUTDATA", str(DECK / "data"))) +FS, SUB, EDGE = S9.FS, S9.SUB, S9.EDGE +SCRATCH = "#882255" +GROUPS = ["5", "58", "58 +\nrecipes"] +ARMS = [("pre", "Pretrained + LoRA", style.ARM["lora"], None), + ("scratch", "From scratch (no pretraining)", SCRATCH, None)] +RUN = {("pre", 0): "lora_n5", ("pre", 1): "real_lora", ("pre", 2): "lora_recipe", + ("scratch", 0): "scratch_n5", ("scratch", 1): "scratch_full", ("scratch", 2): "scratch_recipe"} +TYPES = ("T cell", "B cell", "Monocyte", "NK cell") + + +def main() -> int: + s = json.loads((SC / "summary.json").read_text()) + pd_ = pd.read_csv(SC / "per_donor.csv") + need = {f"{r}__raw" for r in RUN.values()} | {"zs__raw"} + if not need <= set(s["arms"]): + raise SystemExit(f"{SC}: arms missing {need - set(s['arms'])}") + if s["n_donors"] != 17: + raise SystemExit(f"{SC}: expected 17 scored donors, got {s['n_donors']}") + + def comp_r(arm): + g = pd_[pd_.arm == arm] + return float(np.mean([np.corrcoef(g["gen_" + t], g["obs_" + t])[0, 1] for t in TYPES])) + + vals, rows = {}, [] + for (a, i), run in RUN.items(): + arm = f"{run}__raw" + h = s["headline"][arm] + rj = json.loads((RUNS / run / "RUN.json").read_text()) + if (rj.get("init") == "random") != (a == "scratch"): + raise SystemExit(f"{run}: init {rj.get('init')} does not match {a}") + v = {"comp_l1": h["comp_l1"], "coverage": h["coverage"], "logfc_r": h["contrast_mean_cp10k_r_gen"], + "comp_r": comp_r(arm), "minutes": rj["wall_seconds"] / 60, "selected_step": rj["selected_step"], + "steps_run": rj["steps_run"], "train_rows": len(rj["train_rows"])} + vals[(a, i)] = v + rows.append({"group": GROUPS[i].replace("\n", " ") + " pairs", "arm": a, "score_arm": arm, **v, + "source": f"{SC}/summary.json; per_donor.csv; {RUNS / run / 'RUN.json'}"}) + zs = s["headline"]["zs__raw"] + zsv = {"comp_l1": zs["comp_l1"], "coverage": zs["coverage"], "logfc_r": zs["contrast_mean_cp10k_r_gen"], + "comp_r": comp_r("zs__raw")} + rows.append({"group": "0 pairs", "arm": "zero-shot", "score_arm": "zs__raw", **zsv, "source": f"{SC}/summary.json"}) + + panels = [("comp_l1", "Composition L1 ↓", False, None), ("coverage", "Coverage ↑", False, None), + ("logfc_r", "Disease logFC r ↑", False, None), ("comp_r", "Donor comp. r ↑", False, None), + ("minutes", "Train time (min)", True, lambda v: f"{v:.0f}" if v >= 10 else f"{v:.1f}")] + fig, axes = plt.subplots(1, len(panels), figsize=(12.3, 4.1), gridspec_kw={"wspace": 0.38}) + for ax, (mk, lab, log, fmt) in zip(axes, panels): + grouped_bars(ax, GROUPS, ARMS, lambda i, a: vals[(a, i)][mk], FS, EDGE, SUB, fmt=fmt, log=log) + ax.set_title(lab, fontsize=FS - 1) + if mk in zsv: + ax.axhline(zsv[mk], color=style.ARM["zs"], ls=(0, (4, 2)), lw=1.4, zorder=3) + if mk in ("coverage", "comp_r"): + ax.set_ylim(0, 1.0) + if mk == "minutes": + ax.set_ylim(1, 300) + ax.set_yticks([1, 10, 100], ["1", "10", "100"]) + ax.minorticks_off() + for t in ax.get_xticklabels(): + t.set_fontsize(FS - 4) + ax.set_xlabel("Training pairs", fontsize=FS - 4) + handles = [Patch(color=c, label=l) for _, l, c, _ in ARMS] + \ + [Line2D([0], [0], color=style.ARM["zs"], ls=(0, (4, 2)), lw=1.4, label="Zero-shot (pretrained, no pairs)")] + fig.legend(handles=handles, loc="lower center", ncol=3, bbox_to_anchor=(0.5, -0.12), fontsize=FS - 2) + style.save(fig, "sec07_no_pretraining", FIGDIR) + OUTDATA.mkdir(exist_ok=True) + pd.DataFrame(rows).to_csv(OUTDATA / "sec07_no_pretraining.csv", index=False, float_format="%.6g") + + p5, s5, p58, s58 = vals[("pre", 0)], vals[("scratch", 0)], vals[("pre", 1)], vals[("scratch", 1)] + sm = [vals[("scratch", i)]["minutes"] for i in range(3)] + pm = [vals[("pre", i)]["minutes"] for i in range(3)] + kw = [f"Same realism; 5 pairs: donor r {p5['comp_r']:.2f} vs {s5['comp_r']:.2f}", + f"58 pairs: scratch logFC r {s58['logfc_r']:.2f} vs {p58['logfc_r']:.2f}", + f"Scratch {min(sm):.0f}–{max(sm):.0f} min, LoRA {min(pm):.0f}–{max(pm):.0f} min"] + for k in kw: + if len(k) > 45: + raise SystemExit(f"keyword too long: {k}") + numbers = [{"value": f"{g.replace(chr(10), ' ')} pairs: pretrained+LoRA L1 {vals[('pre', i)]['comp_l1']:.3f} / scratch " + f"{vals[('scratch', i)]['comp_l1']:.3f}; coverage {vals[('pre', i)]['coverage']:.2f} / " + f"{vals[('scratch', i)]['coverage']:.2f}; logFC r {vals[('pre', i)]['logfc_r']:.2f} / " + f"{vals[('scratch', i)]['logfc_r']:.2f}; donor composition r {vals[('pre', i)]['comp_r']:.2f} / " + f"{vals[('scratch', i)]['comp_r']:.2f}; time {vals[('pre', i)]['minutes']:.1f} / " + f"{vals[('scratch', i)]['minutes']:.0f} min; steps (selected/run) " + f"{vals[('pre', i)]['selected_step']}/{vals[('pre', i)]['steps_run']} vs " + f"{vals[('scratch', i)]['selected_step']}/{vals[('scratch', i)]['steps_run']}", + "source": f"data/sec07_no_pretraining.csv"} for i, g in enumerate(GROUPS)] + full = ("Pilot on one fold: sepsis fold 0, 17 test donors (12 sepsis, 5 controls); folds 1-4 not run, so no claim " + "yet. From scratch = the same denoiser (54.2 M weights) re-initialised at random (tools/ft_sdd_aug.py --init " + "random; seed 20260627) and trained in full on the cohort's own pairs at the pretraining lr 2e-4, batch 256, " + "EMA 0.999, inner-val selection every 1,000 steps, patience 10, cap 100k steps; the checkpoint supplies only " + "the architecture, 6k panel, value scaler and bulk z-score constants. Pretrained + LoRA = f01 6k 1x E16 + " + "LoRA r16 (lr 5e-4). Same training pairs (5 or 58, + 7-8 inner-val), real-bulk conditions K = 1,000, test " + "donors and sampling seed; recipes = K-diversified pseudobulk augmentation. The 58-pair scratch arms were " + "still improving at the 100k cap. Coverage = PCA-50 k = 10 balls (precision, C2ST, MMD, E_N agree; " + "scores_extra/ye2026_sepsis/fold0_scratch_20261005/). Donor composition r = per cell type (T, B, Mono, NK) " + "Pearson r over the 17 donors of generated vs observed fraction, mean of the four. Dashed = zero-shot. " + "Training time = RUN.json wall seconds on one GB10 (LoRA also needs the one-time 15.9 h pretraining, which " + "every cohort reuses). Source: plans/paired_finetune_intradataset_20260927/scores/ye2026_sepsis/" + "fold0_scratch_20261005/ and README 'No-pretraining ablation'.") + txt = {"title": "No pretraining: same cohort, from scratch", "layout": "full", + "figures": [str(FIGDIR / "sec07_no_pretraining.png")], "keywords": kw, + "footnote_short": "Pilot: sepsis fold 0, 17 test donors (12 sepsis, 5 controls). Folds 1–4 not run yet.", + "footnote": full, "numbers": numbers} + out = {"section": "07-no-pretraining", "scripts": [str(Path(__file__).resolve())], + "generated_from": "tools/sec07_no_pretraining.py (rerun to refresh; do not edit by hand)", "slides": [txt]} + (OUTDATA / "sec07_no_pretraining_slide_text.json").write_text(json.dumps(out, indent=1, ensure_ascii=False)) + print("\n".join(kw)) + for n in numbers: + print(n["value"]) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/paper-releases/pbisc-diffusion/updates/20261005T133325Z-deck-scratch-samepairs-tracking/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec08_cross_scratch.py b/paper-releases/pbisc-diffusion/updates/20261005T133325Z-deck-scratch-samepairs-tracking/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec08_cross_scratch.py new file mode 100644 index 0000000000000000000000000000000000000000..a6e45ee85f3f950776560492f04887685bf4bb98 --- /dev/null +++ b/paper-releases/pbisc-diffusion/updates/20261005T133325Z-deck-scratch-samepairs-tracking/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec08_cross_scratch.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python3 +"""Section 8 slide of the 2026-09-30 paper-summary deck: no pretraining, other cohorts (held-out sepsis pilot, 2026-10-05). + +CPU only. Held-out sepsis (82 usable samples), training pool = ImMicro + Imperial + Giroux + Liu 2021 (split +hoL_ye2026_sepsis), K = 1,000. Arms: zero-shot + cross-cohort calibration, pretrained + LoRA r16 / r64 / full FT at step +saturation (as slides 25-26), the same denoiser trained from random initialisation on the pool (--init random, full, +lr 2e-4, milestones every 50k steps to 162k), and the cohort's own-pair LoRA (5-fold, reference). + +All arms are read from plans/paired_crosscohort_20261002/scores_masked/ye2026_sepsis//summary.json +(tools/mask_rescore.py): the 46 panel genes measured in sepsis but in no training cohort are zeroed in the generated +cells of EVERY arm before scoring. Reason: a model trained from scratch never gets a loss on those genes and puts ~91 % +of its UMI there (observed sepsis cells: 0.014 %), so unmasked scores would measure that artefact. The pretrained arms +change little with the mask (checked against scores/ and printed). Training time = RUN.json wall_seconds (GB10); the own- +cohort LoRA time is the mean of its five fold runs (paired_finetune_intradataset_20260927/runs/ye2026_sepsis/fold*/real_lora). +Outputs: figures/sec08_cross_scratch.{png,pdf}, data/sec08_cross_scratch.csv, data/sec08_cross_scratch_slide_text.json +""" +from __future__ import annotations + +import os + +os.environ["CUDA_VISIBLE_DEVICES"] = "" # plotting only + +import glob +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 +import style # noqa: E402 +from grouped_bars import grouped_bars # noqa: E402 +import matplotlib.pyplot as plt # noqa: E402 + +M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion") +P = M8 / "plans" / "paired_crosscohort_20261002" +TI = M8 / "plans" / "paired_finetune_intradataset_20260927" +MS, UM = P / "scores_masked" / "ye2026_sepsis", P / "scores" / "ye2026_sepsis" +RUNS = P / "runs" / "hoL_ye2026_sepsis" / "K1000" +FIGDIR = Path(os.environ.get("DECK_FIGDIR", str(DECK / "figures"))) +OUTDATA = Path(os.environ.get("DECK_OUTDATA", str(DECK / "data"))) +FS, SUB, EDGE = S9.FS, S9.SUB, S9.EDGE +# key, label, scored arm, run dir (None = no training), colour, hatch (colours as in tools/sec08_cross_cohort.py) +ARMS = [("cal", "Calibration", "xcalL_K1000", None, "#0072B2", None), + ("r16", "LoRA r16", "locoL_lora16sat_s26750_K1000", "lora16sat", "#44AA99", None), + ("r64", "LoRA r64", "locoL_lora64sat_s59000_K1000", "lora64sat", "#117733", None), + ("full", "Full FT", "locoL_fullsat_s108500_K1000", "fullsat", "#332288", None), + ("scratch", "From scratch", "locoL_scratchsat_s162000_K1000", "scratchsat", "#882255", None), + ("own", "Own-cohort LoRA", "within_real_lora__raw", "own", "#D55E00", "///")] +MILESTONES = ["locoL_scratchsat_s50000_K1000", "locoL_scratchsat_s100000_K1000", "locoL_scratchsat_s150000_K1000", + "locoL_scratchsat_s162000_K1000"] + + +def head(root, arm): + s = json.loads((root / arm / "summary.json").read_text()) + h = s["headline"][arm] + return s, {"comp_l1": h["comp_l1"], "coverage": h["coverage"], "logfc_r": h["contrast_mean_cp10k_r_gen"], + "deg": h.get("deg_top50_sum")} + + +def main() -> int: + vals, rows, ref = {}, [], None + for key, lab, arm, run, *_ in ARMS: + s, v = head(MS, arm) + sig = (tuple(sorted(s["donors"])), s["reference"]["reference_sha256"]) + if ref is None: + ref = sig + elif sig != ref: + raise SystemExit(f"{arm}: donors or reference differ from the other masked calls") + if run is None: + v["minutes"], v["steps"] = np.nan, 0 + elif run == "own": + w = [json.loads(Path(f).read_text())["wall_seconds"] for f in + sorted(glob.glob(str(TI / "runs" / "ye2026_sepsis" / "fold*" / "real_lora" / "RUN.json")))] + if len(w) != 5: + raise SystemExit("own-cohort LoRA: expected five fold runs") + v["minutes"], v["steps"] = float(np.mean(w)) / 60, None + else: + rj = json.loads((RUNS / run / "RUN.json").read_text()) + if (rj.get("init") == "random") != (key == "scratch"): + raise SystemExit(f"{run}: init {rj.get('init')}") + v["minutes"], v["steps"] = rj["wall_seconds"] / 60, rj["steps_run"] + um = UM / arm / "summary.json" + if um.exists() and key not in ("scratch",): + _, u = head(UM, arm) + v["unmasked_comp_l1"], v["unmasked_coverage"], v["unmasked_logfc_r"] = u["comp_l1"], u["coverage"], u["logfc_r"] + vals[key] = v + rows.append({"arm": key, "label": lab.replace("\n", " "), "scored_arm": arm, **v, + "source": str(MS / arm / "summary.json")}) + if len(ref[0]) != 82: + raise SystemExit(f"expected 82 scored samples, got {len(ref[0])}") + ms = {a: head(MS, a)[1] for a in MILESTONES} + for a in MILESTONES: + rows.append({"arm": "scratch_milestone", "label": a, "scored_arm": a, **ms[a], "source": str(MS / a / "summary.json")}) + for k, v in vals.items(): + if "unmasked_comp_l1" in v: + print(f"{k}: masked vs unmasked L1 {v['comp_l1']:.3f}/{v['unmasked_comp_l1']:.3f}, coverage " + f"{v['coverage']:.3f}/{v['unmasked_coverage']:.3f}, logFC r {v['logfc_r']:.3f}/{v['unmasked_logfc_r']:.3f}") + + groups = [lab for _, lab, *_ in ARMS] + panels = [("comp_l1", "Composition L1 ↓", False, lambda v: f"{v:.2f}"), + ("coverage", "Coverage ↑", False, lambda v: f"{v:.2f}"), + ("logfc_r", "Disease logFC r ↑", False, lambda v: f"{v:.2f}"), + ("minutes", "Train time (min)", True, lambda v: f"{v:.0f}")] + fig, axes = plt.subplots(1, len(panels), figsize=(12.3, 4.0), gridspec_kw={"wspace": 0.30}) + for ax, (mk, lab, log, fmt) in zip(axes, panels): + x = np.arange(len(ARMS)) + for i, (key, _l, _a, _r, col, hatch) in enumerate(ARMS): + v = vals[key][mk] + if np.isnan(v): + ax.text(i, 0.10, "none", transform=ax.get_xaxis_transform(), ha="center", va="bottom", + fontsize=FS - 5, color=SUB) + continue + ax.bar(i, v, 0.75, color=col, edgecolor=EDGE if hatch else "none", linewidth=0.6, hatch=hatch, zorder=2) + ax.text(i, v * (1.08 if log else 1.0) + (0 if log else 0.008), fmt(v), ha="center", va="bottom", + fontsize=FS - 6, color=SUB) + ax.set_xticks(x, [g for g in groups], rotation=55, ha="right", fontsize=FS - 5) + ax.set_title(lab, fontsize=FS - 1) + ax.tick_params(axis="y", labelsize=FS - 4) + ax.grid(axis="y", color="#E3E3E3", linewidth=0.8, zorder=0) + ax.set_axisbelow(True) + ax.axvline(len(ARMS) - 1.5, color="#BBBBBB", lw=0.8, ls=":") + if mk == "coverage": + ax.set_ylim(0, 1.0) + if log: + ax.set_yscale("log") + ax.set_ylim(1, 400) + ax.set_yticks([1, 10, 100], ["1", "10", "100"]) + ax.minorticks_off() + if mk == "comp_l1": + ax.set_ylim(0, max(v["comp_l1"] for v in vals.values()) * 1.18) + style.save(fig, "sec08_cross_scratch", FIGDIR) + OUTDATA.mkdir(exist_ok=True) + pd.DataFrame(rows).to_csv(OUTDATA / "sec08_cross_scratch.csv", index=False, float_format="%.6g") + + sc, r16, own, cal = vals["scratch"], vals["r16"], vals["own"], vals["cal"] + kw = [f"Scratch ≈ LoRA r16: coverage {sc['coverage']:.2f} vs {r16['coverage']:.2f}", + f"Own-cohort pairs far ahead: coverage {own['coverage']:.2f}", + f"Scratch {sc['minutes']:.0f} min vs LoRA r16 {r16['minutes']:.0f} min"] + for k in kw: + if len(k) > 45: + raise SystemExit(f"keyword too long: {k}") + numbers = [{"value": f"{lab.replace(chr(10), ' ')}: L1 {vals[k]['comp_l1']:.3f}, coverage {vals[k]['coverage']:.3f}, " + f"logFC r {vals[k]['logfc_r']:.3f}, top-50 DEG {vals[k]['deg']}, time " + + ("none" if np.isnan(vals[k]["minutes"]) else f"{vals[k]['minutes']:.0f} min"), + "source": "data/sec08_cross_scratch.csv"} for k, lab, *_ in ARMS] + numbers.append({"value": "Scratch milestones (masked) 50k / 100k / 150k / 162k steps: L1 " + + " / ".join(f"{ms[a]['comp_l1']:.3f}" for a in MILESTONES) + "; coverage " + + " / ".join(f"{ms[a]['coverage']:.3f}" for a in MILESTONES) + "; logFC r " + + " / ".join(f"{ms[a]['logfc_r']:.3f}" for a in MILESTONES), + "source": "data/sec08_cross_scratch.csv"}) + full = ("Pilot, one held-out cohort: sepsis (82 samples), training pool ImMicro + Imperial + Giroux + Liu 2021, " + "K = 1,000, same inner-val selection and sampling as slides 25-26. From scratch = the same denoiser at random " + "initialisation (--init random), full training at lr 2e-4, milestones every 50k steps, stopped at 162k " + "(selected 152k; 127 min on one GB10). Every arm is scored with the 46 panel genes that no training cohort " + "measured set to 0 in the generated cells (tools/mask_rescore.py): the scratch model never gets a loss on " + "them and puts ~91 % of its UMI there (observed sepsis cells 0.014 %); the pretrained arms barely change " + f"(e.g. LoRA r16 coverage {r16['coverage']:.2f} masked vs {r16.get('unmasked_coverage', float('nan')):.2f} unmasked). " + f"Calibration needs no training. Own-cohort LoRA = 5-fold LoRA on sepsis pairs (mean {own['minutes']:.1f} min " + "per fold). Scratch milestones: " + numbers[-1]["value"].split(": ", 1)[1] + ". " + "Source: plans/paired_crosscohort_20261002/scores_masked/ye2026_sepsis/ (table_masked.py), runs/hoL_ye2026_sepsis/K1000/.") + txt = {"title": "No pretraining: other cohorts, from scratch", "layout": "full", + "figures": [str(FIGDIR / "sec08_cross_scratch.png")], "keywords": kw, + "footnote_short": "Pilot: held-out sepsis, 82 samples. Genes no training cohort measured are zeroed in every arm.", + "footnote": full, "numbers": numbers} + out = {"section": "08-cross-scratch", "scripts": [str(Path(__file__).resolve())], + "generated_from": "tools/sec08_cross_scratch.py (rerun to refresh; do not edit by hand)", "slides": [txt]} + (OUTDATA / "sec08_cross_scratch_slide_text.json").write_text(json.dumps(out, indent=1, ensure_ascii=False)) + print("\n".join(kw)) + for n in numbers: + print(n["value"]) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/paper-releases/pbisc-diffusion/updates/20261005T133325Z-deck-scratch-samepairs-tracking/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec09_paired_validation.py b/paper-releases/pbisc-diffusion/updates/20261005T133325Z-deck-scratch-samepairs-tracking/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec09_paired_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..d23eab96276f0cc7de434651a382c153eaeb101d --- /dev/null +++ b/paper-releases/pbisc-diffusion/updates/20261005T133325Z-deck-scratch-samepairs-tracking/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec09_paired_validation.py @@ -0,0 +1,1671 @@ +#!/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")) + # 2026-10-05: scSemiProfiler 5-fold CV arm, from its own scored unit (contrast_extra.py --design scored + # --unit scsemi_cv_20261002/pooled); Pearson r and Welch top-50 must match the scorer. Blank if not computed. + if SR.CV_ARM in pooled[ds]: + P = pooled[ds][SR.CV_ARM] + hf = CX / ds / SR.CV_EXP / "pooled" / "headline.csv" + keys = ("spearman_r", "limma_deg", "deg_chance", "limma_chance") + m = pd.read_csv(hf) if hf.exists() else None + m = m[m.arm == SR.CV_ARM] if m is not None else None + if m is None or len(m) != 1 or np.isnan(P["contrast_r"]): + P.update({k: np.nan for k in keys}) + continue + m = m.iloc[0] + if abs(m.pearson_r - P["contrast_r"]) > 1e-9 or abs(m.welch_top50 - P["deg"]) > 1e-9: + raise ValueError(f"{hf} disagrees with the scorer for {ds} {SR.CV_ARM}") + 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), + cx_source=str(hf.parent)) + 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 "in progress")} + 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()) diff --git a/paper-releases/pbisc-diffusion/updates/20261005T133325Z-deck-scratch-samepairs-tracking/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec09_same_pairs.py b/paper-releases/pbisc-diffusion/updates/20261005T133325Z-deck-scratch-samepairs-tracking/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec09_same_pairs.py new file mode 100644 index 0000000000000000000000000000000000000000..caa751717f06c8e409ff500db2bb2212feb9547c --- /dev/null +++ b/paper-releases/pbisc-diffusion/updates/20261005T133325Z-deck-scratch-samepairs-tracking/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec09_same_pairs.py @@ -0,0 +1,265 @@ +#!/usr/bin/env python3 +"""Section 9 slide of the 2026-09-30 paper-summary deck: scSemiProfiler and LoRA given the SAME training pairs +(5-fold CV, 2026-10-05; cohorts still running are shown as "in progress"). + +CPU only. Per cohort, both methods use exactly the pairs of the other four folds (LoRA's training + inner-val rows = +scSemiProfiler's representatives; checked for every fold by scsemi/tools/check_units.py) and are scored on all usable +samples, each by the fold model that never saw it (one pooled score_ft.py call per method, same donors and reference): + LoRA scores//pooled/summary.json arm real_lora__raw + scSemiProfiler scores//scsemi_cv_20261002/pooled/summary.json arm scsemi__raw + Giroux disease metrics from scores_nosex/ (sex-linked genes excluded), as in the deck. +GPU time per fold (one GB10, every step alone on the GPU; data preparation and scoring not counted on either side): + LoRA runs//fold/real_lora/RUN.json wall_seconds + the sampling job's wall clock in logs/run_queue_*.log + scSemiProfiler scsemi/work//cv/fold/scsemi_project/models/*.receipt.json elapsed_seconds (stage 1 + 2 of every + representative, complete, same run signature as the export) + the export's total_target_seconds + Read on the host that holds each fold's records (server_1 or spark-0110). +The equal-pair-budget runs (n = 5..40, ImMicro and sepsis) are drawn on the "Pairs needed" slide; quoted here. +Outputs: figures/sec09_same_pairs.{png,pdf}, data/sec09_same_pairs.csv, data/sec09_same_pairs_slide_text.json +""" +from __future__ import annotations + +import os + +os.environ["CUDA_VISIBLE_DEVICES"] = "" # plotting only + +import json +import subprocess +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 +import style # noqa: E402 +import matplotlib.pyplot as plt # noqa: E402 +from matplotlib.patches import Patch # noqa: E402 + +T = S9.T +ORDER, ROWNAME = S9.ORDER, S9.ROWNAME +FS, SUB, EDGE = S9.FS, S9.SUB, S9.EDGE +FIGDIR = Path(os.environ.get("DECK_FIGDIR", str(DECK / "figures"))) +OUTDATA = Path(os.environ.get("DECK_OUTDATA", str(DECK / "data"))) +CV = "scsemi_cv_20261002" +BUDGET = "scsemi_budget_20261002" +ARMS = [("scsemi", "scSemiProfiler, same pairs", style.ARM["scsemi"]), ("lora", "LoRA, same pairs", style.ARM["lora"])] +TAG = {"immicro": "imm", "ye2026_sepsis": "ye2", "imperial_eskd": "imp", "giroux2022": "gir", "ji2025_chili": "ji2"} + +COLLECT = r''' +import glob, json, os, re, sys +T = sys.argv[1]; TAG = json.loads(sys.argv[2]) +def jl(p): + try: + return json.load(open(p)) + except Exception: + return None +st, en = {}, {} +for lg in sorted(glob.glob(os.path.join(T, "logs", "run_queue_*.log"))): + for line in open(lg, errors="replace"): + m = re.match(r"^(\S+) --- ([a-z0-9]+_f\d_real_lora_raw) seed=", line) + if m: st.setdefault(m.group(2), []).append(m.group(1)) + m = re.match(r"^(\S+) ([a-z0-9]+_f\d_real_lora_raw) done:", line) + if m: en.setdefault(m.group(2), []).append(m.group(1)) +out = {} +for ds, p in TAG.items(): + for k in range(5): + r = {} + run = jl(os.path.join(T, "runs", ds, f"fold{k}", "real_lora", "RUN.json")) + tag = f"{p}_f{k}_real_lora_raw" + if run and len(st.get(tag, [])) >= 1 and len(en.get(tag, [])) >= 1: + r["lora"] = {"train_s": run["wall_seconds"], "start": st[tag][-1], "end": en[tag][-1]} + ex = jl(os.path.join(T, "generated", ds, f"fold{k}", "scsemi__raw.log")) + w = os.path.join(T, "scsemi", "work", ds, "cv", f"fold{k}") + asg = jl(os.path.join(w, "assignment.json")) + if ex and asg: + rec = [jl(f) for f in glob.glob(os.path.join(w, "scsemi_project", "models", "*.receipt.json"))] + rec = [x for x in rec if x and x.get("complete") and x.get("run_signature") == ex["run_signature"]] + r["scsemi"] = {"n_reps": len(asg["representative_indices"]), "n_rec": len(rec), + "pretrain_s": sum(x["elapsed_seconds"] for x in rec), "target_s": ex["total_target_seconds"], + "bulks": ex["bulks"]} + out[f"{ds}|{k}"] = r +print(json.dumps(out)) +''' + + +def collect(host): + cmd = ["python3", "-", str(T), json.dumps(TAG)] + if host != "server_1": + cmd = ["ssh", "spark-0110"] + ["python3", "-", str(T), "'" + json.dumps(TAG) + "'"] + res = subprocess.run(cmd, input=COLLECT, capture_output=True, text=True, check=True) + return json.loads(res.stdout) + + +def load(p): + f = p / "summary.json" + return json.loads(f.read_text()) if f.exists() else None + + +def main() -> int: + got = {h: collect(h) for h in ("server_1", "server_2")} + vals, rows, done = {}, [], [] + for ds in ORDER: + lo, sc = load(T / "scores" / ds / "pooled"), load(T / "scores" / ds / CV / "pooled") + if sc is None or "scsemi__raw" not in sc["arms"]: + continue + if set(lo["donors"]) != set(sc["donors"]) or lo["reference"]["reference_sha256"] != sc["reference"]["reference_sha256"]: + raise SystemExit(f"{ds}: LoRA and scSemiProfiler pooled calls differ in donors or reference") + hl, hs = dict(lo["headline"]["real_lora__raw"]), dict(sc["headline"]["scsemi__raw"]) + if ds == "giroux2022": + nl, ns = load(T / "scores_nosex" / ds / "pooled"), load(T / "scores_nosex" / ds / CV / "pooled") + if ns is None: + hs["contrast_mean_cp10k_r_gen"] = np.nan + for h, n, a in ((hl, nl, "real_lora__raw"), (hs, ns, "scsemi__raw")): + if n is not None: + h["contrast_mean_cp10k_r_gen"] = n["headline"][a]["contrast_mean_cp10k_r_gen"] + t = {"lora": [], "scsemi": []} + for k in range(5): + for m in ("lora", "scsemi"): + rec = [g[f"{ds}|{k}"][m] for g in got.values() if m in g.get(f"{ds}|{k}", {}) + and (m == "lora" or g[f"{ds}|{k}"][m]["n_rec"] == 2 * g[f"{ds}|{k}"][m]["n_reps"])] + if len(rec) != 1: + raise SystemExit(f"{ds} fold {k} {m}: {len(rec)} complete timing records across hosts") + r = rec[0] + if m == "lora": + gen = (pd.Timestamp(r["end"]) - pd.Timestamp(r["start"])).total_seconds() + t[m].append((r["train_s"] + gen) / 3600) + else: + t[m].append((r["pretrain_s"] + r["target_s"]) / 3600) + for m, h in (("lora", hl), ("scsemi", hs)): + vals[(ds, m)] = {"comp_l1": h["comp_l1"], "coverage": h["coverage"], "precision": h["precision"], + "logfc_r": h.get("contrast_mean_cp10k_r_gen", np.nan), "deg": h.get("deg_top50_sum"), + "hours": float(np.mean(t[m])), "hours_min": min(t[m]), "hours_max": max(t[m])} + rows.append({"dataset": ds, "arm": m, **vals[(ds, m)], "n_scored": lo["n_donors"], + "source": str(T / "scores" / ds / (CV + "/pooled" if m == "scsemi" else "pooled") / "summary.json")}) + done.append(ds) + if not done: + raise SystemExit("no cohort has a scored scSemiProfiler 5-fold CV yet") + # equal pair budget (quoted only) + bud = [] + for ds in ORDER: + sb, lo = load(T / "scores" / ds / BUDGET / "pooled"), load(T / "scores" / ds / "pooled") + if sb is None: + continue + for n in (5, 10, 20, 40): + a, b = f"scsemi_n{n}__raw", f"lora_n{n}__raw" + if a in sb["arms"] and b in lo["arms"]: + bud.append({"dataset": ds, "n": n, "scsemi_l1": sb["headline"][a]["comp_l1"], + "lora_l1": lo["headline"][b]["comp_l1"], "scsemi_cov": sb["headline"][a]["coverage"], + "lora_cov": lo["headline"][b]["coverage"]}) + bud = pd.DataFrame(bud) + + panels = [("comp_l1", "Composition L1 ↓", None), ("coverage", "Coverage ↑", (0, 1)), + ("logfc_r", "Disease logFC r ↑", (0, 1)), ("hours", "GPU hours per fold", None)] + fig, axes = plt.subplots(1, 4, figsize=(12.3, 4.2), gridspec_kw={"wspace": 0.12}) + h = 0.36 + y = np.arange(len(ORDER)) * 1.0 + for ax, (mk, lab, lim) in zip(axes, panels): + for i, ds in enumerate(ORDER): + if ds == "immicro" and mk == "logfc_r" and ds in done: + ax.text(0.03, y[i], "healthy cohort: no contrast", transform=ax.get_yaxis_transform(), va="center", + fontsize=FS - 4, color=SUB) + continue + if ds not in done: + ax.text(0.03, y[i], "in progress", transform=ax.get_yaxis_transform(), va="center", fontsize=FS - 4, + color=SUB) + continue + for k, (m, _l, col) in enumerate(ARMS): + v = vals[(ds, m)][mk] + yy = y[i] + (k - 0.5) * h + if v is None or np.isnan(v): + ax.text(0.03, yy, "no contrast" if ds == "immicro" else "n/a", transform=ax.get_yaxis_transform(), + va="center", fontsize=FS - 5, color=SUB) + continue + ax.barh(yy, v, h * 0.9, color=col, edgecolor="none") + if mk == "hours": + vv = vals[(ds, m)] + s = (f"{vv['hours_min'] * 60:.0f}–{vv['hours_max'] * 60:.0f} min" if m == "lora" + else f"{vv['hours_min']:.1f}–{vv['hours_max']:.1f} h") + else: + s = f"{v:.2f}" + ax.text(v * (1.12 if mk == "hours" else 1.0) + (0 if mk == "hours" else 0.015), yy, s, va="center", + fontsize=FS - 5, color=SUB) + ax.set_title(lab, fontsize=FS - 1) + ax.set_yticks(y, [ROWNAME[d] for d in ORDER] if ax is axes[0] else [""] * len(ORDER), fontsize=FS - 3) + ax.set_ylim(len(ORDER) - 0.5, -0.5) + ax.tick_params(axis="y", length=0) + ax.tick_params(axis="x", labelsize=FS - 4) + if lim: + ax.set_xlim(*lim) + if mk == "comp_l1": + ax.set_xlim(0, 0.75) + if mk == "hours": + ax.set_xscale("log") + ax.set_xlim(0.03, 40) + ax.set_xticks([0.1, 1, 10], ["0.1", "1", "10"]) + ax.minorticks_off() + ax.grid(axis="x", color="#E3E3E3", linewidth=0.8) + ax.set_axisbelow(True) + fig.legend(handles=[Patch(color=c, label=l) for _, l, c in ARMS], loc="lower center", ncol=2, + bbox_to_anchor=(0.5, -0.08), fontsize=FS - 2) + style.save(fig, "sec09_same_pairs", FIGDIR) + OUTDATA.mkdir(exist_ok=True) + pd.DataFrame(rows).to_csv(OUTDATA / "sec09_same_pairs.csv", index=False, float_format="%.6g") + if len(bud): + bud.to_csv(OUTDATA / "sec09_same_pairs_budget.csv", index=False, float_format="%.6g") + + names = [S9.NAME[d] for d in done] + lw = {k: sum((vals[(d, 'lora')][k] < vals[(d, 'scsemi')][k]) if k == "comp_l1" + else (vals[(d, 'lora')][k] > vals[(d, 'scsemi')][k]) for d in done + if not np.isnan(vals[(d, 'lora')][k]) and not np.isnan(vals[(d, 'scsemi')][k])) + for k in ("comp_l1", "coverage", "precision", "logfc_r")} + ratio = [vals[(d, "scsemi")]["hours"] / vals[(d, "lora")]["hours"] for d in done] + kw = [f"Same pairs: LoRA ahead on every metric", + f"Coverage {vals[(done[0], 'lora')]['coverage']:.2f} vs {vals[(done[0], 'scsemi')]['coverage']:.2f} ({S9.NAME[done[0]]})", + f"{min(ratio):.0f}–{max(ratio):.0f}× less GPU time per fold"] + if not all(lw[k] == sum(1 for d in done if not np.isnan(vals[(d, 'lora')][k])) for k in lw): + kw[0] = "Same pairs: " + ", ".join(f"{k} {v}/{len(done)}" for k, v in lw.items()) + for k in kw: + if len(k) > 45: + raise SystemExit(f"keyword too long: {k}") + numbers = [{"value": f"{S9.NAME[d]}: L1 LoRA {vals[(d, 'lora')]['comp_l1']:.3f} / scSemi {vals[(d, 'scsemi')]['comp_l1']:.3f}; " + f"coverage {vals[(d, 'lora')]['coverage']:.3f} / {vals[(d, 'scsemi')]['coverage']:.3f}; precision " + f"{vals[(d, 'lora')]['precision']:.3f} / {vals[(d, 'scsemi')]['precision']:.3f}; logFC r " + f"{vals[(d, 'lora')]['logfc_r']:.3f} / {vals[(d, 'scsemi')]['logfc_r']:.3f}; top-50 DEG " + f"{vals[(d, 'lora')]['deg']} / {vals[(d, 'scsemi')]['deg']}; GPU per fold LoRA " + f"{vals[(d, 'lora')]['hours'] * 60:.1f} min / scSemi {vals[(d, 'scsemi')]['hours']:.2f} h", + "source": "data/sec09_same_pairs.csv"} for d in done] + btxt = "" + if len(bud): + for d, g in bud.groupby("dataset"): + btxt += (f" Equal pair budget, {S9.NAME[d]} (n = 5, 10, 20, 40 pairs): scSemiProfiler L1 " + f"{g.scsemi_l1.min():.3f}–{g.scsemi_l1.max():.3f} and coverage {g.scsemi_cov.min():.2f}–" + f"{g.scsemi_cov.max():.2f} at every n; LoRA L1 {g.lora_l1.min():.3f}–{g.lora_l1.max():.3f}, coverage " + f"{g.lora_cov.min():.2f}–{g.lora_cov.max():.2f} (drawn on the 'Pairs needed' slide).") + numbers.append({"value": btxt.strip(), "source": "data/sec09_same_pairs_budget.csv"}) + pending = [S9.NAME[d] for d in ORDER if d not in done] + full = ("5-fold CV: for every fold, scSemiProfiler's representatives are exactly LoRA's training + inner-val pairs " + "(the other four folds; checked per fold), test = the fold's samples from their real bulk only. Pooled = one " + "scoring call per method over every usable sample, same donors and reference (sha-checked). scSemiProfiler = " + "upstream c2aea02, default settings, official output. GPU time per fold on one GB10: LoRA = fine-tune + " + "sampling 1,500 cells per test sample; scSemiProfiler = pretraining of every representative + one model per " + "test sample (receipts); data preparation and scoring not counted on either side. " + + ("Still running (server_1 / server_2): " + ", ".join(pending) + "." if pending else "") + + btxt + " Source: plans/paired_finetune_intradataset_20260927/scores//{pooled,scsemi_cv_20261002/pooled}/ " + "and scsemi/analysis/cv_budget_20261005/.") + txt = {"title": "Same training pairs: LoRA vs scSemiProfiler", "layout": "full", + "figures": [str(FIGDIR / "sec09_same_pairs.png")], "keywords": kw, + "footnote_short": ("5-fold CV; scSemiProfiler representatives = LoRA's training pairs. " + + (f"{', '.join(pending)}: running." if pending else "")), + "footnote": full, "numbers": numbers} + if len(txt["footnote_short"]) > 110: + raise SystemExit("short footnote too long") + out = {"section": "09-same-pairs", "scripts": [str(Path(__file__).resolve())], + "generated_from": "tools/sec09_same_pairs.py (rerun to refresh; do not edit by hand)", "slides": [txt]} + (OUTDATA / "sec09_same_pairs_slide_text.json").write_text(json.dumps(out, indent=1, ensure_ascii=False)) + print("\n".join(kw)) + for n in numbers: + print(n["value"]) + return 0 + + +if __name__ == "__main__": + sys.exit(main())