junidude14 commited on
Commit
dea2577
·
verified ·
1 Parent(s): 614e74a

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261002T002920Z-deck-extra-metrics-scsemi-prep/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec07_rank_sweep.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Backup slide (section 7, LoRA ablations) of the 2026-09-30 paper-summary deck: LoRA rank r = 4 / 16 / 64 at
3
+ n = 5, 20 and all training pairs (ImMicro, sepsis; donor-level 5-fold CV, pooled cross-fitted scoring).
4
+
5
+ CPU only. Reads plans/paired_finetune_intradataset_20260927/scores/<ds>/rankcal_20261001.json (written by
6
+ tools/aggregate_rankcal.py) and checks every plotted value against the pooled scoring calls it came from:
7
+ r = 16 scores/<ds>/pooled (sepsis: pooled_deg) arms lora_n5__raw, lora_n20__raw, real_lora__raw
8
+ r = 4, 64 scores/<ds>/lora_rank_20261001/pooled arms lora_r{4,64}_n5__raw, lora_r{4,64}_n20__raw, lora_r{4,64}__raw
9
+ Composition L1 / precision / coverage = summary.json headline; logFC r = mean of contrast.csv mean_cp10k r over
10
+ T, B, Monocyte, NK; top-50 DEG = headline deg_top50_sum. Per-donor L1 Wilcoxon vs r = 16 as aggregate_rankcal.py.
11
+ Each LoRA run's rank and checkpoint are checked in runs/<ds>/fold<k>/<arm>/RUN.json.
12
+
13
+ Outputs (deck folder; DECK_FIGDIR / DECK_OUTDATA override):
14
+ figures/sec07_rank_sweep.{png,pdf}, data/sec07_rank_sweep.csv, data/sec07_rank_sweep_slide_text.json
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import os
19
+
20
+ os.environ["CUDA_VISIBLE_DEVICES"] = "" # plotting only
21
+
22
+ import json
23
+ import re
24
+ import sys
25
+ from pathlib import Path
26
+
27
+ import numpy as np
28
+ import pandas as pd
29
+ from scipy.stats import wilcoxon
30
+
31
+ DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/"
32
+ "2026-09-30--paper-summary--r00")
33
+ sys.path.insert(0, str(DECK / "tools"))
34
+ import style # noqa: E402
35
+ import matplotlib.pyplot as plt # noqa: E402
36
+ from matplotlib.lines import Line2D # noqa: E402
37
+
38
+ PLAN = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/"
39
+ "paired_finetune_intradataset_20260927")
40
+ FINAL_CKPT = ("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/runs/"
41
+ "f01_6k_1x_seed20260627/checkpoint_epoch_016.pt")
42
+ FIGDIR = Path(os.environ.get("DECK_FIGDIR", str(DECK / "figures")))
43
+ OUTDATA = Path(os.environ.get("DECK_OUTDATA", str(DECK / "data")))
44
+ SCRIPT = DECK / "tools" / "sec07_rank_sweep.py"
45
+ DSETS = ["immicro", "ye2026_sepsis"]
46
+ NAME = {"immicro": "ImMicro", "ye2026_sepsis": "Sepsis"}
47
+ RANKS = (4, 16, 64)
48
+ NS = ("5", "20", "all")
49
+ RANK_EXP = "lora_rank_20261001"
50
+ TYPES = ["T cell", "B cell", "Monocyte", "NK cell"]
51
+ FS = style.FS
52
+ # r = 16 is the deck's LoRA (orange); 4 and 64 are lighter / darker shades of it, with their own markers
53
+ RCOL = {4: "#F2AE7B", 16: style.ARM["lora"], 64: "#6E2E00"}
54
+ RMK = {4: "v", 16: "o", 64: "s"}
55
+ PANELS = [("comp_l1", "Composition L1 ↓"), ("coverage", "Coverage ↑"), ("precision", "Precision ↑"),
56
+ ("logfc_r", "Disease logFC r ↑"), ("deg", "Top-50 DEG ↑")]
57
+ OFF_STORY = re.compile(r"refcal|reference[ -]calibrat|\bVAE\b|\bTPM\b|\bAIFI\b|\bAIDA\b", re.I)
58
+ KW_MAX, FOOT_MAX = 45, 110
59
+
60
+
61
+ def arm(r: int, n: str) -> str:
62
+ if r == 16:
63
+ return "real_lora__raw" if n == "all" else f"lora_n{n}__raw"
64
+ return f"lora_r{r}__raw" if n == "all" else f"lora_r{r}_n{n}__raw"
65
+
66
+
67
+ def call_dir(ds: str, r: int) -> Path:
68
+ S = PLAN / "scores" / ds
69
+ if r != 16:
70
+ return S / RANK_EXP / "pooled"
71
+ return S / "pooled_deg" if (S / "pooled_deg" / "summary.json").exists() else S / "pooled"
72
+
73
+
74
+ def load():
75
+ rows, pdl, runs = [], {}, []
76
+ for ds in DSETS:
77
+ js_path = PLAN / "scores" / ds / "rankcal_20261001.json"
78
+ js = json.loads(js_path.read_text())
79
+ for r in RANKS:
80
+ d = call_dir(ds, r)
81
+ s = json.loads((d / "summary.json").read_text())
82
+ con = pd.read_csv(d / "contrast.csv") if (d / "contrast.csv").exists() else None
83
+ per = pd.read_csv(d / "per_donor.csv")
84
+ for n in NS:
85
+ a = arm(r, n)
86
+ h, pj = s["headline"][a], js[a]["pooled"]
87
+ v = {"comp_l1": float(h["comp_l1"]), "coverage": float(h["coverage"]), "precision": float(h["precision"]),
88
+ "logfc_r": np.nan, "deg": np.nan}
89
+ if con is not None and s.get("contrast_definition", {}).get("enabled"):
90
+ c = con[(con.arm == a) & (con.statistic == "mean_cp10k") & con.celltype.isin(TYPES)]
91
+ assert set(c.celltype) == set(TYPES), (d, a)
92
+ v["logfc_r"] = float(c.r_generated.mean())
93
+ if h.get("deg_top50_sum") is not None:
94
+ v["deg"] = float(h["deg_top50_sum"])
95
+ # the aggregated JSON must equal the scoring call
96
+ for k, kj in (("comp_l1", "comp_l1"), ("coverage", "coverage"), ("precision", "precision"),
97
+ ("logfc_r", "logfc_r"), ("deg", "deg_top50_sum")):
98
+ x = pj.get(kj)
99
+ if x is None:
100
+ assert np.isnan(v[k]), (ds, a, k)
101
+ else:
102
+ assert abs(float(x) - v[k]) < 1e-9, (ds, a, k, x, v[k])
103
+ for k, val in v.items():
104
+ rows.append({"dataset": ds, "rank": r, "pairs": n, "arm": a, "metric": k, "value": val,
105
+ "source": str(d / ("contrast.csv" if k == "logfc_r" else "summary.json")),
106
+ "aggregate": str(js_path)})
107
+ pdl[(ds, r, n)] = per[per.arm == a].set_index("donor")["comp_l1"]
108
+ for k in range(5):
109
+ rp = PLAN / "runs" / ds / f"fold{k}" / a.removesuffix("__raw") / "RUN.json"
110
+ if not rp.exists():
111
+ continue
112
+ R = json.loads(rp.read_text())
113
+ assert R["source_checkpoint"] == FINAL_CKPT, rp
114
+ assert R["mode"] == "lora" and int(R["trainable"]["lora_rank"]) == r, (rp, R["trainable"].get("lora_rank"))
115
+ runs.append({"dataset": ds, "rank": r, "pairs": n, "fold": k, "n_train": len(R["train_rows"]),
116
+ "n_inner_val": len(R["inner_val_rows"]), "selected_step": R["selected_step"],
117
+ "n_trainable": R["trainable"]["n_trainable"], "source": str(rp)})
118
+ return pd.DataFrame(rows), pdl, pd.DataFrame(runs)
119
+
120
+
121
+ def wil(pdl, ds, r, n):
122
+ x, y = pdl[(ds, r, n)], pdl[(ds, 16, n)]
123
+ j = x.to_frame("a").join(y.to_frame("b"), how="inner")
124
+ d = j["a"] - j["b"]
125
+ return float(d.mean()), float(wilcoxon(j["a"], j["b"]).pvalue), len(j)
126
+
127
+
128
+ def fig(df, runs):
129
+ fig, axs = plt.subplots(2, len(PANELS), figsize=style.FULL,
130
+ gridspec_kw=dict(left=0.135, right=0.995, top=0.855, bottom=0.17, hspace=0.42,
131
+ wspace=0.42))
132
+ xs = np.arange(len(NS))
133
+ for i, ds in enumerate(DSETS):
134
+ for j, (mk, lab) in enumerate(PANELS):
135
+ ax = axs[i, j]
136
+ sub = df[(df.dataset == ds) & (df.metric == mk)]
137
+ if sub.value.isna().all():
138
+ for sp in ax.spines.values():
139
+ sp.set_visible(False)
140
+ ax.set_xticks([])
141
+ ax.set_yticks([])
142
+ if j == len(PANELS) - 1: # centred over the empty disease columns, in figure coordinates
143
+ p0, p1 = axs[i, j - 1].get_position(), ax.get_position()
144
+ fig.text((p0.x0 + p1.x1) / 2, (p1.y0 + p1.y1) / 2, "healthy cohort: no contrast", ha="center",
145
+ va="center", fontsize=FS - 2, color="#595959", style="italic")
146
+ else:
147
+ for r in RANKS:
148
+ v = [float(sub[(sub["rank"] == r) & (sub.pairs == n)].value.iloc[0]) for n in NS]
149
+ ax.plot(xs, v, color=RCOL[r], lw=2.2 if r == 16 else 1.8, marker=RMK[r], ms=7,
150
+ mec=style.INK, mew=0.6, zorder=4 if r == 16 else 3)
151
+ ax.set_xticks(xs)
152
+ ax.set_xticklabels(NS)
153
+ ax.set_xlim(-0.35, len(NS) - 0.65)
154
+ ax.tick_params(axis="both", labelsize=FS - 3)
155
+ ax.yaxis.set_major_locator(plt.MaxNLocator(nbins=4))
156
+ if mk == "deg":
157
+ ax.set_ylim(0, max(sub.value) * 1.15)
158
+ if i == 0:
159
+ ax.set_title(lab, fontsize=FS - 1, pad=8)
160
+ n_d = int(json.loads((call_dir(ds, 16) / "summary.json").read_text())["n_donors"])
161
+ y = (axs[i, 0].get_position().y0 + axs[i, 0].get_position().y1) / 2
162
+ fig.text(0.005, y + 0.02, NAME[ds], fontsize=FS + 1, fontweight="bold", va="bottom", ha="left")
163
+ fig.text(0.005, y + 0.01, f"{n_d} donors", fontsize=FS - 2, va="top", ha="left", color="#4D4D4D")
164
+ iv = sorted(set(runs.n_inner_val))
165
+ ivt = f"{iv[0]}" if len(iv) == 1 else f"{iv[0]}–{iv[-1]}"
166
+ x0, x1 = axs[1, 0].get_position().x0, axs[1, -1].get_position().x1
167
+ fig.text((x0 + x1) / 2, 0.01, f"LoRA training pairs (5-fold CV; each run +{ivt} inner-val pairs for early stopping)",
168
+ ha="center", va="bottom", fontsize=FS - 1)
169
+ handles = [Line2D([0], [0], color=RCOL[r], lw=2.2 if r == 16 else 1.8, marker=RMK[r], ms=7, mec=style.INK,
170
+ mew=0.6, label=f"LoRA rank r = {r}" + (" (used in the deck)" if r == 16 else ""))
171
+ for r in RANKS]
172
+ fig.legend(handles=handles, loc="upper center", bbox_to_anchor=(0.55, 1.0), ncol=3, frameon=False,
173
+ fontsize=FS - 2, handlelength=2.4, columnspacing=2.0, borderaxespad=0.0)
174
+ style.save(fig, "sec07_rank_sweep", FIGDIR)
175
+ return ivt
176
+
177
+
178
+ def words(s):
179
+ return sum(1 for t in s.split() if re.search(r"[A-Za-z0-9]", t))
180
+
181
+
182
+ def check(s, what, maxlen=None, maxwords=None):
183
+ if re.search(r"[가-힣]", s) or OFF_STORY.search(s):
184
+ raise ValueError(f"Korean / off-story text in {what}: {s!r}")
185
+ if maxlen and len(s) > maxlen:
186
+ raise ValueError(f"{what} over {maxlen} characters ({len(s)}): {s!r}")
187
+ if maxwords and words(s) > maxwords:
188
+ raise ValueError(f"{what} over {maxwords} words: {s!r}")
189
+ return s
190
+
191
+
192
+ def main():
193
+ FIGDIR.mkdir(parents=True, exist_ok=True)
194
+ OUTDATA.mkdir(parents=True, exist_ok=True)
195
+ df, pdl, runs = load()
196
+ ivt = fig(df, runs)
197
+ df.to_csv(OUTDATA / "sec07_rank_sweep.csv", index=False, float_format="%.6g")
198
+ runs.to_csv(OUTDATA / "sec07_rank_sweep_runs.csv", index=False)
199
+
200
+ def v(ds, r, n, mk):
201
+ return float(df[(df.dataset == ds) & (df["rank"] == r) & (df.pairs == n) & (df.metric == mk)].value.iloc[0])
202
+
203
+ im, se = "immicro", "ye2026_sepsis"
204
+ c16, c64 = v(im, 16, "all", "coverage"), v(im, 64, "all", "coverage")
205
+ l16, l4 = v(im, 16, "all", "comp_l1"), v(im, 4, "all", "comp_l1")
206
+ p16, p64 = v(im, 16, "all", "precision"), v(im, 64, "all", "precision")
207
+ kw = [f"ImMicro r64, all pairs: coverage {c16:.2f} → {c64:.2f}",
208
+ f"ImMicro r4, all pairs: L1 {l16:.3f} → {l4:.3f}",
209
+ f"Kept r16; r64 precision {p16:.2f} → {p64:.2f}"]
210
+ for k in kw:
211
+ check(k, "keyword", KW_MAX, 7)
212
+ r16, r64, r4 = (v(se, r, "all", "logfc_r") for r in (16, 64, 4))
213
+ d16, d64, d4 = (int(v(se, r, "all", "deg")) for r in (16, 64, 4))
214
+ fs = check(f"Sepsis, all pairs: r64 logFC r {r16:.2f} → {r64:.2f}, DEG {d16} → {d64}; "
215
+ f"r4 {r4:.2f}, DEG {d4}. Pooled 5-fold scores.", "footnote_short", FOOT_MAX)
216
+ # footnote_full: every value and the per-donor tests
217
+ parts = []
218
+ for ds in DSETS:
219
+ for n in NS:
220
+ cells = []
221
+ for r in RANKS:
222
+ t = (f"r{r}: L1 {v(ds, r, n, 'comp_l1'):.3f}, P/C {v(ds, r, n, 'precision'):.3f} / "
223
+ f"{v(ds, r, n, 'coverage'):.3f}")
224
+ if not np.isnan(v(ds, r, n, "logfc_r")):
225
+ t += f", logFC r {v(ds, r, n, 'logfc_r'):.2f}, DEG {int(v(ds, r, n, 'deg'))}"
226
+ if r != 16:
227
+ m, p, nn = wil(pdl, ds, r, n)
228
+ t += f" (L1 vs r16 {m:+.3f}, Wilcoxon p {p:.2g}, {nn} donors)"
229
+ cells.append(t)
230
+ parts.append(f"{NAME[ds]} n = {n}: " + "; ".join(cells))
231
+ ntr = runs.groupby(["dataset", "rank"]).n_trainable.first()
232
+ full = (f"LoRA fine-tune of the final model (f01 6k·1x·E16) with rank r and alpha = r, same recipe as the deck's "
233
+ f"r = 16 runs (early stop on {ivt} inner-val pairs, 20k step cap); n = training pairs, nested subsets; "
234
+ f"donor-level 5-fold CV, each pair scored once by its fold model (pooled call). Trainable parameters "
235
+ + ", ".join(f"r{r} {ntr.loc[(im, r)]:,}" for r in RANKS) + ". "
236
+ + " | ".join(parts)
237
+ + ". r64 vs r16 brings small gains in coverage and disease signal but slightly lower precision and no "
238
+ "composition change; r4 is worse with many pairs; at n = 5 the ranks are mixed. r = 16 is kept. "
239
+ "Scores: scores/<cohort>/lora_rank_20261001/pooled (r4, r64) and scores/<cohort>/pooled{,_deg} (r16); "
240
+ "table: scores/<cohort>/rankcal_20261001.md.")
241
+ check(full, "footnote")
242
+ nums = [{"value": f"ImMicro all pairs coverage r16 {c16:.3f} -> r64 {c64:.3f}; precision {p16:.3f} -> {p64:.3f}; "
243
+ f"L1 r16 {l16:.3f}, r4 {l4:.3f} (Wilcoxon p {wil(pdl, im, 4, 'all')[1]:.2g})",
244
+ "source": f"{call_dir(im, 16)}/summary.json; {call_dir(im, 4)}/summary.json, per_donor.csv"},
245
+ {"value": f"Sepsis all pairs logFC r r16 {r16:.3f}, r64 {r64:.3f}, r4 {r4:.3f}; DEG {d16} / {d64} / {d4}",
246
+ "source": f"{call_dir(se, 16)}/summary.json, contrast.csv; {call_dir(se, 4)}/summary.json, contrast.csv"},
247
+ {"value": "trainable parameters: " + ", ".join(f"r{r} {ntr.loc[(im, r)]}" for r in RANKS),
248
+ "source": "runs/<cohort>/fold<k>/<arm>/RUN.json (trainable.n_trainable)"}]
249
+ spec = {"section": "07-rank", "slides": [{
250
+ "title": "LoRA rank: r = 4, 16, 64", "layout": "full", "figures": [str(FIGDIR / "sec07_rank_sweep.png")],
251
+ "keywords": kw, "footnote": full, "footnote_short": fs, "numbers": nums}],
252
+ "scripts": [str(SCRIPT)], "generated_from": "tools/sec07_rank_sweep.py (rerun to refresh; do not edit by hand)"}
253
+ (OUTDATA / "sec07_rank_sweep_slide_text.json").write_text(json.dumps(spec, indent=1, ensure_ascii=False))
254
+ for p in (OUTDATA / "sec07_rank_sweep_slide_text.json", OUTDATA / "sec07_rank_sweep.csv"):
255
+ m = OFF_STORY.search(p.read_text(encoding="utf-8"))
256
+ if m:
257
+ raise ValueError(f"{p}: off-story text {m.group(0)!r}")
258
+ for k in kw:
259
+ print(" *", k, f"({words(k)} words, {len(k)} chars)")
260
+ print(" footnote_short:", fs, f"({len(fs)} chars)")
261
+ print(" footnote:", full)
262
+ return 0
263
+
264
+
265
+ if __name__ == "__main__":
266
+ sys.exit(main())
paper-releases/pbisc-diffusion/updates/20261002T002920Z-deck-extra-metrics-scsemi-prep/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec08_pairs_needed.py ADDED
@@ -0,0 +1,856 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Section 8 of the 2026-09-30 paper-summary deck: how many bulk-sc pairs LoRA needs (learning curve).
2
+
3
+ CPU only. Reads the pooled 5-fold scoring calls of the paired fine-tune plan and the per-fold RUN.json files,
4
+ then draws two slide figures:
5
+ figures/sec08_pairs_realism.{png,pdf} FULL: composition L1, coverage, selected step x (ImMicro, sepsis)
6
+ figures/sec08_pairs_signal.{png,pdf} TALL: ImMicro NK fraction r, sepsis logFC r, sepsis top-50 DEG
7
+ Every plotted/quoted number is read from a score file here and written with its source to data/sec08_*.csv.
8
+ Model: final f01 6k 1x epoch-16 checkpoint + LoRA (checked against every RUN.json).
9
+ x axis: "0" = no LoRA training. Two zero-shot points sit there, side by side: the pretrained model fed the real bulk
10
+ as measured (score arm zs__raw; uses no pair) and fed gene-wise calibrated bulk (zs__cal). Calibration (back as a
11
+ comparator, user decision 2026-10-01): alpha_g = mean CPM(pseudobulk_g) / mean CPM(bulk_g) over ALL paired training
12
+ donors of the fold (train + inner-val; tools/prepare_dataset.py `fit = fold != f`), applied as bulk CPM x alpha, then
13
+ renormalised. So zs__cal is not pair-free: its alpha uses the same 85-86 / 65-66 donors that LoRA "all" trains and
14
+ early-stops on. LoRA n = training pairs, and every LoRA run also early-stops on 7-8 paired inner-val donors
15
+ (RUN.json inner_val_rows). The LoRA arms are conditioned on the real bulk (*__raw) and share one real-bulk broadcast.
16
+ Cap-limited = ran to max_steps before the patience window closed; its late inner-val loss drop is read from
17
+ history.json.
18
+ When a zero-shot point lies far outside every other value of a panel (BREAK_RATIO), that panel gets a y-axis
19
+ break with a short segment at the same data scale, instead of squeezing the LoRA curve.
20
+
21
+ Equal-budget calibration (optional, drawn only if present): zero-shot + calibration with alpha fitted on exactly the
22
+ pairs a lora_n{5,10,20,40} run saw (n training + its inner-val pairs), per fold. The scores folder is scanned for
23
+ summary.json files (scores/<dataset>/**/summary.json, outside arms/) whose arm names match CAL_N_RE (contain "cal"
24
+ and an n<digits> token) and carry no fine-tune tag (FT_TAGS). An arm is drawn only from a scoring call over the
25
+ same donors as the pooled call (same reference cells, so metrics are comparable). If found, it is drawn as a second
26
+ line across n, ending at "all" with zs__cal (alpha from the same pairs LoRA "all" saw). If none is found, only the
27
+ two x = 0 points are drawn and a note is printed.
28
+
29
+ scSemiProfiler line (optional, drawn only if present; added 2026-10-02): scSemiProfiler trained with n pairs as
30
+ representatives (arms scsemi_n{5,10,20,40}__raw in scores/<dataset>/scsemi_budget_20261002/pooled*/) and with all
31
+ training pairs ("all" = arm scsemi__raw of the 5-fold CV run in scores/<dataset>/scsemi_cv_20261002/pooled*/), looked up
32
+ by tools/scsemi_results.py and drawn only for calls over the same donors and reference cells as the pooled call. If
33
+ nothing is found, a note is printed and the figures are unchanged. DECK_FIGDIR / DECK_OUTDATA redirect the outputs and
34
+ DECK_SCSEMI_PLAN_ROOT the scSemiProfiler lookup (synthetic presence test).
35
+ """
36
+ import os
37
+ import json
38
+ import re
39
+ import sys
40
+ from pathlib import Path
41
+
42
+ import numpy as np
43
+ import pandas as pd
44
+ from scipy.stats import wilcoxon
45
+
46
+ DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/"
47
+ "2026-09-30--paper-summary--r00")
48
+ sys.path.insert(0, str(DECK / "tools"))
49
+ import style # noqa: E402
50
+ import scsemi_results as SR # noqa: E402
51
+ import matplotlib.pyplot as plt # noqa: E402
52
+ from matplotlib.lines import Line2D # noqa: E402
53
+
54
+ PLAN = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/"
55
+ "paired_finetune_intradataset_20260927")
56
+ FINAL_CKPT = ("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/runs/"
57
+ "f01_6k_1x_seed20260627/checkpoint_epoch_016.pt")
58
+ FIGDIR = Path(os.environ.get("DECK_FIGDIR", str(DECK / "figures")))
59
+ DATADIR = Path(os.environ.get("DECK_OUTDATA", str(DECK / "data")))
60
+ FIGDIR.mkdir(exist_ok=True)
61
+ DATADIR.mkdir(exist_ok=True)
62
+
63
+ DSETS = ["immicro", "ye2026_sepsis"]
64
+ DS_LABEL = {"immicro": "ImMicro", "ye2026_sepsis": "Sepsis"}
65
+ LC_N = [5, 10, 20, 40]
66
+ LORA_ARMS = [f"lora_n{n}__raw" for n in LC_N] + ["real_lora__raw"]
67
+ RUN_ARMS = [f"lora_n{n}" for n in LC_N] + ["real_lora"]
68
+ ZS = "zs__raw" # zero-shot on the real bulk as measured: 0 pairs
69
+ ZS_CAL = "zs__cal" # zero-shot + calibration, alpha from all fold pairs (train + inner-val)
70
+ X_LAB = ["0", "5", "10", "20", "40", "all"]
71
+ KEY_LAB = ["zero_shot", "5", "10", "20", "40", "all"] # the same points, as keys in sec08_slide_numbers.csv
72
+ X_POS = [0.0, 1.3, 2.3, 3.3, 4.3, 5.3] # small gap after the zero-shot points (no fine-tuning)
73
+ DX0 = 0.2 # raw zero-shot left of x = 0, calibrated right of it
74
+ X_RAW, X_CAL = X_POS[0] - DX0, X_POS[0] + DX0
75
+ XLIM = (-0.5, X_POS[-1] + 0.5) # same x range as the selected-step panel
76
+ COL_RAW, COL_CAL = style.ARM["zs_raw"], style.ARM["zs_cal"] # archived pair: pale = raw, #0072B2 = calibrated
77
+ RAW_EDGE = "#5E8FB5" # edge of the pale raw marker (same as sec05 RAW_EDGE)
78
+ # equal-budget calibration arms: "cal" and an n<digits> token, and no fine-tune tag
79
+ CAL_N_RE = re.compile(r"(?:^|[^a-z0-9])n(\d+)(?![0-9])", re.I)
80
+ FT_TAGS = ("lora", "real", "pseudo", "full", "condenc", "multik", "recipe")
81
+ BREAK_RATIO = 1.5 # y-axis break when the zero-shot point sits > 1.5 spans of the other values beyond them
82
+ CELLTYPES = ["T cell", "B cell", "Monocyte", "NK cell"]
83
+ DEG_TYPES = ["T cell", "B cell", "Monocyte", "NK cell", "DC"]
84
+ RAW_ARMS = LORA_ARMS + ["zs__raw", "real_full__raw", "pseudo_full__raw"] # all conditioned on raw real bulk
85
+
86
+ REF = { # reference-line styles; pseudo/broadcast copied from sec09 REFSTYLE so the deck is consistent
87
+ "pseudo": dict(ls=(0, (4, 2)), color=style.ARM["pseudo"], lw=1.6, label="Zero-shot from sc pseudobulk"),
88
+ "broadcast": dict(ls=(0, (1, 1.2)), color=style.ARM["broadcast"], lw=2.4, label="Real-bulk broadcast"),
89
+ "null": dict(ls=(0, (6, 2, 1.5, 2)), color=style.GREY, lw=1.4, label="Cohort-mean null"),
90
+ }
91
+ LEG_ZS = "Zero-shot, real bulk"
92
+ LEG_CAL = "Zero-shot + calibration (α from all fold pairs)"
93
+ LEG_CAL_N = "ZS + cal., α from the same pairs" # short label: the legend line above spells it out
94
+ COL_SC = style.ARM["scsemi"]
95
+ LEG_SC = "scSemiProfiler, n pairs as representatives"
96
+
97
+
98
+ def xlabel(st):
99
+ """x-axis label; the inner-val range is read from the RUN.json files."""
100
+ return f"LoRA training pairs (each run +{rng_txt(st.n_inner_val)} inner-val pairs for early stopping)"
101
+
102
+
103
+ def close(a, b, tol=1e-6):
104
+ return abs(float(a) - float(b)) <= tol
105
+
106
+
107
+ class Call:
108
+ """One pooled score_ft.py scoring call."""
109
+
110
+ def __init__(self, path: Path):
111
+ self.path = path
112
+ self.summary = json.loads((path / "summary.json").read_text())
113
+ self.contrast = pd.read_csv(path / "contrast.csv") if (path / "contrast.csv").exists() else None
114
+ self.per_donor = pd.read_csv(path / "per_donor.csv")
115
+ self.src_summary = str(path / "summary.json")
116
+ self.src_contrast = str(path / "contrast.csv")
117
+ self.src_per_donor = str(path / "per_donor.csv")
118
+
119
+ def head(self, arm, key):
120
+ return float(self.summary["headline"][arm][key])
121
+
122
+ def contrast_r(self, arm, col="r_generated"):
123
+ c = self.contrast
124
+ c = c[(c.arm == arm) & (c.statistic == "mean_cp10k") & (c.celltype.isin(CELLTYPES))]
125
+ assert set(c.celltype) == set(CELLTYPES), (self.path, arm)
126
+ return float(c[col].mean())
127
+
128
+ def deg(self, arm, col="top50_overlap"):
129
+ d = self.contrast
130
+ d = d[(d.arm == arm) & (d.statistic == "welch_top50_deg")]
131
+ assert len(d) == 5, (self.path, arm, len(d)) # T/B/Mono/NK/DC
132
+ return float(d[col].sum())
133
+
134
+ def deg_type(self, arm, ct, col="top50_overlap"):
135
+ d = self.contrast
136
+ d = d[(d.arm == arm) & (d.statistic == "welch_top50_deg") & (d.celltype == ct)]
137
+ assert len(d) == 1, (self.path, arm, ct, len(d))
138
+ return float(d[col].iloc[0])
139
+
140
+ def frac_r(self, arm, ct):
141
+ d = self.per_donor[self.per_donor.arm == arm]
142
+ return float(np.corrcoef(d[f"gen_{ct}"].astype(float), d[f"obs_{ct}"].astype(float))[0, 1])
143
+
144
+
145
+ def load():
146
+ calls = {ds: Call(PLAN / "scores" / ds / "pooled") for ds in DSETS}
147
+ deg_call = Call(PLAN / "scores" / "ye2026_sepsis" / "pooled_deg")
148
+ for ds, c in calls.items():
149
+ for a in LORA_ARMS + [ZS, ZS_CAL, "zs__pseudo"]:
150
+ assert a in c.summary["arms"], (ds, a)
151
+ assert c.summary["per_arm"][a].get("receipt_verified", True) is not False, (ds, a)
152
+ # headline composition L1 equals the donor mean of per_donor.csv
153
+ assert close(c.per_donor.loc[c.per_donor.arm == a, "comp_l1"].mean(), c.head(a, "comp_l1"), 1e-9), a
154
+ # headline contrast means equal the per-type mean of contrast.csv
155
+ se = calls["ye2026_sepsis"]
156
+ for a in LORA_ARMS + [ZS, ZS_CAL, "zs__pseudo"]:
157
+ assert close(se.contrast_r(a), se.head(a, "contrast_mean_cp10k_r_gen"), 1e-9), a
158
+ assert close(deg_call.deg(a), deg_call.head(a, "deg_top50_sum"), 1e-9), a
159
+ # broadcast is the same for every arm conditioned on raw real bulk
160
+ bc = {a: se.contrast_r(a, "r_broadcast") for a in RAW_ARMS}
161
+ assert max(bc.values()) - min(bc.values()) < 1e-12, bc
162
+ bcd = {a: deg_call.deg(a, "top50_overlap_broadcast") for a in RAW_ARMS}
163
+ assert len(set(bcd.values())) == 1, bcd
164
+ assert close(bcd["real_lora__raw"], deg_call.head("real_lora__raw", "deg_top50_sum_broadcast"), 1e-9)
165
+ # non-DEG metrics agree between the two sepsis scoring calls (k-NN ties allow 1e-3)
166
+ for a in LORA_ARMS + [ZS, ZS_CAL]:
167
+ for k in ("comp_l1", "coverage"):
168
+ assert abs(se.head(a, k) - deg_call.head(a, k)) <= 1e-3, (a, k)
169
+ return calls, deg_call
170
+
171
+
172
+ def find_cal_budget(calls, deg_call):
173
+ """Scan the scores folder for equal-budget calibration arms (see module docstring).
174
+
175
+ Returns (budget, log): budget[ds][n] = dict(arm, calls=[Call, ...]) for drawable arms (pooled call first, then
176
+ other calls over the same donors; the sepsis DEG call first for DEG); log = one dict per matching arm found."""
177
+ budget, log = {ds: {} for ds in DSETS}, []
178
+ cache = {c.path: c for c in list(calls.values()) + [deg_call]}
179
+ for ds in DSETS:
180
+ root = PLAN / "scores" / ds
181
+ pooled = calls[ds]
182
+ donors = set(pooled.per_donor.donor)
183
+ cands = {}
184
+ for sp in sorted(root.rglob("summary.json")):
185
+ rel = sp.relative_to(root)
186
+ if "arms" in rel.parts:
187
+ continue
188
+ try:
189
+ arms = json.loads(sp.read_text()).get("arms") or []
190
+ except (OSError, ValueError):
191
+ continue
192
+ for a in arms:
193
+ m = CAL_N_RE.search(a)
194
+ if "cal" not in a.lower() or m is None or any(t in a.lower() for t in FT_TAGS):
195
+ continue
196
+ n = int(m.group(1))
197
+ if sp.parent not in cache:
198
+ try:
199
+ cache[sp.parent] = Call(sp.parent)
200
+ except (OSError, ValueError) as e:
201
+ log.append(dict(dataset=ds, call=str(rel.parent), arm=a, n=n, drawn=False,
202
+ note=f"not drawn: cannot read the call ({e.__class__.__name__})"))
203
+ continue
204
+ call = cache[sp.parent]
205
+ same = set(call.per_donor.loc[call.per_donor.arm == a, "donor"]) == donors
206
+ ok = same and n in LC_N
207
+ why = ("drawn" if ok else "not drawn: " + ("n not in " + str(LC_N) if same else
208
+ "call does not score the pooled donor set"))
209
+ log.append(dict(dataset=ds, call=str(rel.parent), arm=a, n=n, drawn=ok, note=why))
210
+ if ok:
211
+ cands.setdefault(n, []).append((a, call))
212
+ for n, lst in cands.items():
213
+ names = sorted({a for a, _ in lst})
214
+ if len(names) > 1:
215
+ pref = sorted({a for a, c in lst if c is pooled})
216
+ if len(pref) != 1:
217
+ sys.exit(f"{ds}: several equal-budget calibration arms for n = {n}: {names}; pick one")
218
+ names = pref
219
+ arm = names[0]
220
+ cl = [c for a, c in lst if a == arm]
221
+ cl.sort(key=lambda c: (c is not pooled, c is not deg_call, str(c.path)))
222
+ for c in cl: # a call other than the pooled one must reproduce shared arms (k-NN ties allow 1e-3)
223
+ if c is pooled:
224
+ continue
225
+ for shared in (ZS_CAL, "real_lora__raw"):
226
+ if shared in c.summary["arms"]:
227
+ for k in ("comp_l1", "coverage"):
228
+ assert abs(c.head(shared, k) - pooled.head(shared, k)) <= 1e-3, (c.path, shared, k)
229
+ budget[ds][n] = dict(arm=arm, calls=cl)
230
+ return budget, log
231
+
232
+
233
+ def find_scsemi(calls):
234
+ """scSemiProfiler at n = 5..40 (equal-budget arms) and "all" (5-fold CV arm), see module docstring.
235
+
236
+ Returns (scs, log): scs[ds][pairs label] = dict(arm, calls=[Call, ...]) for accepted calls; log = one dict per
237
+ arm found (accepted or not)."""
238
+ scs, log = {ds: {} for ds in DSETS}, []
239
+ for ds in DSETS:
240
+ ref = calls[ds].summary
241
+ found = [(str(n), a, d) for n, lst in sorted(SR.budget_calls(ds).items()) for a, d in lst]
242
+ found += [("all", SR.CV_ARM, d) for d in SR.cv_calls(ds)]
243
+ for lab, a, d in found:
244
+ try:
245
+ c = Call(d)
246
+ except (OSError, ValueError) as e:
247
+ log.append(dict(dataset=ds, call=str(d), arm=a, pairs=lab, drawn=False,
248
+ note=f"not drawn: cannot read the call ({e.__class__.__name__})"))
249
+ continue
250
+ why = SR.accept(c.summary, ref, a)
251
+ if lab not in X_LAB[1:]:
252
+ why.append(f"n {lab} not in {X_LAB[1:]}")
253
+ ent = scs[ds].get(lab)
254
+ if ent is not None and ent["arm"] != a:
255
+ why.append(f"a different arm ({ent['arm']}) already gives n = {lab}")
256
+ log.append(dict(dataset=ds, call=str(d), arm=a, pairs=lab, drawn=not why,
257
+ note="drawn" if not why else "not drawn: " + "; ".join(why)))
258
+ if not why:
259
+ scs[ds].setdefault(lab, dict(arm=a, calls=[]))["calls"].append(c)
260
+ return scs, log
261
+
262
+
263
+ def scsemi_series(scs, ds, getter):
264
+ """[(pairs label, value, source)] of the scSemiProfiler line for one panel ([] when nothing is found)."""
265
+ out = []
266
+ for lab in X_LAB[1:]:
267
+ if lab in scs[ds]:
268
+ v, c = budget_value(scs[ds][lab], getter)
269
+ if v is not None:
270
+ out.append((lab, v, f"{c.path} arm {scs[ds][lab]['arm']}"))
271
+ return out
272
+
273
+
274
+ def budget_value(entry, getter):
275
+ """First call of a budget entry that provides the metric (None if no call does)."""
276
+ for c in entry["calls"]:
277
+ try:
278
+ return getter(c, entry["arm"]), c
279
+ except (AssertionError, KeyError, TypeError, AttributeError):
280
+ continue
281
+ return None, None
282
+
283
+
284
+ def load_steps():
285
+ rows = []
286
+ for ds in DSETS:
287
+ for k in range(5):
288
+ for arm in RUN_ARMS:
289
+ p = PLAN / "runs" / ds / f"fold{k}" / arm / "RUN.json"
290
+ r = json.loads(p.read_text())
291
+ assert r["source_checkpoint"] == FINAL_CKPT, (p, r["source_checkpoint"])
292
+ assert r["mode"] == "lora", p
293
+ assert r["inner_val_rows"], p # every LoRA run early-stops on paired inner-val donors
294
+ hist = json.loads((p.parent / "history.json").read_text())
295
+ h = {int(e["step"]): float(e["inner_val_loss"]) for e in hist}
296
+ # cap-limited = ran to max_steps without the patience window closing
297
+ cap_limited = (r["steps_run"] >= r["max_steps"]
298
+ and r["steps_run"] - r["selected_step"] < r["patience"] * r["eval_every"])
299
+ last = max(h)
300
+ win = r["patience"] * r["eval_every"] # last patience window (2,000 steps)
301
+ drop_total = h[0] - h[last]
302
+ drop_last = h[last - win] - h[last]
303
+ rows.append({"dataset": ds, "fold": k, "arm": arm, "n_train": len(r["train_rows"]),
304
+ "n_inner_val": len(r["inner_val_rows"]), "selected_step": r["selected_step"],
305
+ "max_steps": r["max_steps"], "steps_run": r["steps_run"],
306
+ "patience_steps": win, "cap_limited": bool(cap_limited),
307
+ "val_loss_step0": h[0], "val_loss_last": h[last],
308
+ "val_loss_last_window_drop_frac": drop_last / drop_total,
309
+ "wall_seconds": r.get("wall_seconds"), "source": str(p),
310
+ "history": str(p.parent / "history.json")})
311
+ st = pd.DataFrame(rows)
312
+ # nested subsets: n_train equals the arm size for lora_n*
313
+ for n in LC_N:
314
+ assert (st[st.arm == f"lora_n{n}"].n_train == n).all(), n
315
+ return st
316
+
317
+
318
+ def load_fold_sizes():
319
+ """Test donors per fold (PREPARE.json); their sum must equal the donors in the pooled scoring call.
320
+ alpha = paired donors the zs__cal alpha is fitted on per fold (train + inner-val)."""
321
+ out = {}
322
+ for ds in DSETS:
323
+ p = PLAN / "data" / ds / "PREPARE.json"
324
+ fs = json.loads(p.read_text())["fold_sizes"]
325
+ out[ds] = dict(test=[int(v["test"]) for v in fs.values()],
326
+ alpha=[int(v["train"]) + int(v["inner_val"]) for v in fs.values()], source=str(p))
327
+ return out
328
+
329
+
330
+ def load_fewshot():
331
+ """Few-pair call (5 draws): zero-shot + calibration with alpha from the same 5 pairs vs LoRA on those 5 pairs
332
+ (fixed 3k steps, no inner-val). Its own donor set, so it is only quoted in the notes, never drawn."""
333
+ out = {}
334
+ for ds in DSETS:
335
+ p = PLAN / "scores" / ds / "fewshot_n5" / "aggregate.json"
336
+ a = json.loads(p.read_text())["arms"]
337
+ out[ds] = dict(zs_cal=float(a["zs_cal"]["coverage"][0]), lora5=float(a["lora5"]["coverage"][0]),
338
+ source=str(p))
339
+ return out
340
+
341
+
342
+ def rng_txt(v):
343
+ v = sorted(int(x) for x in v)
344
+ return f"{v[0]}" if v[0] == v[-1] else f"{v[0]}–{v[-1]}"
345
+
346
+
347
+ def break_axis(ax, v0, lo, hi, x_txt=X_RAW):
348
+ """Shrink ax to lo..hi and add a short segment above it that shows v0 at the same data scale."""
349
+ p = ax.get_position()
350
+ h_top, gap = 0.22 * p.height, 0.08 * p.height
351
+ h_main = p.height - h_top - gap
352
+ ax.set_position([p.x0, p.y0, p.width, h_main])
353
+ ax.set_ylim(lo, hi)
354
+ half = (hi - lo) * h_top / h_main / 2
355
+ top = ax.figure.add_axes([p.x0, p.y0 + h_main + gap, p.width, h_top], sharex=ax)
356
+ top.set_ylim(v0 - half, v0 + half)
357
+ # one tick in the short segment: the nearest value on the main axis' tick grid that fits inside it
358
+ step = float(np.diff(ax.get_yticks()[:2])[0]) / 2
359
+ tick = round(round(v0 / step) * step, 10)
360
+ top.set_yticks([tick] if abs(tick - v0) < half else [])
361
+ if not len(top.get_yticks()): # no grid value fits: print the value next to the point instead
362
+ top.text(x_txt + 0.3, v0, f"{v0:.2f}", va="center", ha="left", fontsize=12)
363
+ top.spines["bottom"].set_visible(False)
364
+ top.tick_params(axis="x", bottom=False, labelbottom=False)
365
+ mk = dict(marker=[(-1, -0.5), (1, 0.5)], markersize=10, ls="none", color=style.INK, mec=style.INK, mew=1.2,
366
+ clip_on=False)
367
+ top.plot([0], [0], transform=top.transAxes, **mk)
368
+ ax.plot([0], [1], transform=ax.transAxes, **mk)
369
+ return top
370
+
371
+
372
+ def curve(ax, z0, vl, refs, rows, panel, ds, srcl, ylim0=None, vb=None, vs=None):
373
+ """Zero-shot points at x = 0 (z0: [(series, value, source)] for raw and calibrated), LoRA curve at 5..all,
374
+ optional equal-budget calibration line (vb: [(pairs label, value, source)]), reference lines.
375
+ Returns the axis that carries the panel title."""
376
+ vb = vb or []
377
+ vs = vs or [] # scSemiProfiler line (n = 5..all)
378
+ lo, hi = min(vl), max(vl)
379
+ for _, val, _ in list(refs) + [(None, v, None) for _, v, _ in vb + vs]:
380
+ lo, hi = min(lo, val), max(hi, val)
381
+ span = hi - lo
382
+ # a zero-shot point goes to the break segment when it sits > BREAK_RATIO spans beyond everything else
383
+ out = {ser for ser, v, _ in z0
384
+ if ylim0 is None and span > 0 and (v - hi > BREAK_RATIO * span or lo - v > BREAK_RATIO * span)}
385
+ for ser, v, _ in z0:
386
+ if ser in out:
387
+ assert v > hi, (panel, ds, ser, "axis break below the curve is not implemented")
388
+ else:
389
+ lo, hi = min(lo, v), max(hi, v)
390
+ broken = bool(out)
391
+ assert len(out) <= 1, (panel, ds, out, "only one zero-shot point fits in the break segment")
392
+ pad = (hi - lo) * 0.15
393
+ axes = [ax]
394
+ xz = {"zero_shot": X_RAW, "zs_cal": X_CAL}
395
+ if broken:
396
+ (ser_b, v_b, _), = [z for z in z0 if z[0] in out]
397
+ top = break_axis(ax, v_b, lo - pad, hi + pad, xz[ser_b])
398
+ axes.append(top)
399
+ else:
400
+ ax.set_ylim(ylim0 if ylim0 is not None else lo - pad, hi + pad)
401
+ for ser, v, src in z0:
402
+ a = axes[-1] if ser in out else ax
403
+ if ser == "zero_shot":
404
+ a.scatter([X_RAW], [v], s=70, color=COL_RAW, edgecolor=RAW_EDGE, lw=1.0, zorder=5, clip_on=False)
405
+ else:
406
+ a.scatter([X_CAL], [v], s=70, color=COL_CAL, edgecolor=style.INK, lw=0.6, zorder=5, clip_on=False)
407
+ rows.append(dict(panel=panel, dataset=ds, series=ser, pairs=X_LAB[0], value=v, source=src,
408
+ y_axis_break=bool(broken)))
409
+ if vb:
410
+ xb = [X_POS[X_LAB.index(lab)] for lab, _, _ in vb]
411
+ ax.plot(xb, [v for _, v, _ in vb], color=COL_CAL, lw=1.8, zorder=3)
412
+ ax.scatter(xb, [v for _, v, _ in vb], s=60, marker="s", color=COL_CAL, edgecolor=style.INK, lw=0.6,
413
+ zorder=5)
414
+ for lab, v, src in vb:
415
+ rows.append(dict(panel=panel, dataset=ds, series="zs_cal_budget", pairs=lab, value=v, source=src,
416
+ y_axis_break=bool(broken)))
417
+ if vs:
418
+ xs = [X_POS[X_LAB.index(lab)] for lab, _, _ in vs]
419
+ ax.plot(xs, [v for _, v, _ in vs], color=COL_SC, lw=1.8, zorder=3)
420
+ ax.scatter(xs, [v for _, v, _ in vs], s=55, marker="D", color=COL_SC, edgecolor=style.INK, lw=0.6, zorder=5)
421
+ for lab, v, src in vs:
422
+ rows.append(dict(panel=panel, dataset=ds, series="scsemi", pairs=lab, value=v, source=src,
423
+ y_axis_break=bool(broken)))
424
+ ax.plot(X_POS[1:], vl, color=style.ARM["lora"], lw=2.0, zorder=3)
425
+ ax.scatter(X_POS[1:], vl, s=70, color=style.ARM["lora"], edgecolor=style.INK, lw=0.6, zorder=5)
426
+ for lab, v, s in zip(X_LAB[1:], vl, srcl):
427
+ rows.append(dict(panel=panel, dataset=ds, series="lora", pairs=lab, value=v, source=s,
428
+ y_axis_break=bool(broken)))
429
+ for key, val, src in refs:
430
+ r = REF[key]
431
+ for a in axes:
432
+ a.axhline(val, ls=r["ls"], color=r["color"], lw=r["lw"], zorder=2)
433
+ rows.append(dict(panel=panel, dataset=ds, series=f"ref_{key}", pairs="", value=val, source=src,
434
+ y_axis_break=bool(broken)))
435
+ ax.set_xlim(*XLIM)
436
+ ax.set_xticks(X_POS)
437
+ ax.set_xticklabels(X_LAB)
438
+ # nothing is clipped: every plotted value is inside the y range of the axis that draws it
439
+ for v in list(vl) + [val for _, val, _ in refs] + [v for _, v, _ in vb + vs] + [v for ser, v, _ in z0
440
+ if ser not in out]:
441
+ assert ax.get_ylim()[0] <= v <= ax.get_ylim()[1], (panel, ds, v, ax.get_ylim())
442
+ for ser, v, _ in z0:
443
+ if ser in out:
444
+ assert axes[-1].get_ylim()[0] <= v <= axes[-1].get_ylim()[1], (panel, ds, ser, v)
445
+ return axes[-1]
446
+
447
+
448
+ def budget_series(budget, ds, getter, cal_all, src_all):
449
+ """Equal-budget calibration line for one panel: [(pairs label, value, source)] at n = 5..40 (where present)
450
+ plus "all" = zs__cal (alpha from the same train + inner-val pairs LoRA "all" saw). [] when nothing is found."""
451
+ out = []
452
+ for n in LC_N:
453
+ if n not in budget[ds]:
454
+ continue
455
+ v, c = budget_value(budget[ds][n], getter)
456
+ if v is not None:
457
+ out.append((str(n), v, f"{c.path} arm {budget[ds][n]['arm']}"))
458
+ if out:
459
+ out.append(("all", cal_all, src_all + " arm zs__cal (alpha from all fold pairs = LoRA all's pairs)"))
460
+ return out
461
+
462
+
463
+ def fig_realism(calls, st, fold_sizes, rows, steprows, budget, scs):
464
+ has_budget = any(budget[ds] for ds in DSETS)
465
+ has_sc = any(scs[ds] for ds in DSETS)
466
+ n_leg = 6 + has_budget + has_sc
467
+ fig, axs = plt.subplots(2, 3, figsize=style.FULL, # a third legend row when an optional line is drawn
468
+ gridspec_kw=dict(left=0.168, right=0.99, top=0.79 if n_leg > 6 else 0.83,
469
+ bottom=0.12, hspace=0.36, wspace=0.30))
470
+ heads = ["Composition L1 ↓", "Coverage ↑", "Selected step (×1,000)"]
471
+ pos0 = {ri: axs[ri, 2].get_position() for ri in range(len(DSETS))} # row extents before any y-axis break
472
+ title_ax = {ci: axs[0, ci] for ci in range(3)}
473
+ for ri, ds in enumerate(DSETS):
474
+ c = calls[ds]
475
+ for ci, key in enumerate(["comp_l1", "coverage"]):
476
+ ax = axs[ri, ci]
477
+ refs = [("pseudo", c.head("zs__pseudo", key), c.src_summary)]
478
+ if key == "comp_l1":
479
+ refs.append(("null", c.head("real_lora__raw", "comp_l1_obs_loo_null"), c.src_summary))
480
+ z0 = [("zero_shot", c.head(ZS, key), c.src_summary), ("zs_cal", c.head(ZS_CAL, key), c.src_summary)]
481
+ vb = budget_series(budget, ds, lambda cc, a, k=key: cc.head(a, k), c.head(ZS_CAL, key), c.src_summary)
482
+ vs = scsemi_series(scs, ds, lambda cc, a, k=key: cc.head(a, k))
483
+ tax = curve(ax, z0, [c.head(a, key) for a in LORA_ARMS], refs, rows,
484
+ f"{key}", ds, [c.src_summary] * 5, vb=vb, vs=vs)
485
+ if ri == 0:
486
+ title_ax[ci] = tax
487
+ # selected early-stopping step per fold
488
+ ax = axs[ri, 2]
489
+ s = st[st.dataset == ds]
490
+ for xi, arm in zip(X_POS[1:], RUN_ARMS):
491
+ f = s[s.arm == arm].sort_values("fold")
492
+ v = f.selected_step.astype(float).values / 1000
493
+ jit = np.linspace(-0.22, 0.22, len(v))
494
+ ax.scatter(xi + jit, v, s=36, color=style.ARM["lora"], edgecolor=style.INK, lw=0.5, zorder=4)
495
+ med = float(np.median(v))
496
+ ax.plot([xi - 0.36, xi + 0.36], [med, med], color=style.INK, lw=2.0, zorder=5)
497
+ steprows.append(dict(dataset=ds, arm=arm, pairs=X_LAB[X_POS.index(xi)], median_step=med * 1000,
498
+ min_step=v.min() * 1000, max_step=v.max() * 1000,
499
+ n_cap_limited=int(f.cap_limited.sum()),
500
+ max_last_window_drop_frac=(float(f[f.cap_limited].val_loss_last_window_drop_frac.max())
501
+ if f.cap_limited.any() else np.nan),
502
+ n_train=rng_txt(f.n_train), n_inner_val=rng_txt(f.n_inner_val),
503
+ source=";".join(f.source)))
504
+ cap = float(s.max_steps.max()) / 1000
505
+ ax.axhline(cap, color=style.GREY, lw=1.0, ls=(0, (2, 2)), zorder=1)
506
+ ax.text(X_POS[0] - 0.4, cap + 0.6, f"cap {cap:g}k", color=style.GREY, fontsize=12, va="bottom")
507
+ ax.text(X_POS[0], cap * 0.45, "no training", color=style.GREY, fontsize=12, ha="center",
508
+ va="center", rotation=90)
509
+ ax.set_ylim(0, cap * 1.18)
510
+ ax.set_xlim(-0.5, X_POS[-1] + 0.5)
511
+ ax.set_xticks(X_POS)
512
+ ax.set_xticklabels(X_LAB)
513
+ n_all = rng_txt(s[s.arm == "real_lora"].n_train)
514
+ n_iv = rng_txt(s.n_inner_val)
515
+ n_scored = int(c.summary["n_donors"])
516
+ assert n_scored == sum(fold_sizes[ds]["test"]), (ds, n_scored, fold_sizes[ds]["test"])
517
+ n_alpha = rng_txt(fold_sizes[ds]["alpha"])
518
+ # zs__cal alpha uses the same donors LoRA "all" trains and early-stops on (train + inner-val)
519
+ lora_all_seen = sorted(int(a) + int(b) for a, b in zip(s[s.arm == "real_lora"].sort_values("fold").n_train,
520
+ s[s.arm == "real_lora"].sort_values("fold").n_inner_val))
521
+ assert lora_all_seen == sorted(fold_sizes[ds]["alpha"]), (ds, lora_all_seen, fold_sizes[ds]["alpha"])
522
+ ymid = (pos0[ri].y0 + pos0[ri].y1) / 2
523
+ fig.text(0.005, ymid + 0.075, DS_LABEL[ds], fontsize=15, fontweight="bold", va="bottom", ha="left")
524
+ fig.text(0.005, ymid + 0.065,
525
+ f"{n_scored} donors\nall = {n_all} pairs\ninner-val = {n_iv}\ncal. α = {n_alpha}",
526
+ fontsize=12.5, va="top", ha="left", linespacing=1.35)
527
+ rows.append(dict(panel="meta", dataset=ds, series="n_scored_donors", pairs="", value=n_scored,
528
+ source=c.src_summary))
529
+ rows.append(dict(panel="meta", dataset=ds, series="n_pairs_all", pairs="all", value=n_all,
530
+ source="RUN.json train_rows: " + ";".join(s[s.arm == "real_lora"].source)))
531
+ rows.append(dict(panel="meta", dataset=ds, series="n_inner_val", pairs="", value=n_iv,
532
+ source="RUN.json inner_val_rows (all LoRA arms, 5 folds)"))
533
+ rows.append(dict(panel="meta", dataset=ds, series="n_test_donors_per_fold", pairs="",
534
+ value="/".join(map(str, fold_sizes[ds]["test"])),
535
+ source=fold_sizes[ds]["source"] + " fold_sizes test"))
536
+ rows.append(dict(panel="meta", dataset=ds, series="n_alpha_fit_pairs", pairs="0", value=n_alpha,
537
+ source=fold_sizes[ds]["source"] + " fold_sizes train+inner_val; prepare_dataset.py "
538
+ "fit = fold != f"))
539
+ for ci, h in enumerate(heads):
540
+ title_ax[ci].set_title(h, fontsize=14, pad=8)
541
+ x0, x1 = axs[1, 0].get_position().x0, axs[1, 2].get_position().x1
542
+ fig.text((x0 + x1) / 2, 0.005, xlabel(st), ha="center", va="bottom", fontsize=14)
543
+ handles = [ # column-wise fill: [raw, cal, (equal-budget cal)] | [LoRA, (scSemi), median] | [pseudo, null]
544
+ h_raw(), h_cal()] + ([h_budget()] if has_budget else []) + ([h_scsemi()] if has_sc else []) + [
545
+ Line2D([0], [0], marker="o", color=style.ARM["lora"], lw=2.0, markeredgecolor=style.INK, markersize=8,
546
+ label="LoRA fine-tune (dots in step panel = folds)"),
547
+ Line2D([0], [0], color=style.INK, lw=2.0, label="Median of 5 folds"),
548
+ Line2D([0], [0], ls=REF["pseudo"]["ls"], color=REF["pseudo"]["color"], lw=REF["pseudo"]["lw"],
549
+ label=REF["pseudo"]["label"]),
550
+ Line2D([0], [0], ls=REF["null"]["ls"], color=REF["null"]["color"], lw=REF["null"]["lw"],
551
+ label=REF["null"]["label"]),
552
+ ]
553
+ fig.legend(handles=handles, loc="upper left", bbox_to_anchor=(0.005, 1.0), ncol=3, frameon=False,
554
+ fontsize=12, handlelength=2.4, columnspacing=1.6, labelspacing=0.4, borderaxespad=0.0)
555
+ style.save(fig, "sec08_pairs_realism", FIGDIR)
556
+
557
+
558
+ def h_raw():
559
+ return Line2D([0], [0], marker="o", color=COL_RAW, lw=0, markeredgecolor=RAW_EDGE, markersize=8, label=LEG_ZS)
560
+
561
+
562
+ def h_cal():
563
+ return Line2D([0], [0], marker="o", color=COL_CAL, lw=0, markeredgecolor=style.INK, markersize=8, label=LEG_CAL)
564
+
565
+
566
+ def h_scsemi():
567
+ return Line2D([0], [0], marker="D", color=COL_SC, lw=1.8, markeredgecolor=style.INK, markersize=7, label=LEG_SC)
568
+
569
+
570
+ def h_budget():
571
+ return Line2D([0], [0], marker="s", color=COL_CAL, lw=1.8, markeredgecolor=style.INK, markersize=7,
572
+ label=LEG_CAL_N)
573
+
574
+
575
+ def fig_signal(calls, deg_call, st, rows, budget, scs):
576
+ has_budget = any(budget[ds] for ds in DSETS)
577
+ has_sc = any(scs[ds] for ds in DSETS)
578
+ leg_rows = -(-(5 + has_budget + has_sc) // 2)
579
+ fig, axs = plt.subplots(1, 3, figsize=style.TALL,
580
+ gridspec_kw=dict(left=0.085, right=0.99, top=0.755 - 0.055 * (leg_rows - 3), bottom=0.115,
581
+ wspace=0.42)) # 3 legend rows (4 with both optional lines)
582
+ im, se = calls["immicro"], calls["ye2026_sepsis"]
583
+ tax = [None] * 3
584
+ # a: ImMicro across-donor NK fraction r
585
+ tax[0] = curve(axs[0], [("zero_shot", im.frac_r(ZS, "NK cell"), im.src_per_donor),
586
+ ("zs_cal", im.frac_r(ZS_CAL, "NK cell"), im.src_per_donor)],
587
+ [im.frac_r(a, "NK cell") for a in LORA_ARMS],
588
+ [("pseudo", im.frac_r("zs__pseudo", "NK cell"), im.src_per_donor)], rows, "nk_fraction_r",
589
+ "immicro", [im.src_per_donor] * 5,
590
+ vb=budget_series(budget, "immicro", lambda cc, a: cc.frac_r(a, "NK cell"),
591
+ im.frac_r(ZS_CAL, "NK cell"), im.src_per_donor),
592
+ vs=scsemi_series(scs, "immicro", lambda cc, a: cc.frac_r(a, "NK cell")))
593
+ # other cell types, recorded for the footnote ("0+cal" = zero-shot + calibration)
594
+ for ct in ["T cell", "B cell", "Monocyte"]:
595
+ for a, lab in zip([ZS, ZS_CAL] + LORA_ARMS, ["0", "0+cal"] + X_LAB[1:]):
596
+ rows.append(dict(panel="other_fraction_r", dataset="immicro", series=ct, pairs=lab,
597
+ value=im.frac_r(a, ct), source=im.src_per_donor))
598
+ # b: sepsis disease logFC r (mean of T/B/Mono/NK, mean_cp10k)
599
+ tax[1] = curve(axs[1], [("zero_shot", se.contrast_r(ZS), se.src_contrast),
600
+ ("zs_cal", se.contrast_r(ZS_CAL), se.src_contrast)],
601
+ [se.contrast_r(a) for a in LORA_ARMS],
602
+ [("pseudo", se.contrast_r("zs__pseudo"), se.src_contrast),
603
+ ("broadcast", se.contrast_r("real_lora__raw", "r_broadcast"), se.src_contrast)],
604
+ rows, "logfc_r", "ye2026_sepsis", [se.src_contrast] * 5,
605
+ vb=budget_series(budget, "ye2026_sepsis", lambda cc, a: cc.contrast_r(a),
606
+ se.contrast_r(ZS_CAL), se.src_contrast),
607
+ vs=scsemi_series(scs, "ye2026_sepsis", lambda cc, a: cc.contrast_r(a)))
608
+ # c: sepsis top-50 DEG (Welch, sum over T/B/Mono/NK/DC)
609
+ tax[2] = curve(axs[2], [("zero_shot", deg_call.deg(ZS), deg_call.src_contrast),
610
+ ("zs_cal", deg_call.deg(ZS_CAL), deg_call.src_contrast)],
611
+ [deg_call.deg(a) for a in LORA_ARMS],
612
+ [("pseudo", deg_call.deg("zs__pseudo"), deg_call.src_contrast),
613
+ ("broadcast", deg_call.deg("real_lora__raw", "top50_overlap_broadcast"), deg_call.src_contrast)],
614
+ rows, "top50_deg", "ye2026_sepsis", [deg_call.src_contrast] * 5, ylim0=0,
615
+ vb=budget_series(budget, "ye2026_sepsis", lambda cc, a: cc.deg(a),
616
+ deg_call.deg(ZS_CAL), deg_call.src_contrast),
617
+ vs=scsemi_series(scs, "ye2026_sepsis", lambda cc, a: cc.deg(a)))
618
+ # top-50 DEG overlap per cell type (footnote: which types carry the gain), incl. broadcast
619
+ for ct in DEG_TYPES:
620
+ for a, lab in zip([ZS, ZS_CAL] + LORA_ARMS + ["zs__pseudo"], ["0", "0+cal"] + X_LAB[1:] + ["pseudo"]):
621
+ rows.append(dict(panel="top50_deg_by_type", dataset="ye2026_sepsis", series=ct, pairs=lab,
622
+ value=deg_call.deg_type(a, ct), source=deg_call.src_contrast))
623
+ rows.append(dict(panel="top50_deg_by_type", dataset="ye2026_sepsis", series=ct, pairs="broadcast",
624
+ value=deg_call.deg_type("real_lora__raw", ct, "top50_overlap_broadcast"),
625
+ source=deg_call.src_contrast))
626
+ cd = se.summary["contrast_definition"]
627
+ grp = f"Sepsis {cd['n_case_donors']} vs {cd['n_control_donors']}"
628
+ heads = [f"ImMicro, {int(im.summary['n_donors'])} donors\ndonor NK fraction r",
629
+ f"{grp}\ndisease logFC r", f"{grp}\ntop-50 DEG overlap"]
630
+ for ax, h in zip(tax, heads):
631
+ ax.set_title(h, fontsize=14, pad=8, linespacing=1.3)
632
+ x0, x1 = axs[0].get_position().x0, axs[2].get_position().x1
633
+ fig.text((x0 + x1) / 2, 0.005, xlabel(st), ha="center", va="bottom", fontsize=13)
634
+ rows.append(dict(panel="meta", dataset="ye2026_sepsis", series="n_case_vs_control", pairs="",
635
+ value=f"{se.summary['contrast_definition']['n_case_donors']} vs "
636
+ f"{se.summary['contrast_definition']['n_control_donors']}", source=se.src_summary))
637
+ handles = [ # column-wise fill: [raw, cal, pseudo, ...] | [LoRA, (equal-budget cal), (scSemi), broadcast]
638
+ h_raw(), h_cal(),
639
+ Line2D([0], [0], ls=REF["pseudo"]["ls"], color=REF["pseudo"]["color"], lw=REF["pseudo"]["lw"],
640
+ label=REF["pseudo"]["label"]),
641
+ Line2D([0], [0], marker="o", color=style.ARM["lora"], lw=2.0, markeredgecolor=style.INK, markersize=8,
642
+ label="LoRA fine-tune"),
643
+ ] + ([h_budget()] if has_budget else []) + ([h_scsemi()] if has_sc else []) + [
644
+ Line2D([0], [0], ls=REF["broadcast"]["ls"], color=REF["broadcast"]["color"], lw=REF["broadcast"]["lw"],
645
+ label=REF["broadcast"]["label"]),
646
+ ]
647
+ fig.legend(handles=handles, loc="upper left", bbox_to_anchor=(0.005, 1.0), ncol=2, frameon=False,
648
+ fontsize=12, handlelength=2.4, columnspacing=1.2, labelspacing=0.4, borderaxespad=0.0)
649
+ style.save(fig, "sec08_pairs_signal", FIGDIR)
650
+
651
+
652
+ def slide_numbers(calls, deg_call, st, fold_sizes, fewshot, budget, budget_log, scs=None, sc_log=()):
653
+ """Numbers quoted in the slide keywords/footnote, each with its source file."""
654
+ im, se = calls["immicro"], calls["ye2026_sepsis"]
655
+ out = []
656
+
657
+ def add(key, value, src):
658
+ out.append(dict(key=key, value=value, source=src))
659
+
660
+ for ds, c in calls.items():
661
+ for key in ("coverage", "comp_l1"):
662
+ add(f"{ds}.{key}.zero_shot", round(c.head(ZS, key), 3), c.src_summary)
663
+ add(f"{ds}.{key}.zs_cal", round(c.head(ZS_CAL, key), 3), c.src_summary)
664
+ add(f"{ds}.{key}.lora_n5", round(c.head("lora_n5__raw", key), 3), c.src_summary)
665
+ add(f"{ds}.{key}.lora_all", round(c.head("real_lora__raw", key), 3), c.src_summary)
666
+ add(f"{ds}.{key}.zs_pseudo", round(c.head("zs__pseudo", key), 3), c.src_summary)
667
+ add(f"{ds}.comp_l1.null", round(c.head("real_lora__raw", "comp_l1_obs_loo_null"), 3), c.src_summary)
668
+ # donor-level composition L1, each LoRA size vs zero-shot (paired Wilcoxon, uncorrected)
669
+ piv = c.per_donor.pivot(index="donor", columns="arm", values="comp_l1")
670
+ for a, lab in zip(LORA_ARMS, X_LAB[1:]):
671
+ x = (piv[a] - piv[ZS]).dropna()
672
+ add(f"{ds}.comp_l1.lora_{lab}_minus_zero_shot.mean", round(float(x.mean()), 3), c.src_per_donor)
673
+ add(f"{ds}.comp_l1.lora_{lab}_minus_zero_shot.frac_donors_lower", round(float((x < 0).mean()), 2),
674
+ c.src_per_donor)
675
+ add(f"{ds}.comp_l1.lora_{lab}_vs_zero_shot.wilcoxon_p", float(f"{wilcoxon(x).pvalue:.2g}"),
676
+ c.src_per_donor)
677
+ # each LoRA size vs zero-shot + calibration (donor L1 and donor coverage; paired Wilcoxon, uncorrected)
678
+ for met in ("comp_l1", "coverage"):
679
+ pv = c.per_donor.pivot(index="donor", columns="arm", values=met)
680
+ for a, lab in zip(LORA_ARMS, X_LAB[1:]):
681
+ x = (pv[a] - pv[ZS_CAL]).dropna()
682
+ add(f"{ds}.{met}.lora_{lab}_minus_zs_cal.mean", round(float(x.mean()), 3), c.src_per_donor)
683
+ add(f"{ds}.{met}.lora_{lab}_minus_zs_cal.frac_donors_lower", round(float((x < 0).mean()), 2),
684
+ c.src_per_donor)
685
+ add(f"{ds}.{met}.lora_{lab}_vs_zs_cal.wilcoxon_p", float(f"{wilcoxon(x).pvalue:.2g}"),
686
+ c.src_per_donor)
687
+ # the raw -> calibrated zero-shot gap
688
+ x = (pv[ZS_CAL] - pv[ZS]).dropna()
689
+ add(f"{ds}.{met}.zs_cal_minus_zero_shot.mean", round(float(x.mean()), 3), c.src_per_donor)
690
+ add(f"{ds}.{met}.zs_cal_vs_zero_shot.wilcoxon_p", float(f"{wilcoxon(x).pvalue:.2g}"), c.src_per_donor)
691
+ add(f"{ds}.cal_alpha_fit_pairs", rng_txt(fold_sizes[ds]["alpha"]),
692
+ fold_sizes[ds]["source"] + " fold_sizes train+inner_val; tools/prepare_dataset.py fit = fold != f")
693
+ # few-pair call (its own donors): alpha from the same 5 pairs vs LoRA on them (fixed 3k steps, no inner-val)
694
+ add(f"{ds}.fewshot_n5.coverage.zs_cal_same5", round(fewshot[ds]["zs_cal"], 3), fewshot[ds]["source"])
695
+ add(f"{ds}.fewshot_n5.coverage.lora5_fixed3k", round(fewshot[ds]["lora5"], 3), fewshot[ds]["source"])
696
+ add(f"{ds}.n_scored_donors", int(c.summary["n_donors"]), c.src_summary)
697
+ s = st[st.dataset == ds]
698
+ add(f"{ds}.selected_step.lora_n5.range", rng_txt(s[s.arm == "lora_n5"].selected_step), "RUN.json: "
699
+ + ";".join(s[s.arm == "lora_n5"].source))
700
+ add(f"{ds}.n_train.all", rng_txt(s[s.arm == "real_lora"].n_train), "RUN.json: "
701
+ + ";".join(s[s.arm == "real_lora"].source))
702
+ add(f"{ds}.n_inner_val", rng_txt(s.n_inner_val), "RUN.json inner_val_rows (all LoRA arms, 5 folds)")
703
+ for arm in RUN_ARMS:
704
+ f = s[s.arm == arm]
705
+ add(f"{ds}.folds_cap_limited.{arm}", f"{int(f.cap_limited.sum())}/{len(f)}",
706
+ "RUN.json steps_run == max_steps and steps_run - selected_step < patience*eval_every: "
707
+ + ";".join(f.source))
708
+ capped = s[s.cap_limited]
709
+ if len(capped):
710
+ add(f"{ds}.cap_limited.max_val_loss_drop_frac_last_2k_steps",
711
+ round(float(capped.val_loss_last_window_drop_frac.max()), 4),
712
+ "history.json inner_val_loss (drop over last patience window / drop from step 0): "
713
+ + ";".join(capped.history))
714
+ for a, lab in zip([ZS, ZS_CAL] + LORA_ARMS + ["zs__pseudo"], KEY_LAB[:1] + ["zs_cal"] + KEY_LAB[1:] + ["pseudo"]):
715
+ add(f"immicro.nk_fraction_r.{lab}", round(im.frac_r(a, "NK cell"), 2), im.src_per_donor)
716
+ add(f"sepsis.logfc_r.{lab}", round(se.contrast_r(a), 2), se.src_contrast)
717
+ add(f"sepsis.top50_deg.{lab}", int(deg_call.deg(a)), deg_call.src_contrast)
718
+ add("sepsis.logfc_r.broadcast", round(se.contrast_r("real_lora__raw", "r_broadcast"), 2), se.src_contrast)
719
+ add("sepsis.top50_deg.broadcast", int(deg_call.deg("real_lora__raw", "top50_overlap_broadcast")),
720
+ deg_call.src_contrast)
721
+
722
+ def first_sustained(v, thr, strict=True):
723
+ """First LoRA n from which every later n is above (or >=) thr."""
724
+ for i in range(len(v)):
725
+ if all((x > thr) if strict else (x >= thr) for x in v[i:]):
726
+ return X_LAB[1 + i]
727
+ return "never"
728
+ bc_r = se.contrast_r("real_lora__raw", "r_broadcast")
729
+ bc_d = deg_call.deg("real_lora__raw", "top50_overlap_broadcast")
730
+ vr = [se.contrast_r(a) for a in LORA_ARMS]
731
+ vd = [deg_call.deg(a) for a in LORA_ARMS]
732
+ add("sepsis.logfc_r.first_n_above_broadcast", first_sustained(vr, bc_r), se.src_contrast)
733
+ add("sepsis.logfc_r.first_n_above_zero_shot", first_sustained(vr, se.contrast_r(ZS)), se.src_contrast)
734
+ add("sepsis.top50_deg.first_n_at_or_above_broadcast", first_sustained(vd, bc_d, strict=False),
735
+ deg_call.src_contrast)
736
+ add("sepsis.top50_deg.first_n_above_zero_shot", first_sustained(vd, deg_call.deg(ZS)), deg_call.src_contrast)
737
+ add("sepsis.logfc_r.first_n_above_zs_cal", first_sustained(vr, se.contrast_r(ZS_CAL)), se.src_contrast)
738
+ add("sepsis.top50_deg.first_n_above_zs_cal", first_sustained(vd, deg_call.deg(ZS_CAL)), deg_call.src_contrast)
739
+ vn = [im.frac_r(a, "NK cell") for a in LORA_ARMS]
740
+ add("immicro.nk_fraction_r.first_n_above_zs_cal", first_sustained(vn, im.frac_r(ZS_CAL, "NK cell")),
741
+ im.src_per_donor)
742
+ for ds, c in calls.items():
743
+ for key in ("coverage", "comp_l1"):
744
+ v = [c.head(a, key) for a in LORA_ARMS]
745
+ thr = c.head(ZS_CAL, key)
746
+ first = first_sustained([-x for x in v], -thr) if key == "comp_l1" else first_sustained(v, thr)
747
+ add(f"{ds}.{key}.first_n_better_than_zs_cal", first, c.src_summary)
748
+ # across-donor fraction r per cell type: first n from which LoRA stays at/above zero-shot (footnote)
749
+ for ct, key in [("T cell", "T"), ("B cell", "B"), ("Monocyte", "Mono"), ("NK cell", "NK")]:
750
+ v = [im.frac_r(a, ct) for a in LORA_ARMS]
751
+ add(f"immicro.fraction_r.{key}.first_n_at_or_above_zero_shot",
752
+ first_sustained(v, im.frac_r(ZS, ct), strict=False), im.src_per_donor)
753
+ add(f"immicro.fraction_r.{key}.zero_shot", round(im.frac_r(ZS, ct), 2), im.src_per_donor)
754
+ add(f"immicro.fraction_r.{key}.zs_cal", round(im.frac_r(ZS_CAL, ct), 2), im.src_per_donor)
755
+ add(f"immicro.fraction_r.{key}.first_n_at_or_above_zs_cal",
756
+ first_sustained(v, im.frac_r(ZS_CAL, ct), strict=False), im.src_per_donor)
757
+ add(f"immicro.fraction_r.{key}.lora_5_10_20_40_all", "/".join(f"{x:.2f}" for x in v), im.src_per_donor)
758
+ # top-50 DEG overlap by cell type (which types carry the gain)
759
+ for ct, key in [("T cell", "T"), ("B cell", "B"), ("Monocyte", "Mono"), ("NK cell", "NK"), ("DC", "DC")]:
760
+ v = [deg_call.deg_type(a, ct) for a in [ZS] + LORA_ARMS]
761
+ add(f"sepsis.top50_deg.{key}.zero_shot_5_10_20_40_all", "/".join(f"{x:g}" for x in v),
762
+ deg_call.src_contrast)
763
+ add(f"sepsis.top50_deg.{key}.zs_cal", int(deg_call.deg_type(ZS_CAL, ct)), deg_call.src_contrast)
764
+ add(f"sepsis.top50_deg.{key}.broadcast", int(deg_call.deg_type("real_lora__raw", ct,
765
+ "top50_overlap_broadcast")),
766
+ deg_call.src_contrast)
767
+ add("sepsis.n_case", int(se.summary["contrast_definition"]["n_case_donors"]), se.src_summary)
768
+ add("sepsis.n_control", int(se.summary["contrast_definition"]["n_control_donors"]), se.src_summary)
769
+ add("final_checkpoint", FINAL_CKPT, "RUN.json source_checkpoint (all 50 LoRA runs)")
770
+ # equal-budget calibration scan (zero-shot + calibration with alpha from the n + inner-val pairs of lora_n*)
771
+ add("cal_budget.pattern", f"scores/<dataset>/**/summary.json arm names: 'cal' and regex {CAL_N_RE.pattern}, "
772
+ f"none of {list(FT_TAGS)}", str(PLAN / "scores"))
773
+ add("cal_budget.found", ";".join(f"{r['dataset']}:{r['call']}:{r['arm']}" for r in budget_log) or "none",
774
+ str(PLAN / "scores"))
775
+ for ds in DSETS:
776
+ add(f"{ds}.cal_budget.n_drawn", ",".join(str(n) for n in sorted(budget[ds])) or "none", str(PLAN / "scores"))
777
+ # scSemiProfiler line (equal-budget n + 5-fold CV "all")
778
+ add("scsemi.found", ";".join(f"{r['dataset']}:{r['call']}:{r['arm']}:{r['note']}" for r in sc_log) or "none",
779
+ f"{SR.plan_root()}/scores/<dataset>/{{{SR.BUDGET_EXP},{SR.CV_EXP}}}/pooled*")
780
+ for ds in DSETS:
781
+ sc = (scs or {}).get(ds, {})
782
+ add(f"{ds}.scsemi.pairs_drawn", ",".join(lab for lab in X_LAB[1:] if lab in sc) or "none",
783
+ f"{SR.plan_root()}/scores/{ds}")
784
+ for lab in X_LAB[1:]:
785
+ if lab in sc:
786
+ for key in ("coverage", "comp_l1"):
787
+ v, c = budget_value(sc[lab], lambda cc, a, k=key: cc.head(a, k))
788
+ if v is not None:
789
+ add(f"{ds}.{key}.scsemi_{lab}", round(v, 3), str(c.path / "summary.json"))
790
+ return pd.DataFrame(out)
791
+
792
+
793
+ def check_against_fig3(rows):
794
+ """Cross-check the LoRA curve, the zero-shot + calibration point and the reference lines with the plan's own
795
+ fig3 source data (same numbers, independent code path; the plan's fig3 n=0 point is zs__cal). The zero-shot
796
+ real-bulk point is not in fig3; it is checked in load() instead (headline vs per_donor.csv / contrast.csv)."""
797
+ ref = pd.read_csv(PLAN / "figures" / "source_data" / "fig3_learning_curve.csv")
798
+ pmap = {("comp_l1", "immicro"): "3a", ("comp_l1", "ye2026_sepsis"): "3b",
799
+ ("coverage", "immicro"): "3c", ("coverage", "ye2026_sepsis"): "3d",
800
+ ("nk_fraction_r", "immicro"): "3e", ("logfc_r", "ye2026_sepsis"): "3f",
801
+ ("top50_deg", "ye2026_sepsis"): "3h"}
802
+ n = 0
803
+ for r in rows:
804
+ p = pmap.get((r["panel"], r["dataset"]))
805
+ if p is None or r["series"] in ("zero_shot", "zs_cal_budget", "scsemi"):
806
+ continue
807
+ if r["series"] == "lora":
808
+ m = ref[(ref.panel == p) & (ref.series == r["series"]) & (ref.draw == f"n={r['pairs']}")]
809
+ elif r["series"] == "zs_cal":
810
+ m = ref[(ref.panel == p) & (ref.series == "zs_cal") & (ref.draw == "n=0")]
811
+ else:
812
+ m = ref[(ref.panel == p) & (ref.series == r["series"])]
813
+ assert len(m) == 1, (r, len(m))
814
+ assert abs(float(m.value.iloc[0]) - float(r["value"])) < 1e-5, (r, float(m.value.iloc[0]))
815
+ n += 1
816
+ return n
817
+
818
+
819
+ def main():
820
+ calls, deg_call = load()
821
+ st = load_steps()
822
+ fold_sizes = load_fold_sizes()
823
+ fewshot = load_fewshot()
824
+ budget, budget_log = find_cal_budget(calls, deg_call)
825
+ scs, sc_log = find_scsemi(calls)
826
+ rows, steprows = [], []
827
+ fig_realism(calls, st, fold_sizes, rows, steprows, budget, scs)
828
+ rows_sig = []
829
+ fig_signal(calls, deg_call, st, rows_sig, budget, scs)
830
+ n_checked = check_against_fig3(rows + rows_sig)
831
+ pd.DataFrame(rows).to_csv(DATADIR / "sec08_pairs_realism.csv", index=False, float_format="%.6g")
832
+ pd.DataFrame(steprows).to_csv(DATADIR / "sec08_selected_steps.csv", index=False, float_format="%.6g")
833
+ st.to_csv(DATADIR / "sec08_selected_steps_per_fold.csv", index=False)
834
+ pd.DataFrame(rows_sig).to_csv(DATADIR / "sec08_pairs_signal.csv", index=False, float_format="%.6g")
835
+ nums = slide_numbers(calls, deg_call, st, fold_sizes, fewshot, budget, budget_log, scs, sc_log)
836
+ nums.to_csv(DATADIR / "sec08_slide_numbers.csv", index=False)
837
+ print(nums.to_string(index=False, max_colwidth=70))
838
+ print(f"cross-checked {n_checked} plotted values against fig3_learning_curve.csv")
839
+ brk = [(r["panel"], r["dataset"]) for r in rows + rows_sig if r.get("series") == "zero_shot" and r["y_axis_break"]]
840
+ print(f"y-axis breaks: {brk}")
841
+ print(f"equal-budget calibration scan: arm names with 'cal' and regex {CAL_N_RE.pattern!r}, none of {FT_TAGS}, "
842
+ f"in {PLAN / 'scores'}/<dataset>/**/summary.json")
843
+ for r in budget_log:
844
+ print(f" found {r['dataset']} {r['call']} {r['arm']} (n {r['n']}): {r['note']}")
845
+ if not any(budget[ds] for ds in DSETS):
846
+ print(" NOTE: no equal-budget calibration arms found; only the two x = 0 zero-shot points are drawn.")
847
+ print(f"scSemiProfiler scan: {SR.plan_root()}/scores/<dataset>/{SR.BUDGET_EXP}/pooled* (scsemi_n<n>__raw) and "
848
+ f"{SR.CV_EXP}/pooled* ({SR.CV_ARM}, drawn at 'all')")
849
+ for r in sc_log:
850
+ print(f" found {r['dataset']} {r['call']} {r['arm']} (pairs {r['pairs']}): {r['note']}")
851
+ if not any(scs[ds] for ds in DSETS):
852
+ print(" NOTE: no scSemiProfiler equal-budget or 5-fold calls found; no scSemiProfiler line is drawn.")
853
+
854
+
855
+ if __name__ == "__main__":
856
+ main()
paper-releases/pbisc-diffusion/updates/20261002T002920Z-deck-extra-metrics-scsemi-prep/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec09_extra_metrics.py ADDED
@@ -0,0 +1,738 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Section 9 extras of the 2026-09-30 paper-summary deck: realism / diversity metrics beyond precision and coverage
3
+ (classifier AUC, MMD^2, scSemiProfiler's E_N, precision/coverage at k = 3 / 5 / 10).
4
+
5
+ CPU only: reads the per-unit outputs of plans/paired_finetune_intradataset_20260927/tools/extra_metrics.py
6
+ (scores_extra/<ds>/{fewshot_n5/draw<j>, pooled}/{metrics.csv, en.csv, manifest.json}) and draws slide figures.
7
+ No torch, no CUDA, no scoring. The headline definitions are the collector's (tools/collect_extra_metrics.py,
8
+ scores_extra/README.md) and every value is checked against scores_extra/{fewshot,pooled}_headline.csv:
9
+ classifier AUC (kNN, RF), 1-NN accuracy, MMD^2 real side R2 (held-out real cells), no depth matching;
10
+ control = real vs real, R2 vs R3
11
+ E_N all cells, squared L2 (their code); control = within-sample half
12
+ split; undefined (UB <= LB) -> left out of means, ranks last
13
+ precision / coverage at k = 3, 5, 10 the scorer's space (real side R1); control = R1 vs R2
14
+
15
+ Outputs (deck folder; DECK_FIGDIR / DECK_OUTDATA override the folders, used by the synthetic test):
16
+ figures/sec09_extra_fewpair.{png,pdf} main slide: 5 donors, kNN AUC / MMD^2 / E_N per cohort
17
+ figures/sec09_extra_fivefold.{png,pdf} backup: the same for the 5-fold pooled design
18
+ figures/sec09_extra_ksens.{png,pdf} backup: precision / coverage at k = 3, 5, 10 (5 donors)
19
+ data/sec09_extra_{fewpair,fivefold,ksens}.csv every plotted value with its source file
20
+ data/sec09_extra_scsemi_status.csv scSemiProfiler CV / equal-budget extra-metric units found or not
21
+ data/sec09_extra_quoted_numbers.csv quoted numbers (flat)
22
+ data/sec09_extra_slide_text.json titles, keywords, footnotes, quoted numbers (synced into
23
+ data/slides_spec.json by tools/sync_sec09_text.py)
24
+
25
+ scSemiProfiler with all training pairs (5-fold CV, arm scsemi__raw): drawn in the 5-fold figure as its own bar when an
26
+ extra-metric unit with that set exists (scores_extra/<ds>/pooled/ itself, or below scores_extra/<ds>/scsemi_cv_20261002/,
27
+ see tools/scsemi_results.py) for the same donors and reference cells; otherwise a note is printed and nothing is drawn.
28
+ Equal-budget units (scsemi_n<n>__raw) are only listed in the status CSV.
29
+ """
30
+ from __future__ import annotations
31
+
32
+ import os
33
+
34
+ os.environ["CUDA_VISIBLE_DEVICES"] = "" # plotting only
35
+
36
+ import json
37
+ import sys
38
+ from pathlib import Path
39
+
40
+ import numpy as np
41
+ import pandas as pd
42
+
43
+ DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/"
44
+ "2026-09-30--paper-summary--r00")
45
+ sys.path.insert(0, str(DECK / "tools"))
46
+ import sec09_paired_validation as S9 # noqa: E402 (shared section 9 drawing helpers; sets the deck rcParams)
47
+ import scsemi_results as SR # noqa: E402
48
+ import style # noqa: E402
49
+ import matplotlib.pyplot as plt # noqa: E402
50
+ from matplotlib.lines import Line2D # noqa: E402
51
+ from matplotlib.patches import Patch # noqa: E402
52
+
53
+ T = S9.T
54
+ X = T / "scores_extra"
55
+ FIGDIR = Path(os.environ.get("DECK_FIGDIR", str(DECK / "figures")))
56
+ OUTDATA = Path(os.environ.get("DECK_OUTDATA", str(DECK / "data")))
57
+ SCRIPT = DECK / "tools" / "sec09_extra_metrics.py"
58
+ ORDER, NAME, ROWNAME = S9.ORDER, S9.NAME, S9.ROWNAME
59
+ FS, SUB, EDGE = S9.FS, S9.SUB, S9.EDGE
60
+
61
+ # arm keys (deck colours / labels from sec09) -> set names in scores_extra
62
+ FEW_SETS = {"zs_raw": "zs_raw", "zs_cal": "zs_cal", "scsemi5": "scsemi5", "lora": "lora5", "pseudo": "zs_pseudo"}
63
+ POOL_SETS = {"zs_raw": "zs__raw", "zs_cal": "zs__cal", "sconly_cal": "pseudo_full__cal", "scsemi_all": SR.CV_ARM,
64
+ "lora": "real_lora__raw", "pseudo": "zs__pseudo"}
65
+ COL = {**S9.COL, "scsemi_all": style.ARM["scsemi"]}
66
+ LAB = {**S9.LAB, "scsemi_all": SR.LABEL_CV}
67
+ # headline metrics (collector's HEADLINE): column, short name, direction (0: closer to 0.5, -1 lower, +1 higher), space
68
+ TWO = [("c2st_knn_auc", "kNN AUC", 0), ("c2st_rf_auc", "RF AUC", 0), ("nn1_acc", "1-NN accuracy", 0),
69
+ ("mmd2_bw1", "MMD² (σ = m)", -1), ("mmd2_sum", "MMD² (σ sum)", -1)]
70
+ EN = [("en_all_sq", "E_N (all cells)", -1)]
71
+ PC = [(f"{q}_k{k}", f"{q} k{k}", 1) for k in (3, 5, 10) for q in ("precision", "coverage")]
72
+ HEAD = TWO + EN + PC
73
+ DIRS = {c: s for c, _, s in HEAD}
74
+ SHORT = {c: n for c, n, _ in HEAD}
75
+ # drawn columns of the two realism figures
76
+ PANELS = [("c2st_knn_auc", "Classifier AUC (kNN) ↓"), ("mmd2_bw1", "MMD² ↓"), ("en_all_sq", "scSemiProfiler E_N ↓ (log)")]
77
+ CTRL = dict(ls=(0, (6, 2, 1.5, 2)), color="#7A7A7A", lw=1.8, label="Real vs real (same samples)")
78
+ KS = (3, 5, 10)
79
+ NUMS = {k: [] for k in "abc"}
80
+
81
+
82
+ def num(slide, value, source):
83
+ NUMS[slide].append({"value": str(value), "source": str(source)})
84
+
85
+
86
+ # ------------------------------------------------------------------------------------------
87
+ # Loading
88
+ # ------------------------------------------------------------------------------------------
89
+ def unit_values(u: Path) -> dict:
90
+ """set -> {metric: value} in the headline spaces of one extra-metric unit; 'control' = the real-vs-real rows."""
91
+ m = pd.read_csv(u / "metrics.csv")
92
+ e = pd.read_csv(u / "en.csv")
93
+ raw = m[m["mode"] == "raw"]
94
+ out = {}
95
+ for s in sorted(set(raw["set"])):
96
+ r2 = raw[(raw["set"] == s) & (raw.real_side == "R2")]
97
+ r1 = raw[(raw["set"] == s) & (raw.real_side == "R1")]
98
+ if len(r2) > 1 or len(r1) > 1:
99
+ raise ValueError(f"{u}: several raw rows for set {s}")
100
+ d = {c: (float(r2[c].iloc[0]) if len(r2) else np.nan) for c, _, _ in TWO}
101
+ d.update({c: (float(r1[c].iloc[0]) if len(r1) else np.nan) for c, _, _ in PC})
102
+ en = e[(e["set"] == s) & (e.cellset == "all") & (e.distance == "sq")]
103
+ if len(en) > 1:
104
+ raise ValueError(f"{u}: several E_N rows for set {s}")
105
+ ok = bool(len(en)) and float(en.ub.iloc[0]) > float(en.lb.iloc[0])
106
+ d["en_all_sq"] = float(en.en.iloc[0]) if ok else np.nan
107
+ d["en_all_sq_undefined"] = bool(len(en)) and not ok
108
+ out[s] = d
109
+ ctrl = {c: out["real_R3"][c] for c, _, _ in TWO}
110
+ ctrl.update({c: out["real_R2"][c] for c, _, _ in PC + EN})
111
+ ctrl["en_all_sq_undefined"] = False
112
+ out["control"] = ctrl
113
+ return out
114
+
115
+
116
+ def manifest(u: Path) -> dict:
117
+ p = u / "manifest.json"
118
+ return json.loads(p.read_text()) if p.is_file() else {}
119
+
120
+
121
+ def load_fewpair():
122
+ """Long table: dataset, draw, arm (deck key or 'control'), metric, value, undefined, source."""
123
+ rows, info = [], {}
124
+ for ds in ORDER:
125
+ units = [d for d in sorted((X / ds / "fewshot_n5").glob("draw*")) if (d / "manifest.json").is_file()]
126
+ few_min = []
127
+ for u in units:
128
+ j = int(u.name.removeprefix("draw"))
129
+ mf_ = manifest(u)
130
+ sj = T / "scores" / ds / "fewshot_n5" / f"draw{j}" / "summary.json"
131
+ s = json.loads(sj.read_text())
132
+ if set(map(str, mf_["donors"])) != set(map(str, s["donors"])):
133
+ raise ValueError(f"{u}: scored donors differ from {sj}")
134
+ if mf_["reference_sha256"] != s["reference"]["reference_sha256"]:
135
+ raise ValueError(f"{u}: reference differs from {sj}")
136
+ few_min.append({"dataset": ds, "arm": "lora", "draw": j, "n_scored": int(s["n_donors"])})
137
+ vals = unit_values(u)
138
+ for key in list(FEW_SETS) + ["control"]:
139
+ sname = FEW_SETS.get(key, "control")
140
+ if sname not in vals:
141
+ continue
142
+ for c, _, _ in HEAD:
143
+ rows.append({"dataset": ds, "draw": j, "arm": key, "set": sname, "metric": c,
144
+ "value": vals[sname][c],
145
+ "undefined": bool(vals[sname].get(f"{c}_undefined", False)),
146
+ "source": str(u / ("en.csv" if c.startswith("en_") else "metrics.csv"))})
147
+ info[ds] = S9.draw_info(pd.DataFrame(few_min), ds)
148
+ return pd.DataFrame(rows), info
149
+
150
+
151
+ def load_pooled():
152
+ """dataset -> {arm key: {metric: value}}, plus the scSemiProfiler lookup log."""
153
+ out, log = {}, []
154
+ for ds in ORDER:
155
+ u = X / ds / "pooled"
156
+ vals = unit_values(u)
157
+ ref = manifest(u)
158
+ d = {}
159
+ for key, sname in POOL_SETS.items():
160
+ if sname in vals:
161
+ d[key] = {**vals[sname], "source": str(u)}
162
+ d["control"] = {**vals["control"], "source": str(u)}
163
+ # scSemiProfiler, all training pairs: in the pooled unit itself, else below scores_extra/<ds>/scsemi_cv_20261002/
164
+ if "scsemi_all" in d:
165
+ log.append(dict(dataset=ds, design="cv", unit=str(u), set=SR.CV_ARM, status="used", reason="in pooled unit"))
166
+ for cu in SR.extra_units(ds, SR.CV_EXP):
167
+ cv = unit_values(cu)
168
+ if SR.CV_ARM not in cv:
169
+ log.append(dict(dataset=ds, design="cv", unit=str(cu), set="", status="ignored",
170
+ reason=f"no set {SR.CV_ARM}"))
171
+ continue
172
+ cm = manifest(cu)
173
+ why = []
174
+ if cm.get("donors") is not None and set(map(str, cm["donors"])) != set(map(str, ref["donors"])):
175
+ why.append("donor set differs from the pooled unit")
176
+ if cm.get("reference_sha256") is not None and cm["reference_sha256"] != ref["reference_sha256"]:
177
+ why.append("reference differs from the pooled unit")
178
+ if "scsemi_all" in d:
179
+ why.append("already taken from an earlier unit")
180
+ if why:
181
+ log.append(dict(dataset=ds, design="cv", unit=str(cu), set=SR.CV_ARM, status="rejected",
182
+ reason="; ".join(why)))
183
+ continue
184
+ d["scsemi_all"] = {**cv[SR.CV_ARM], "source": str(cu)}
185
+ log.append(dict(dataset=ds, design="cv", unit=str(cu), set=SR.CV_ARM, status="used",
186
+ reason="no manifest: donors not checked" if not cm else ""))
187
+ for bu in SR.extra_units(ds, SR.BUDGET_EXP):
188
+ for s in sorted(unit_values(bu)):
189
+ if SR.BUDGET_RE.match(s):
190
+ log.append(dict(dataset=ds, design="budget", unit=str(bu), set=s, status="listed only",
191
+ reason="equal-budget units are not drawn"))
192
+ out[ds] = d
193
+ return out, pd.DataFrame(log, columns=["dataset", "design", "unit", "set", "status", "reason"])
194
+
195
+
196
+ def check_headline(few: pd.DataFrame, pooled: dict):
197
+ """Every value equals the collector's headline tables (few-pair: mean and n over draws; pooled: the value)."""
198
+ n = 0
199
+ hf = pd.read_csv(X / "fewshot_headline.csv")
200
+ for r in hf.itertuples():
201
+ key = "control" if r.set == "control" else {v: k for k, v in FEW_SETS.items()}[r.set]
202
+ for c, _, _ in HEAD:
203
+ x = few[(few.dataset == r.dataset) & (few.arm == key) & (few.metric == c) & ~few.undefined]["value"]
204
+ want = getattr(r, c)
205
+ if int(getattr(r, f"{c}_n")) != len(x) or abs(float(x.mean()) - want) > 1e-9:
206
+ raise ValueError(f"few-pair {r.dataset} {r.set} {c}: {x.mean()} (n {len(x)}) != headline {want}")
207
+ n += 1
208
+ hp = pd.read_csv(X / "pooled_headline.csv")
209
+ for r in hp.itertuples():
210
+ key = "control" if r.set == "control" else {v: k for k, v in POOL_SETS.items()}[r.set]
211
+ for c, _, _ in HEAD:
212
+ v, want = pooled[r.dataset][key][c], getattr(r, c)
213
+ if not (abs(v - want) <= 1e-9 or (np.isnan(v) and np.isnan(want))):
214
+ raise ValueError(f"pooled {r.dataset} {r.set} {c}: {v} != headline {want}")
215
+ n += 1
216
+ return n
217
+
218
+
219
+ # ------------------------------------------------------------------------------------------
220
+ # Drawing
221
+ # ------------------------------------------------------------------------------------------
222
+ def hbars_base(ax, arms, vals_of, base, seed=0, dots=True, na_text=None):
223
+ """S9.hbars with bars starting at `base` (0.5 for AUC, the axis floor for a log axis)."""
224
+ out = {}
225
+ for i, arm in enumerate(arms):
226
+ vals = np.asarray([v for v in vals_of(arm) if not np.isnan(v)], float)
227
+ if len(vals) == 0:
228
+ ax.text(0.01, i, (na_text or {}).get(arm, "not run"), transform=ax.get_yaxis_transform(), va="center",
229
+ fontsize=FS - 3, color=SUB)
230
+ out[arm] = (np.nan, np.nan, 0)
231
+ continue
232
+ m = float(vals.mean())
233
+ sd = float(vals.std(ddof=1)) if len(vals) > 1 else 0.0
234
+ ax.barh(i, m - base, left=base, height=S9.BAR_H, color=COL[arm], edgecolor=EDGE, linewidth=0.6, zorder=2)
235
+ if dots and len(vals) > 1:
236
+ lo = max(m - sd, base) if ax.get_xscale() == "log" else m - sd
237
+ ax.errorbar(m, i, xerr=[[m - lo], [sd]], fmt="none", ecolor="#111111", elinewidth=1.0, capsize=3,
238
+ capthick=1.0, zorder=4)
239
+ ax.scatter(vals, i + S9.jitter(len(vals), seed + i), s=16, facecolor="white", edgecolor="#111111",
240
+ linewidth=0.7, zorder=5, clip_on=False)
241
+ out[arm] = (m, sd, len(vals))
242
+ ax.set_ylim(len(arms) - 0.5, -0.5)
243
+ ax.set_yticks([])
244
+ return out
245
+
246
+
247
+ def vline(ax, x, style_, na):
248
+ if x is None or np.isnan(x):
249
+ return
250
+ ax.plot([x, x], [-0.5, na - 0.5], ls=style_["ls"], color=style_["color"], lw=style_["lw"], zorder=3,
251
+ solid_capstyle="butt")
252
+
253
+
254
+ def ctrl_handle():
255
+ return Line2D([0], [0], ls=CTRL["ls"], color=CTRL["color"], lw=CTRL["lw"], label=CTRL["label"])
256
+
257
+
258
+ def patch(key, label=None):
259
+ return Patch(facecolor=COL[key], edgecolor=EDGE, linewidth=0.6, label=label or LAB[key])
260
+
261
+
262
+ def nice_log_limits(vals):
263
+ v = [x for x in vals if x > 0 and not np.isnan(x)]
264
+ lo = max([c for c in (0.01, 0.02, 0.03, 0.05, 0.1, 0.2, 0.5) if c <= min(v) / 1.3] or [0.005])
265
+ hi = min([c for c in (2, 5, 10, 20, 50, 100, 200, 500, 1000) if c >= max(v) * 1.3] or [max(v) * 2])
266
+ return lo, hi
267
+
268
+
269
+ def axis_setup(axs_col, metric, allv, label):
270
+ """Shared x scale of one metric column; returns the bar base."""
271
+ if metric.startswith("c2st") or metric.startswith("nn1"):
272
+ lo = min(0.45, np.floor(min(allv) * 20) / 20)
273
+ S9.shared_x(axs_col, lo, 1.0, label, [0.5, 0.75, 1.0])
274
+ for ax in axs_col: # bars start at 0.5 (chance); the real-vs-real line sits there, so no spine at lo
275
+ ax.spines["left"].set_visible(False)
276
+ return 0.5
277
+ if metric.startswith("mmd"):
278
+ hi = np.ceil(max(allv) * 1.08 / 0.05) * 0.05
279
+ lo = min(-0.02 * hi, min(allv) - 0.01 * hi)
280
+ S9.shared_x(axs_col, lo, hi, label, [round(t, 2) for t in np.arange(0, hi + 1e-9, 0.1)])
281
+ for ax in axs_col:
282
+ ax.spines["left"].set_visible(False)
283
+ ax.axvline(0, color="#555555", lw=0.8, zorder=1)
284
+ return 0.0
285
+ lo, hi = nice_log_limits(allv)
286
+ for ax in axs_col:
287
+ ax.set_xscale("log")
288
+ ticks = [t for t in (0.01, 0.1, 1, 10, 100, 1000) if lo <= t <= hi]
289
+ S9.shared_x(axs_col, lo, hi, label, ticks)
290
+ for ax in axs_col:
291
+ ax.set_xticklabels([f"{t:g}" for t in ticks])
292
+ ax.xaxis.set_minor_locator(plt.NullLocator())
293
+ return lo
294
+
295
+
296
+ def realism_figure(name, arms, vals_of, ref_of, row_subs, legend_handles, dots, na_text=None, header=None):
297
+ """rows = cohorts, columns = PANELS; vals_of(ds, arm, metric) -> list; ref_of(ds, kind, metric) -> float."""
298
+ leg_rows = -(-len(legend_handles) // 3)
299
+ fig, axs = S9.grid(len(ORDER), len(PANELS), style.FULL, left=S9.LEFT_IN, right=0.25, top=0.45,
300
+ bottom=0.65 + 0.30 * leg_rows, hspace=0.22, wspace=0.12)
301
+ rows = []
302
+ for j, (mk, lab) in enumerate(PANELS):
303
+ allv = [v for ds in ORDER for a in arms for v in vals_of(ds, a, mk) if not np.isnan(v)]
304
+ allv += [ref_of(ds, k, mk) for ds in ORDER for k in ("control", "pseudo")]
305
+ allv = [v for v in allv if not np.isnan(v)]
306
+ base = axis_setup(axs[:, j], mk, allv, lab)
307
+ for i, ds in enumerate(ORDER):
308
+ ax = axs[i, j]
309
+ hbars_base(ax, arms, lambda a: vals_of(ds, a, mk), base, seed=17 * i + j, dots=dots,
310
+ na_text=(na_text or {}).get(ds))
311
+ vline(ax, ref_of(ds, "control", mk), CTRL, len(arms))
312
+ vline(ax, ref_of(ds, "pseudo", mk), S9.REFSTYLE["pseudo"], len(arms))
313
+ for a in arms:
314
+ for v in vals_of(ds, a, mk):
315
+ rows.append({"figure": name, "dataset": ds, "metric": mk, "series": a, "value": v})
316
+ for k in ("control", "pseudo"):
317
+ rows.append({"figure": name, "dataset": ds, "metric": mk, "series": f"ref_{k}",
318
+ "value": ref_of(ds, k, mk)})
319
+ for i, ds in enumerate(ORDER):
320
+ S9.row_label(axs[i, 0], ROWNAME[ds], row_subs(ds))
321
+ if header:
322
+ S9.label_header(axs[0, 0], header)
323
+ S9.legend_bottom(fig, legend_handles, ncol=3)
324
+ S9.check_inside(fig, name)
325
+ style.save(fig, name, FIGDIR)
326
+ return rows
327
+
328
+
329
+ # ------------------------------------------------------------------------------------------
330
+ # Figures
331
+ # ------------------------------------------------------------------------------------------
332
+ FEW_ARMS = ["zs_raw", "zs_cal", "scsemi5", "lora"]
333
+
334
+
335
+ def few_vals(few, ds, arm, mk):
336
+ s = few[(few.dataset == ds) & (few.arm == arm) & (few.metric == mk)].sort_values("draw")
337
+ return [np.nan if u else v for v, u in zip(s.value, s.undefined)]
338
+
339
+
340
+ def few_mean(few, ds, arm, mk):
341
+ v = [x for x in few_vals(few, ds, arm, mk) if not np.isnan(x)]
342
+ return float(np.mean(v)) if v else np.nan
343
+
344
+
345
+ def fig_fewpair(few, info):
346
+ nd = {info[d]["n_draws"] for d in ORDER}
347
+ per_row = len(nd) > 1
348
+ handles = [patch("zs_raw"), patch("zs_cal"), patch("scsemi5"), patch("lora"), ctrl_handle(), S9.refh("pseudo"),
349
+ S9.dot_handle(None if per_row else next(iter(nd)))]
350
+ return realism_figure(
351
+ "sec09_extra_fewpair", FEW_ARMS, lambda ds, a, mk: few_vals(few, ds, a, mk),
352
+ lambda ds, k, mk: few_mean(few, ds, k, mk), lambda ds: S9.row_subs(info[ds], per_row), handles, dots=True,
353
+ header="pairs per draw")
354
+
355
+
356
+ def fig_fivefold(pooled, arms, tab):
357
+ def vals(ds, a, mk):
358
+ d = pooled[ds].get(a)
359
+ return [np.nan] if d is None else [d[mk]]
360
+
361
+ def ref(ds, k, mk):
362
+ return pooled[ds][k][mk]
363
+
364
+ def subs(ds):
365
+ n, nd = tab[ds]
366
+ return [f"n={n}" + (f" ({nd} donors)" if nd != n else "")]
367
+
368
+ handles = [patch(a, LAB["lora_all"] if a == "lora" else None) for a in arms] + [ctrl_handle(), S9.refh("pseudo")]
369
+ na = {ds: {"scsemi_all": "pending"} for ds in ORDER}
370
+ return realism_figure("sec09_extra_fivefold", arms, vals, ref, subs, handles, dots=False, na_text=na)
371
+
372
+
373
+ def fig_ksens(few):
374
+ fig, axs = plt.subplots(2, len(ORDER), figsize=style.FULL, sharey=True,
375
+ gridspec_kw=dict(left=0.075, right=0.995, top=0.93, bottom=0.25, hspace=0.18,
376
+ wspace=0.10))
377
+ xs = np.arange(len(KS))
378
+ rows = []
379
+ mk_style = {"zs_raw": "o", "zs_cal": "o", "scsemi5": "D", "lora": "o"}
380
+ off = {"zs_raw": -0.09, "zs_cal": -0.03, "scsemi5": 0.03, "lora": 0.09}
381
+ for i, q in enumerate(("coverage", "precision")):
382
+ for j, ds in enumerate(ORDER):
383
+ ax = axs[i, j]
384
+ cv = [few_mean(few, ds, "control", f"{q}_k{k}") for k in KS]
385
+ ax.plot(xs, cv, ls=CTRL["ls"], color=CTRL["color"], lw=CTRL["lw"], marker="s", ms=4, zorder=2)
386
+ for k, v in zip(KS, cv):
387
+ rows.append({"figure": "sec09_extra_ksens", "dataset": ds, "metric": f"{q}_k{k}",
388
+ "series": "control", "value": v, "sd": np.nan})
389
+ for a in FEW_ARMS:
390
+ m = [few_mean(few, ds, a, f"{q}_k{k}") for k in KS]
391
+ sd = [float(np.std([x for x in few_vals(few, ds, a, f"{q}_k{k}") if not np.isnan(x)], ddof=1))
392
+ for k in KS]
393
+ ax.errorbar(xs + off[a], m, yerr=sd, color=COL[a], lw=2.0, marker=mk_style[a], ms=6,
394
+ mec=EDGE, mew=0.6, capsize=2.5, elinewidth=1.0, zorder=4 if a == "lora" else 3)
395
+ for k, v, s in zip(KS, m, sd):
396
+ rows.append({"figure": "sec09_extra_ksens", "dataset": ds, "metric": f"{q}_k{k}",
397
+ "series": a, "value": v, "sd": s})
398
+ ax.set_xticks(xs)
399
+ ax.set_xticklabels([str(k) for k in KS])
400
+ ax.set_xlim(-0.4, len(KS) - 0.6)
401
+ ax.set_ylim(0, 1.05)
402
+ ax.set_yticks([0, 0.5, 1.0])
403
+ if i == 0:
404
+ ax.set_title(ROWNAME[ds], fontsize=FS, pad=6)
405
+ ax.tick_params(axis="x", labelbottom=False)
406
+ if j == 0:
407
+ ax.set_ylabel(f"{q.capitalize()} ↑")
408
+ fig.text(0.535, 0.155, "k (nearest neighbours per ball)", ha="center", va="center", fontsize=FS)
409
+ handles = [Line2D([0], [0], color=COL[a], lw=2.0, marker=mk_style[a], ms=6, mec=EDGE, mew=0.6, label=LAB[a])
410
+ for a in FEW_ARMS] + [Line2D([0], [0], ls=CTRL["ls"], color=CTRL["color"], lw=CTRL["lw"], marker="s",
411
+ ms=4, label="Real vs real (held-out cells)")]
412
+ S9.legend_bottom(fig, handles, ncol=3)
413
+ style.save(fig, "sec09_extra_ksens", FIGDIR)
414
+ return rows
415
+
416
+
417
+ # ------------------------------------------------------------------------------------------
418
+ # Comparisons for the slide text
419
+ # ------------------------------------------------------------------------------------------
420
+ def better(a, b, sign):
421
+ """a better than b (NaN = undefined E_N ranks last)."""
422
+ if np.isnan(a):
423
+ return False
424
+ if np.isnan(b):
425
+ return True
426
+ return (abs(a - 0.5) < abs(b - 0.5)) if sign == 0 else (a > b if sign > 0 else a < b)
427
+
428
+
429
+ def few_wide(few, mk):
430
+ s = few[few.metric == mk].copy()
431
+ s.loc[s.undefined, "value"] = np.nan
432
+ return s.pivot_table(index=["dataset", "draw"], columns="arm", values="value", dropna=False)
433
+
434
+
435
+ def few_compare(few, comps=("scsemi5", "zs_raw", "zs_cal")):
436
+ """Per cohort x comparator x metric: draws where LoRA-5 is better / worse / tied."""
437
+ out = []
438
+ for c, _, sign in HEAD:
439
+ w = few_wide(few, c)
440
+ for ds in ORDER:
441
+ x = w.loc[ds]
442
+ for comp in comps:
443
+ xx = x[["lora", comp]].dropna(how="all")
444
+ nb = sum(better(a, b, sign) for a, b in zip(xx.lora, xx[comp]))
445
+ nw = sum(better(b, a, sign) for a, b in zip(xx.lora, xx[comp]))
446
+ out.append(dict(dataset=ds, comp=comp, metric=c, n=len(xx), n_better=nb, n_worse=nw,
447
+ lora=float(np.nanmean(xx.lora)), other=float(np.nanmean(xx[comp]))))
448
+ return pd.DataFrame(out)
449
+
450
+
451
+ def best_draws(few, mk, arms=FEW_ARMS):
452
+ """Draws where LoRA-5 is best of the arms on one metric."""
453
+ sign = DIRS[mk]
454
+ w = few_wide(few, mk)
455
+ n = 0
456
+ for _, r in w.iterrows():
457
+ n += all(better(r["lora"], r[a], sign) for a in arms if a != "lora")
458
+ return n, len(w)
459
+
460
+
461
+ def fmt_metric(c, v):
462
+ return f"{v:.4f}" if c.startswith("mmd") else (f"{v:.2f}" if c.startswith("en_") else f"{v:.3f}")
463
+
464
+
465
+ def exceptions_text(exc):
466
+ """'vs zero-shot + calibration: Imperial E_N (all cells) 3/5 (1.28 vs 1.22), ...' grouped by comparator / cohort."""
467
+ parts = []
468
+ for comp, g in exc.groupby("comp", sort=True):
469
+ items = []
470
+ for ds in ORDER:
471
+ h = g[g.dataset == ds]
472
+ if len(h):
473
+ items.append(f"{NAME[ds]} " + ", ".join(
474
+ f"{SHORT[r.metric]} {r.n_worse}/{r.n} ({fmt_metric(r.metric, r.lora)} vs "
475
+ f"{fmt_metric(r.metric, r.other)})" for r in h.itertuples()))
476
+ parts.append(f"vs {S9.LAB[comp].lower()}: " + "; ".join(items))
477
+ return " | ".join(parts)
478
+
479
+
480
+ def rng2(v, nd=2):
481
+ v = [x for x in v if not np.isnan(x)]
482
+ a, b = f"{min(v):.{nd}f}", f"{max(v):.{nd}f}"
483
+ return a if a == b else f"{a}–{b}"
484
+
485
+
486
+ # ------------------------------------------------------------------------------------------
487
+ def main():
488
+ FIGDIR.mkdir(parents=True, exist_ok=True)
489
+ OUTDATA.mkdir(parents=True, exist_ok=True)
490
+ few, info = load_fewpair()
491
+ pooled, sclog = load_pooled()
492
+ n_checked = check_headline(few, pooled)
493
+ sclog.to_csv(OUTDATA / "sec09_extra_scsemi_status.csv", index=False)
494
+ tab = {}
495
+ for ds in ORDER:
496
+ dj = json.loads((T / "data" / ds / "fewshot_n5" / "DRAWS.json").read_text())
497
+ n = int(json.loads((T / "scores" / ds / "pooled" / "summary.json").read_text())["n_donors"])
498
+ if n != int(dj["n_usable_rows"]):
499
+ raise ValueError(f"{ds}: pooled n {n} != usable rows")
500
+ tab[ds] = (n, int(dj["n_usable_donors"]))
501
+ has_sc = [ds for ds in ORDER if "scsemi_all" in pooled[ds]]
502
+ arms5 = ["zs_raw", "zs_cal", "sconly_cal"] + (["scsemi_all"] if has_sc else []) + ["lora"]
503
+
504
+ rows_a = fig_fewpair(few, info)
505
+ rows_b = fig_fivefold(pooled, arms5, tab)
506
+ rows_c = fig_ksens(few)
507
+ srcf = f"{X}/<cohort>/fewshot_n5/draw<j>/{{metrics,en}}.csv"
508
+ srcp = f"{X}/<cohort>/pooled/{{metrics,en}}.csv"
509
+ pd.DataFrame(rows_a).assign(source=srcf).to_csv(OUTDATA / "sec09_extra_fewpair.csv", index=False,
510
+ float_format="%.6g")
511
+ pd.DataFrame(rows_b).assign(source=srcp).to_csv(OUTDATA / "sec09_extra_fivefold.csv", index=False,
512
+ float_format="%.6g")
513
+ pd.DataFrame(rows_c).assign(source=srcf).to_csv(OUTDATA / "sec09_extra_ksens.csv", index=False,
514
+ float_format="%.6g")
515
+ slides = []
516
+
517
+ # ---------------- slide a: 5 donors, realism beyond P/C ----------------
518
+ cmp = few_compare(few)
519
+ nb_knn, ntot = best_draws(few, "c2st_knn_auc")
520
+ nb_rf, _ = best_draws(few, "c2st_rf_auc")
521
+ nb_nn1, _ = best_draws(few, "nn1_acc")
522
+ nb_mmd, _ = best_draws(few, "mmd2_bw1")
523
+ nb_en, _ = best_draws(few, "en_all_sq")
524
+ en_sc = cmp[(cmp.comp == "scsemi5") & (cmp.metric == "en_all_sq")]
525
+ en_sc_better, en_sc_n = int(en_sc.n_better.sum()), int(en_sc.n.sum())
526
+ auc_l = [few_mean(few, d, "lora", "c2st_knn_auc") for d in ORDER]
527
+ auc_draws = few[(few.arm == "lora") & (few.metric == "c2st_knn_auc")].value
528
+ kw1 = S9.keyword_or_short(f"Classifier AUC: LoRA-5 best in {nb_knn}/{ntot} draws",
529
+ f"AUC: LoRA-5 best in {nb_knn}/{ntot} draws")
530
+ kw2 = f"E_N: LoRA-5 below scSemi-5 in {en_sc_better}/{en_sc_n} draws"
531
+ kw3 = f"Still separable: LoRA-5 AUC {rng2(auc_l)}"
532
+ kw_a = S9.check_keywords([kw1, kw2, kw3])
533
+ # exceptions over every headline metric (LoRA-5 worse in >= 1 draw)
534
+ exc = cmp[cmp.n_worse > 0].copy()
535
+ exc_comps = sorted(set(exc.comp))
536
+ drawn = {m for m, _ in PANELS}
537
+ exc_drawn = exc[exc.metric.isin(drawn)].sort_values(["n_worse", "dataset"], ascending=[False, True])
538
+ if exc.empty:
539
+ fs_a = "E_N: scSemiProfiler's own error metric. LoRA-5 best of the 4 arms on every metric in every draw."
540
+ elif exc_comps == ["zs_cal"]:
541
+ e0 = exc_drawn.iloc[0] if len(exc_drawn) else exc.sort_values("n_worse", ascending=False).iloc[0]
542
+ nd = 2 if e0.metric.startswith("en_") else 3
543
+ fs_a = (f"E_N: scSemiProfiler's own error metric. Misses only vs calibration, e.g. {NAME[e0.dataset]} "
544
+ f"{SHORT[e0.metric].split(' (')[0]} {e0.lora:.{nd}f} vs {e0.other:.{nd}f}.")
545
+ else:
546
+ fs_a = (f"E_N: scSemiProfiler's own error metric. LoRA-5 behind in {len(exc)} cohort × arm × metric cases; "
547
+ f"see notes.")
548
+ fs_a = S9.check_foot_short(fs_a)
549
+ rf_l = [few_mean(few, d, "lora", "c2st_rf_auc") for d in ORDER]
550
+ ctrl_auc = [few_mean(few, d, "control", "c2st_knn_auc") for d in ORDER]
551
+ ctrl_en = [few_mean(few, d, "control", "en_all_sq") for d in ORDER]
552
+ nn_c = cmp[cmp.metric.isin(["c2st_knn_auc", "c2st_rf_auc", "nn1_acc"] + [f"coverage_k{k}" for k in KS])]
553
+ wins_all = (nn_c.n_better == nn_c.n).all()
554
+ exc_txt = exceptions_text(exc)
555
+ en_means = "; ".join(f"{NAME[d]} {few_mean(few, d, 'scsemi5', 'en_all_sq'):.2f} vs "
556
+ f"{few_mean(few, d, 'lora', 'en_all_sq'):.2f}" for d in ORDER)
557
+ foot_a = (f"Same 5-donor draws as the previous slides; every metric on exactly the scored cells (scores_extra/, "
558
+ f"tools/extra_metrics.py). Real side for AUC and MMD² = held-out real cells of the same samples (R2), "
559
+ f"projected like the generated cells; real vs real = R2 vs R3 (AUC {rng2(ctrl_auc)}). Classifier AUC: "
560
+ f"5-fold CV ROC AUC of a kNN classifier (k = 5) separating real from generated cells, 0.5 = "
561
+ f"indistinguishable; bars start at 0.5. MMD²: unbiased, Gaussian kernel, bandwidth = median distance "
562
+ f"among real cells. E_N: scSemiProfiler's normalized error (Wang et al. 2024, eq. 17–18), their code's "
563
+ f"squared L2 on all cells, per-arm PCA-100; real vs real = within-sample half split "
564
+ f"({rng2(ctrl_en)}); every generated arm is above 1. LoRA-5 best of the 4 arms in {nb_knn}/{ntot} "
565
+ f"draws on kNN AUC, {nb_rf}/{ntot} on RF AUC, {nb_nn1}/{ntot} on 1-NN accuracy, {nb_mmd}/{ntot} on MMD², "
566
+ f"{nb_en}/{ntot} on E_N. "
567
+ + ("LoRA-5 better than scSemi-5, zero-shot and zero-shot + calibration on both AUCs, 1-NN accuracy and "
568
+ "coverage at k = 3, 5, 10 in every draw. " if wins_all else "")
569
+ + f"E_N scSemi-5 vs LoRA-5 (cohort means): {en_means}; LoRA-5 lower in {en_sc_better}/{en_sc_n} draws. "
570
+ f"Draws where LoRA-5 is worse (cohort means in brackets): {exc_txt if len(exc) else 'none'}. "
571
+ f"LoRA-5 AUC per draw "
572
+ f"{auc_draws.min():.2f}–{auc_draws.max():.2f} (kNN), RF cohort means {rng2(rf_l)}: a classifier still "
573
+ f"tells generated from real cells. Scores: scores_extra/<cohort>/fewshot_n5/draw<j>/.")
574
+ S9.check_text(foot_a, "footnote")
575
+ num("a", f"LoRA-5 best of 4 arms (draws): kNN AUC {nb_knn}/{ntot}, RF AUC {nb_rf}/{ntot}, 1-NN {nb_nn1}/{ntot}, "
576
+ f"MMD² {nb_mmd}/{ntot}, E_N {nb_en}/{ntot}", srcf)
577
+ num("a", f"E_N LoRA-5 < scSemi-5 in {en_sc_better}/{en_sc_n} draws; cohort means scSemi-5 vs LoRA-5: {en_means}",
578
+ f"{X}/<cohort>/fewshot_n5/draw<j>/en.csv (cellset all, distance sq)")
579
+ num("a", "LoRA-5 kNN AUC cohort means: " + ", ".join(f"{NAME[d]} {v:.3f}" for d, v in zip(ORDER, auc_l)) +
580
+ f"; per draw {auc_draws.min():.3f}–{auc_draws.max():.3f}", srcf)
581
+ num("a", "real vs real: kNN AUC " + ", ".join(f"{NAME[d]} {v:.3f}" for d, v in zip(ORDER, ctrl_auc)) +
582
+ "; E_N " + ", ".join(f"{NAME[d]} {v:.3f}" for d, v in zip(ORDER, ctrl_en)), srcf)
583
+ num("a", f"LoRA-5 worse than a comparator (draws): {exc_txt if len(exc) else 'none'}", srcf)
584
+ num("a", f"cross-check: {n_checked} cohort × arm × metric values equal scores_extra/{{fewshot,pooled}}_headline.csv",
585
+ f"{X}/fewshot_headline.csv; {X}/pooled_headline.csv")
586
+ slides.append({"title": "5 donors: realism beyond precision/coverage", "layout": "full",
587
+ "figures": [str(FIGDIR / "sec09_extra_fewpair.png")], "keywords": kw_a, "footnote": foot_a,
588
+ "footnote_short": fs_a, "numbers": NUMS["a"]})
589
+
590
+ # ---------------- slide b: 5-fold pooled ----------------
591
+ comps = [a for a in arms5 if a != "lora"]
592
+ first = {}
593
+ for c, _, sign in HEAD:
594
+ first[c] = [ds for ds in ORDER if all(better(pooled[ds]["lora"][c], pooled[ds][a][c], sign)
595
+ for a in comps if a in pooled[ds])]
596
+ n_all = sum(len(v) == len(ORDER) for v in first.values())
597
+ if n_all == len(HEAD):
598
+ kwb1 = f"Every metric: LoRA first in {len(ORDER)}/{len(ORDER)} cohorts"
599
+ else:
600
+ kwb1 = f"LoRA first everywhere on {n_all}/{len(HEAD)} metrics"
601
+ ji = pooled["ji2025_chili"]
602
+ oth = [ji[a]["en_all_sq"] for a in comps if a in ji]
603
+ kwb2 = S9.keyword_or_short(f"Ji whole blood: E_N {ji['lora']['en_all_sq']:.1f} vs {rng2(oth, 1)}",
604
+ f"Ji: E_N {ji['lora']['en_all_sq']:.1f} vs {rng2(oth, 1)}")
605
+ auc_p = [pooled[d]["lora"]["c2st_knn_auc"] for d in ORDER]
606
+ kwb3 = f"Still separable: LoRA AUC {rng2(auc_p)}"
607
+ kw_b = S9.check_keywords([kwb1, kwb2, kwb3])
608
+ fs_b = S9.check_foot_short("Donor-level 5-fold CV, one pooled call per cohort. E_N: scSemiProfiler's own error "
609
+ "metric.")
610
+ lost = {SHORT[c]: [NAME[d] for d in ORDER if d not in v] for c, v in first.items() if len(v) < len(ORDER)}
611
+ sc_txt = (f"scSemiProfiler, all training pairs (every training donor of the fold, inner-val included, as "
612
+ f"representatives; arm {SR.CV_ARM}) drawn for {', '.join(NAME[d] for d in has_sc)}; sources: "
613
+ + "; ".join(f"{NAME[d]} {pooled[d]['scsemi_all']['source']}" for d in has_sc) + ". "
614
+ if has_sc else "scSemiProfiler 5-fold CV not available yet (no extra-metric unit with set "
615
+ f"{SR.CV_ARM}). ")
616
+ foot_b = (f"Donor-level 5-fold CV; each pair scored once by the fold model that never trained on its donor (one "
617
+ f"pooled call per cohort, all cross-fitted pairs). Arms as on the 5-fold slide. Metric definitions as on "
618
+ f"the 5-donor realism slide. LoRA first among the {len(comps) + 1} arms in all {len(ORDER)} cohorts on "
619
+ f"{n_all}/{len(HEAD)} headline metrics (kNN and RF AUC, 1-NN accuracy, MMD² at σ = m and summed, E_N all "
620
+ f"cells, precision and coverage at k = 3, 5, 10)"
621
+ + (f"; exceptions: " + "; ".join(f"{k}: {', '.join(v)}" for k, v in lost.items()) if lost else "")
622
+ + f". LoRA kNN AUC " + ", ".join(f"{NAME[d]} {v:.3f}" for d, v in zip(ORDER, auc_p))
623
+ + f"; real vs real " + ", ".join(f"{NAME[d]} {pooled[d]['control']['c2st_knn_auc']:.3f}" for d in ORDER)
624
+ + ". E_N LoRA vs other arms: " + "; ".join(
625
+ f"{NAME[d]} {pooled[d]['lora']['en_all_sq']:.2f} vs {rng2([pooled[d][a]['en_all_sq'] for a in comps if a in pooled[d]])}"
626
+ for d in ORDER)
627
+ + f". {sc_txt}Scores: scores_extra/<cohort>/pooled/.")
628
+ S9.check_text(foot_b, "footnote")
629
+ num("b", f"LoRA first among {len(comps) + 1} arms in all {len(ORDER)} cohorts on {n_all}/{len(HEAD)} metrics", srcp)
630
+ num("b", f"Ji E_N: LoRA {ji['lora']['en_all_sq']:.3f}; " +
631
+ ", ".join(f"{LAB[a]} {ji[a]['en_all_sq']:.3f}" for a in comps if a in ji), srcp)
632
+ num("b", "LoRA kNN AUC (pooled): " + ", ".join(f"{NAME[d]} {v:.3f}" for d, v in zip(ORDER, auc_p)), srcp)
633
+ num("b", "scSemiProfiler, all training pairs: " + (", ".join(NAME[d] for d in has_sc) if has_sc else "not available"),
634
+ OUTDATA / "sec09_extra_scsemi_status.csv")
635
+ slides.append({"title": "5-fold: realism beyond precision/coverage", "layout": "full",
636
+ "figures": [str(FIGDIR / "sec09_extra_fivefold.png")], "keywords": kw_b, "footnote": foot_b,
637
+ "footnote_short": fs_b, "numbers": NUMS["b"]})
638
+
639
+ # ---------------- slide c: k sensitivity ----------------
640
+ sets_k = FEW_ARMS + ["control"]
641
+ mono = all(few_mean(few, d, a, f"{q}_k3") <= few_mean(few, d, a, f"{q}_k5") <= few_mean(few, d, a, f"{q}_k10")
642
+ for d in ORDER for a in sets_k for q in ("coverage", "precision"))
643
+ ctrl_c3 = [few_mean(few, d, "control", "coverage_k3") for d in ORDER]
644
+ kwc1 = ("Smaller k lowers every set, real included" if mono else
645
+ f"Real vs real coverage at k = 3: {rng2(ctrl_c3)}")
646
+ cov_all_k = 0
647
+ wc = {k: few_wide(few, f"coverage_k{k}") for k in KS}
648
+ for idx in wc[10].index:
649
+ cov_all_k += all(all(better(wc[k].loc[idx, "lora"], wc[k].loc[idx, a], 1) for a in FEW_ARMS if a != "lora")
650
+ for k in KS)
651
+ kwc2 = f"Coverage: LoRA-5 first at all k, {cov_all_k}/{len(wc[10])}"
652
+ pb = [best_draws(few, f"precision_k{k}")[0] for k in KS]
653
+ kwc3 = f"Precision: LoRA-5 first in {min(pb)}–{max(pb)}/{ntot} draws" if min(pb) != max(pb) else \
654
+ f"Precision: LoRA-5 first in {pb[0]}/{ntot} draws"
655
+ kw_c = S9.check_keywords([kwc1, kwc2, kwc3])
656
+ fs_c = S9.check_foot_short("5 donors, 5 draws per cohort; error bars = SD over draws. k = 10 is the value on the main "
657
+ "slides.")
658
+ # who beats LoRA-5 on precision, per k
659
+ who_n, who_arms = {}, set()
660
+ for k in KS:
661
+ w = few_wide(few, f"precision_k{k}")
662
+ for (d, j), r in w.iterrows():
663
+ b = [a for a in FEW_ARMS if a != "lora" and not better(r["lora"], r[a], 1)]
664
+ if b:
665
+ who_n.setdefault(d, {kk: 0 for kk in KS})[k] += 1
666
+ who_arms.update(b)
667
+ who = ", ".join(f"{NAME[d]} {'/'.join(str(who_n[d][k]) for k in KS)}" for d in ORDER if d in who_n)
668
+ who = (f"{who} draws at k = 3/5/10, beaten by {' or '.join(S9.LAB[a].lower() for a in sorted(who_arms))}"
669
+ if who else "none")
670
+ exp_cov = {}
671
+ for d in ORDER:
672
+ mt = pd.concat([pd.read_csv(u / "metrics.csv") for u in sorted((X / d / "fewshot_n5").glob("draw*"))])
673
+ mt = mt[(mt["set"] == "lora5") & (mt.real_side == "R1") & (mt["mode"] == "raw")]
674
+ exp_cov[d] = "/".join(f"{mt[f'expected_coverage_identical_k{k}'].mean():.2f}" for k in KS)
675
+ exp_cov = (f"{next(iter(exp_cov.values()))} in every cohort" if len(set(exp_cov.values())) == 1
676
+ else "; ".join(f"{NAME[d]} {v}" for d, v in exp_cov.items()))
677
+ same_rank, lora_top = [], []
678
+ for d in ORDER:
679
+ r = {k: sorted([a for a in arms5 if a in pooled[d]], key=lambda a: -pooled[d][a][f"coverage_k{k}"]) for k in KS}
680
+ same_rank.append(r[3] == r[5] == r[10])
681
+ lora_top.append(all(r[k][0] == "lora" for k in KS))
682
+ pooled_rank = (f"{'unchanged' if all(same_rank) else 'changes in ' + ', '.join(NAME[d] for d, x in zip(ORDER, same_rank) if not x)}"
683
+ f"; LoRA first at every k in {sum(lora_top)}/{len(ORDER)} cohorts")
684
+ foot_c = (f"Precision and coverage recomputed with k = 3, 5, 10 nearest-neighbour balls in the scorer's PCA-50 "
685
+ f"(k = 10 reproduces the main-slide values exactly). Means over the 5 draws per cohort; error bars = SD; "
686
+ f"grey = real vs real (R1 vs R2, same samples). Both metrics fall with smaller k for every set "
687
+ f"{'including' if mono else 'but not always'} the real control (real coverage at k = 3: {rng2(ctrl_c3)}), "
688
+ f"so compare arms with the real row, not with 1. Expected coverage of a perfect generator (Naeem et al. "
689
+ f"2020, eq. 9) at k = 3/5/10: {exp_cov}. LoRA-5 first on coverage at every k in "
690
+ f"{cov_all_k}/{len(wc[10])} draws; on precision in {'/'.join(map(str, pb))} of {ntot} draws "
691
+ f"(k = 3/5/10); not first: {who}. 5-fold pooled design (not drawn): "
692
+ f"coverage ranking of the {len(arms5)} arms across k {pooled_rank}. Scores: "
693
+ f"scores_extra/<cohort>/fewshot_n5/draw<j>/metrics.csv.")
694
+ S9.check_text(foot_c, "footnote")
695
+ num("c", f"LoRA-5 first on coverage at k = 3, 5 and 10: {cov_all_k}/{len(wc[10])} draws", srcf)
696
+ num("c", f"LoRA-5 first on precision (draws) at k = 3/5/10: {'/'.join(map(str, pb))} of {ntot}", srcf)
697
+ num("c", "real vs real coverage at k = 3: " + ", ".join(f"{NAME[d]} {v:.3f}" for d, v in zip(ORDER, ctrl_c3)), srcf)
698
+ num("c", f"every set falls with smaller k (cohort means): {mono}", srcf)
699
+ slides.append({"title": "5 donors: precision/coverage at k = 3, 5, 10", "layout": "full",
700
+ "figures": [str(FIGDIR / "sec09_extra_ksens.png")], "keywords": kw_c, "footnote": foot_c,
701
+ "footnote_short": fs_c, "numbers": NUMS["c"]})
702
+
703
+ for s in slides:
704
+ for k in ("title", "footnote", "footnote_short"):
705
+ S9.check_text(s[k], k)
706
+ for n in s["numbers"]:
707
+ S9.check_text(n["value"], "quoted number")
708
+ spec = {"section": "09-extra", "slides": slides, "scripts": [str(SCRIPT)],
709
+ "generated_from": "tools/sec09_extra_metrics.py (rerun to refresh; do not edit by hand)",
710
+ "scsemi_cv_cohorts": [NAME[d] for d in has_sc]}
711
+ (OUTDATA / "sec09_extra_slide_text.json").write_text(json.dumps(spec, indent=1, ensure_ascii=False))
712
+ pd.DataFrame([{"slide": k, "value": n["value"], "source": n["source"]} for k in "abc" for n in NUMS[k]]).to_csv(
713
+ OUTDATA / "sec09_extra_quoted_numbers.csv", index=False)
714
+ for p in [OUTDATA / "sec09_extra_slide_text.json"] + sorted(OUTDATA.glob("sec09_extra_*.csv")):
715
+ m = S9.OFF_STORY.search(p.read_text(encoding="utf-8"))
716
+ if m:
717
+ raise ValueError(f"{p}: off-story text {m.group(0)!r}")
718
+
719
+ print(f"cross-checked {n_checked} values against the collector's headline tables")
720
+ if not has_sc:
721
+ print(f"NOTE: no scSemiProfiler 5-fold extra-metric unit (set {SR.CV_ARM}) under "
722
+ f"{SR.plan_root()}/scores_extra/<ds>/{SR.CV_EXP}/ or in the pooled units; the 5-fold figure has no "
723
+ f"scSemiProfiler row.")
724
+ else:
725
+ print(f"scSemiProfiler, all training pairs drawn for: {[NAME[d] for d in has_sc]}")
726
+ for r in sclog.itertuples():
727
+ print(f" scSemiProfiler extra unit {r.dataset} {r.design} {r.set}: {r.status} {r.reason} ({r.unit})")
728
+ for s in slides:
729
+ print(f"\n== {s['title']}")
730
+ for k in s["keywords"]:
731
+ print(" *", k, f"({S9.n_words(k)} words, {len(k)} chars)")
732
+ print(" footnote_short:", s["footnote_short"], f"({len(s['footnote_short'])} chars)")
733
+ print(" footnote:", s["footnote"])
734
+ return 0
735
+
736
+
737
+ if __name__ == "__main__":
738
+ sys.exit(main())
paper-releases/pbisc-diffusion/updates/20261002T002920Z-deck-extra-metrics-scsemi-prep/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec09_paired_validation.py ADDED
@@ -0,0 +1,1531 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Section 9 of the 2026-09-30 paper-summary deck: the final method in five paired cohorts,
3
+ and scSemiProfiler trained on the same 5 donors.
4
+
5
+ CPU only: reads score files, draws slide-sized figures. No torch, no CUDA, no generation, no scANVI.
6
+
7
+ Data loading is imported unchanged from the benchmark's own figure script
8
+ (plans/paired_finetune_intradataset_20260927/figures/make_figures.py: load_fewpair, load_pooled),
9
+ so every plotted number and every scSemiProfiler acceptance check (same donor set, same reference
10
+ sha, receipt verified) is the same as in the paper figures. Only the drawing is new.
11
+
12
+ Outputs (deck folder):
13
+ figures/sec09_cohorts.{png,pdf} slide a: five paired cohorts (table)
14
+ figures/sec09_fewpair_cells.{png,pdf} slide b: 5 donors, cell-level metrics
15
+ figures/sec09_fewpair_disease.{png,pdf} slide c: 5 donors, disease signal
16
+ figures/sec09_fivefold.{png,pdf} slide d: all pairs, 5-fold pooled
17
+ data/sec09_*.csv every plotted number with its source file
18
+ data/sec09_slide_text.json slide titles, keywords, footnotes (long "footnote" for the speaker
19
+ notes + one-line "footnote_short") and quoted numbers (+ sources),
20
+ all built by this script from the same data as the figures
21
+ data/sec09_quoted_numbers.csv the quoted numbers as a flat table
22
+
23
+ Baselines (user decisions 2026-09-30 and 2026-10-01): the no-fine-tune baseline is zero-shot on the real bulk as
24
+ measured (few-pair arm zs_raw, pooled arm zs__raw). The gene-wise calibration comparator is back (2026-10-01) and is
25
+ called "Zero-shot + calibration" (few-pair arm zs_cal, alpha fitted on the same 5 training donors; pooled arm zs__cal,
26
+ alpha from each fold's training donors). The sc-only control is the sc-only fine-tune fed calibrated bulk (pooled arm
27
+ pseudo_full__cal, "sc-only fine-tune (+ calibration)"). OFF_STORY still bans refcal / reference calibration, VAE,
28
+ TPM, AIFI and AIDA wording in every output.
29
+
30
+ Giroux (user decision 2026-10-01): severity is confounded with sex, so its disease-signal metrics (logFC r, partial r,
31
+ top-50 DEG, broadcast) are read from scores_nosex/giroux2022/ (tools/rescore_excluding_genes.py: the same calls with
32
+ data/sex_linked_genes/sex_linked_genes_exclude.csv excluded and the same frozen labels). Every other Giroux metric is
33
+ asserted equal to the original scores/ files. The other cohorts use scores/ unchanged.
34
+
35
+ scSemiProfiler with all training pairs (5-fold CV, arm scsemi__raw; added 2026-10-02): drawn as its own bar on the 5-fold
36
+ slide when an accepted pooled call exists at scores/<ds>/scsemi_cv_20261002/pooled*/ (tools/scsemi_results.py: same donors,
37
+ same reference cells, receipt not unverified). Giroux's disease metrics for it are read from
38
+ scores_nosex/giroux2022/scsemi_cv_20261002/ when that rescore exists, else left blank ("rescore pending"). Without any
39
+ accepted call a note is printed and the slide is unchanged. DECK_FIGDIR / DECK_OUTDATA redirect the outputs and
40
+ DECK_SCSEMI_PLAN_ROOT the scSemiProfiler lookup (synthetic presence test).
41
+
42
+ RERUN CHECKLIST (all 25 scSemiProfiler draws are scored; rerun whenever a score file changes):
43
+ 1. /home/sj_server_1/miniforge3/bin/python3 tools/sec09_paired_validation.py (no edits needed; must exit 0)
44
+ 2. Rebuild the four slides from data/sec09_slide_text.json: every title, keyword line, footnote and quoted
45
+ number there is regenerated. Do not keep hand-copied slide text.
46
+ 3. Look at the four PNGs again.
47
+ """
48
+ from __future__ import annotations
49
+
50
+ import os
51
+
52
+ os.environ["CUDA_VISIBLE_DEVICES"] = "" # plotting only
53
+
54
+ import gzip
55
+ import importlib
56
+ import importlib.util
57
+ import json
58
+ import re
59
+ import sys
60
+ from pathlib import Path
61
+
62
+ import numpy as np
63
+ import pandas as pd
64
+ from scipy.stats import wilcoxon
65
+
66
+ DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/"
67
+ "2026-09-30--paper-summary--r00")
68
+ T = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/"
69
+ "paired_finetune_intradataset_20260927")
70
+ SCORES = T / "scores"
71
+ DATA = T / "data"
72
+ FIGDIR = Path(os.environ.get("DECK_FIGDIR", str(DECK / "figures")))
73
+ OUTDATA = Path(os.environ.get("DECK_OUTDATA", str(DECK / "data")))
74
+ SCRIPT = DECK / "tools" / "sec09_paired_validation.py"
75
+ DATALAKE = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc")
76
+
77
+ # 1) the benchmark's loaders (this import sets print-size rcParams) ...
78
+ _spec = importlib.util.spec_from_file_location("pf_make_figures", T / "figures" / "make_figures.py")
79
+ mf = importlib.util.module_from_spec(_spec)
80
+ _spec.loader.exec_module(mf)
81
+ # 2) ... then the deck style, which must win the rcParams
82
+ sys.path.insert(0, str(DECK / "tools"))
83
+ import style # noqa: E402
84
+ import scsemi_results as SR # noqa: E402
85
+
86
+ importlib.reload(style)
87
+ import matplotlib.pyplot as plt # noqa: E402
88
+ from matplotlib.lines import Line2D # noqa: E402
89
+ from matplotlib.patches import Patch # noqa: E402
90
+ from matplotlib.ticker import MaxNLocator # noqa: E402
91
+
92
+ # deck order: healthy first, whole-blood cohort last
93
+ ORDER = ["immicro", "ye2026_sepsis", "imperial_eskd", "giroux2022", "ji2025_chili"]
94
+ DISEASE = [d for d in ORDER if d != "immicro"]
95
+ NAME = {"immicro": "ImMicro", "ye2026_sepsis": "Sepsis", "imperial_eskd": "Imperial",
96
+ "giroux2022": "Giroux", "ji2025_chili": "Ji"}
97
+ ROWNAME = {**NAME, "ji2025_chili": "Ji (whole blood)"}
98
+ # pale = raw real bulk, #0072B2 = calibrated (the pair used by sections 7 and 8 and the paper figures)
99
+ COL = {"zs_raw": style.ARM["zs_raw"], "zs_cal": style.ARM["zs_cal"], "scsemi5": style.ARM["scsemi"],
100
+ "lora": style.ARM["lora"], "sconly_cal": style.ARM["sconly"], "scsemi_all": style.ARM["scsemi"]}
101
+ LAB = {"zs_raw": "Zero-shot, real bulk", "zs_cal": "Zero-shot + calibration", "scsemi5": "scSemiProfiler, 5 donors",
102
+ "lora": "LoRA, 5 donors", "sconly_cal": "sc-only fine-tune (+ calibration)",
103
+ "lora_all": "LoRA, all training pairs", "scsemi_all": SR.LABEL_CV}
104
+ # few-pair arms kept from load_fewpair (canonical key -> arm name in summary.json); everything else is dropped
105
+ ARM_FILE = {"lora": "lora5", "scsemi5": "scsemi5", "zs_raw": "zs_raw", "zs_cal": "zs_cal", "pseudo": "zs_pseudo"}
106
+ # pooled 5-fold arms (plot key -> arm name in scores/<cohort>/pooled/summary.json)
107
+ POOLED_ARMS = {"zs_raw": "zs__raw", "zs_cal": "zs__cal", "sconly_cal": "pseudo_full__cal", "lora": "real_lora__raw"}
108
+ SC_ALL = "scsemi_all" # plot key of scSemiProfiler with all training pairs (pooled arm SR.CV_ARM), drawn when present
109
+ POOLED_FILE = {**POOLED_ARMS, SC_ALL: SR.CV_ARM}
110
+ # text that must not appear in any figure, CSV label or slide text of this section ("calibration" itself is allowed)
111
+ OFF_STORY = re.compile(r"refcal|reference[ -]calibrat|\bVAE\b|\bTPM\b|\bAIFI\b|\bAIDA\b", re.I)
112
+ # Giroux: disease-signal metrics without sex-linked genes (see module docstring)
113
+ SCORES_NOSEX = T / "scores_nosex"
114
+ NOSEX = ("giroux2022",)
115
+ SEXLIST = DATA / "sex_linked_genes" / "sex_linked_genes_exclude.csv"
116
+ DISEASE_KEYS = ("contrast_r", "broadcast_r", "deg", "deg_broadcast", "deg_max", "r_type", "bc_type")
117
+ KW_MAX_CHARS = 45 # keyword line length on the slide
118
+ FOOT_SHORT_MAX = 110 # one-line on-slide footnote
119
+ REFSTYLE = {"pseudo": dict(ls=(0, (4, 2)), color=style.ARM["pseudo"], lw=1.6, label="Zero-shot, sc pseudobulk input"),
120
+ "broadcast": dict(ls=(0, (1, 1.2)), color=style.ARM["broadcast"], lw=2.4, label="Real-bulk broadcast")}
121
+ EDGE = "#333333"
122
+ SUB = "#595959"
123
+ FS = style.FS
124
+ HILITE = "#FFF3D1"
125
+ LEFT_IN = 2.25 # room for the row labels (cohort + train/test pairs)
126
+ WIN_FRAC = 0.8 # a cohort verdict needs one method better in >= 80 % of the shared draws
127
+ QC = {d: DATA / d / "QC_REPORT.md" for d in DISEASE}
128
+ ARGS = T / "tools" / "contrast_args.sh"
129
+ README = T / "README.md"
130
+ SCORE_FT = T / "tools" / "score_ft.py"
131
+ PREPARE = T / "tools" / "prepare_dataset.py"
132
+ INV = DATALAKE / "docs" / "dataset_inventory.csv"
133
+ SOFT_SC = DATALAKE / "datasets" / "GSE314416" / "metadata" / "GSE314416_family.soft.gz"
134
+ SOFT_BULK = DATALAKE / "datasets" / "GSE314922" / "metadata" / "GSE314922_family.soft.gz"
135
+
136
+ CKPT = "runs/f01_6k_1x_seed20260627/checkpoint_epoch_016.pt"
137
+ NUMS = {k: [] for k in "abcd"} # slide -> [{"value", "source"}] quoted on the slide
138
+ EXTRA = [] # further numbers written to the CSV only
139
+
140
+
141
+ def num(slide, value, source):
142
+ NUMS[slide].append({"value": str(value), "source": str(source)})
143
+
144
+
145
+ def extra(slide, item, value, source):
146
+ EXTRA.append({"slide": slide, "item": item, "value": str(value), "source": str(source)})
147
+
148
+
149
+ def rng(vals, fmt="{:d}"):
150
+ vals = sorted(set(vals))
151
+ return fmt.format(vals[0]) if len(vals) == 1 else f"{fmt.format(vals[0])}–{fmt.format(vals[-1])}"
152
+
153
+
154
+ # ------------------------------------------------------------------------------------------
155
+ # Evidence: every label on the cohort table must match ONE line of its source file
156
+ # ------------------------------------------------------------------------------------------
157
+ _TEXT_CACHE: dict = {}
158
+
159
+
160
+ def _read_text(p: Path) -> str:
161
+ if p not in _TEXT_CACHE:
162
+ if p.suffix == ".gz":
163
+ with gzip.open(p, "rt", encoding="utf-8", errors="replace") as fh:
164
+ _TEXT_CACHE[p] = fh.read()
165
+ else:
166
+ _TEXT_CACHE[p] = p.read_text(encoding="utf-8", errors="replace")
167
+ return _TEXT_CACHE[p]
168
+
169
+
170
+ def evidence(p: Path, pattern: str) -> str:
171
+ """The full source line (with its number) that contains a match of `pattern`; the match may not span lines."""
172
+ text = _read_text(p)
173
+ m = re.search(pattern, text, flags=re.M)
174
+ if not m:
175
+ raise ValueError(f"evidence not found: /{pattern}/ in {p}")
176
+ if "\n" in m.group(0):
177
+ raise ValueError(f"evidence /{pattern}/ spans lines in {p}")
178
+ a = text.rfind("\n", 0, m.start()) + 1
179
+ b = text.find("\n", m.end())
180
+ line = text[a:(len(text) if b < 0 else b)].strip()
181
+ return f"L{text.count(chr(10), 0, m.start()) + 1}: {line[:240]}"
182
+
183
+
184
+ def match_text(p: Path, pattern: str) -> str:
185
+ """Only the matched text (one line) of `pattern` in p, after the same checks as evidence()."""
186
+ evidence(p, pattern)
187
+ return re.search(pattern, _read_text(p), flags=re.M).group(0)
188
+
189
+
190
+ def evidences(pairs) -> tuple[str, str]:
191
+ ev = [evidence(p, pat) for p, pat in pairs]
192
+ return " || ".join(ev), " ; ".join(sorted({str(p) for p, _ in pairs}))
193
+
194
+
195
+ # display text -> [(file, one-line regex), ...]; each regex must match a single line of its file
196
+ COHORT_TEXT = {
197
+ "immicro": {
198
+ "study": ("ImMicro 2026", [(INV, r"Babdor et al\., Cell 2026 ImMicro")]),
199
+ "disease": ("healthy", [(INV, r'Babdor et al\., Cell 2026 ImMicro",Healthy humans')]),
200
+ "bulk": ("PBMC, mRNA-Seq", [(SOFT_BULK, r"^!Sample_source_name_ch1 = PBMC *$"),
201
+ (SOFT_BULK, r"Universal Plus mRNA-Seq with NuQuant kit")]),
202
+ "sc": ("10x 5′ v1.1 CITE-seq", [(SOFT_SC, r"Chromium Next GEM Single Cell 5.{1,2} v1\.1 Library Kit"),
203
+ (SOFT_SC, r"Library strategy: CITE-seq")]),
204
+ },
205
+ "ye2026_sepsis": {
206
+ "study": ("Ye 2026", [(QC["ye2026_sepsis"], r"Ye Q et al\., Nat Immunol 2026")]),
207
+ "disease": ("sepsis", [(QC["ye2026_sepsis"], r"^# Ye 2026 sepsis")]),
208
+ # extraction is total RNA (Trizol) but the library (polyA vs rRNA depletion) is not stated -> show PBMC only
209
+ "bulk": ("PBMC", [(QC["ye2026_sepsis"], r"GEO protocol: PBMC total RNA \(Trizol\).*polyA vs rRNA depletion not stated")]),
210
+ "sc": ("10x 5′", [(QC["ye2026_sepsis"], r"Chemistry: GEO says .*but the data show 5'")]),
211
+ },
212
+ "imperial_eskd": {
213
+ "study": ("Imperial ESKD", [(QC["imperial_eskd"], r"patients with COVID-19, Imperial cohort")]),
214
+ "disease": ("COVID-19, dialysis", [(QC["imperial_eskd"], r"haemodialysis \(end-stage kidney disease\) patients with COVID-19")]),
215
+ "bulk": ("PBMC", [(QC["imperial_eskd"], r"^- Bulk: .*PBMC RNA-seq")]),
216
+ "sc": ("10x 5′ v2 CITE-seq", [(QC["imperial_eskd"], r"^- scRNA: .*PBMC CITE-seq"),
217
+ (QC["imperial_eskd"], r"Chemistry: 10x 5′ v2")]),
218
+ },
219
+ "giroux2022": {
220
+ "study": ("Giroux 2022", [(QC["giroux2022"], r"Giroux NS et al\., Sci Rep 2022")]),
221
+ "disease": ("COVID-19, outpatient", [(QC["giroux2022"], r"Duke outpatients, early COVID-19")]),
222
+ "bulk": ("PBMC, total RNA (SoLo)", [(QC["giroux2022"], r"^# Giroux 2022 COVID-19: paired PBMC bulk and scRNA"),
223
+ (QC["giroux2022"], r"GEO protocol: Zymo Direct-zol total RNA, NuGEN Ovation SoLo")]),
224
+ "sc": ("10x 5′ v1", [(QC["giroux2022"], r"10x library per subject-day \(5' v1")]),
225
+ },
226
+ "ji2025_chili": {
227
+ "study": ("Ji 2025", [(QC["ji2025_chili"], r"Ji C et al\., Cancer Immunol Immunother 2025")]),
228
+ "disease": ("ICI liver injury", [(QC["ji2025_chili"], r"liver injury on checkpoint inhibitors \(ChILI\)")]),
229
+ "bulk": ("whole blood, 3′ QuantSeq", [(QC["ji2025_chili"], r"\*\*PAXgene whole-blood tubes\*\*"),
230
+ (QC["ji2025_chili"], r"Protocol: Lexogen QuantSeq 3′ FWD")]),
231
+ "sc": ("10x 5′", [(QC["ji2025_chili"], r"Chemistry: 10x 5′ GEX")]),
232
+ },
233
+ }
234
+ # display labels of the scorer's case / control groups; the group lists are asserted against summary.json and
235
+ # contrast_args.sh; `neither` = groups scored in neither arm of the contrast
236
+ CONTRAST = {
237
+ "ye2026_sepsis": dict(case="sepsis", control="control", case_groups=["adult_sepsis", "ped_sepsis"],
238
+ control_groups=["adult_HC", "adult_ICU_ctrl", "ped_HC", "ped_ICU_ctrl"], neither=[],
239
+ ev=[(ARGS, r'ye2026_sepsis\) echo "--case-groups adult_sepsis,ped_sepsis '
240
+ r'--control-groups adult_HC,adult_ICU_ctrl,ped_HC,ped_ICU_ctrl"')]),
241
+ "imperial_eskd": dict(case="COVID+", control="COVID−", case_groups=["covid_positive"],
242
+ control_groups=["covid_negative"], neither=["recovery"],
243
+ ev=[(ARGS, r"COVID-positive vs COVID-negative haemodialysis patients \(recovery samples in neither group\)"),
244
+ (ARGS, r'imperial_eskd\) echo "--case-groups covid_positive --control-groups covid_negative"')]),
245
+ # the GEO label is "severe"; the paper and the author sheet call this group "moderate" (all are outpatients)
246
+ "giroux2022": dict(case="moderate", control="mild", case_groups=["severe"], control_groups=["mild"], neither=[],
247
+ ev=[(QC["giroux2022"], r'The paper and the author sheet call the "severe" group "moderate"'),
248
+ (ARGS, r'giroux2022\) echo "--case-groups severe --control-groups mild"')]),
249
+ "ji2025_chili": dict(case="ChILI", control="ICI control", case_groups=["TOL", "FU1"], control_groups=["BC", "AC"],
250
+ neither=[],
251
+ ev=[(ARGS, r"ChILI patients \(liver injury and its follow-up\) vs checkpoint-inhibitor controls"),
252
+ (ARGS, r'ji2025_chili\) echo "--case-groups TOL,FU1 --control-groups BC,AC"')]),
253
+ }
254
+
255
+
256
+ def usable_folds(ds):
257
+ f = pd.read_csv(DATA / ds / "folds.csv")
258
+ f["donor_id"] = f["donor_id"].astype(str)
259
+ f["sample_id"] = f["sample_id"].astype(str)
260
+ return f[f.fold >= 0].copy()
261
+
262
+
263
+ def min_cells() -> int:
264
+ return int(re.search(r"^MIN_CELLS = (\d+)", _read_text(PREPARE), flags=re.M).group(1))
265
+
266
+
267
+ def cohort_rows():
268
+ mc = min_cells()
269
+ rows = []
270
+ for ds in ORDER:
271
+ r = {"dataset": ds}
272
+ for key, (txt, pairs) in COHORT_TEXT[ds].items():
273
+ r[key] = txt
274
+ r[f"{key}_evidence"], r[f"{key}_source"] = evidences(pairs)
275
+ dj = DATA / ds / "fewshot_n5" / "DRAWS.json"
276
+ draws = json.loads(dj.read_text())
277
+ used = usable_folds(ds)
278
+ if len(used) != draws["n_usable_rows"] or used.donor_id.nunique() != draws["n_usable_donors"]:
279
+ raise ValueError(f"{ds}: folds.csv and DRAWS.json disagree on usable rows/donors")
280
+ # exclusion tally, re-derived with prepare_dataset.py's rule: identity_pass & n_cells >= MIN_CELLS
281
+ feats = np.load(DATA / ds / "features.npz", allow_pickle=False)
282
+ samples = pd.read_csv(DATA / ds / "samples.csv")
283
+ n_all = int(feats["bulk_raw"].shape[0])
284
+ idp = feats["identity_pass"].astype(bool) if "identity_pass" in feats.files else np.ones(n_all, bool)
285
+ chk = (pd.Series(feats["identity_check"].astype(str)).str.split(":").str[0].str.strip()
286
+ if "identity_check" in feats.files else pd.Series(["(no flag)"] * n_all))
287
+ low = (samples["n_cells"].to_numpy() < mc)
288
+ n_fail, n_border = int((chk == "fail").sum()), int((chk == "borderline").sum())
289
+ if int((~idp).sum()) != n_fail + n_border:
290
+ raise ValueError(f"{ds}: identity_pass False rows != fail + borderline")
291
+ n_low = int((idp & low).sum())
292
+ if n_all - n_fail - n_border - n_low != draws["n_usable_rows"]:
293
+ raise ValueError(f"{ds}: exclusion tally does not reproduce the usable rows")
294
+ pooled_sum = json.loads((SCORES / ds / "pooled" / "summary.json").read_text())
295
+ if pooled_sum["n_donors"] != draws["n_usable_rows"]:
296
+ raise ValueError(f"{ds}: pooled scored n {pooled_sum['n_donors']} != usable rows {draws['n_usable_rows']}")
297
+ r.update(n_pairs_all=n_all, n_identity_fail=n_fail, n_identity_borderline=n_border,
298
+ n_low_cells=n_low, min_cells=mc, identity_flag=("identity_pass" in feats.files),
299
+ n_rows=draws["n_usable_rows"], n_donors=draws["n_usable_donors"], n_rows_source=str(dj),
300
+ exclusion_source=f"{DATA / ds / 'features.npz'} (identity_pass, identity_check); "
301
+ f"{DATA / ds / 'samples.csv'} (n_cells); {PREPARE} (MIN_CELLS)")
302
+ cd = pooled_sum["contrast_definition"]
303
+ psrc = str(SCORES / ds / "pooled" / "summary.json")
304
+ if ds in CONTRAST:
305
+ C = CONTRAST[ds]
306
+ if list(cd["case_groups"]) != C["case_groups"] or list(cd["control_groups"]) != C["control_groups"]:
307
+ raise ValueError(f"{ds}: contrast groups changed: {cd['case_groups']} / {cd['control_groups']}")
308
+ neither = sorted({g for g, a, b in zip(cd["groups"], cd["case"], cd["ctrl"]) if not a and not b})
309
+ if neither != sorted(C["neither"]) or (int(cd.get("n_donors_in_neither", 0)) > 0) != bool(neither):
310
+ raise ValueError(f"{ds}: groups in neither arm {neither} != expected {C['neither']}")
311
+ ev, evsrc = evidences(C["ev"])
312
+ r.update(case_label=C["case"], control_label=C["control"], n_case=int(cd["n_case_donors"]),
313
+ n_control=int(cd["n_control_donors"]), n_neither=int(cd.get("n_donors_in_neither", 0)),
314
+ neither_label=",".join(neither), contrast_source=psrc, contrast_label_evidence=ev,
315
+ contrast_label_source=evsrc)
316
+ else:
317
+ if cd.get("enabled"):
318
+ raise ValueError(f"{ds}: expected no contrast")
319
+ r.update(case_label="", control_label="", n_case=np.nan, n_control=np.nan, n_neither=0,
320
+ neither_label="", contrast_source=psrc)
321
+ rows.append(r)
322
+ return pd.DataFrame(rows)
323
+
324
+
325
+ def fig_cohorts(tab: pd.DataFrame):
326
+ """Plain table: columns are placed by measuring the rendered text, so nothing overlaps."""
327
+ headers = ["Cohort", "Condition", "Bulk", "scRNA-seq", "Pairs (donors)", "Case vs control"]
328
+ center = {4}
329
+ body = []
330
+ for r in tab.itertuples():
331
+ pd_txt = f"{r.n_rows}" if r.n_rows == r.n_donors else f"{r.n_rows} ({r.n_donors})"
332
+ ctxt = (f"{r.case_label} {int(r.n_case)} vs {r.control_label} {int(r.n_control)}" if r.case_label
333
+ else "none (healthy)")
334
+ csub = f"+{r.n_neither} {r.neither_label} (neither)" if r.n_neither else None
335
+ body.append([(r.study, {}, None), (r.disease, {}, None),
336
+ (r.bulk, {"fontweight": "bold"} if r.dataset == "ji2025_chili" else {}, None),
337
+ (r.sc, {}, None), (pd_txt, {}, None), (ctxt, {} if r.case_label else {"color": SUB}, csub)])
338
+ W, H = style.FULL[0], 3.7
339
+ fig = plt.figure(figsize=(W, H))
340
+ ax = fig.add_axes([0.0, 0.0, 1.0, 1.0])
341
+ ax.set_axis_off()
342
+ ax.set_xlim(0, 1)
343
+ ax.set_ylim(0, 1)
344
+ n = len(body)
345
+ top, rowh = 0.87, 0.84 / n
346
+ texts = [[] for _ in headers]
347
+ for j, h in enumerate(headers):
348
+ texts[j].append(ax.text(0, top + 0.055, h, ha="left", va="center", fontsize=FS, fontweight="bold",
349
+ color=style.INK))
350
+ for i, row in enumerate(body):
351
+ y = top - rowh * (i + 0.5)
352
+ for j, (txt, kw, sub) in enumerate(row):
353
+ if sub:
354
+ texts[j].append(ax.text(0, y + 0.03, txt, ha="left", va="center", fontsize=FS,
355
+ **{"color": style.INK, **kw}))
356
+ texts[j].append(ax.text(0, y - 0.035, sub, ha="left", va="center", fontsize=FS - 3, color=SUB))
357
+ else:
358
+ texts[j].append(ax.text(0, y, txt, ha="left", va="center", fontsize=FS,
359
+ **{"color": style.INK, **kw}))
360
+ fig.canvas.draw()
361
+ rend = fig.canvas.get_renderer()
362
+ widths = [max(t.get_window_extent(rend).width for t in col) / (fig.dpi * W) for col in texts]
363
+ gap = (1.0 - sum(widths)) / (len(headers) - 1)
364
+ if gap < 0.012:
365
+ raise ValueError(f"cohort table too wide for the slide (gap {gap:.3f})")
366
+ x = 0.0
367
+ for j, col in enumerate(texts):
368
+ for t in col:
369
+ if j in center:
370
+ t.set_x(x + widths[j] / 2)
371
+ t.set_ha("center")
372
+ else:
373
+ t.set_x(x)
374
+ x += widths[j] + gap
375
+ ax.plot([0, 1], [top + 0.005] * 2, color=style.INK, lw=1.2)
376
+ for i in range(1, n):
377
+ ax.plot([0, 1], [top - rowh * i] * 2, color="#C8C8C8", lw=0.7)
378
+ ax.plot([0, 1], [top - rowh * n] * 2, color=style.INK, lw=1.2)
379
+ style.save(fig, "sec09_cohorts", FIGDIR)
380
+
381
+
382
+ # ------------------------------------------------------------------------------------------
383
+ # Shared drawing helpers: rows = cohorts, columns = metrics, horizontal bars
384
+ # ------------------------------------------------------------------------------------------
385
+ BAR_H = 0.72
386
+
387
+
388
+ def jitter(n, seed):
389
+ r = np.random.default_rng(seed)
390
+ return (r.random(n) - 0.5) * BAR_H * 0.6
391
+
392
+
393
+ def hbars(ax, arms, vals_of, seed=0, dots=True, na_text=None):
394
+ """arms drawn top to bottom at y = 0..na-1. vals_of(arm) -> list of floats. Returns stats.
395
+ na_text: {arm: text} shown instead of "not run" when an arm has no value."""
396
+ out = {}
397
+ for i, arm in enumerate(arms):
398
+ vals = np.asarray([v for v in vals_of(arm) if not np.isnan(v)], float)
399
+ if len(vals) == 0:
400
+ ax.text(0.01, i, (na_text or {}).get(arm, "not run"), transform=ax.get_yaxis_transform(), va="center",
401
+ fontsize=FS - 3, color=SUB)
402
+ out[arm] = (np.nan, np.nan, 0)
403
+ continue
404
+ m = float(vals.mean())
405
+ sd = float(vals.std(ddof=1)) if len(vals) > 1 else 0.0
406
+ ax.barh(i, m, height=BAR_H, color=COL[arm], edgecolor=EDGE, linewidth=0.6, zorder=2)
407
+ if dots and len(vals) > 1:
408
+ ax.errorbar(m, i, xerr=sd, fmt="none", ecolor="#111111", elinewidth=1.0, capsize=3, capthick=1.0,
409
+ zorder=4)
410
+ # dots unclipped so a draw at an axis end (precision 1.0) stays whole; check_inside() asserts that every
411
+ # dot and bar lies within the final x-limits. SD whiskers stay clipped (a count's SD can reach below 0).
412
+ ax.scatter(vals, i + jitter(len(vals), seed + i), s=16, facecolor="white", edgecolor="#111111",
413
+ linewidth=0.7, zorder=5, clip_on=False)
414
+ out[arm] = (m, sd, len(vals))
415
+ ax.set_ylim(len(arms) - 0.5, -0.5)
416
+ ax.set_yticks([])
417
+ return out
418
+
419
+
420
+ def check_inside(fig, name):
421
+ """Every draw dot, bar end and reference line lies within its panel's final x-limits (nothing cut off)."""
422
+ from matplotlib.collections import PathCollection
423
+ from matplotlib.patches import Rectangle
424
+ for ax in fig.axes:
425
+ lo, hi = sorted(ax.get_xlim())
426
+ eps = 1e-9 * max(1.0, abs(hi - lo))
427
+ xs = [float(x) for c in ax.collections if isinstance(c, PathCollection) for x in c.get_offsets()[:, 0]]
428
+ xs += [x for p in ax.patches if isinstance(p, Rectangle) for x in (p.get_x(), p.get_x() + p.get_width())]
429
+ xs += [float(x) for ln in ax.lines for x in np.atleast_1d(ln.get_xdata()) if ln.get_linestyle() != "None"]
430
+ bad = [x for x in xs if not (lo - eps <= x <= hi + eps)]
431
+ if bad:
432
+ raise ValueError(f"{name}: value(s) {bad[:3]} outside the x-limits ({lo:.3g}, {hi:.3g})")
433
+
434
+
435
+ def ref_line(ax, x, kind, na):
436
+ """Reference line above the bars (zorder 2) but below error bars (4) and draw dots (5)."""
437
+ if x is None or np.isnan(x):
438
+ return
439
+ s = REFSTYLE[kind]
440
+ ax.plot([x, x], [-0.5, na - 0.5], ls=s["ls"], color=s["color"], lw=s["lw"], zorder=3,
441
+ solid_capstyle="butt")
442
+
443
+
444
+ def row_label(ax, name, subs):
445
+ """Cohort name (FS) with grey sub-lines (FS-3) stacked below it, the block centred on the row."""
446
+ lines = [(name, FS, style.INK)] + [(s, FS - 3, SUB) for s in subs]
447
+ y = sum(fs * 1.3 for _, fs, _ in lines) / 2
448
+ for txt, fs, col in lines:
449
+ h = fs * 1.3
450
+ ax.annotate(txt, xy=(0, 0.5), xycoords="axes fraction", xytext=(-12, y - h / 2), textcoords="offset points",
451
+ ha="right", va="center", fontsize=fs, color=col)
452
+ y -= h
453
+
454
+
455
+ def label_header(ax, text):
456
+ ax.annotate(text, xy=(0, 1), xycoords="axes fraction", xytext=(-12, 10), textcoords="offset points",
457
+ ha="right", va="bottom", fontsize=FS - 3, color=SUB, style="italic")
458
+
459
+
460
+ def blank(ax, text):
461
+ for sp in ax.spines.values():
462
+ sp.set_visible(False)
463
+ ax.set_xticks([])
464
+ ax.set_yticks([])
465
+ ax.text(0.5, 0.5, text, transform=ax.transAxes, ha="center", va="center", fontsize=FS - 3, color=SUB,
466
+ style="italic")
467
+
468
+
469
+ def grid(nrows, ncols, figsize, left, right, top, bottom, hspace, wspace):
470
+ fig = plt.figure(figsize=figsize)
471
+ gs = fig.add_gridspec(nrows, ncols, left=left / figsize[0], right=1 - right / figsize[0],
472
+ top=1 - top / figsize[1], bottom=bottom / figsize[1], hspace=hspace, wspace=wspace)
473
+ axs = np.empty((nrows, ncols), dtype=object)
474
+ for i in range(nrows):
475
+ for j in range(ncols):
476
+ axs[i, j] = fig.add_subplot(gs[i, j])
477
+ return fig, axs
478
+
479
+
480
+ def shared_x(axs_col, lo, hi, xlabel, ticks=None):
481
+ for k, ax in enumerate(axs_col):
482
+ ax.set_xlim(lo, hi)
483
+ if ticks is not None:
484
+ ax.set_xticks(ticks)
485
+ if k < len(axs_col) - 1:
486
+ ax.tick_params(axis="x", labelbottom=False, length=0)
487
+ ax.spines["bottom"].set_visible(False)
488
+ axs_col[-1].set_xlabel(xlabel)
489
+
490
+
491
+ def legend_bottom(fig, handles, ncol, y=0.0):
492
+ fig.legend(handles=handles, loc="lower center", bbox_to_anchor=(0.5, y), ncol=ncol, frameon=False,
493
+ fontsize=FS - 2, handlelength=2.2, columnspacing=1.6, borderaxespad=0.0)
494
+
495
+
496
+ def patch(key, label=None):
497
+ return Patch(facecolor=COL[key], edgecolor=EDGE, linewidth=0.6, label=label or LAB[key])
498
+
499
+
500
+ def refh(kind):
501
+ s = REFSTYLE[kind]
502
+ return Line2D([0], [0], ls=s["ls"], color=s["color"], lw=s["lw"], label=s["label"])
503
+
504
+
505
+ def dot_handle(n_draws):
506
+ lab = "one draw; bar = mean ± SD" + (f" of {n_draws}" if n_draws else "")
507
+ return Line2D([0], [0], marker="o", lw=0, markerfacecolor="white", markeredgecolor="#111111",
508
+ markersize=5, label=lab)
509
+
510
+
511
+ # ------------------------------------------------------------------------------------------
512
+ # Few-pair (5 donors) data
513
+ # ------------------------------------------------------------------------------------------
514
+ _JSON: dict = {}
515
+
516
+
517
+ def jload(p: Path):
518
+ if p not in _JSON:
519
+ _JSON[p] = json.loads(Path(p).read_text())
520
+ return _JSON[p]
521
+
522
+
523
+ def load_nosex(loader):
524
+ """A make_figures loader (load_fewpair / load_pooled, unchanged) run on SCORES_NOSEX for the NOSEX cohorts only."""
525
+ saved = mf.DATASETS
526
+ mf.DATASETS = list(NOSEX)
527
+ try:
528
+ return loader(SCORES_NOSEX)
529
+ finally:
530
+ mf.DATASETS = saved
531
+
532
+
533
+ def nosex_calls(ds):
534
+ """Every sex-gene-excluded score dir of a cohort: same exclusion file (the current one), labels reused from the
535
+ original call of the same relative path."""
536
+ out = []
537
+ for p in sorted((SCORES_NOSEX / ds).rglob("summary.json")):
538
+ s = jload(p)
539
+ ge = s.get("gene_exclusion")
540
+ if ge is None or Path(ge["file"]) != SEXLIST or ge["sha256"] != mf_sha(SEXLIST):
541
+ raise ValueError(f"{p}: not scored with the current {SEXLIST}")
542
+ rel = p.parent.relative_to(SCORES_NOSEX)
543
+ if Path(s["labels_reused_from"]) != SCORES / rel:
544
+ raise ValueError(f"{p}: labels not reused from {SCORES / rel}")
545
+ out.append(p)
546
+ return out
547
+
548
+
549
+ _SHA: dict = {}
550
+
551
+
552
+ def mf_sha(p: Path) -> str:
553
+ if p not in _SHA:
554
+ import hashlib
555
+ _SHA[p] = hashlib.sha256(Path(p).read_bytes()).hexdigest()
556
+ return _SHA[p]
557
+
558
+
559
+ def same_non_disease(a: dict, b: dict, what: str):
560
+ """Every metric except the disease-signal ones must be identical between original and sex-gene-excluded scores."""
561
+ for k in ("comp_l1", "null", "precision", "coverage", "n_scored"):
562
+ if not (a[k] == b[k] or (np.isnan(a[k]) and np.isnan(b[k]))):
563
+ raise ValueError(f"{what}: {k} differs between scores/ and scores_nosex/ ({a[k]} vs {b[k]})")
564
+
565
+
566
+ def fewpair():
567
+ few, status = mf.load_fewpair(SCORES)
568
+ fn, sn = load_nosex(mf.load_fewpair)
569
+ for ds in NOSEX: # Giroux: disease metrics without sex-linked genes; everything else must be unchanged
570
+ nosex_calls(ds)
571
+ o = few[few.dataset == ds].set_index(["draw", "arm"]).sort_index()
572
+ n = fn[fn.dataset == ds].set_index(["draw", "arm"]).sort_index()
573
+ if list(o.index) != list(n.index):
574
+ raise ValueError(f"{ds}: few-pair draws/arms differ between scores/ and scores_nosex/")
575
+ for key in o.index:
576
+ same_non_disease(o.loc[key], n.loc[key], f"{ds} few-pair {key}")
577
+ so = status[status.dataset == ds][["draw", "status"]].reset_index(drop=True)
578
+ if not so.equals(sn[["draw", "status"]].reset_index(drop=True)):
579
+ raise ValueError(f"{ds}: scSemiProfiler acceptance differs between scores/ and scores_nosex/")
580
+ few = pd.concat([few[few.dataset != ds], fn], ignore_index=True)
581
+ status = pd.concat([status[status.dataset != ds], sn], ignore_index=True)
582
+ few = few[few.arm.isin(ARM_FILE)].reset_index(drop=True)
583
+ status = status.sort_values(["dataset", "draw"], key=lambda c: c.map(mf.DATASETS.index) if c.name == "dataset" else c,
584
+ kind="stable").reset_index(drop=True)
585
+ status.to_csv(OUTDATA / "sec09_scsemi_status.csv", index=False)
586
+ # depth-matched precision / coverage are in each call's summary.json headline (not in load_fewpair's metrics)
587
+ for k in ("precision_dm", "coverage_dm"):
588
+ few[k] = [float(jload(T / s)["headline"][ARM_FILE[a]][k]) for s, a in zip(few.source, few.arm)]
589
+ return few, status
590
+
591
+
592
+ def pooled_scores():
593
+ """mf.load_pooled on scores/, with the NOSEX cohorts read from scores_nosex/ (non-disease metrics asserted equal)."""
594
+ pooled, calls = mf.load_pooled(SCORES)
595
+ pn, _ = load_nosex(mf.load_pooled)
596
+ for ds in NOSEX:
597
+ for a in POOLED_ARMS.values():
598
+ same_non_disease(pooled[ds][a], pn[ds][a], f"{ds} pooled {a}")
599
+ pooled[ds] = pn[ds]
600
+ add_scsemi_cv(pooled, calls)
601
+ return pooled, calls
602
+
603
+
604
+ SC_LOG: list = [] # scSemiProfiler 5-fold lookup: one dict per cohort (status, reason, source)
605
+
606
+
607
+ def add_scsemi_cv(pooled, calls):
608
+ """scSemiProfiler with all training pairs (SR.CV_ARM) from scores/<ds>/scsemi_cv_20261002/pooled*/, when present.
609
+ Accepted only for the main pooled call's donors and reference (SR.accept). Metrics from the first accepted call;
610
+ DEG from the first accepted call with DEG enabled; Giroux's disease metrics from the scores_nosex rescore of the
611
+ same call (non-disease metrics asserted equal), else blank."""
612
+ for ds in ORDER:
613
+ dirs = SR.cv_calls(ds)
614
+ ok, why_all = [], []
615
+ for d in dirs:
616
+ c = mf.Call(d)
617
+ why = SR.accept(c.summary, calls[ds].summary, SR.CV_ARM)
618
+ (ok if not why else why_all).append(c if not why else f"{d}: {'; '.join(why)}")
619
+ if not ok:
620
+ SC_LOG.append(dict(dataset=ds, status="missing" if not dirs else "rejected", reason=" | ".join(why_all),
621
+ source=str(SR.plan_root() / "scores" / ds / SR.CV_EXP)))
622
+ continue
623
+ m = mf.arm_metrics(ok[0], SR.CV_ARM)
624
+ m["source"] = str(ok[0].path / "summary.json")
625
+ degc = [c for c in ok if c.deg_enabled and c.summary["headline"][SR.CV_ARM].get("deg_top50_sum") is not None]
626
+ if degc and degc[0] is not ok[0]:
627
+ md = mf.arm_metrics(degc[0], SR.CV_ARM)
628
+ for k in ("deg", "deg_broadcast", "deg_max"):
629
+ m[k] = md[k]
630
+ m["deg_source"] = str(degc[0].path / "summary.json")
631
+ note = ""
632
+ if ds in NOSEX:
633
+ ns = [mf.Call(d) for d in SR.cv_calls(ds, tree="scores_nosex")]
634
+ ns = [c for c in ns if not SR.accept(c.summary, calls[ds].summary, SR.CV_ARM)]
635
+ if ns:
636
+ mn = mf.arm_metrics(ns[0], SR.CV_ARM)
637
+ same_non_disease(m, mn, f"{ds} pooled {SR.CV_ARM}")
638
+ for k in DISEASE_KEYS:
639
+ m[k] = mn[k]
640
+ m["source"] = m["deg_source"] = str(ns[0].path / "summary.json")
641
+ else:
642
+ for k in ("contrast_r", "broadcast_r", "deg", "deg_broadcast", "deg_max"):
643
+ m[k] = np.nan
644
+ m["r_type"], m["bc_type"] = {}, {}
645
+ note = "disease metrics blank: no sex-gene-excluded rescore (scores_nosex) yet"
646
+ pooled[ds][SR.CV_ARM] = m
647
+ SC_LOG.append(dict(dataset=ds, status="used", reason=note, source=m["source"]))
648
+
649
+
650
+ def sex_split(ds):
651
+ """Subjects of the scorer's case / control groups by sex, for the scored (usable) rows and for all paired rows.
652
+ Sex = features.npz sex_bulk_expr (bulk chrY expression call), checked against sex_sc_expr and sex_geo."""
653
+ f = np.load(DATA / ds / "features.npz", allow_pickle=False)
654
+ t = pd.DataFrame({k: f[k].astype(str) for k in ("sample_ids", "donor_ids", "groups", "sex_bulk_expr", "sex_sc_expr",
655
+ "sex_geo")})
656
+ if (t.sex_bulk_expr.str.lower() != t.sex_sc_expr.str.lower()).any() or \
657
+ (t.sex_bulk_expr.str.lower() != t.sex_geo.str.lower()).any():
658
+ raise ValueError(f"{ds}: bulk, sc and GEO sex calls disagree")
659
+ used = set(usable_folds(ds).sample_id)
660
+ C = CONTRAST[ds]
661
+ out = {}
662
+ for scope, rows in (("scored", t[t.sample_ids.isin(used)]), ("all", t)):
663
+ d = rows.drop_duplicates("donor_ids")
664
+ out[scope] = {arm: {sx: int(((d.groups.isin(C[f"{arm}_groups"])) & (d.sex_bulk_expr.str.lower() == sx)).sum())
665
+ for sx in ("female", "male")} for arm in ("case", "control")}
666
+ out["source"] = f"{DATA / ds / 'features.npz'} (sex_bulk_expr = sex_sc_expr = sex_geo); {DATA / ds / 'folds.csv'}"
667
+ return out
668
+
669
+
670
+ def fm(x):
671
+ """'4F/0M' from a {'female': n, 'male': m} count."""
672
+ return f"{x['female']}F/{x['male']}M"
673
+
674
+
675
+ def few_vals(few, ds, arm, metric):
676
+ s = few[(few.dataset == ds) & (few.arm == arm)].sort_values("draw")
677
+ return s[metric].astype(float).tolist(), s["draw"].tolist(), s["source"].tolist()
678
+
679
+
680
+ def few_ref(few, ds, kind, metric):
681
+ """pseudo = zero-shot from sc pseudobulk (zs_pseudo arm); broadcast = raw real bulk logFC/DEG; mean over draws."""
682
+ if kind == "pseudo":
683
+ s = few[(few.dataset == ds) & (few.arm == "pseudo")]
684
+ v = s[metric]
685
+ else:
686
+ s = few[(few.dataset == ds) & (few.arm == "lora")]
687
+ v = s["broadcast_r" if metric == "contrast_r" else "deg_broadcast"]
688
+ v = v.dropna()
689
+ return (float(v.mean()) if len(v) else np.nan), ";".join(sorted(set(s["source"])))
690
+
691
+
692
+ def n_draws(few, ds, arm):
693
+ return int(few[(few.dataset == ds) & (few.arm == arm)]["draw"].nunique())
694
+
695
+
696
+ def draw_info(few, ds):
697
+ """Training / test pairs of the scored LoRA draws (DRAWS.json), and test subjects per contrast arm."""
698
+ dj = DATA / ds / "fewshot_n5" / "DRAWS.json"
699
+ D = jload(dj)["draw"]
700
+ u = usable_folds(ds)
701
+ lora = few[(few.dataset == ds) & (few.arm == "lora")].sort_values("draw")
702
+ tr, te, n_sub, sub_cc = [], [], [], []
703
+ for r in lora.itertuples():
704
+ v = D[str(int(r.draw))] if str(int(r.draw)) in D else D[int(r.draw)]
705
+ if int(r.n_scored) != int(v["n_test_rows"]):
706
+ raise ValueError(f"{ds} draw {r.draw}: scored n {r.n_scored} != DRAWS n_test_rows {v['n_test_rows']}")
707
+ train = {str(x) for x in v["train_donors"]}
708
+ if int(u[u.donor_id.isin(train)].shape[0]) != int(v["n_train_rows"]):
709
+ raise ValueError(f"{ds} draw {r.draw}: train rows in folds.csv != DRAWS n_train_rows")
710
+ tr.append(int(v["n_train_rows"]))
711
+ te.append(int(r.n_scored))
712
+ test = u[~u.donor_id.isin(train)]
713
+ n_sub.append(int(test.donor_id.nunique()))
714
+ if ds in CONTRAST:
715
+ C = CONTRAST[ds]
716
+ cs = set(test[test.group.isin(C["case_groups"])].donor_id)
717
+ ct = set(test[test.group.isin(C["control_groups"])].donor_id)
718
+ sub_cc.append((len(cs), len(ct)))
719
+ return {"train": rng(tr), "test": rng(te), "n_train": tr, "n_test": te, "n_test_subjects": n_sub,
720
+ "subjects_cc": sub_cc, "n_draws": len(tr), "source": str(dj)}
721
+
722
+
723
+ def subjects_text(info):
724
+ """'2 vs 2' when a cohort's test set holds few subjects (< 10) per draw; else ''."""
725
+ if not info["subjects_cc"] or max(info["n_test_subjects"]) >= 10:
726
+ return ""
727
+ a = rng([c for c, _ in info["subjects_cc"]])
728
+ b = rng([t for _, t in info["subjects_cc"]])
729
+ return f"{a} vs {b}"
730
+
731
+
732
+ def row_subs(info, per_row_draws):
733
+ subs = [f"train {info['train']} / test {info['test']}"]
734
+ st = subjects_text(info)
735
+ if st:
736
+ subs.append(f"test = {st} subjects")
737
+ if per_row_draws:
738
+ subs.append(f"{info['n_draws']} draws")
739
+ return subs
740
+
741
+
742
+ def long_rows(fig, few, datasets, arms, metrics, refs):
743
+ rows = []
744
+ for ds in datasets:
745
+ for metric in metrics:
746
+ for arm in arms:
747
+ vals, draws, srcs = few_vals(few, ds, arm, metric)
748
+ for v, d, s in zip(vals, draws, srcs):
749
+ rows.append({"figure": fig, "dataset": ds, "metric": metric, "series": arm, "kind": "draw",
750
+ "draw": d, "value": v, "source": s})
751
+ vv = [v for v in vals if not np.isnan(v)]
752
+ if vv:
753
+ rows.append({"figure": fig, "dataset": ds, "metric": metric, "series": arm, "kind": "mean",
754
+ "draw": "", "value": float(np.mean(vv)),
755
+ "sd": float(np.std(vv, ddof=1)) if len(vv) > 1 else 0.0, "n_draws": len(vv),
756
+ "source": "derived: mean/SD of the draw rows"})
757
+ for kind in refs.get(metric, []):
758
+ v, s = few_ref(few, ds, kind, metric)
759
+ rows.append({"figure": fig, "dataset": ds, "metric": metric, "series": f"ref_{kind}",
760
+ "kind": "reference (mean over draws)", "draw": "", "value": v, "source": s})
761
+ return rows
762
+
763
+
764
+ def same_draw_compare(few, status, datasets, metric, lower_better=False, min_margin=0.0, other="scsemi5"):
765
+ """LoRA-5 vs another arm (scSemi-5 by default, or zero-shot zs_raw) draw by draw, on the draws where both
766
+ exist (same test pairs; scSemi-5 draws only when load_fewpair accepted them).
767
+
768
+ Per draw: LoRA better / other better / tie (equal values). Cohort verdict:
769
+ 'tie' if at least half the shared draws tie, or |mean difference| < min_margin;
770
+ 'lora' if LoRA is better in >= WIN_FRAC of the shared draws;
771
+ 'other' if the other arm is better in >= WIN_FRAC of the shared draws;
772
+ 'split' otherwise.
773
+ """
774
+ used = status[status.status == "used"]
775
+ res = {}
776
+ for ds in datasets:
777
+ a = few[(few.dataset == ds) & (few.arm == "lora")].set_index("draw")[metric].astype(float)
778
+ b = few[(few.dataset == ds) & (few.arm == other)].set_index("draw")[metric].astype(float)
779
+ cand = sorted(used[used.dataset == ds]["draw"]) if other == "scsemi5" else sorted(a.index)
780
+ 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]))]
781
+ if not dr:
782
+ continue
783
+ d = (a[dr] - b[dr]) * (-1.0 if lower_better else 1.0) # > 0: LoRA better
784
+ nL, nO = int((d > 0).sum()), int((d < 0).sum())
785
+ nT = len(dr) - nL - nO
786
+ mdiff = float(a[dr].mean() - b[dr].mean())
787
+ if 2 * nT >= len(dr) or abs(mdiff) < min_margin:
788
+ verdict = "tie"
789
+ elif nL >= WIN_FRAC * len(dr):
790
+ verdict = "lora"
791
+ elif nO >= WIN_FRAC * len(dr):
792
+ verdict = "other"
793
+ else:
794
+ verdict = "split"
795
+ res[ds] = dict(lora=float(a[dr].mean()), other=float(b[dr].mean()), n=len(dr), n_lora=nL, n_other=nO,
796
+ n_tie=nT, verdict=verdict, draws=dr)
797
+ return res
798
+
799
+
800
+ def l1_vs_zeroshot_per_donor(ds, other="zs_raw"):
801
+ """LoRA-5 minus zero-shot (raw real bulk zs_raw, or zero-shot + calibration zs_cal) composition L1, averaged per
802
+ donor over every draw the donor was tested in, then a Wilcoxon signed-rank test over donors (units repeat across
803
+ draws, so donor-draw rows are not independent). The donor-draw row test is returned too, for the CSV only.
804
+ Composition does not depend on the gene set, so the original scores/ files are read for every cohort."""
805
+ s2d = dict(zip(usable_folds(ds).sample_id, usable_folds(ds).donor_id))
806
+ parts = []
807
+ for j, p in mf.draw_dirs(SCORES / ds / "fewshot_n5"):
808
+ pdn = pd.read_csv(p / "per_donor.csv", usecols=["arm", "donor", "comp_l1"])
809
+ w = pdn[pdn.arm.isin(["lora5", other])].pivot(index="donor", columns="arm", values="comp_l1")
810
+ if w[["lora5", other]].isna().any().any():
811
+ raise ValueError(f"{p}: per_donor.csv lacks lora5 or {other} rows for some donors")
812
+ x = (w["lora5"] - w[other]).rename("diff").reset_index()
813
+ x["draw"] = j
814
+ parts.append(x)
815
+ x = pd.concat(parts)
816
+ x["donor_id"] = x["donor"].astype(str).map(s2d)
817
+ if x["donor_id"].isna().any():
818
+ raise ValueError(f"{ds}: per_donor units missing from folds.csv")
819
+ per = x.groupby("donor_id")["diff"].mean()
820
+ return dict(n_donors=int(len(per)), n_rows=int(len(x)), mean_diff=float(per.mean()),
821
+ frac_better=float((per < 0).mean()), p=float(wilcoxon(per).pvalue),
822
+ row_mean_diff=float(x["diff"].mean()), row_p=float(wilcoxon(x["diff"]).pvalue),
823
+ source=f"{SCORES / ds / 'fewshot_n5'}/draw<j>/per_donor.csv (comp_l1, arms lora5 / {other}); "
824
+ f"{DATA / ds / 'folds.csv'} (sample -> donor)")
825
+
826
+
827
+ # ------------------------------------------------------------------------------------------
828
+ # Slide b: 5 donors, cells
829
+ # ------------------------------------------------------------------------------------------
830
+ def fig_fewpair_cells(few, info):
831
+ arms = ["zs_raw", "zs_cal", "scsemi5", "lora"]
832
+ metrics = [("coverage", "Coverage ↑", (0, 1.0), [0, 0.5, 1.0]),
833
+ ("precision", "Precision ↑", (0, 1.0), [0, 0.5, 1.0]),
834
+ ("comp_l1", "Composition L1 ↓", None, None)]
835
+ nd_all = {info[d]["n_draws"] for d in ORDER}
836
+ per_row = len(nd_all) > 1
837
+ fig, axs = grid(len(ORDER), len(metrics), style.FULL, left=LEFT_IN, right=0.15, top=0.45, bottom=1.25,
838
+ hspace=0.22, wspace=0.10)
839
+ l1max = 0.0
840
+ for i, ds in enumerate(ORDER):
841
+ nl = n_draws(few, ds, "lora")
842
+ ns = n_draws(few, ds, "scsemi5")
843
+ for j, (mk, _, _, _) in enumerate(metrics):
844
+ ax = axs[i, j]
845
+ st = hbars(ax, arms, lambda a: few_vals(few, ds, a, mk)[0], seed=17 * i + j)
846
+ ref = few_ref(few, ds, "pseudo", mk)[0]
847
+ ref_line(ax, ref, "pseudo", len(arms))
848
+ if mk == "comp_l1":
849
+ allv = [v for a in arms for v in few_vals(few, ds, a, mk)[0] if not np.isnan(v)] + [ref]
850
+ l1max = max([l1max, np.nanmax(allv)] + [m + sd for m, sd, n in st.values() if n])
851
+ 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:
852
+ raise ValueError(f"{ds} {mk}: value above the fixed 0-1 axis")
853
+ if j == 0 and 0 < ns < nl:
854
+ m, sd, n = st["scsemi5"]
855
+ ax.text(max(m + sd, max(few_vals(few, ds, "scsemi5", mk)[0])) + 0.03, arms.index("scsemi5"),
856
+ f"{ns} of {nl} draws",
857
+ va="center", ha="left", fontsize=FS - 3, color="#8A5A00")
858
+ row_label(axs[i, 0], ROWNAME[ds], row_subs(info[ds], per_row))
859
+ label_header(axs[0, 0], "pairs per draw")
860
+ for j, (mk, lab, lim, ticks) in enumerate(metrics):
861
+ if lim is None: # raw zero-shot L1 reaches ~0.8: the axis follows the data (every draw dot and SD bar)
862
+ lim = (0, np.ceil(l1max * 1.08 * 10) / 10)
863
+ ticks = [round(t, 1) for t in np.arange(0, lim[1] + 1e-9, 0.2)]
864
+ shared_x(axs[:, j], lim[0], lim[1], lab, ticks)
865
+ handles = [patch("zs_raw"), patch("zs_cal"), patch("scsemi5"), patch("lora"), refh("pseudo"),
866
+ dot_handle(None if per_row else nd_all.pop())]
867
+ legend_bottom(fig, handles, ncol=3)
868
+ check_inside(fig, "sec09_fewpair_cells")
869
+ style.save(fig, "sec09_fewpair_cells", FIGDIR)
870
+ rows = long_rows("sec09_fewpair_cells", few, ORDER, arms, [m[0] for m in metrics] + ["precision_dm", "coverage_dm"],
871
+ {"coverage": ["pseudo"], "precision": ["pseudo"], "comp_l1": ["pseudo"]})
872
+ pd.DataFrame(rows).to_csv(OUTDATA / "sec09_fewpair_cells.csv", index=False, float_format="%.6g")
873
+
874
+
875
+ # ------------------------------------------------------------------------------------------
876
+ # Slide c: 5 donors, disease signal
877
+ # ------------------------------------------------------------------------------------------
878
+ def fmt_deg(v):
879
+ return f"{v:.1f}" if v < 10 else f"{v:.0f}"
880
+
881
+
882
+ def fig_fewpair_disease(few, info):
883
+ arms = ["zs_raw", "zs_cal", "scsemi5", "lora"]
884
+ nd_all = {info[d]["n_draws"] for d in DISEASE}
885
+ per_row = len(nd_all) > 1
886
+ fig, axs = grid(len(DISEASE), 2, style.TALL, left=LEFT_IN, right=0.25, top=0.45, bottom=1.55,
887
+ hspace=0.45, wspace=0.12)
888
+ rmin, rmax = 0.0, 0.0
889
+ for i, ds in enumerate(DISEASE):
890
+ nl = n_draws(few, ds, "lora")
891
+ ns = n_draws(few, ds, "scsemi5")
892
+ # logFC r
893
+ ax = axs[i, 0]
894
+ hbars(ax, arms, lambda a: few_vals(few, ds, a, "contrast_r")[0], seed=31 * i)
895
+ bc = few_ref(few, ds, "broadcast", "contrast_r")[0]
896
+ ref_line(ax, bc, "broadcast", len(arms))
897
+ ax.axvline(0, color="#555555", lw=0.8, zorder=1)
898
+ ax.spines["left"].set_visible(False)
899
+ allv = [v for a in arms for v in few_vals(few, ds, a, "contrast_r")[0] if not np.isnan(v)] + [bc]
900
+ rmin, rmax = min(rmin, min(allv)), max(rmax, max(allv))
901
+ if ns < nl:
902
+ ax.text(1.0, arms.index("scsemi5"), f"{ns} of {nl} draws", transform=ax.get_yaxis_transform(), va="center", ha="right",
903
+ fontsize=FS - 3, color="#8A5A00")
904
+ # top-50 DEG, own scale per cohort
905
+ ax = axs[i, 1]
906
+ st = hbars(ax, arms, lambda a: few_vals(few, ds, a, "deg")[0], seed=37 * i)
907
+ bcd = few_ref(few, ds, "broadcast", "deg")[0]
908
+ ref_line(ax, bcd, "broadcast", len(arms))
909
+ hi = max([bcd] + [v for a in arms for v in few_vals(few, ds, a, "deg")[0] if not np.isnan(v)])
910
+ hi = max(hi, 4.0)
911
+ ax.set_xlim(0, hi * 1.40)
912
+ ax.xaxis.set_major_locator(MaxNLocator(nbins=3, integer=True))
913
+ for k, a in enumerate(arms):
914
+ m, sd, n = st[a]
915
+ if n:
916
+ ax.text(0.995, k, fmt_deg(m), transform=ax.get_yaxis_transform(), va="center", ha="right",
917
+ fontsize=FS - 3, color=SUB)
918
+ row_label(axs[i, 0], ROWNAME[ds], row_subs(info[ds], per_row))
919
+ label_header(axs[0, 0], "pairs per draw")
920
+ lo = min(-0.1, np.floor(rmin * 10) / 10)
921
+ hi = max(0.9, np.ceil(rmax * 10) / 10 + 0.05)
922
+ shared_x(axs[:, 0], lo, hi, "Disease logFC r ↑", [0, 0.4, 0.8])
923
+ axs[-1, 1].set_xlabel("Top-50 DEG overlap ↑")
924
+ for ax in axs[:, 1]:
925
+ ax.tick_params(axis="x", labelsize=FS - 3)
926
+ handles = [patch("zs_raw"), patch("zs_cal"), patch("scsemi5"), patch("lora"), refh("broadcast"),
927
+ dot_handle(None if per_row else nd_all.pop())]
928
+ legend_bottom(fig, handles, ncol=2)
929
+ check_inside(fig, "sec09_fewpair_disease")
930
+ style.save(fig, "sec09_fewpair_disease", FIGDIR)
931
+ rows = long_rows("sec09_fewpair_disease", few, DISEASE, arms, ["contrast_r", "deg"],
932
+ {"contrast_r": ["broadcast"], "deg": ["broadcast"]})
933
+ pd.DataFrame(rows).to_csv(OUTDATA / "sec09_fewpair_disease.csv", index=False, float_format="%.6g")
934
+
935
+
936
+ # ------------------------------------------------------------------------------------------
937
+ # Slide d: all pairs, 5-fold pooled
938
+ # ------------------------------------------------------------------------------------------
939
+ def baselines_text(vals):
940
+ """'0.11' when every baseline rounds to the same 2 decimals, else '0.10–0.12' (lowest–highest)."""
941
+ s = sorted({f"{v:.2f}" for v in vals})
942
+ return s[0] if len(s) == 1 else f"{s[0]}–{s[-1]}"
943
+
944
+
945
+ def sc_cohorts(pooled):
946
+ """Cohorts with an accepted scSemiProfiler 5-fold (all training pairs) call."""
947
+ return [d for d in ORDER if SR.CV_ARM in pooled[d]]
948
+
949
+
950
+ def pooled_val(P, a, mk):
951
+ m = P.get(POOLED_FILE[a])
952
+ return np.nan if m is None else m[mk]
953
+
954
+
955
+ def fivefold_arms(pooled):
956
+ return ["zs_raw", "zs_cal", "sconly_cal"] + ([SC_ALL] if sc_cohorts(pooled) else []) + ["lora"]
957
+
958
+
959
+ def fig_fivefold(pooled, tab):
960
+ arms = fivefold_arms(pooled)
961
+ base = ["zs_raw", "zs_cal", "sconly_cal"] # the Ji note sits next to these three bars
962
+ metrics = [("coverage", "Coverage ↑"), ("contrast_r", "Disease logFC r ↑"), ("deg", "Top-50 DEG overlap ↑")]
963
+ leg_rows = -(-(len(arms) + 2) // 3) # arm patches + 2 reference lines, 3 per legend row
964
+ fig, axs = grid(len(ORDER), 3, style.FULL, left=LEFT_IN, right=0.35, top=0.45, bottom=0.65 + 0.30 * leg_rows,
965
+ hspace=0.40, wspace=0.12)
966
+ rows = []
967
+ ji_note = None
968
+ tabi = tab.set_index("dataset")
969
+
970
+ def src(m, mk):
971
+ return m.get("deg_source", m["source"]) if mk == "deg" else m["source"]
972
+
973
+ for i, ds in enumerate(ORDER):
974
+ P = pooled[ds]
975
+ for j, (mk, _) in enumerate(metrics):
976
+ ax = axs[i, j]
977
+ if ds == "ji2025_chili":
978
+ ax.set_facecolor(HILITE)
979
+ if mk in ("contrast_r", "deg") and ds == "immicro":
980
+ blank(ax, "healthy cohort: no contrast")
981
+ continue
982
+ sc_na = {SC_ALL: ("rescore pending" if POOLED_FILE[SC_ALL] in P else "not run")}
983
+ hbars(ax, arms, lambda a: [pooled_val(P, a, mk)], dots=False, na_text=sc_na)
984
+ for a in arms:
985
+ if POOLED_FILE[a] not in P:
986
+ continue
987
+ rows.append({"figure": "sec09_fivefold", "dataset": ds, "metric": mk, "series": a,
988
+ "arm_file": POOLED_FILE[a], "value": P[POOLED_FILE[a]][mk],
989
+ "n_scored": P[POOLED_FILE[a]]["n_scored"], "source": src(P[POOLED_FILE[a]], mk)})
990
+ if mk == "coverage":
991
+ ref = P["zs__pseudo"]["coverage"]
992
+ ref_line(ax, ref, "pseudo", len(arms))
993
+ rows.append({"figure": "sec09_fivefold", "dataset": ds, "metric": mk, "series": "ref_pseudo",
994
+ "arm_file": "zs__pseudo", "value": ref, "source": P["zs__pseudo"]["source"]})
995
+ else:
996
+ m = P["real_lora__raw"]
997
+ ref = m["broadcast_r"] if mk == "contrast_r" else m["deg_broadcast"]
998
+ ref_line(ax, ref, "broadcast", len(arms))
999
+ rows.append({"figure": "sec09_fivefold", "dataset": ds, "metric": mk, "series": "ref_broadcast",
1000
+ "arm_file": "real_lora__raw (raw real bulk)", "value": ref, "source": src(m, mk)})
1001
+ if mk == "deg":
1002
+ hi = float(np.nanmax([ref] + [pooled_val(P, a, "deg") for a in arms] + [4.0]))
1003
+ ax.set_xlim(0, hi * 1.25)
1004
+ ax.xaxis.set_major_locator(MaxNLocator(nbins=3, integer=True))
1005
+ ax.tick_params(axis="x", labelsize=FS - 3)
1006
+ for k, a in enumerate(arms):
1007
+ v = pooled_val(P, a, "deg")
1008
+ if not np.isnan(v):
1009
+ ax.text(v + hi * 0.03, k, f"{v:.0f}", va="center", ha="left", fontsize=FS - 3, color=SUB)
1010
+ if mk == "contrast_r":
1011
+ ax.axvline(0, color="#555555", lw=0.8, zorder=1)
1012
+ ax.spines["left"].set_visible(False)
1013
+ if ds == "ji2025_chili" and mk == "coverage":
1014
+ vb = [P[POOLED_ARMS[a]]["coverage"] for a in base]
1015
+ v_lo = P[POOLED_ARMS["lora"]]["coverage"]
1016
+ txt = ax.text(max(vb) + 0.03, (len(base) - 1) / 2, f"baselines {baselines_text(vb)}",
1017
+ va="center", ha="left", fontsize=FS - 2, color="#5A5A5A")
1018
+ ji_note = (txt, ax, P["zs__pseudo"]["coverage"])
1019
+ ax.text(v_lo + 0.02, arms.index("lora"), f"{v_lo:.2f}", va="center", ha="left", fontsize=FS - 3,
1020
+ color=SUB)
1021
+ n = P["real_lora__raw"]["n_scored"]
1022
+ nd = int(tabi.loc[ds, "n_donors"])
1023
+ if int(tabi.loc[ds, "n_rows"]) != int(n):
1024
+ raise ValueError(f"{ds}: pooled n {n} != usable rows")
1025
+ row_label(axs[i, 0], ROWNAME[ds], [f"n={n}" + (f" ({nd} donors)" if nd != n else "")])
1026
+ shared_x(axs[:, 0], 0, 1.0, metrics[0][1], [0, 0.5, 1.0])
1027
+ # the Ji annotation must end left of the pseudobulk reference line (checked on the final x scale)
1028
+ txt, ax, ref = ji_note
1029
+ fig.canvas.draw()
1030
+ x1 = ax.transData.inverted().transform(txt.get_window_extent(fig.canvas.get_renderer()))[1, 0]
1031
+ if x1 >= ref - 0.01:
1032
+ raise ValueError(f"Ji annotation ends at {x1:.2f}, over the pseudobulk reference line at {ref:.2f}")
1033
+ rvals = [r["value"] for r in rows if r["metric"] == "contrast_r" and not np.isnan(r["value"])]
1034
+ shared_x(axs[1:, 1], min(-0.1, np.floor(min(rvals) * 10) / 10), max(0.9, np.ceil(max(rvals) * 10) / 10),
1035
+ metrics[1][1], [0, 0.4, 0.8])
1036
+ axs[-1, 2].set_xlabel(metrics[2][1])
1037
+ handles = [patch(a, LAB["lora_all"] if a == "lora" else None) for a in arms] + [refh("pseudo"), refh("broadcast")]
1038
+ legend_bottom(fig, handles, ncol=3)
1039
+ check_inside(fig, "sec09_fivefold")
1040
+ style.save(fig, "sec09_fivefold", FIGDIR)
1041
+ pd.DataFrame(rows).to_csv(OUTDATA / "sec09_fivefold.csv", index=False, float_format="%.6g")
1042
+ return rows
1043
+
1044
+
1045
+ # ------------------------------------------------------------------------------------------
1046
+ # Slide text: every keyword / footnote / quoted number is built here from the same data
1047
+ # ------------------------------------------------------------------------------------------
1048
+ BANNED = ("novel", "powerful", "robust", "state-of-the-art", "seamless", "leverage")
1049
+
1050
+
1051
+ def n_words(s):
1052
+ return sum(1 for t in s.split() if re.search(r"[A-Za-z0-9]", t))
1053
+
1054
+
1055
+ def check_text(s, what):
1056
+ if any(b in s.lower() for b in BANNED) or re.search(r"[가-힣]", s):
1057
+ raise ValueError(f"banned word / Korean in {what}: {s!r}")
1058
+ if OFF_STORY.search(s):
1059
+ raise ValueError(f"off-story wording (refcal / VAE / TPM / AIFI / AIDA) in {what}: {s!r}")
1060
+ return s
1061
+
1062
+
1063
+ def check_keywords(kws):
1064
+ if len(kws) > 3:
1065
+ raise ValueError(f"more than 3 keyword lines: {kws}")
1066
+ for k in kws:
1067
+ if n_words(k) > 7:
1068
+ raise ValueError(f"keyword over 7 words: {k!r}")
1069
+ if len(k) > KW_MAX_CHARS:
1070
+ raise ValueError(f"keyword over {KW_MAX_CHARS} characters ({len(k)}): {k!r}")
1071
+ check_text(k, "keyword")
1072
+ return kws
1073
+
1074
+
1075
+ def check_foot_short(s):
1076
+ """One on-slide line: <= FOOT_SHORT_MAX characters, no file paths."""
1077
+ if len(s) > FOOT_SHORT_MAX or "\n" in s:
1078
+ raise ValueError(f"footnote_short over {FOOT_SHORT_MAX} characters ({len(s)}): {s!r}")
1079
+ if re.search(r"/home|\b(scores|data|runs|tools|figures)/|\.(json|csv|npz|md|py|pt)\b", s):
1080
+ raise ValueError(f"file path in footnote_short: {s!r}")
1081
+ return check_text(s, "footnote_short")
1082
+
1083
+
1084
+ def keyword_or_short(long, short):
1085
+ """The long wording when it fits a keyword line, else the short one (both computed from the same numbers)."""
1086
+ return long if len(long) <= KW_MAX_CHARS else short
1087
+
1088
+
1089
+ def names(dss):
1090
+ return ", ".join(NAME[d] for d in dss)
1091
+
1092
+
1093
+ def fmt_p(p):
1094
+ return f"{p:.0e}" if p < 0.01 else f"{p:.2f}"
1095
+
1096
+
1097
+ def main():
1098
+ FIGDIR.mkdir(parents=True, exist_ok=True)
1099
+ OUTDATA.mkdir(parents=True, exist_ok=True)
1100
+
1101
+ tab = cohort_rows()
1102
+ tab.to_csv(OUTDATA / "sec09_cohorts.csv", index=False)
1103
+ fig_cohorts(tab)
1104
+
1105
+ few, status = fewpair()
1106
+ info = {ds: draw_info(few, ds) for ds in ORDER}
1107
+ pooled, calls = pooled_scores()
1108
+ fig_fewpair_cells(few, info)
1109
+ fig_fewpair_disease(few, info)
1110
+ fig_fivefold(pooled, tab)
1111
+
1112
+ used = status[status.status == "used"]
1113
+ run_json = T / "runs" / "immicro" / "fewshot_n5" / "draw0" / "lora" / "RUN.json"
1114
+ evidence(run_json, re.escape(CKPT)) # the few-pair LoRA runs start from the final checkpoint
1115
+ steps = int(re.search(r'"fixed_steps": (\d+)', evidence(run_json, r'"fixed_steps": \d+')).group(1))
1116
+ lora_r = re.search(r"LoRA r = (\d+)", evidence(README, r"LoRA r = \d+ \(1\.3 M")).group(1)
1117
+ sampling = match_text(README, r"test donors only, 1,500 cells each, seed \d+, DDIM 50, EMA, Bernoulli read-out")
1118
+ early = match_text(README, r"About 10 % of each fold's training donors are inner-validation, used only for early stopping")
1119
+ pc_def = match_text(SCORE_FT, r"precision/coverage/density \(PCA-50 \+ k = 10 balls fitted on the scored donors' observed R1 cells\)")
1120
+ pca_n = {int(jload(SCORES / ds / "fewshot_n5" / "draw0" / "summary.json")["reference"]["pca"]["n_components"])
1121
+ for ds in ORDER}
1122
+ if pca_n != {50}:
1123
+ raise ValueError(f"PCA components differ from the footnote: {pca_n}")
1124
+ ddef = jload(SCORES / "ji2025_chili" / "fewshot_n5" / "draw0" / "summary.json")["deg_definition"]
1125
+ if not ("welch_bh_deg" in ddef["functions"] and ddef["top_n"] == 50 and len(ddef["types"]) == 5):
1126
+ raise ValueError("DEG definition differs from the footnote")
1127
+ n_types = len(ddef["types"])
1128
+ base_src = f"{run_json}; {README}"
1129
+ slides = []
1130
+
1131
+ # ---------------- slide a ----------------
1132
+ tot_rows, tot_donors = int(tab.n_rows.sum()), int(tab.n_donors.sum())
1133
+ n_all = int(tab.n_pairs_all.sum())
1134
+ n_fail, n_bord, n_low = int(tab.n_identity_fail.sum()), int(tab.n_identity_borderline.sum()), int(tab.n_low_cells.sum())
1135
+ ji = tab.set_index("dataset").loc["ji2025_chili"]
1136
+ if not ji.bulk.startswith("whole blood"):
1137
+ raise ValueError("Ji bulk label changed")
1138
+ noflag = [NAME[d] for d in tab[~tab.identity_flag].dataset]
1139
+ multi = [NAME[d] for d in tab[tab.n_rows != tab.n_donors].dataset]
1140
+ sxa = sex_split("giroux2022")
1141
+ kw_a = check_keywords([f"{tot_rows} paired samples, {tot_donors} donors",
1142
+ "Only identity-pass pairs; donor-level splits",
1143
+ "Ji bulk: whole blood, not PBMC"])
1144
+ foot_a = (f"Usable pair = passed the pairing identity check and >= {int(tab.min_cells.iloc[0])} cells "
1145
+ f"(fold >= 0 in data/<cohort>/folds.csv); dropped {n_fail} identity-fail, {n_bord} borderline and "
1146
+ f"{n_low} low-cell pairs of {n_all}. {', '.join(noflag)}: no identity flag, all used. "
1147
+ f"{', '.join(multi)}: several pairs per donor. Case vs control = samples in "
1148
+ f"scores/<cohort>/pooled/summary.json. Giroux 'moderate' = GEO 'severe' (paper term); its moderate vs mild "
1149
+ f"subjects are {fm(sxa['scored']['case'])} vs {fm(sxa['scored']['control'])} (scored), so its disease "
1150
+ f"metrics exclude sex-linked genes. Labels: data/<cohort>/QC_REPORT.md; ImMicro: GEO GSE314922/GSE314416.")
1151
+ num("a", f"{tot_rows} paired samples (sum of usable rows)", f"{DATA}/<cohort>/fewshot_n5/DRAWS.json (n_usable_rows)")
1152
+ num("a", f"{tot_donors} donors (sum of usable donors)", f"{DATA}/<cohort>/fewshot_n5/DRAWS.json (n_usable_donors)")
1153
+ num("a", f"dropped {n_fail} identity-fail, {n_bord} borderline, {n_low} < {int(tab.min_cells.iloc[0])} cells, of {n_all}",
1154
+ f"{DATA}/<cohort>/features.npz (identity_pass, identity_check); samples.csv (n_cells); {PREPARE} (MIN_CELLS)")
1155
+ for r in tab.itertuples():
1156
+ v = f"{NAME[r.dataset]} {r.n_rows} pairs / {r.n_donors} donors"
1157
+ s = r.n_rows_source
1158
+ if r.case_label:
1159
+ v += f"; {r.case_label} {int(r.n_case)} vs {r.control_label} {int(r.n_control)}"
1160
+ if r.n_neither:
1161
+ v += f" (+{r.n_neither} {r.neither_label}, neither)"
1162
+ s += f"; {r.contrast_source}"
1163
+ num("a", v, s)
1164
+ fs_a = check_foot_short(f"Usable pair = passed identity check and ≥ {int(tab.min_cells.iloc[0])} cells: "
1165
+ f"{tot_rows} of {n_all} pairs; donor-level splits.")
1166
+ slides.append({"title": "Five paired cohorts", "layout": "full",
1167
+ "figures": [str(FIGDIR / "sec09_cohorts.png")], "keywords": kw_a, "footnote": foot_a,
1168
+ "footnote_short": fs_a, "numbers": NUMS["a"]})
1169
+
1170
+ # ---------------- slide b ----------------
1171
+ mk_b = (("coverage", False), ("precision", False), ("comp_l1", True), ("coverage_dm", False),
1172
+ ("precision_dm", False))
1173
+ cmp_b = {mk: same_draw_compare(few, status, ORDER, mk, lower) for mk, lower in mk_b}
1174
+ cmp_bz = {mk: same_draw_compare(few, status, ORDER, mk, lower, other="zs_raw") for mk, lower in mk_b}
1175
+ cmp_bc = {mk: same_draw_compare(few, status, ORDER, mk, lower, other="zs_cal") for mk, lower in mk_b}
1176
+ wins = {mk: sum(v["verdict"] == "lora" for v in c.values()) for mk, c in cmp_b.items()}
1177
+ wins_z = {mk: sum(v["verdict"] == "lora" for v in c.values()) for mk, c in cmp_bz.items()}
1178
+ wins_c = {mk: sum(v["verdict"] == "lora" for v in c.values()) for mk, c in cmp_bc.items()}
1179
+ ncoh = {mk: len(c) for mk, c in cmp_b.items()}
1180
+ if ncoh["coverage"] != len(ORDER):
1181
+ raise ValueError("a cohort has no shared scSemiProfiler draw")
1182
+ if any(len(c) != len(ORDER) for cc in (cmp_bz, cmp_bc) for c in cc.values()):
1183
+ raise ValueError("a cohort has no zero-shot draw")
1184
+ nb = len(ORDER)
1185
+ if wins["coverage"] == wins["precision"]:
1186
+ kw_b1 = f"LoRA-5 > scSemi-5: coverage, precision {wins['coverage']}/{nb}"
1187
+ else:
1188
+ kw_b1 = f"Beats scSemi-5: coverage {wins['coverage']}/{nb}, precision {wins['precision']}/{nb}"
1189
+
1190
+ def span(v):
1191
+ return f"{min(v):.2f}–{max(v):.2f}"
1192
+
1193
+ cov_mean = {a: [float(np.mean(few_vals(few, d, a, "coverage")[0])) for d in ORDER]
1194
+ for a in ("lora", "scsemi5", "zs_raw", "zs_cal")}
1195
+ kw_b2 = keyword_or_short(f"Beats zero-shot + calibration: coverage {wins_c['coverage']}/{nb}",
1196
+ f"Coverage > calibration: {wins_c['coverage']}/{nb}")
1197
+ l1t = {ds: l1_vs_zeroshot_per_donor(ds) for ds in ORDER}
1198
+ l1c = {ds: l1_vs_zeroshot_per_donor(ds, "zs_cal") for ds in ORDER}
1199
+ gain = [d for d in ORDER if l1t[d]["p"] < 0.05 and l1t[d]["mean_diff"] < 0]
1200
+ gain_c = [d for d in ORDER if l1c[d]["p"] < 0.05 and l1c[d]["mean_diff"] < 0]
1201
+ worse_c = [d for d in ORDER if l1c[d]["p"] < 0.05 and l1c[d]["mean_diff"] > 0]
1202
+ if not gain_c:
1203
+ kw_b3 = "Composition: no gain over calibration"
1204
+ elif len(gain_c) == nb:
1205
+ kw_b3 = "Lower L1 than calibration: all cohorts"
1206
+ else:
1207
+ kw_b3 = keyword_or_short(f"Lower L1 than calibration: {names(gain_c)} only",
1208
+ f"Lower L1 than calibration: {len(gain_c)}/{nb}")
1209
+ kw_b = check_keywords([kw_b1, kw_b2, kw_b3])
1210
+ l1_split = [d for d, v in cmp_b["comp_l1"].items() if v["verdict"] != "lora"]
1211
+ dm_c = {a: [cmp_b["coverage_dm"][d][k] for d in ORDER] for a, k in (("lora", "lora"), ("scsemi5", "other"))}
1212
+ if wins["coverage_dm"] != wins["coverage"] or wins["precision_dm"] != wins["precision"]:
1213
+ raise ValueError("depth-matched ranking differs from raw P/C: rewrite the 'same ranking' footnote")
1214
+ tr_all = [x for d in ORDER for x in info[d]["n_train"]]
1215
+ missing = status[status.status != "used"]
1216
+ miss_txt = ", ".join(f"{NAME[r.dataset]} draw{r.draw}" for r in missing.itertuples())
1217
+ ns_used, ns_all = len(used), len(status)
1218
+
1219
+ def pc_wins(w):
1220
+ return (f"coverage {w['coverage']}/{nb}, precision {w['precision']}/{nb}, "
1221
+ f"depth-matched {w['coverage_dm']}/{nb} and {w['precision_dm']}/{nb}")
1222
+
1223
+ def l1_list(t):
1224
+ return ", ".join(f"{NAME[d]} {t[d]['mean_diff']:+.2f} (p {fmt_p(t[d]['p'])})" for d in ORDER)
1225
+
1226
+ foot_b = (f"Base f01 6k·1x·E16 (EMA, DDIM 50) + LoRA r={lora_r}, {steps:,} steps. LoRA-5 / scSemi-5 = LoRA / "
1227
+ f"scSemiProfiler trained on the same 5 donors ({min(tr_all)}–{max(tr_all)} pairs); test = all other usable "
1228
+ f"pairs. Zero-shot = base model without fine-tuning, fed each test pair's real bulk as measured; zero-shot + "
1229
+ f"calibration = the same model fed that bulk after gene-wise calibration, alpha fitted on the same 5 "
1230
+ f"training donors' pairs (both in the same call as LoRA-5). scSemi-5 scored in a separate call, same test "
1231
+ f"set and reference (sha-checked); {ns_used}/{ns_all} draws" + (f" (missing: {miss_txt})" if len(missing) else "")
1232
+ + ". Verdict = better in >= 80% of shared draws. LoRA-5 lower L1 than scSemi-5 in "
1233
+ f"{wins['comp_l1']}/{nb}"
1234
+ + (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)})"
1235
+ if l1_split else "")
1236
+ + f". LoRA-5 > zero-shot + calibration: {pc_wins(wins_c)} cohorts; > zero-shot (real bulk): "
1237
+ f"{pc_wins(wins_z)}. Depth-matched P/C vs scSemi-5: same ranking, coverage LoRA-5 {span(dm_c['lora'])} vs "
1238
+ f"scSemi-5 {span(dm_c['scsemi5'])}. Composition L1, LoRA-5 minus zero-shot + calibration, per-donor Wilcoxon "
1239
+ f"(gain = p < 0.05): {l1_list(l1c)}; minus zero-shot (real bulk): {l1_list(l1t)}. scANVI labels; P/C = "
1240
+ f"PCA-50, k=10 balls. Scores: scores/<cohort>/fewshot_n5/.")
1241
+ nd_b = sorted({info[d]["n_draws"] for d in ORDER})
1242
+ fs_b = check_foot_short(f"{rng(nd_b)} draws per cohort; test = all other usable pairs. Calibration α from the same "
1243
+ f"5 donors. scANVI labels.")
1244
+ scs = f"{SCORES}/<cohort>/fewshot_n5/draw<j>/summary.json and draw<j>_scsemi5/summary.json"
1245
+ for mk in ("coverage", "precision", "comp_l1", "coverage_dm", "precision_dm"):
1246
+ c = cmp_b[mk]
1247
+ num("b", f"LoRA-5 vs scSemi-5 {mk} (shared-draw means; LoRA-better draws/n; verdict): " +
1248
+ "; ".join(f"{NAME[d]} {v['lora']:.3f} vs {v['other']:.3f} ({v['n_lora']}/{v['n']}, {v['verdict']})"
1249
+ for d, v in c.items()) + f" -> LoRA verdicts {wins[mk]}/{ncoh[mk]}", scs)
1250
+ for cmpx, w, lab, arm in ((cmp_bc, wins_c, "zero-shot + calibration", "zs_cal"),
1251
+ (cmp_bz, wins_z, "zero-shot (real bulk)", "zs_raw")):
1252
+ for mk in ("coverage", "precision", "comp_l1", "coverage_dm", "precision_dm"):
1253
+ c = cmpx[mk]
1254
+ num("b", f"LoRA-5 vs {lab} {mk} (same-draw means; LoRA-better draws/n; verdict): " +
1255
+ "; ".join(f"{NAME[d]} {v['lora']:.3f} vs {v['other']:.3f} ({v['n_lora']}/{v['n']}, {v['verdict']})"
1256
+ for d, v in c.items()) + f" -> LoRA verdicts {w[mk]}/{len(c)}",
1257
+ f"{SCORES}/<cohort>/fewshot_n5/draw<j>/summary.json (arms lora5, {arm})")
1258
+ num("b", "coverage cohort means over all draws: " + "; ".join(
1259
+ f"{lab} " + ", ".join(f"{NAME[d]} {v:.3f}" for d, v in zip(ORDER, cov_mean[a]))
1260
+ for a, lab in (("lora", "LoRA-5"), ("scsemi5", "scSemi-5"), ("zs_cal", "zero-shot + calibration"),
1261
+ ("zs_raw", "zero-shot"))), scs)
1262
+ for t, lab, g in ((l1c, "zero-shot + calibration", gain_c), (l1t, "zero-shot (real bulk)", gain)):
1263
+ num("b", f"LoRA-5 minus {lab} composition L1, per-donor Wilcoxon (draw-averaged): " +
1264
+ "; ".join(f"{NAME[d]} {v['mean_diff']:+.3f}, n={v['n_donors']}, p={v['p']:.2g}" for d, v in t.items()) +
1265
+ f" -> gain in {len(g)}/{nb}", f"{SCORES}/<cohort>/fewshot_n5/draw<j>/per_donor.csv; {DATA}/<cohort>/folds.csv")
1266
+ if worse_c:
1267
+ num("b", "LoRA-5 L1 significantly higher than zero-shot + calibration: " + names(worse_c),
1268
+ f"{SCORES}/<cohort>/fewshot_n5/draw<j>/per_donor.csv")
1269
+ num("b", "scSemiProfiler draws used / LoRA draws: " +
1270
+ ", ".join(f"{NAME[d]} {int((used.dataset == d).sum())}/{n_draws(few, d, 'lora')}" for d in ORDER),
1271
+ OUTDATA / "sec09_scsemi_status.csv")
1272
+ num("b", "training pairs per draw: " + ", ".join(f"{NAME[d]} {info[d]['train']}" for d in ORDER) +
1273
+ "; test pairs: " + ", ".join(f"{NAME[d]} {info[d]['test']}" for d in ORDER),
1274
+ f"{DATA}/<cohort>/fewshot_n5/DRAWS.json (n_train_rows, n_test_rows)")
1275
+ num("b", f"LoRA r = {lora_r}; {steps} fixed steps; base {CKPT}; sampling: {sampling}", base_src)
1276
+ num("b", f"P/C definition: {pc_def}; PCA components in every summary.json = 50", SCORE_FT)
1277
+ for ds in ORDER:
1278
+ for t, lab in ((l1c, "zero-shot + calibration"), (l1t, "zero-shot (real bulk)")):
1279
+ extra("b", f"{ds} LoRA-5 minus {lab} L1, Wilcoxon over donor-draw rows (pseudo-replicated; not quoted, "
1280
+ f"replaced by the per-donor test)",
1281
+ f"{t[ds]['row_mean_diff']:+.3f}, n={t[ds]['n_rows']}, p {t[ds]['row_p']:.2g}", t[ds]["source"])
1282
+ slides.append({"title": "5 donors: LoRA vs scSemiProfiler — cells", "layout": "full",
1283
+ "figures": [str(FIGDIR / "sec09_fewpair_cells.png")], "keywords": kw_b, "footnote": foot_b,
1284
+ "footnote_short": fs_b, "numbers": NUMS["b"]})
1285
+
1286
+ # ---------------- Giroux: sex-linked genes excluded from the disease metrics ----------------
1287
+ sx = {d: sex_split(d) for d in NOSEX}
1288
+ gex = jload(SCORES_NOSEX / "giroux2022" / "pooled" / "summary.json")["gene_exclusion"]
1289
+ sexbuild = jload(SEXLIST.parent / "BUILD.json")["counts"]
1290
+ sx_txt = {d: f"{fm(sx[d]['scored']['case'])} vs {fm(sx[d]['scored']['control'])}" for d in NOSEX}
1291
+ sx_all = {d: f"{fm(sx[d]['all']['case'])} vs {fm(sx[d]['all']['control'])}" for d in NOSEX}
1292
+ nosex_short = " ".join(f"{NAME[d]}: sex-linked genes excluded (severity confounded with sex: {sx_txt[d]})."
1293
+ for d in NOSEX)
1294
+ nosex_long = " ".join(
1295
+ f"{NAME[d]}: {CONTRAST[d]['case']} vs {CONTRAST[d]['control']} subjects are {sx_txt[d]} (scored; all paired "
1296
+ f"subjects {sx_all[d]}; sex from bulk chrY expression = sc = GEO), so its disease metrics (logFC r, partial r, "
1297
+ f"top-50 DEG, broadcast) exclude {gex['n_listed']} sex-linked genes ({sexbuild['chrY_nonPAR_excluded']} chrY "
1298
+ f"non-PAR + {sexbuild['chrX_escape_excluded']} X-inactivation escape / variable-escape genes of Tukiainen et al. "
1299
+ f"2017; PAR genes kept), {gex['n_dropped_from_scoring_genes']} of them scoring genes; same labels and cells as "
1300
+ f"before (scores_nosex/{d}/)." for d in NOSEX)
1301
+ for d in NOSEX:
1302
+ num("c", f"{NAME[d]} sex by contrast arm (subjects, F/M): scored {CONTRAST[d]['case']} {fm(sx[d]['scored']['case'])}"
1303
+ f" vs {CONTRAST[d]['control']} {fm(sx[d]['scored']['control'])}; all paired {fm(sx[d]['all']['case'])} "
1304
+ f"vs {fm(sx[d]['all']['control'])}", sx[d]["source"])
1305
+ num("c", f"{NAME[d]} sex-linked genes excluded from the disease metrics: {gex['n_listed']} listed "
1306
+ f"({sexbuild['chrY_nonPAR_excluded']} chrY non-PAR + {sexbuild['chrX_escape_excluded']} X escape), "
1307
+ f"{gex['n_dropped_from_scoring_genes']} of {gex['n_scoring_genes']} scoring genes",
1308
+ f"{SEXLIST}; {SEXLIST.parent / 'BUILD.json'}; {SCORES_NOSEX / d / 'pooled' / 'summary.json'} (gene_exclusion)")
1309
+
1310
+ # ---------------- slide c ----------------
1311
+ cmp_r = same_draw_compare(few, status, DISEASE, "contrast_r")
1312
+ cmp_d = same_draw_compare(few, status, DISEASE, "deg", min_margin=1.0)
1313
+ cmp_rz = same_draw_compare(few, status, DISEASE, "contrast_r", other="zs_raw")
1314
+ cmp_dz = same_draw_compare(few, status, DISEASE, "deg", min_margin=1.0, other="zs_raw")
1315
+ cmp_rc = same_draw_compare(few, status, DISEASE, "contrast_r", other="zs_cal")
1316
+ cmp_dc = same_draw_compare(few, status, DISEASE, "deg", min_margin=1.0, other="zs_cal")
1317
+ nd = len(DISEASE)
1318
+ deg_l = [d for d, v in cmp_d.items() if v["verdict"] == "lora"]
1319
+ r_l = [d for d, v in cmp_r.items() if v["verdict"] == "lora"]
1320
+ kw_c1 = f"LoRA-5 > scSemi-5: DEG {len(deg_l)}/{len(cmp_d)}, logFC r {len(r_l)}/{len(cmp_r)}"
1321
+ rc_l = [d for d, v in cmp_rc.items() if v["verdict"] == "lora"]
1322
+ kw_c2 = keyword_or_short(f"logFC r: LoRA-5 > calibrated zero-shot {len(rc_l)}/{len(cmp_rc)}",
1323
+ f"logFC r > calibration: {len(rc_l)}/{len(cmp_rc)}")
1324
+ arms4 = ("zs_raw", "zs_cal", "scsemi5", "lora")
1325
+
1326
+ def arm_mean(ds, a, mk):
1327
+ v = [x for x in few_vals(few, ds, a, mk)[0] if not np.isnan(x)]
1328
+ return float(np.mean(v)) if v else np.nan
1329
+
1330
+ def best_arm(d, mk):
1331
+ return float(np.nanmax([arm_mean(d, a, mk) for a in arms4]))
1332
+
1333
+ bc_r = [d for d in DISEASE if few_ref(few, d, "broadcast", "contrast_r")[0] > best_arm(d, "contrast_r")]
1334
+ bc_d = [d for d in DISEASE if few_ref(few, d, "broadcast", "deg")[0] > best_arm(d, "deg")]
1335
+ bc_both = [d for d in bc_r if d in bc_d]
1336
+ if bc_both and bc_both == bc_r:
1337
+ kw_c3 = keyword_or_short(f"{names(bc_both)}: real-bulk broadcast beats all arms",
1338
+ f"Broadcast beats all arms: {len(bc_both)}/{nd}")
1339
+ elif bc_r:
1340
+ kw_c3 = keyword_or_short(f"{names(bc_r)}: broadcast r beats all arms",
1341
+ f"Broadcast r beats all arms: {len(bc_r)}/{nd}")
1342
+ else:
1343
+ kw_c3 = "Every cohort: some arm beats broadcast"
1344
+ kw_c = check_keywords([kw_c1, kw_c2, kw_c3])
1345
+ dmax = {d: sorted({int(x) for x in few[(few.dataset == d) & (few.arm == "lora")]["deg_max"].dropna()}) for d in DISEASE}
1346
+ small = [d for d in DISEASE if subjects_text(info[d])]
1347
+
1348
+ def vz(c, other):
1349
+ return ", ".join(f"{NAME[d]} {v['verdict'].replace('other', other)} {v['n_lora']}/{v['n']}" for d, v in c.items())
1350
+
1351
+ foot_c = (f"Same draws and verdict rule as the previous slide; DEG tie = half the draws equal or mean gap < 1 gene. "
1352
+ f"logFC r = mean over T/B/Mono/NK of case-vs-control log2FC r (generated vs observed); top-50 DEG = "
1353
+ f"Welch+BH overlap summed over {n_types} types (max 250; "
1354
+ + ", ".join(f"{NAME[d]} {rng(dmax[d])}" for d in DISEASE if dmax[d] != [250]) + " per draw). "
1355
+ + "".join(f"{NAME[d]} test = {subjects_text(info[d])} subjects per draw. " for d in small)
1356
+ + f"LoRA-5-better draws (verdict): vs scSemi-5 logFC r {vz(cmp_r, 'scSemi-5')}; DEG {vz(cmp_d, 'scSemi-5')}. "
1357
+ f"Vs zero-shot + calibration: logFC r {vz(cmp_rc, 'calibration')}; DEG {vz(cmp_dc, 'calibration')}. "
1358
+ f"Vs zero-shot (real bulk): logFC r {vz(cmp_rz, 'zero-shot')}; DEG {vz(cmp_dz, 'zero-shot')}. "
1359
+ + f"Broadcast = the input real bulk's own logFC. {nosex_long} "
1360
+ + "Scores: scores/<cohort>/fewshot_n5/draw<j>{,_scsemi5}/.")
1361
+ fs_c = check_foot_short(f"{nosex_short} Top-50 DEG over {n_types} types.")
1362
+ srcc = f"{SCORES}/<cohort>/fewshot_n5/draw<j>{{,_scsemi5}}/summary.json and contrast.csv (Giroux: {SCORES_NOSEX}/giroux2022/)"
1363
+ for cmpx, lab, arm in ((cmp_d, "scSemi-5", "scsemi5"), (cmp_dc, "zero-shot + calibration", "zs_cal"),
1364
+ (cmp_dz, "zero-shot (real bulk)", "zs_raw")):
1365
+ num("c", f"Top-50 DEG LoRA-5 vs {lab} (shared-draw means; LoRA-better / tied draws; verdict): " +
1366
+ "; ".join(f"{NAME[d]} {v['lora']:.1f} vs {v['other']:.1f} ({v['n_lora']}/{v['n']}, {v['n_tie']} tied, {v['verdict']})"
1367
+ for d, v in cmpx.items()), srcc)
1368
+ for cmpx, lab, arm in ((cmp_r, "scSemi-5", "scsemi5"), (cmp_rc, "zero-shot + calibration", "zs_cal"),
1369
+ (cmp_rz, "zero-shot (real bulk)", "zs_raw")):
1370
+ num("c", f"logFC r LoRA-5 vs {lab} (shared-draw means; LoRA-better draws; verdict): " +
1371
+ "; ".join(f"{NAME[d]} {v['lora']:.3f} vs {v['other']:.3f} ({v['n_lora']}/{v['n']}, {v['verdict']})"
1372
+ for d, v in cmpx.items()), srcc)
1373
+ for d in DISEASE:
1374
+ num("c", f"{NAME[d]} broadcast logFC r {few_ref(few, d, 'broadcast', 'contrast_r')[0]:.3f} vs best arm "
1375
+ f"{best_arm(d, 'contrast_r'):.3f}; broadcast DEG {few_ref(few, d, 'broadcast', 'deg')[0]:.1f} vs best arm "
1376
+ f"{best_arm(d, 'deg'):.1f} (means over all draws; arms: zero-shot, zero-shot + calibration, scSemi-5, "
1377
+ f"LoRA-5)", f"{SCORES if d not in NOSEX else SCORES_NOSEX}/{d}/fewshot_n5/draw<j>{{,_scsemi5}}/summary.json")
1378
+ num("c", "DEG maximum per draw: " + ", ".join(f"{NAME[d]} {rng(dmax[d])}" for d in DISEASE),
1379
+ f"{SCORES}/<cohort>/fewshot_n5/draw<j>/summary.json (deg_top50_max; Giroux: {SCORES_NOSEX})")
1380
+ for d in small:
1381
+ num("c", f"{NAME[d]} test subjects per draw: {subjects_text(info[d])} ({CONTRAST[d]['case']} vs "
1382
+ f"{CONTRAST[d]['control']}); test pairs {info[d]['test']}",
1383
+ f"{info[d]['source']} (train_donors); {DATA / d / 'folds.csv'} (group)")
1384
+ # Giroux before / after the exclusion (CSV only)
1385
+ for d in NOSEX:
1386
+ saved = mf.DATASETS
1387
+ mf.DATASETS = [d]
1388
+ try:
1389
+ fo, _ = mf.load_fewpair(SCORES)
1390
+ finally:
1391
+ mf.DATASETS = saved
1392
+ for a in arms4:
1393
+ o = fo[fo.arm == ARM_FILE[a]]
1394
+ n = few[(few.dataset == d) & (few.arm == a)]
1395
+ extra("c", f"{d} few-pair {a}: logFC r / DEG mean over draws, all genes -> sex-linked genes excluded",
1396
+ f"{o.contrast_r.mean():.3f} / {o.deg.mean():.1f} -> {n.contrast_r.mean():.3f} / {n.deg.mean():.1f}",
1397
+ f"{SCORES}/{d}/fewshot_n5 -> {SCORES_NOSEX}/{d}/fewshot_n5")
1398
+ o = fo[fo.arm == "lora5"]
1399
+ n = few[(few.dataset == d) & (few.arm == "lora")]
1400
+ extra("c", f"{d} few-pair broadcast: logFC r / DEG mean over draws, all genes -> sex-linked genes excluded",
1401
+ f"{o.broadcast_r.mean():.3f} / {o.deg_broadcast.mean():.1f} -> {n.broadcast_r.mean():.3f} / "
1402
+ f"{n.deg_broadcast.mean():.1f}", f"{SCORES}/{d}/fewshot_n5 -> {SCORES_NOSEX}/{d}/fewshot_n5")
1403
+ slides.append({"title": "5 donors: LoRA vs scSemiProfiler — disease signal", "layout": "figure_keywords",
1404
+ "figures": [str(FIGDIR / "sec09_fewpair_disease.png")], "keywords": kw_c, "footnote": foot_c,
1405
+ "footnote_short": fs_c, "numbers": NUMS["c"]})
1406
+
1407
+ # ---------------- slide d ----------------
1408
+ L = {d: pooled[d][POOLED_ARMS["lora"]] for d in ORDER}
1409
+ Z = {d: pooled[d][POOLED_ARMS["zs_raw"]] for d in ORDER}
1410
+ ZC = {d: pooled[d][POOLED_ARMS["zs_cal"]] for d in ORDER}
1411
+ S = {d: pooled[d][POOLED_ARMS["sconly_cal"]] for d in ORDER}
1412
+ has_sc = sc_cohorts(pooled)
1413
+ B = {d: [Z[d], ZC[d], S[d]] + ([pooled[d][SR.CV_ARM]] if d in has_sc else []) for d in ORDER}
1414
+ n_arms = len(fivefold_arms(pooled))
1415
+ 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]])]
1416
+ for mk in ("coverage", "contrast_r", "deg")}
1417
+ kw_d1 = f"LoRA tops coverage {len(best['coverage'])}/{len(ORDER)}, logFC r {len(best['contrast_r'])}/{len(DISEASE)}"
1418
+ jb = baselines_text([b["coverage"] for b in B["ji2025_chili"] if not np.isnan(b["coverage"])])
1419
+ jl = f"{L['ji2025_chili']['coverage']:.2f}"
1420
+ kw_d2 = keyword_or_short(f"Ji whole blood: baselines {jb}, LoRA {jl}", f"Ji whole blood: LoRA {jl}, others {jb}")
1421
+ bc_win = [d for d in DISEASE if L[d]["broadcast_r"] > L[d]["contrast_r"]]
1422
+ kw_d3 = ("; ".join(f"{NAME[d]}: broadcast r {L[d]['broadcast_r']:.2f} > LoRA {L[d]['contrast_r']:.2f}" for d in bc_win)
1423
+ if bc_win else "LoRA above broadcast in every cohort")
1424
+ kw_d3 = keyword_or_short(kw_d3, f"Broadcast r above LoRA: {names(bc_win)}")
1425
+ kw_d = check_keywords([kw_d1, kw_d2, kw_d3])
1426
+ foot_d = (f"Donor-level 5-fold CV; each pair scored once, by the fold model that never trained on its donor "
1427
+ f"(one pooled call per cohort). LoRA r={lora_r} on all training donors' real bulk, early stop on "
1428
+ f"inner-val donors. Zero-shot = base model without fine-tuning, fed the test pair's real bulk as measured; "
1429
+ f"zero-shot + calibration = the same model fed gene-wise calibrated bulk (alpha fitted on the fold's "
1430
+ f"training donors); sc-only fine-tune (+ calibration) = full fine-tune on training donors' sc pseudobulk, "
1431
+ f"fed calibrated bulk. " + (
1432
+ f"scSemiProfiler, all training pairs = scSemiProfiler with every training donor of the fold "
1433
+ f"(inner-val included) as representatives, scored for the same pairs and reference cells "
1434
+ f"({names(has_sc)}"
1435
+ + "".join(f"; {NAME[r['dataset']]}: {r['reason']}" for r in SC_LOG if r["status"] == "used" and r["reason"])
1436
+ + "). " if has_sc else "")
1437
+ + f"Base f01 6k·1x·E16. LoRA best of {n_arms} arms: coverage {len(best['coverage'])}/{len(ORDER)}, "
1438
+ f"logFC r {len(best['contrast_r'])}/{len(DISEASE)}, top-50 DEG {len(best['deg'])}/{len(DISEASE)}. "
1439
+ f"Broadcast = raw real bulk. Sepsis DEG from pooled_deg. {nosex_long} "
1440
+ f"Scores: scores/<cohort>/pooled/summary.json.")
1441
+ fs_d = check_foot_short(f"Donor-level 5-fold CV. {nosex_short}")
1442
+ psrc = (f"{SCORES}/<cohort>/pooled/summary.json (Sepsis DEG: {SCORES}/ye2026_sepsis/pooled_deg/summary.json; "
1443
+ f"Giroux: {SCORES_NOSEX}/giroux2022/pooled/summary.json)")
1444
+ num("d", f"LoRA best of {n_arms} arms: coverage {len(best['coverage'])}/{len(ORDER)}, logFC r "
1445
+ f"{len(best['contrast_r'])}/{len(DISEASE)}, top-50 DEG {len(best['deg'])}/{len(DISEASE)}", psrc)
1446
+ num("d", f"Ji coverage: zero-shot {Z['ji2025_chili']['coverage']:.3f}, zero-shot + calibration "
1447
+ f"{ZC['ji2025_chili']['coverage']:.3f}, sc-only (+ calibration) {S['ji2025_chili']['coverage']:.3f}, "
1448
+ f"LoRA {L['ji2025_chili']['coverage']:.3f}", SCORES / "ji2025_chili" / "pooled" / "summary.json")
1449
+ for d in bc_win:
1450
+ num("d", f"{NAME[d]} logFC r: broadcast {L[d]['broadcast_r']:.3f} vs LoRA {L[d]['contrast_r']:.3f}; "
1451
+ f"DEG broadcast {L[d]['deg_broadcast']:.0f} vs LoRA {L[d]['deg']:.0f}",
1452
+ (SCORES_NOSEX if d in NOSEX else SCORES) / d / "pooled" / "summary.json")
1453
+ num("d", "LoRA logFC r vs broadcast: " + ", ".join(f"{NAME[d]} {L[d]['contrast_r']:.3f} vs {L[d]['broadcast_r']:.3f}"
1454
+ for d in DISEASE), psrc)
1455
+ for mk, lab in (("coverage", "coverage"), ("contrast_r", "logFC r"), ("deg", "top-50 DEG")):
1456
+ dd = ORDER if mk == "coverage" else DISEASE
1457
+ f = "{:.3f}" if mk != "deg" else "{:.0f}"
1458
+ num("d", f"{lab} LoRA / zero-shot + calibration / zero-shot / sc-only (+ calibration): " +
1459
+ ", ".join(f"{NAME[d]} {f.format(L[d][mk])} / {f.format(ZC[d][mk])} / {f.format(Z[d][mk])} / "
1460
+ f"{f.format(S[d][mk])}" for d in dd), psrc)
1461
+ if has_sc:
1462
+ def _f(x, nd):
1463
+ return "n/a" if np.isnan(x) else f"{x:.{nd}f}"
1464
+ num("d", "scSemiProfiler, all training pairs: coverage / logFC r / top-50 DEG (n/a = no contrast or rescore "
1465
+ "pending): " + ", ".join(
1466
+ f"{NAME[d]} {_f(pooled[d][SR.CV_ARM]['coverage'], 3)} / {_f(pooled[d][SR.CV_ARM]['contrast_r'], 3)} / "
1467
+ f"{_f(pooled[d][SR.CV_ARM]['deg'], 0)}" for d in has_sc),
1468
+ "; ".join(pooled[d][SR.CV_ARM]["source"] for d in has_sc))
1469
+ num("d", "Pooled n (pairs / donors): " + ", ".join(f"{NAME[r.dataset]} {r.n_rows}/{r.n_donors}" for r in tab.itertuples()),
1470
+ f"{SCORES}/<cohort>/pooled/summary.json (n_donors); {DATA}/<cohort>/fewshot_n5/DRAWS.json")
1471
+ num("d", f"early stopping: {early}", README)
1472
+ po, _ = mf.load_pooled(SCORES)
1473
+ for d in ORDER:
1474
+ for a, f in POOLED_ARMS.items():
1475
+ extra("d", f"{d} pooled {a} ({f}) coverage / precision / L1 / r / DEG",
1476
+ f"{pooled[d][f]['coverage']:.3f} / {pooled[d][f]['precision']:.3f} / {pooled[d][f]['comp_l1']:.3f} / "
1477
+ f"{pooled[d][f]['contrast_r']:.3f} / {pooled[d][f]['deg']:.0f}",
1478
+ pooled[d][f]["source"] + (f"; DEG: {pooled[d][f]['deg_source']}" if "deg_source" in pooled[d][f] else ""))
1479
+ if d in NOSEX:
1480
+ extra("d", f"{d} pooled {a} ({f}) logFC r / broadcast r / DEG / DEG broadcast, all genes -> "
1481
+ f"sex-linked genes excluded",
1482
+ f"{po[d][f]['contrast_r']:.3f} / {po[d][f]['broadcast_r']:.3f} / {po[d][f]['deg']:.0f} / "
1483
+ f"{po[d][f]['deg_broadcast']:.0f} -> {pooled[d][f]['contrast_r']:.3f} / "
1484
+ f"{pooled[d][f]['broadcast_r']:.3f} / {pooled[d][f]['deg']:.0f} / {pooled[d][f]['deg_broadcast']:.0f}",
1485
+ f"{po[d][f]['source']} -> {pooled[d][f]['source']}")
1486
+ for r in SC_LOG:
1487
+ extra("d", f"{r['dataset']} scSemiProfiler 5-fold ({SR.CV_ARM}) lookup", f"{r['status']} {r['reason']}".strip(),
1488
+ r["source"])
1489
+ slides.append({"title": "All pairs, 5-fold", "layout": "full", "figures": [str(FIGDIR / "sec09_fivefold.png")],
1490
+ "keywords": kw_d, "footnote": foot_d, "footnote_short": fs_d, "numbers": NUMS["d"]})
1491
+
1492
+ for s in slides:
1493
+ for k in ("title", "footnote"):
1494
+ check_text(s[k], k)
1495
+ for n in s["numbers"]:
1496
+ check_text(n["value"], "quoted number")
1497
+ spec = {"section": "09", "slides": slides, "scripts": [str(SCRIPT)],
1498
+ "generated_from": "tools/sec09_paired_validation.py (rerun to refresh; do not edit by hand)",
1499
+ "scsemi_draws_used": f"{ns_used}/{ns_all}"}
1500
+ (OUTDATA / "sec09_slide_text.json").write_text(json.dumps(spec, indent=1, ensure_ascii=False))
1501
+ flat = [{"slide": k, "item": "quoted on slide", "value": n["value"], "source": n["source"]}
1502
+ for k in "abcd" for n in NUMS[k]] + EXTRA
1503
+ pd.DataFrame(flat).to_csv(OUTDATA / "sec09_quoted_numbers.csv", index=False)
1504
+ # nothing written by this script may carry refcal / VAE / TPM / AIFI / AIDA wording
1505
+ for p in [OUTDATA / "sec09_slide_text.json"] + sorted(OUTDATA.glob("sec09_*.csv")):
1506
+ m = OFF_STORY.search(p.read_text(encoding="utf-8"))
1507
+ if m:
1508
+ raise ValueError(f"{p}: off-story text {m.group(0)!r}")
1509
+
1510
+ if not any(r["status"] == "used" for r in SC_LOG):
1511
+ print(f"NOTE: no scSemiProfiler 5-fold call ({SR.CV_ARM}) under {SR.plan_root()}/scores/<ds>/{SR.CV_EXP}/pooled*; "
1512
+ f"the 5-fold slide has no scSemiProfiler bar.")
1513
+ for r in SC_LOG:
1514
+ print(f" scSemiProfiler 5-fold {r['dataset']}: {r['status']} {r['reason']} ({r['source']})")
1515
+ print("scSemiProfiler draws used per dataset:",
1516
+ {NAME[d]: f"{int((used.dataset == d).sum())}/{n_draws(few, d, 'lora')}" for d in ORDER})
1517
+ for s in slides:
1518
+ print(f"\n== {s['title']} [{s['layout']}]")
1519
+ for k in s["keywords"]:
1520
+ print(" *", k, f"({n_words(k)} words, {len(k)} chars)")
1521
+ print(" footnote_short:", s["footnote_short"], f"({len(s['footnote_short'])} chars)")
1522
+ print(" footnote:", s["footnote"])
1523
+ for n in s["numbers"]:
1524
+ print(" #", n["value"])
1525
+ for p in sorted(FIGDIR.glob("sec09_*.png")):
1526
+ print("wrote", p)
1527
+ return 0
1528
+
1529
+
1530
+ if __name__ == "__main__":
1531
+ sys.exit(main())