junidude14 commited on
Commit
53be089
·
verified ·
1 Parent(s): 9b08c22

Archive 4 checkpoints (1-4)

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