Archive 4 checkpoints (1-4)
Browse files- paper-releases/pbisc-diffusion/updates/20261008T121550Z-deck-fig4-rules-no-broadcast/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/fig4_disease.py +276 -0
- paper-releases/pbisc-diffusion/updates/20261008T121550Z-deck-fig4-rules-no-broadcast/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec04_sle_benchmark.py +355 -0
- paper-releases/pbisc-diffusion/updates/20261008T121550Z-deck-fig4-rules-no-broadcast/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec08_pairs_needed.py +892 -0
- paper-releases/pbisc-diffusion/updates/20261008T121550Z-deck-fig4-rules-no-broadcast/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec09_cat_curves.py +157 -0
paper-releases/pbisc-diffusion/updates/20261008T121550Z-deck-fig4-rules-no-broadcast/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/fig4_disease.py
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Fig. 4 disease-signal slides of the 2026-09-30 paper-summary deck (2026-10-08; user decisions of that day: the
|
| 3 |
+
main comparison is 5 pairs, LoRA-5 vs scSemiProfiler with the same 5 donors as representatives; 5-fold CV is
|
| 4 |
+
reported separately; no bulk-broadcast baseline; partial r, the cell-type signal beyond the input bulk, is emphasised).
|
| 5 |
+
|
| 6 |
+
CPU only, plotting only. Four paired disease cohorts; Giroux disease metrics from scores_nosex/ (sex-linked genes
|
| 7 |
+
excluded), as everywhere in the deck. Per arm, from the scorer's summary.json (paired_finetune_intradataset_20260927):
|
| 8 |
+
logFC r headline contrast_mean_cp10k_r_gen: Pearson r of case-vs-control logFC (mean CP10K), mean of T/B/Mono/NK
|
| 9 |
+
partial r per_arm contrast.mean_cp10k.mean_partial_r: the same r after both logFCs are residualised on the input
|
| 10 |
+
bulk's logFC (the part of the cell-type signal the bulk does not carry)
|
| 11 |
+
DEG headline deg_top50_sum: top-50 Welch DEG overlap with the observed cells, summed over types
|
| 12 |
+
(older pooled sepsis calls keep it in pooled_deg/)
|
| 13 |
+
Slides:
|
| 14 |
+
A "Disease signal with 5 pairs" 5 donors x 5 draws: zero-shot (real bulk), zero-shot + calibration,
|
| 15 |
+
scSemiProfiler-5, LoRA-5 (bars = mean, dots = draws)
|
| 16 |
+
B "5-fold CV: disease signal" pooled 5-fold: zero-shot, + calibration, sc-only fine-tune (+ cal),
|
| 17 |
+
scSemiProfiler (same pairs), LoRA
|
| 18 |
+
C "Sepsis: fine-tuning variants" 5-fold sepsis: LoRA rank 4 / 16 / 64, full fine-tune, multi-K, recipes
|
| 19 |
+
Gates: every logFC r and DEG value equals data/sec09_fewpair_disease.csv / data/sec09_fivefold.csv (the deck's
|
| 20 |
+
section-9 tables); the two calls of one draw score the same donors.
|
| 21 |
+
Outputs: figures/fig4_disease_{fewpair,fivefold,variants}.{png,pdf}, data/fig4_disease.csv,
|
| 22 |
+
data/fig4_disease_slide_text.json
|
| 23 |
+
"""
|
| 24 |
+
from __future__ import annotations
|
| 25 |
+
|
| 26 |
+
import json
|
| 27 |
+
import os
|
| 28 |
+
import sys
|
| 29 |
+
from pathlib import Path
|
| 30 |
+
|
| 31 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = "" # plotting only
|
| 32 |
+
|
| 33 |
+
import numpy as np
|
| 34 |
+
import pandas as pd
|
| 35 |
+
|
| 36 |
+
DECK = Path(__file__).resolve().parents[1]
|
| 37 |
+
sys.path.insert(0, str(DECK / "tools"))
|
| 38 |
+
import style as ST # noqa: E402
|
| 39 |
+
import matplotlib.pyplot as plt # noqa: E402
|
| 40 |
+
|
| 41 |
+
T = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927")
|
| 42 |
+
FIGDIR, OUTDATA = DECK / "figures", DECK / "data"
|
| 43 |
+
DIS = ["ye2026_sepsis", "imperial_eskd", "giroux2022", "ji2025_chili"]
|
| 44 |
+
NAME = {"ye2026_sepsis": "Sepsis", "imperial_eskd": "Imperial", "giroux2022": "Giroux", "ji2025_chili": "Ji"}
|
| 45 |
+
METRICS = [("r", "logFC r ↑"), ("partial", "Partial r beyond bulk ↑"), ("deg", "Top-50 DEG overlap ↑")]
|
| 46 |
+
FEW = [("zs_raw", "zs_raw", "Zero-shot, real bulk", ST.ARM["zs_raw"]),
|
| 47 |
+
("zs_cal", "zs_cal", "Zero-shot + calibration", ST.ARM["zs_cal"]),
|
| 48 |
+
("scsemi5", "scsemi5", "scSemiProfiler, 5 donors", ST.ARM["scsemi"]),
|
| 49 |
+
("lora5", "lora", "PBISC LoRA, 5 donors", ST.ARM["lora"])]
|
| 50 |
+
POOL = [("zs__raw", "zs_raw", "Zero-shot, real bulk", ST.ARM["zs_raw"]),
|
| 51 |
+
("zs__cal", "zs_cal", "Zero-shot + calibration", ST.ARM["zs_cal"]),
|
| 52 |
+
("pseudo_full__cal", "sconly_cal", "sc-only fine-tune (+ cal.)", ST.ARM["sconly"]),
|
| 53 |
+
("scsemi__raw", "scsemi_all", "scSemiProfiler, same pairs", ST.ARM["scsemi"]),
|
| 54 |
+
("real_lora__raw", "lora", "PBISC LoRA", ST.ARM["lora"])]
|
| 55 |
+
VARIANTS = [("lora_r4__raw", "lora_rank_20261001/pooled", "LoRA r = 4"),
|
| 56 |
+
("real_lora__raw", "pooled_deg", "LoRA r = 16 (used)"),
|
| 57 |
+
("lora_r64__raw", "lora_rank_20261001/pooled", "LoRA r = 64"),
|
| 58 |
+
("real_full__raw", "pooled_deg", "Full fine-tune"),
|
| 59 |
+
("lora_multik__raw", "pooled_deg", "LoRA, multi-K"),
|
| 60 |
+
("lora_recipe__raw", "pooled_deg", "LoRA + recipes")]
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def root(ds: str) -> Path:
|
| 64 |
+
return T / ("scores_nosex" if ds == "giroux2022" else "scores") / ds
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def read(sdir: Path, arm: str) -> dict:
|
| 68 |
+
s = json.loads((sdir / "summary.json").read_text())
|
| 69 |
+
h, c = s["headline"][arm], s["per_arm"][arm]["contrast"]["mean_cp10k"]
|
| 70 |
+
return {"r": h.get("contrast_mean_cp10k_r_gen"), "partial": c.get("mean_partial_r"), "deg": h.get("deg_top50_sum"),
|
| 71 |
+
"donors": tuple(sorted(map(str, s["donors"]))), "source": str(sdir.relative_to(T))}
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def refs_from_spec(short: list[str]) -> list[str]:
|
| 75 |
+
spec = json.loads((OUTDATA / "slides_spec.json").read_text())["slides"]
|
| 76 |
+
full = {}
|
| 77 |
+
for s in spec:
|
| 78 |
+
for a, b in zip(s.get("refs", []), s.get("refs_full", [])):
|
| 79 |
+
full.setdefault(a, b)
|
| 80 |
+
return [full[k] for k in short]
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def load() -> pd.DataFrame:
|
| 84 |
+
rows = []
|
| 85 |
+
for ds in DIS:
|
| 86 |
+
for j in range(5):
|
| 87 |
+
base = root(ds) / "fewshot_n5" / f"draw{j}"
|
| 88 |
+
donors = None
|
| 89 |
+
for arm, series, _l, _c in FEW:
|
| 90 |
+
v = read(base.parent / f"draw{j}_scsemi5" if arm == "scsemi5" else base, arm)
|
| 91 |
+
donors = donors or v["donors"]
|
| 92 |
+
if v["donors"] != donors:
|
| 93 |
+
raise SystemExit(f"{ds} draw {j}: {arm} scores other donors")
|
| 94 |
+
rows.append({"design": "fewpair", "dataset": ds, "draw": j, "arm": arm, "series": series, **v})
|
| 95 |
+
for arm, series, _l, _c in POOL:
|
| 96 |
+
sdir = root(ds) / ("scsemi_cv_20261002/pooled" if arm == "scsemi__raw" else "pooled")
|
| 97 |
+
v = read(sdir, arm)
|
| 98 |
+
if v["deg"] is None and (root(ds) / "pooled_deg" / "summary.json").exists():
|
| 99 |
+
d2 = read(root(ds) / "pooled_deg", arm)
|
| 100 |
+
if d2["donors"] != v["donors"] or abs(d2["r"] - v["r"]) > 1e-9:
|
| 101 |
+
raise SystemExit(f"{ds} {arm}: pooled_deg differs from pooled")
|
| 102 |
+
v["deg"], v["source"] = d2["deg"], v["source"] + " (DEG: pooled_deg)"
|
| 103 |
+
rows.append({"design": "fivefold", "dataset": ds, "draw": None, "arm": arm, "series": series, **v})
|
| 104 |
+
for arm, sub, _l in VARIANTS:
|
| 105 |
+
v = read(T / "scores" / "ye2026_sepsis" / sub, arm)
|
| 106 |
+
rows.append({"design": "variants", "dataset": "ye2026_sepsis", "draw": None, "arm": arm, "series": arm, **v})
|
| 107 |
+
tab = pd.DataFrame(rows).drop(columns=["donors"])
|
| 108 |
+
# gates: logFC r and DEG equal the deck's section-9 tables
|
| 109 |
+
fp = pd.read_csv(OUTDATA / "sec09_fewpair_disease.csv")
|
| 110 |
+
ff = pd.read_csv(OUTDATA / "sec09_fivefold.csv")
|
| 111 |
+
n = 0
|
| 112 |
+
for _, r in tab[tab.design != "variants"].iterrows():
|
| 113 |
+
ref = fp[(fp.dataset == r.dataset) & (fp.series == r.series) & (pd.to_numeric(fp.draw, errors="coerce") == float(r.draw))] \
|
| 114 |
+
if r.design == "fewpair" else ff[(ff.dataset == r.dataset) & (ff.series == r.series)]
|
| 115 |
+
for m, col in (("contrast_r", "r"), ("deg", "deg")):
|
| 116 |
+
x = ref[ref.metric == m].value
|
| 117 |
+
if len(x) == 1 and pd.notna(r[col]):
|
| 118 |
+
if abs(float(x.iloc[0]) - float(r[col])) > 1e-6:
|
| 119 |
+
raise SystemExit(f"{r.design} {r.dataset} {r.arm} draw {r.draw}: {m} {r[col]} != deck {x.iloc[0]}")
|
| 120 |
+
n += 1
|
| 121 |
+
want = 2 * len(tab[tab.design == "fewpair"]) + 2 * len(tab[tab.design == "fivefold"])
|
| 122 |
+
print(f"gate: {n} of {want} logFC r / DEG values checked against the section-9 tables")
|
| 123 |
+
if n < want - 8: # a few DEG cells are blank in the deck tables (older pooled calls)
|
| 124 |
+
raise SystemExit("too few values matched the section-9 tables")
|
| 125 |
+
return tab
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def bars(ax, tab, arms, metric, dots):
|
| 129 |
+
"""grouped bars over the four cohorts; dots = draws (5-donor design)"""
|
| 130 |
+
k = len(arms)
|
| 131 |
+
w = 0.8 / k
|
| 132 |
+
for i, (arm, _s, _l, col) in enumerate(arms):
|
| 133 |
+
for g, ds in enumerate(DIS):
|
| 134 |
+
v = tab[(tab.dataset == ds) & (tab.arm == arm)][metric].astype(float)
|
| 135 |
+
x = g + (i - (k - 1) / 2) * w
|
| 136 |
+
ax.bar(x, v.mean(), w * 0.92, color=col, edgecolor="none", zorder=2)
|
| 137 |
+
if dots and len(v) > 1:
|
| 138 |
+
ax.scatter(np.full(len(v), x) + np.linspace(-w * 0.2, w * 0.2, len(v)), v, s=7, color="white",
|
| 139 |
+
edgecolor=ST.INK, linewidth=0.5, zorder=3)
|
| 140 |
+
if not dots:
|
| 141 |
+
ax.text(x, max(v.mean(), 0) + (2 if metric == "deg" else 0.012), f"{v.mean():.0f}" if metric == "deg"
|
| 142 |
+
else f"{v.mean():.2f}", ha="center", va="bottom", fontsize=ST.FS - 7, color=ST.SUBINK, rotation=90)
|
| 143 |
+
ax.axhline(0, color=ST.INK, linewidth=0.8)
|
| 144 |
+
ax.set_xticks(range(len(DIS)), [NAME[d] for d in DIS], fontsize=ST.FS - 3)
|
| 145 |
+
ax.grid(axis="y", color="#E3E3E3", linewidth=0.8)
|
| 146 |
+
ax.set_axisbelow(True)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def figure(tab, arms, name, dots):
|
| 150 |
+
fig, axes = plt.subplots(1, 3, figsize=ST.FULL, gridspec_kw={"wspace": 0.28})
|
| 151 |
+
for ax, (m, lab) in zip(axes, METRICS):
|
| 152 |
+
bars(ax, tab, arms, m, dots)
|
| 153 |
+
ax.set_title(lab, fontsize=ST.FS - 1, loc="left", fontweight="bold" if m == "partial" else "normal")
|
| 154 |
+
if m != "deg":
|
| 155 |
+
ax.set_ylim(min(-0.12, ax.get_ylim()[0]), 0.95)
|
| 156 |
+
handles = [plt.Rectangle((0, 0), 1, 1, color=c) for _a, _s, _l, c in arms]
|
| 157 |
+
fig.legend(handles, [l for _a, _s, l, _c in arms], loc="lower center", ncol=len(arms), bbox_to_anchor=(0.5, -0.08),
|
| 158 |
+
fontsize=ST.FS - 3)
|
| 159 |
+
ST.save(fig, name, FIGDIR)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def main() -> int:
|
| 163 |
+
tab = load()
|
| 164 |
+
tab.to_csv(OUTDATA / "fig4_disease.csv", index=False, float_format="%.6g")
|
| 165 |
+
few, ff, var = (tab[tab.design == d] for d in ("fewpair", "fivefold", "variants"))
|
| 166 |
+
figure(few, FEW, "fig4_disease_fewpair", dots=True)
|
| 167 |
+
figure(ff, POOL, "fig4_disease_fivefold", dots=False)
|
| 168 |
+
# C: sepsis variants, horizontal bars per metric
|
| 169 |
+
fig, axes = plt.subplots(1, 3, figsize=ST.FULL, sharey=True, gridspec_kw={"wspace": 0.12})
|
| 170 |
+
y = np.arange(len(VARIANTS))
|
| 171 |
+
for ax, (m, lab) in zip(axes, METRICS):
|
| 172 |
+
for i, (arm, _sub, _l) in enumerate(VARIANTS):
|
| 173 |
+
v = float(var[var.arm == arm][m].iloc[0])
|
| 174 |
+
col = ST.ARM["full_ft"] if arm == "real_full__raw" else ST.ARM["lora"]
|
| 175 |
+
ax.barh(i, v, 0.62, color=col, alpha=1.0 if arm == "real_lora__raw" else 0.55, edgecolor="none")
|
| 176 |
+
ax.text(v + (0.6 if m == "deg" else 0.01), i, f"{v:.0f}" if m == "deg" else f"{v:.2f}", va="center",
|
| 177 |
+
fontsize=ST.FS - 4, color=ST.SUBINK)
|
| 178 |
+
ax.set_title(lab, fontsize=ST.FS - 1, loc="left", fontweight="bold" if m == "partial" else "normal")
|
| 179 |
+
ax.grid(axis="x", color="#E3E3E3", linewidth=0.8)
|
| 180 |
+
ax.set_axisbelow(True)
|
| 181 |
+
ax.tick_params(axis="y", length=0)
|
| 182 |
+
if m != "deg":
|
| 183 |
+
ax.set_xlim(0, 0.7)
|
| 184 |
+
axes[0].set_yticks(y, [l for _a, _s, l in VARIANTS], fontsize=ST.FS - 2)
|
| 185 |
+
axes[0].set_ylim(len(VARIANTS) - 0.5, -0.5)
|
| 186 |
+
ST.save(fig, "fig4_disease_variants", FIGDIR)
|
| 187 |
+
|
| 188 |
+
# ------------------------------------------------------------------ keywords and numbers
|
| 189 |
+
piv = few.pivot_table(index=["dataset", "draw"], columns="arm", values=["r", "partial", "deg"])
|
| 190 |
+
win = {m: int((piv[m]["lora5"] > piv[m]["scsemi5"]).sum()) for m in ("r", "partial", "deg")}
|
| 191 |
+
tie_deg = int((piv["deg"]["lora5"] == piv["deg"]["scsemi5"]).sum())
|
| 192 |
+
nd = len(piv)
|
| 193 |
+
mean = few.groupby(["dataset", "arm"])[["r", "partial", "deg"]].mean()
|
| 194 |
+
beats_zs = sum(all(mean.loc[(ds, "lora5"), m] > max(mean.loc[(ds, "zs_raw"), m], mean.loc[(ds, "zs_cal"), m])
|
| 195 |
+
for m in ("r", "partial")) for ds in DIS)
|
| 196 |
+
best_p = max(DIS, key=lambda d: mean.loc[(d, "lora5"), "partial"])
|
| 197 |
+
kwA = [f"vs scSemiProfiler-5: logFC r {win['r']}/{nd}, partial r {win['partial']}/{nd} draws",
|
| 198 |
+
f"Beyond bulk: partial r {mean.loc[(best_p, 'lora5'), 'partial']:.2f} vs "
|
| 199 |
+
f"{mean.loc[(best_p, 'scsemi5'), 'partial']:.2f} ({NAME[best_p]})",
|
| 200 |
+
f"Above zero-shot and calibration in {beats_zs}/{len(DIS)} cohorts"]
|
| 201 |
+
fm = ff.set_index(["dataset", "arm"])
|
| 202 |
+
top_r = max(DIS, key=lambda d: fm.loc[(d, "real_lora__raw"), "r"])
|
| 203 |
+
vs_sc = {m: sum(fm.loc[(d, "real_lora__raw"), m] > fm.loc[(d, "scsemi__raw"), m] for d in DIS) for m in ("r", "partial", "deg")}
|
| 204 |
+
others = [a for a, *_ in POOL if a not in ("real_lora__raw", "scsemi__raw")]
|
| 205 |
+
top_pbisc = sum(fm.loc[(d, "real_lora__raw"), "r"] > max(fm.loc[(d, a), "r"] for a in others) for d in DIS)
|
| 206 |
+
kwB = [f"logFC r up to {fm.loc[(top_r, 'real_lora__raw'), 'r']:.2f} ({NAME[top_r]})",
|
| 207 |
+
f"vs scSemiProfiler: r {vs_sc['r']}/4, partial r {vs_sc['partial']}/4, DEG {vs_sc['deg']}/4 cohorts",
|
| 208 |
+
f"Top PBISC version on logFC r in {top_pbisc}/4 cohorts"]
|
| 209 |
+
vv = var.set_index("arm")
|
| 210 |
+
kwC = [f"LoRA r16 ≈ full fine-tune: r {vv.loc['real_lora__raw', 'r']:.2f} vs {vv.loc['real_full__raw', 'r']:.2f}",
|
| 211 |
+
f"Rank 64: r {vv.loc['lora_r64__raw', 'r']:.2f}, DEG {vv.loc['lora_r64__raw', 'deg']:.0f} vs "
|
| 212 |
+
f"{vv.loc['real_lora__raw', 'deg']:.0f}",
|
| 213 |
+
"Multi-K and recipes: no gain"]
|
| 214 |
+
if not (vv.loc["lora_multik__raw", "r"] <= vv.loc["real_lora__raw", "r"] + 0.01
|
| 215 |
+
and vv.loc["lora_recipe__raw", "r"] <= vv.loc["real_lora__raw", "r"] + 0.01):
|
| 216 |
+
kwC[2] = "Multi-K and recipes: see notes"
|
| 217 |
+
ties_txt = (f"Top-50 DEG: LoRA-5 ahead in {win['deg']}/{nd} draws, tied in {tie_deg} (Giroux and Ji: few DEG in "
|
| 218 |
+
"the observed cells, mostly 0 for every method).")
|
| 219 |
+
giroux_txt = ("Giroux's 5-donor test sets hold 10-12 samples from 4 subjects (2 vs 2), so its disease metrics are "
|
| 220 |
+
"noisy; there scSemiProfiler-5 is ahead.")
|
| 221 |
+
fullA = ("Main comparison: 5 donors per draw, LoRA-5 vs scSemiProfiler with the same 5 donors as representatives "
|
| 222 |
+
"(and the two zero-shot PBISC versions), 5 draws per cohort, every other usable sample tested. logFC r = "
|
| 223 |
+
"Pearson r of case-vs-control logFC (mean CP10K) with the observed cells, mean over T, B, monocyte and NK. "
|
| 224 |
+
"Partial r = the same after both logFCs are residualised on the input bulk's logFC: the cell-type signal "
|
| 225 |
+
"the bulk does not carry. " + ties_txt + " " + giroux_txt + " Giroux: sex-linked genes excluded (severity "
|
| 226 |
+
"is confounded with sex). Per cohort, mean over draws (r / partial r / DEG): "
|
| 227 |
+
+ "; ".join(f"{NAME[d]} LoRA-5 {mean.loc[(d, 'lora5'), 'r']:.2f} / {mean.loc[(d, 'lora5'), 'partial']:.2f} / "
|
| 228 |
+
f"{mean.loc[(d, 'lora5'), 'deg']:.1f}, scSemiProfiler-5 {mean.loc[(d, 'scsemi5'), 'r']:.2f} / "
|
| 229 |
+
f"{mean.loc[(d, 'scsemi5'), 'partial']:.2f} / {mean.loc[(d, 'scsemi5'), 'deg']:.1f}" for d in DIS)
|
| 230 |
+
+ ". Source: data/fig4_disease.csv (scores[_nosex]/<cohort>/fewshot_n5/draw<j>[_scsemi5]).").replace("-", "–")
|
| 231 |
+
fullB = ("Reported separately from the 5-pair comparison: donor-level 5-fold CV, each sample generated by the fold "
|
| 232 |
+
"model that never trained on it, one pooled scoring call per method; scSemiProfiler uses exactly LoRA's "
|
| 233 |
+
"training pairs as representatives. Per cohort LoRA vs scSemiProfiler (r / partial r / DEG): "
|
| 234 |
+
+ "; ".join(f"{NAME[d]} {fm.loc[(d, 'real_lora__raw'), 'r']:.2f} / {fm.loc[(d, 'real_lora__raw'), 'partial']:.2f}"
|
| 235 |
+
f" / {fm.loc[(d, 'real_lora__raw'), 'deg']:.0f} vs {fm.loc[(d, 'scsemi__raw'), 'r']:.2f} / "
|
| 236 |
+
f"{fm.loc[(d, 'scsemi__raw'), 'partial']:.2f} / {fm.loc[(d, 'scsemi__raw'), 'deg']:.0f}" for d in DIS)
|
| 237 |
+
+ ". Giroux: sex-linked genes excluded. Source: data/fig4_disease.csv (scores[_nosex]/<cohort>/pooled, "
|
| 238 |
+
"scsemi_cv_20261002/pooled; sepsis DEG from pooled_deg).")
|
| 239 |
+
fullC = ("Sepsis, 82 donors, pooled 5-fold CV, same scorer and donors for every variant. LoRA r = 16 is the model "
|
| 240 |
+
"used throughout the deck. Full fine-tune trains all 54.2 M weights, LoRA r16 1.30 M. Multi-K: LoRA "
|
| 241 |
+
"trained on K = 250-4,000 conditions; recipes: half of each batch is pseudobulk from the training donors' "
|
| 242 |
+
"cells. " + "; ".join(f"{l}: r {vv.loc[a, 'r']:.3f}, partial r {vv.loc[a, 'partial']:.3f}, DEG "
|
| 243 |
+
f"{vv.loc[a, 'deg']:.0f}" for a, _s, l in VARIANTS)
|
| 244 |
+
+ ". Source: data/fig4_disease.csv (scores/ye2026_sepsis/{pooled_deg, lora_rank_20261001/pooled}).").replace("-", "–")
|
| 245 |
+
refsA = ["Wang 2024, Nat Commun", "Viñas Torné 2026, Nat Biotechnol"]
|
| 246 |
+
slides = [
|
| 247 |
+
{"title": "Disease signal with 5 pairs: LoRA-5 vs others", "layout": "full",
|
| 248 |
+
"figures": [str(FIGDIR / "fig4_disease_fewpair.png")], "keywords": kwA,
|
| 249 |
+
"footnote_short": "5 donors, 5 draws; bars = mean, dots = draws. Partial r = cell-type signal beyond the bulk.",
|
| 250 |
+
"footnote": fullA, "refs": refsA, "refs_full": refs_from_spec(refsA),
|
| 251 |
+
"numbers": [{"value": fullA.split("Per cohort, mean over draws (r / partial r / DEG): ")[1].split(". Source")[0],
|
| 252 |
+
"source": "data/fig4_disease.csv"}]},
|
| 253 |
+
{"title": "5-fold CV: disease signal", "layout": "full",
|
| 254 |
+
"figures": [str(FIGDIR / "fig4_disease_fivefold.png")], "keywords": kwB,
|
| 255 |
+
"footnote_short": "Donor-level 5-fold CV, pooled; reported separately from the 5-pair comparison.",
|
| 256 |
+
"footnote": fullB, "refs": refsA, "refs_full": refs_from_spec(refsA),
|
| 257 |
+
"numbers": [{"value": fullB.split("(r / partial r / DEG): ")[1].split(". Giroux")[0],
|
| 258 |
+
"source": "data/fig4_disease.csv"}]},
|
| 259 |
+
{"title": "Sepsis: fine-tuning variants", "layout": "full",
|
| 260 |
+
"figures": [str(FIGDIR / "fig4_disease_variants.png")], "keywords": kwC,
|
| 261 |
+
"footnote_short": "Sepsis, 82 donors, pooled 5-fold. LoRA r = 16 is the model used throughout.",
|
| 262 |
+
"footnote": fullC, "refs": ["Hu 2022, ICLR"], "refs_full": refs_from_spec(["Hu 2022, ICLR"]),
|
| 263 |
+
"numbers": [{"value": fullC.split("cells. ")[1].split(". Source")[0], "source": "data/fig4_disease.csv"}]}]
|
| 264 |
+
for s in slides:
|
| 265 |
+
if len(s["footnote_short"]) > 110:
|
| 266 |
+
raise SystemExit(f"short footnote too long: {s['title']}")
|
| 267 |
+
out = {"section": "fig4-disease", "scripts": [str(Path(__file__).resolve())],
|
| 268 |
+
"generated_from": "tools/fig4_disease.py (rerun to refresh; do not edit by hand)", "slides": slides}
|
| 269 |
+
(OUTDATA / "fig4_disease_slide_text.json").write_text(json.dumps(out, indent=1, ensure_ascii=False))
|
| 270 |
+
for s in slides:
|
| 271 |
+
print(s["title"], "|", " | ".join(s["keywords"]))
|
| 272 |
+
return 0
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
if __name__ == "__main__":
|
| 276 |
+
sys.exit(main())
|
paper-releases/pbisc-diffusion/updates/20261008T121550Z-deck-fig4-rules-no-broadcast/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec04_sle_benchmark.py
ADDED
|
@@ -0,0 +1,355 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Section 4 figures: final PBISC on the held-out SLE single-cell benchmark (GSE135779).
|
| 2 |
+
|
| 3 |
+
CPU only. Reads existing score tables; recomputes nothing heavy.
|
| 4 |
+
Model: runs/f01_6k_1x_seed20260627/checkpoint_epoch_016.pt (6k genes, 1x, part 16, Bernoulli read-out,
|
| 5 |
+
DDIM 50, EMA). Input = sc pseudobulk of 42 held-out donors. Scoring = frozen f01common scANVI, six-type gate.
|
| 6 |
+
scSemiProfiler run = sle_primary_cap1500_default_budget (14 in-cohort representative donors with real sc,
|
| 7 |
+
capped at 1,500 cells each); PBISC sees only the target pseudobulk.
|
| 8 |
+
Methods drawn: PBISC and scSemiProfiler only (the source tables carry more rows; they are not read into the figures
|
| 9 |
+
or the data CSVs). No bulk-broadcast baseline (user decision 2026-10-08); its summary table is still read once to
|
| 10 |
+
cross-check the PBISC and scSemiProfiler values.
|
| 11 |
+
|
| 12 |
+
Figures (all 12.3 x 4.6 in so they fit under a keyword line on a 5.7-in content area)
|
| 13 |
+
sec04_sle_benchmark logFC r, top-50 DEG, partial r beyond the bulk, comp L1: PBISC (5 seeds) vs
|
| 14 |
+
scSemiProfiler, on the 1,006-gene axis (shared by all panels) and the 2,279-gene axis
|
| 15 |
+
(6k panel intersect the published 2,980 list); partial r on the 1,006-gene axis.
|
| 16 |
+
sec04_sle_per_celltype per-type logFC r and top-50 overlap, 1,006-gene axis, all six types incl. Other.
|
| 17 |
+
"""
|
| 18 |
+
import json
|
| 19 |
+
import sys
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
import pandas as pd
|
| 24 |
+
|
| 25 |
+
DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/2026-09-30--paper-summary--r00")
|
| 26 |
+
sys.path.insert(0, str(DECK / "tools"))
|
| 27 |
+
import style # noqa: E402
|
| 28 |
+
import matplotlib.pyplot as plt # noqa: E402
|
| 29 |
+
|
| 30 |
+
FIG = DECK / "figures"
|
| 31 |
+
DATA = DECK / "data"
|
| 32 |
+
SLE = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/utility_studies_final6k_20260925/sle")
|
| 33 |
+
BCAST = SLE.parent / "sle_broadcast" / "tables"
|
| 34 |
+
SCSEMI_RES = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/bulk2sc-paper/results/scsemiprofiler_vs_pbisc_heldout_20260629")
|
| 35 |
+
SCSEMI_INPUT = SCSEMI_RES / "inputs/004_A_GSE135779_SLE_PBMC/primary_kmeans/input_manifest.json"
|
| 36 |
+
|
| 37 |
+
FIGSIZE = (12.3, 4.6)
|
| 38 |
+
VFS = 12 # value-label font size (pt on the slide)
|
| 39 |
+
AXES = ["1006", "2279"]
|
| 40 |
+
AXIS_LABEL = {"1006": "1,006 genes", "2279": "2,279 genes"}
|
| 41 |
+
SEED_TAGS = ["diffusion_f016k_e16", "diffusion_f016ks1_e16", "diffusion_f016ks2_e16",
|
| 42 |
+
"diffusion_f016ks3_e16", "diffusion_f016ks4_e16"]
|
| 43 |
+
TYPES = ["T cell", "B cell", "Monocyte", "NK cell", "DC", "Other"]
|
| 44 |
+
TYPE_SHORT = {"T cell": "T", "B cell": "B", "Monocyte": "Mono", "NK cell": "NK", "DC": "DC", "Other": "Other"}
|
| 45 |
+
C_P, C_S, C_B = style.ARM["pbisc"], style.ARM["scsemi"], style.ARM["broadcast"]
|
| 46 |
+
LBL_P = "PBISC 6k (5 seeds)"
|
| 47 |
+
LBL_S = "scSemiProfiler"
|
| 48 |
+
W2 = 0.34 # bar width when a group has two bars (PBISC, scSemiProfiler)
|
| 49 |
+
GAP = 1.05 # centre-to-centre spacing of neighbouring bars, in bar widths
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def pair_x(x, w=W2):
|
| 53 |
+
"""Centres of the two bars (PBISC, scSemiProfiler) of a group centred on x."""
|
| 54 |
+
return x - w * GAP / 2, x + w * GAP / 2
|
| 55 |
+
|
| 56 |
+
numbers = [] # (key, value, source)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def note(key, value, source):
|
| 60 |
+
numbers.append({"key": key, "value": value, "source": str(source)})
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def base_dir(axis):
|
| 64 |
+
return SLE / f"metrics_{axis}" / "panel_2980_diffusion_f016k_e16" / "pbmc5_other"
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
# ------------------------------------------------------------------ inputs
|
| 68 |
+
def load_summary(axis):
|
| 69 |
+
"""Headline rows from tables_<axis>.csv (5-seed mean/SD, per-seed values, baselines)."""
|
| 70 |
+
path = SLE / f"tables_{axis}.csv"
|
| 71 |
+
t = pd.read_csv(path).set_index("row")
|
| 72 |
+
seeds = t.loc[["base (seed 20260913)", "seed s1", "seed s2", "seed s3", "seed s4"]]
|
| 73 |
+
out = {
|
| 74 |
+
"path": path,
|
| 75 |
+
"seed_r": seeds["logfc_r"].to_numpy(), "seed_deg": seeds["top50"].to_numpy(),
|
| 76 |
+
"seed_l1": seeds["comp_l1"].to_numpy(),
|
| 77 |
+
"mean": t.loc["seed mean (5 seeds)"], "sd": t.loc["seed SD (ddof=1)"],
|
| 78 |
+
"scsemi": t.loc["scSemiProfiler"],
|
| 79 |
+
}
|
| 80 |
+
# sanity: the stored mean/SD equal the per-seed values
|
| 81 |
+
assert np.isclose(out["seed_r"].mean(), out["mean"]["logfc_r"])
|
| 82 |
+
assert np.isclose(out["seed_r"].std(ddof=1), out["sd"]["logfc_r"])
|
| 83 |
+
return out
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def load_broadcast_summary():
|
| 87 |
+
"""Mean r (6 types) and total top-50 of the input-bulk broadcast per axis; cross-checked vs tables_<axis>."""
|
| 88 |
+
sm = BCAST / "summary_mean_r_top50.csv"
|
| 89 |
+
s = pd.read_csv(sm)
|
| 90 |
+
out = {}
|
| 91 |
+
for a in AXES:
|
| 92 |
+
d = s[s["axis"] == int(a)].set_index("method")
|
| 93 |
+
t = load_summary(a)
|
| 94 |
+
assert np.isclose(d.loc["diffusion_5seed_mean", "mean_logFC_pearson"], t["mean"]["logfc_r"])
|
| 95 |
+
assert np.isclose(d.loc["diffusion_5seed_mean", "total_top50_overlap"], t["mean"]["top50"])
|
| 96 |
+
assert np.isclose(d.loc["scSemiProfiler", "mean_logFC_pearson"], t["scsemi"]["logfc_r"])
|
| 97 |
+
out[a] = (float(d.loc["broadcast_input_bulk", "mean_logFC_pearson"]),
|
| 98 |
+
float(d.loc["broadcast_input_bulk", "total_top50_overlap"]))
|
| 99 |
+
return out, sm
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def truth_list_size(axis):
|
| 103 |
+
p = base_dir(axis) / "top50_deg_overlap.csv"
|
| 104 |
+
d = pd.read_csv(p)
|
| 105 |
+
d = d[d["method"] == "diffusion_f016k_e16"]
|
| 106 |
+
return int(d["truth_top_list_size"].sum()), p
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def donor_counts():
|
| 110 |
+
p = base_dir("1006") / "pseudobulk_row_manifest.csv"
|
| 111 |
+
m = pd.read_csv(p)
|
| 112 |
+
m = m[m["method"] == "real"].drop_duplicates("sample_id")
|
| 113 |
+
c = m["condition"].value_counts()
|
| 114 |
+
return int(len(m)), int(c.get("SLE", 0)), int(c.get("HC", 0)), p
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def scsemi_setting():
|
| 118 |
+
"""Representative donors that give scSemiProfiler real sc, and its per-donor cell cap."""
|
| 119 |
+
inp = json.loads(SCSEMI_INPUT.read_text())
|
| 120 |
+
man = json.loads((SLE / "MANIFEST.json").read_text())
|
| 121 |
+
runs = [f["path"] for group in man["files"].values() if isinstance(group, list) for f in group
|
| 122 |
+
if isinstance(f, dict) and "/outputs/scsemiprofiler/004_A_GSE135779_SLE_PBMC/" in f.get("path", "")]
|
| 123 |
+
assert len(runs) == 1, runs
|
| 124 |
+
run_dir = Path(runs[0]).parent
|
| 125 |
+
cfg_path = run_dir / "run_config.json"
|
| 126 |
+
cfg = json.loads(cfg_path.read_text())
|
| 127 |
+
rep = inp["condition_counts"]["representative"]
|
| 128 |
+
n_rep = len(inp["representative_donors"])
|
| 129 |
+
note("scSemiProfiler run used in SLE benchmark", run_dir.name, SLE / "MANIFEST.json")
|
| 130 |
+
note("scSemiProfiler representative donors with real sc", f"{n_rep} ({rep['SLE']} SLE / {rep['HC']} HC)",
|
| 131 |
+
SCSEMI_INPUT)
|
| 132 |
+
note("scSemiProfiler representative-cell cap per donor", cfg["max_rep_cells_per_donor"], cfg_path)
|
| 133 |
+
return n_rep, cfg["max_rep_cells_per_donor"]
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def cell_shares():
|
| 137 |
+
"""Share of each type among real target cells (evaluation manifest) and generated DC per donor."""
|
| 138 |
+
em = base_dir("1006") / "evaluation_manifest.json"
|
| 139 |
+
counts = json.loads(em.read_text())["truth_labels_override"]["raw_label_counts"]
|
| 140 |
+
total = sum(counts.values())
|
| 141 |
+
share = {k: v / total for k, v in counts.items()}
|
| 142 |
+
note("real target cells total", total, em)
|
| 143 |
+
for k in TYPES:
|
| 144 |
+
note(f"real cells {k}", f"{counts[k]} ({100 * share[k]:.1f}%)", em)
|
| 145 |
+
cl = base_dir("1006") / "composition_long.csv"
|
| 146 |
+
c = pd.read_csv(cl)
|
| 147 |
+
for meth in ["diffusion_f016k_e16", "scSemiProfiler", "real"]:
|
| 148 |
+
d = c[(c["method"] == meth) & (c["celltype"] == "DC")]
|
| 149 |
+
note(f"DC cells per donor, {meth} (base seed for diffusion)",
|
| 150 |
+
f"mean {d['n_cells_celltype'].mean():.1f} of {d['n_cells_total'].mean():.0f}; "
|
| 151 |
+
f"{int((d['n_cells_celltype'] > 0).sum())}/{len(d)} donors with any", cl)
|
| 152 |
+
return share, counts, total
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
# ------------------------------------------------------------------ helpers
|
| 156 |
+
def seed_dots(ax, x, vals, width):
|
| 157 |
+
rng = np.random.default_rng(0)
|
| 158 |
+
jit = (rng.random(len(vals)) - 0.5) * width * 0.55
|
| 159 |
+
ax.scatter(x + jit, vals, s=18, color="white", edgecolor=style.INK, linewidth=0.8, zorder=4, clip_on=False)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def bar(ax, x, h, color, width, label=None, err=None):
|
| 163 |
+
ax.bar(x, h, width=width, color=color, edgecolor="none", label=label, zorder=2)
|
| 164 |
+
if err is not None:
|
| 165 |
+
ax.errorbar(x, h, yerr=err, fmt="none", ecolor=style.INK, elinewidth=1.2, capsize=4, zorder=3)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def base_label(ax, x, text, y0):
|
| 169 |
+
"""Value written inside the bar near its base: same height for every bar, so no bar looks ahead."""
|
| 170 |
+
ax.text(x, y0, text, ha="center", va="bottom", fontsize=VFS, color=style.INK, zorder=5)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def seed_legend(fig, ax, ncol, extra=None):
|
| 174 |
+
h, l = ax.get_legend_handles_labels()
|
| 175 |
+
h.append(plt.Line2D([], [], marker="o", ls="none", mfc="white", mec=style.INK, ms=6))
|
| 176 |
+
l.append("single seed")
|
| 177 |
+
if extra:
|
| 178 |
+
h.append(extra[0])
|
| 179 |
+
l.append(extra[1])
|
| 180 |
+
fig.legend(h, l, loc="upper center", ncol=ncol, bbox_to_anchor=(0.5, 1.01), handlelength=1.4,
|
| 181 |
+
columnspacing=1.4)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
# ------------------------------------------------------------------ figure (a)
|
| 185 |
+
def fig_benchmark():
|
| 186 |
+
S = {a: load_summary(a) for a in AXES}
|
| 187 |
+
n_donor, n_sle, n_hc, p_donor = donor_counts()
|
| 188 |
+
note("donors", f"{n_donor} ({n_sle} SLE / {n_hc} HC)", p_donor)
|
| 189 |
+
lists = {a: truth_list_size(a) for a in AXES}
|
| 190 |
+
load_broadcast_summary() # gate only: PBISC / scSemiProfiler values equal the summary table
|
| 191 |
+
|
| 192 |
+
fig = plt.figure(figsize=FIGSIZE)
|
| 193 |
+
gs = fig.add_gridspec(1, 4, width_ratios=[2.0, 2.0, 1.15, 1.1], wspace=0.5, top=0.86)
|
| 194 |
+
axr, axd, axp, axl = (fig.add_subplot(gs[0, i]) for i in range(4))
|
| 195 |
+
w = W2
|
| 196 |
+
rows = []
|
| 197 |
+
for gi, a in enumerate(AXES):
|
| 198 |
+
s = S[a]
|
| 199 |
+
for ax, key, seedkey, fmt_p, fmt_b, y0, bidx in [
|
| 200 |
+
(axr, "logfc_r", "seed_r", "{:.2f}", "{:.2f}", 0.012, 0),
|
| 201 |
+
(axd, "top50", "seed_deg", "{:.1f}", "{:.0f}", 2.0, 1)]:
|
| 202 |
+
xs = pair_x(gi, w)
|
| 203 |
+
m, sd = s["mean"][key], s["sd"][key]
|
| 204 |
+
bar(ax, xs[0], m, C_P, w, LBL_P if gi == 0 else None, err=sd)
|
| 205 |
+
seed_dots(ax, xs[0], s[seedkey], w)
|
| 206 |
+
bar(ax, xs[1], s["scsemi"][key], C_S, w, LBL_S if gi == 0 else None)
|
| 207 |
+
base_label(ax, xs[0], fmt_p.format(m), y0)
|
| 208 |
+
base_label(ax, xs[1], fmt_b.format(s["scsemi"][key]), y0)
|
| 209 |
+
for meth, v, sdv in [("PBISC 6k 5-seed mean", m, sd), ("scSemiProfiler", s["scsemi"][key], np.nan)]:
|
| 210 |
+
rows.append({"axis_genes": a, "metric": key, "method": meth, "value": v, "seed_sd": sdv,
|
| 211 |
+
"source": s["path"]})
|
| 212 |
+
for tag, v in zip(SEED_TAGS, s[seedkey]):
|
| 213 |
+
rows.append({"axis_genes": a, "metric": key, "method": tag, "value": v, "seed_sd": np.nan,
|
| 214 |
+
"source": s["path"]})
|
| 215 |
+
note(f"{key} {a}: PBISC 5-seed mean", round(float(m), 3 if key == "logfc_r" else 1), s["path"])
|
| 216 |
+
note(f"{key} {a}: PBISC 5-seed SD", round(float(sd), 3 if key == "logfc_r" else 1), s["path"])
|
| 217 |
+
note(f"{key} {a}: scSemiProfiler", round(float(s["scsemi"][key]), 3), s["path"])
|
| 218 |
+
axr.set_xticks([0, 1], [AXIS_LABEL[a] for a in AXES])
|
| 219 |
+
axd.set_xticks([0, 1], [f"{AXIS_LABEL[a]}\n(of {lists[a][0]})" for a in AXES])
|
| 220 |
+
axr.set_ylabel("Disease logFC r (higher better)")
|
| 221 |
+
axd.set_ylabel("Top-50 DEG overlap (higher better)")
|
| 222 |
+
axr.set_ylim(0, 0.6)
|
| 223 |
+
axd.set_ylim(0, 105)
|
| 224 |
+
# partial r beyond the bulk (1,006-gene axis): the cell-type signal the input bulk's logFC does not carry
|
| 225 |
+
rs = BCAST / "residual_specificity_summary.csv"
|
| 226 |
+
res = pd.read_csv(rs)
|
| 227 |
+
res = res[(res["axis"] == 1006) & (res["gene_space"] == "full_axis")].set_index("method")
|
| 228 |
+
sv = np.array([float(res.loc[t, "partial_r"]) for t in SEED_TAGS])
|
| 229 |
+
scs = float(res.loc["scSemiProfiler", "partial_r"])
|
| 230 |
+
assert np.isclose(float(res.loc["diffusion_5seed_mean", "partial_r"]), sv.mean())
|
| 231 |
+
xs = pair_x(0, w)
|
| 232 |
+
bar(axp, xs[0], sv.mean(), C_P, w, err=sv.std(ddof=1))
|
| 233 |
+
seed_dots(axp, xs[0], sv, w)
|
| 234 |
+
bar(axp, xs[1], scs, C_S, w)
|
| 235 |
+
base_label(axp, xs[0], f"{sv.mean():.2f}", 0.006)
|
| 236 |
+
base_label(axp, xs[1], f"{scs:.2f}", 0.006)
|
| 237 |
+
axp.set_xticks([0], ["1,006 genes"])
|
| 238 |
+
axp.set_xlim(-0.6, 0.6)
|
| 239 |
+
axp.set_ylim(0, 0.3)
|
| 240 |
+
axp.set_ylabel("Partial r beyond bulk (higher better)", fontweight="bold")
|
| 241 |
+
note("partial r 1006: PBISC 5-seed mean / SD / scSemiProfiler",
|
| 242 |
+
f"{sv.mean():.3f} / {sv.std(ddof=1):.3f} / {scs:.3f}", rs)
|
| 243 |
+
for meth, v, sdv in [("PBISC 6k 5-seed mean", sv.mean(), sv.std(ddof=1)), ("scSemiProfiler", scs, np.nan)]:
|
| 244 |
+
rows.append({"axis_genes": "1006", "metric": "partial_r", "method": meth, "value": v, "seed_sd": sdv,
|
| 245 |
+
"source": str(rs)})
|
| 246 |
+
for a in AXES:
|
| 247 |
+
note(f"top-50 truth list size {a}", lists[a][0], lists[a][1])
|
| 248 |
+
|
| 249 |
+
# composition L1: labels only, identical on both axes (check it)
|
| 250 |
+
s = S["1006"]
|
| 251 |
+
for k in ["mean", "sd", "scsemi"]:
|
| 252 |
+
assert np.isclose(S["1006"][k]["comp_l1"], S["2279"][k]["comp_l1"])
|
| 253 |
+
xs = pair_x(0, w)
|
| 254 |
+
m, sd = s["mean"]["comp_l1"], s["sd"]["comp_l1"]
|
| 255 |
+
bar(axl, xs[0], m, C_P, w, err=sd)
|
| 256 |
+
seed_dots(axl, xs[0], s["seed_l1"], w)
|
| 257 |
+
bar(axl, xs[1], s["scsemi"]["comp_l1"], C_S, w)
|
| 258 |
+
y0 = 0.006
|
| 259 |
+
base_label(axl, xs[0], f"{m:.2f}", y0)
|
| 260 |
+
base_label(axl, xs[1], f"{s['scsemi']['comp_l1']:.2f}", y0)
|
| 261 |
+
axl.set_xticks([0], ["labels only,\nboth axes"])
|
| 262 |
+
axl.set_xlim(-0.6, 0.6)
|
| 263 |
+
axl.set_ylim(0, 0.3)
|
| 264 |
+
axl.set_ylabel("Composition L1 (lower better)")
|
| 265 |
+
for meth, v, sdv in [("PBISC 6k 5-seed mean", m, sd), ("scSemiProfiler", s["scsemi"]["comp_l1"], np.nan)]:
|
| 266 |
+
rows.append({"axis_genes": "labels only", "metric": "comp_l1", "method": meth, "value": v,
|
| 267 |
+
"seed_sd": sdv, "source": s["path"]})
|
| 268 |
+
note("comp_l1: PBISC 5-seed mean", round(float(m), 3), s["path"])
|
| 269 |
+
note("comp_l1: PBISC 5-seed SD", round(float(sd), 4), s["path"])
|
| 270 |
+
note("comp_l1: scSemiProfiler", round(float(s["scsemi"]["comp_l1"]), 3), s["path"])
|
| 271 |
+
for ax in (axr, axd):
|
| 272 |
+
ax.set_xlim(-0.6, 1.6)
|
| 273 |
+
|
| 274 |
+
seed_legend(fig, axr, ncol=3)
|
| 275 |
+
style.save(fig, "sec04_sle_benchmark", FIG)
|
| 276 |
+
pd.DataFrame(rows).to_csv(DATA / "sec04_sle_benchmark.csv", index=False)
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
# ------------------------------------------------------------------ figure (b)
|
| 280 |
+
def per_type_tables(axis):
|
| 281 |
+
ps = SLE / f"per_celltype_seed_{axis}.csv"
|
| 282 |
+
seeds = pd.read_csv(ps)
|
| 283 |
+
pr = base_dir(axis) / "pseudobulk_logfc_metrics.csv"
|
| 284 |
+
pt = base_dir(axis) / "top50_deg_overlap.csv"
|
| 285 |
+
r = pd.read_csv(pr)
|
| 286 |
+
t = pd.read_csv(pt)
|
| 287 |
+
return seeds, r, t, ps, pr, pt
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def type_ticks(share):
|
| 291 |
+
out = []
|
| 292 |
+
for c in TYPES:
|
| 293 |
+
pct = round(100 * share[c], 1)
|
| 294 |
+
out.append(f"{TYPE_SHORT[c]}\n{pct:.0f}%" if pct >= 10 else f"{TYPE_SHORT[c]}\n{pct:.1f}%")
|
| 295 |
+
return out
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def fig_per_celltype(share, axis="1006"):
|
| 299 |
+
seeds, r, t, ps, pr, pt = per_type_tables(axis)
|
| 300 |
+
fig, (a1, a2) = plt.subplots(1, 2, figsize=FIGSIZE, gridspec_kw={"wspace": 0.18, "top": 0.86})
|
| 301 |
+
w = W2
|
| 302 |
+
x = np.arange(len(TYPES))
|
| 303 |
+
rows = []
|
| 304 |
+
sds = {}
|
| 305 |
+
drawn_top = {} # tallest drawn element per type on the top-50 panel (bar or seed dot)
|
| 306 |
+
for ax, skey, btab, bsrc in [(a1, "logFC_pearson", r, pr), (a2, "top50_overlap_count", t, pt)]:
|
| 307 |
+
for i, ct in enumerate(TYPES):
|
| 308 |
+
sv = seeds[(seeds["celltype"] == ct) & (seeds["set"].isin(SEED_TAGS))][skey].to_numpy(float)
|
| 309 |
+
assert len(sv) == 5
|
| 310 |
+
scs = float(btab[(btab["method"] == "scSemiProfiler") & (btab["celltype"] == ct)][skey].iloc[0])
|
| 311 |
+
# the base-seed row of the seed table must equal the evaluator's own per-type file
|
| 312 |
+
base = float(btab[(btab["method"] == "diffusion_f016k_e16") & (btab["celltype"] == ct)][skey].iloc[0])
|
| 313 |
+
assert np.isclose(base, seeds[(seeds["celltype"] == ct) & (seeds["set"] == SEED_TAGS[0])][skey].iloc[0])
|
| 314 |
+
xp, xs_ = pair_x(x[i], w)
|
| 315 |
+
bar(ax, xp, sv.mean(), C_P, w, LBL_P if i == 0 else None, err=sv.std(ddof=1))
|
| 316 |
+
seed_dots(ax, xp, sv, w)
|
| 317 |
+
bar(ax, xs_, scs, C_S, w, LBL_S if i == 0 else None)
|
| 318 |
+
sds[(skey, ct)] = sv.std(ddof=1)
|
| 319 |
+
if skey == "top50_overlap_count":
|
| 320 |
+
drawn_top[ct] = max(sv.max(), sv.mean() + sv.std(ddof=1), scs)
|
| 321 |
+
for meth, v, sd, src in [("PBISC 6k 5-seed mean", sv.mean(), sv.std(ddof=1), ps),
|
| 322 |
+
("scSemiProfiler", scs, np.nan, bsrc)]:
|
| 323 |
+
rows.append({"axis_genes": axis, "metric": skey, "celltype": ct, "method": meth,
|
| 324 |
+
"value": v, "seed_sd": sd, "real_cell_share": share[ct], "source": src})
|
| 325 |
+
note(f"{skey} {ct} {axis}: PBISC 5-seed mean / scSemiProfiler",
|
| 326 |
+
f"{sv.mean():.3f} / {scs:.3f}" if skey == "logFC_pearson"
|
| 327 |
+
else f"{sv.mean():.1f} / {scs:.0f}", f"{ps} ; {bsrc}")
|
| 328 |
+
ax.set_xticks(x, type_ticks(share))
|
| 329 |
+
ax.set_xlim(-0.6, len(TYPES) - 0.4)
|
| 330 |
+
# Other has a truth top list of 12 genes, not 50 -- say so where it is drawn
|
| 331 |
+
n_other = int(t[(t["method"] == "diffusion_f016k_e16") & (t["celltype"] == "Other")]["truth_top_list_size"].iloc[0])
|
| 332 |
+
other_top = max(float(drawn_top["Other"]), 0)
|
| 333 |
+
a2.text(x[-1], other_top + 1.2, f"of {n_other}", ha="center", va="bottom", fontsize=VFS, color=style.GREY)
|
| 334 |
+
note("Other truth top list size (top-50 panel)", n_other, pt)
|
| 335 |
+
for ct in TYPES:
|
| 336 |
+
note(f"logFC r seed SD {ct} {axis}", round(float(sds[("logFC_pearson", ct)]), 4), ps)
|
| 337 |
+
a1.set_ylabel("Disease logFC r (higher better)")
|
| 338 |
+
a2.set_ylabel("Top-50 DEG overlap (of 50)")
|
| 339 |
+
a1.set_ylim(0, 0.7)
|
| 340 |
+
a2.set_ylim(0, 30)
|
| 341 |
+
a1.text(-0.02, -0.035, "% of real cells", transform=a1.transAxes, ha="right", va="top",
|
| 342 |
+
fontsize=11, color=style.GREY)
|
| 343 |
+
seed_legend(fig, a1, ncol=3)
|
| 344 |
+
style.save(fig, "sec04_sle_per_celltype", FIG)
|
| 345 |
+
pd.DataFrame(rows).to_csv(DATA / "sec04_sle_per_celltype.csv", index=False)
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
if __name__ == "__main__":
|
| 349 |
+
scsemi_setting()
|
| 350 |
+
share, counts, total = cell_shares()
|
| 351 |
+
fig_benchmark()
|
| 352 |
+
fig_per_celltype(share, "1006")
|
| 353 |
+
pd.DataFrame(numbers).to_csv(DATA / "sec04_sle_numbers.csv", index=False)
|
| 354 |
+
for n in numbers:
|
| 355 |
+
print(f"{n['key']}: {n['value']} <- {n['source']}")
|
paper-releases/pbisc-diffusion/updates/20261008T121550Z-deck-fig4-rules-no-broadcast/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec08_pairs_needed.py
ADDED
|
@@ -0,0 +1,892 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Section 8 of the 2026-09-30 paper-summary deck: how many bulk-sc pairs LoRA needs (learning curve).
|
| 2 |
+
|
| 3 |
+
CPU only. Reads the pooled 5-fold scoring calls of the paired fine-tune plan and the per-fold RUN.json files,
|
| 4 |
+
then draws two slide figures:
|
| 5 |
+
figures/sec08_pairs_realism.{png,pdf} FULL: composition L1, coverage, selected step x (ImMicro, sepsis)
|
| 6 |
+
figures/sec08_pairs_signal.{png,pdf} TALL: ImMicro NK fraction r, sepsis logFC r, sepsis top-50 DEG
|
| 7 |
+
Every plotted/quoted number is read from a score file here and written with its source to data/sec08_*.csv.
|
| 8 |
+
Model: final f01 6k 1x epoch-16 checkpoint + LoRA (checked against every RUN.json).
|
| 9 |
+
x axis: "0" = no LoRA training. Two zero-shot points sit there, side by side: the pretrained model fed the real bulk
|
| 10 |
+
as measured (score arm zs__raw; uses no pair) and fed gene-wise calibrated bulk (zs__cal). Calibration (back as a
|
| 11 |
+
comparator, user decision 2026-10-01): alpha_g = mean CPM(pseudobulk_g) / mean CPM(bulk_g) over ALL paired training
|
| 12 |
+
donors of the fold (train + inner-val; tools/prepare_dataset.py `fit = fold != f`), applied as bulk CPM x alpha, then
|
| 13 |
+
renormalised. So zs__cal is not pair-free: its alpha uses the same 85-86 / 65-66 donors that LoRA "all" trains and
|
| 14 |
+
early-stops on. LoRA n = training pairs, and every LoRA run also early-stops on 7-8 paired inner-val donors
|
| 15 |
+
(RUN.json inner_val_rows). The LoRA arms are conditioned on the real bulk (*__raw) and share one real-bulk broadcast.
|
| 16 |
+
Cap-limited = ran to max_steps before the patience window closed; its late inner-val loss drop is read from
|
| 17 |
+
history.json.
|
| 18 |
+
When a zero-shot point lies far outside every other value of a panel (BREAK_RATIO), that panel gets a y-axis
|
| 19 |
+
break with a short segment at the same data scale, instead of squeezing the LoRA curve.
|
| 20 |
+
|
| 21 |
+
Equal-budget calibration (optional, drawn only if present): zero-shot + calibration with alpha fitted on exactly the
|
| 22 |
+
pairs a lora_n{5,10,20,40} run saw (n training + its inner-val pairs), per fold. The scores folder is scanned for
|
| 23 |
+
summary.json files (scores/<dataset>/**/summary.json, outside arms/) whose arm names match CAL_N_RE (contain "cal"
|
| 24 |
+
and an n<digits> token) and carry no fine-tune tag (FT_TAGS). An arm is drawn only from a scoring call over the
|
| 25 |
+
same donors as the pooled call (same reference cells, so metrics are comparable). If found, it is drawn as a second
|
| 26 |
+
line across n, ending at "all" with zs__cal (alpha from the same pairs LoRA "all" saw). If none is found, only the
|
| 27 |
+
two x = 0 points are drawn and a note is printed.
|
| 28 |
+
|
| 29 |
+
scSemiProfiler line (optional, drawn only if present; added 2026-10-02): scSemiProfiler trained with n pairs as
|
| 30 |
+
representatives (arms scsemi_n{5,10,20,40}__raw in scores/<dataset>/scsemi_budget_20261002/pooled*/) and with all
|
| 31 |
+
training pairs ("all" = arm scsemi__raw of the 5-fold CV run in scores/<dataset>/scsemi_cv_20261002/pooled*/), looked up
|
| 32 |
+
by tools/scsemi_results.py and drawn only for calls over the same donors and reference cells as the pooled call. If
|
| 33 |
+
nothing is found, a note is printed and the figures are unchanged. DECK_FIGDIR / DECK_OUTDATA redirect the outputs and
|
| 34 |
+
DECK_SCSEMI_PLAN_ROOT the scSemiProfiler lookup (synthetic presence test).
|
| 35 |
+
"""
|
| 36 |
+
import os
|
| 37 |
+
import json
|
| 38 |
+
import re
|
| 39 |
+
import sys
|
| 40 |
+
from pathlib import Path
|
| 41 |
+
|
| 42 |
+
import numpy as np
|
| 43 |
+
import pandas as pd
|
| 44 |
+
from scipy.stats import wilcoxon
|
| 45 |
+
|
| 46 |
+
DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/"
|
| 47 |
+
"2026-09-30--paper-summary--r00")
|
| 48 |
+
sys.path.insert(0, str(DECK / "tools"))
|
| 49 |
+
import style # noqa: E402
|
| 50 |
+
import scsemi_results as SR # noqa: E402
|
| 51 |
+
import fold_sizes as FZ # noqa: E402 (2026-10-02: the "all" point is labelled with its training-pair count)
|
| 52 |
+
import matplotlib.pyplot as plt # noqa: E402
|
| 53 |
+
from matplotlib.lines import Line2D # noqa: E402
|
| 54 |
+
|
| 55 |
+
PLAN = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/"
|
| 56 |
+
"paired_finetune_intradataset_20260927")
|
| 57 |
+
FINAL_CKPT = ("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/runs/"
|
| 58 |
+
"f01_6k_1x_seed20260627/checkpoint_epoch_016.pt")
|
| 59 |
+
FIGDIR = Path(os.environ.get("DECK_FIGDIR", str(DECK / "figures")))
|
| 60 |
+
DATADIR = Path(os.environ.get("DECK_OUTDATA", str(DECK / "data")))
|
| 61 |
+
FIGDIR.mkdir(exist_ok=True)
|
| 62 |
+
DATADIR.mkdir(exist_ok=True)
|
| 63 |
+
|
| 64 |
+
DSETS = ["immicro", "ye2026_sepsis"]
|
| 65 |
+
DS_LABEL = {"immicro": "ImMicro", "ye2026_sepsis": "Sepsis"}
|
| 66 |
+
LC_N = [5, 10, 20, 40]
|
| 67 |
+
LORA_ARMS = [f"lora_n{n}__raw" for n in LC_N] + ["real_lora__raw"]
|
| 68 |
+
RUN_ARMS = [f"lora_n{n}" for n in LC_N] + ["real_lora"]
|
| 69 |
+
ZS = "zs__raw" # zero-shot on the real bulk as measured: 0 pairs
|
| 70 |
+
ZS_CAL = "zs__cal" # zero-shot + calibration, alpha from all fold pairs (train + inner-val)
|
| 71 |
+
# 2026-10-02 (user): x = 0 must use no paired data. The second x = 0 point is now the zero-shot model fed the real bulk
|
| 72 |
+
# after exon-length correction (no pairs); zs__cal (alpha from every training pair of the fold) is only drawn where it
|
| 73 |
+
# belongs, as the right end of the equal-budget calibration line (same pairs as the rightmost LoRA point).
|
| 74 |
+
ZS_LEN = "zs__len" # zero-shot, exon-length-corrected real bulk (tools/build_tpm_zeroshot.py)
|
| 75 |
+
LEN_SUB = "zeroshot_tpm_20261002/pooled" # its scoring call (same donors and reference cells as scores/<ds>/pooled)
|
| 76 |
+
X_LAB = ["0", "5", "10", "20", "40", "all"]
|
| 77 |
+
KEY_LAB = ["zero_shot", "5", "10", "20", "40", "all"] # the same points, as keys in sec08_slide_numbers.csv
|
| 78 |
+
X_POS = [0.0, 1.3, 2.3, 3.3, 4.3, 5.55] # small gap after the zero-shot points; extra room for the "78–79" tick
|
| 79 |
+
DX0 = 0.2 # raw zero-shot left of x = 0, calibrated right of it
|
| 80 |
+
X_RAW, X_CAL = X_POS[0] - DX0, X_POS[0] + DX0 # X_CAL: position of the second zero-shot point
|
| 81 |
+
XLIM = (-0.5, X_POS[-1] + 0.5) # same x range as the selected-step panel
|
| 82 |
+
COL_RAW, COL_CAL = style.ARM["zs_raw"], style.ARM["zs_cal"] # archived pair: pale = raw, #0072B2 = calibrated
|
| 83 |
+
RAW_EDGE = "#5E8FB5" # edge of the pale raw marker (same as sec05 RAW_EDGE)
|
| 84 |
+
COL_LEN = style.ARM["tpm"] # zero-shot, length-corrected bulk (sand)
|
| 85 |
+
# equal-budget calibration arms: "cal" and an n<digits> token, and no fine-tune tag
|
| 86 |
+
CAL_N_RE = re.compile(r"(?:^|[^a-z0-9])n(\d+)(?![0-9])", re.I)
|
| 87 |
+
FT_TAGS = ("lora", "real", "pseudo", "full", "condenc", "multik", "recipe")
|
| 88 |
+
BREAK_RATIO = 1.5 # y-axis break when the zero-shot point sits > 1.5 spans of the other values beyond them
|
| 89 |
+
CELLTYPES = ["T cell", "B cell", "Monocyte", "NK cell"]
|
| 90 |
+
DEG_TYPES = ["T cell", "B cell", "Monocyte", "NK cell", "DC"]
|
| 91 |
+
RAW_ARMS = LORA_ARMS + ["zs__raw", "real_full__raw", "pseudo_full__raw"] # all conditioned on raw real bulk
|
| 92 |
+
|
| 93 |
+
REF = { # reference-line styles; pseudo/broadcast copied from sec09 REFSTYLE so the deck is consistent
|
| 94 |
+
"pseudo": dict(ls=(0, (4, 2)), color=style.ARM["pseudo"], lw=1.6, label="Zero-shot from sc pseudobulk"),
|
| 95 |
+
"broadcast": dict(ls=(0, (1, 1.2)), color=style.ARM["broadcast"], lw=2.4, label="Real-bulk broadcast"),
|
| 96 |
+
"null": dict(ls=(0, (6, 2, 1.5, 2)), color=style.GREY, lw=1.4, label="Cohort-mean null"),
|
| 97 |
+
}
|
| 98 |
+
LEG_ZS = "Zero-shot, real bulk as measured (no pairs)"
|
| 99 |
+
LEG_LEN = "Zero-shot, exon-length-corrected bulk (no pairs)"
|
| 100 |
+
LEG_CAL_N = "Zero-shot + calibration, α from the same pairs"
|
| 101 |
+
COL_SC = style.ARM["scsemi"]
|
| 102 |
+
LEG_SC = "scSemiProfiler, n pairs as representatives"
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def xlabel(st):
|
| 106 |
+
"""x-axis label; the inner-val range is read from the RUN.json files."""
|
| 107 |
+
return (f"LoRA training pairs per fold (each run +{rng_txt(st.n_inner_val)} inner-val pairs for early stopping; "
|
| 108 |
+
f"test fold never trained on)")
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def xticks(ds):
|
| 112 |
+
"""x tick labels of one cohort: the rightmost point is every training donor of the fold, shown as its count."""
|
| 113 |
+
return X_LAB[:-1] + [FZ.all_label(ds)]
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def close(a, b, tol=1e-6):
|
| 117 |
+
return abs(float(a) - float(b)) <= tol
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class Call:
|
| 121 |
+
"""One pooled score_ft.py scoring call."""
|
| 122 |
+
|
| 123 |
+
def __init__(self, path: Path):
|
| 124 |
+
self.path = path
|
| 125 |
+
self.summary = json.loads((path / "summary.json").read_text())
|
| 126 |
+
self.contrast = pd.read_csv(path / "contrast.csv") if (path / "contrast.csv").exists() else None
|
| 127 |
+
self.per_donor = pd.read_csv(path / "per_donor.csv")
|
| 128 |
+
self.src_summary = str(path / "summary.json")
|
| 129 |
+
self.src_contrast = str(path / "contrast.csv")
|
| 130 |
+
self.src_per_donor = str(path / "per_donor.csv")
|
| 131 |
+
|
| 132 |
+
def head(self, arm, key):
|
| 133 |
+
return float(self.summary["headline"][arm][key])
|
| 134 |
+
|
| 135 |
+
def contrast_r(self, arm, col="r_generated"):
|
| 136 |
+
c = self.contrast
|
| 137 |
+
c = c[(c.arm == arm) & (c.statistic == "mean_cp10k") & (c.celltype.isin(CELLTYPES))]
|
| 138 |
+
assert set(c.celltype) == set(CELLTYPES), (self.path, arm)
|
| 139 |
+
return float(c[col].mean())
|
| 140 |
+
|
| 141 |
+
def deg(self, arm, col="top50_overlap"):
|
| 142 |
+
d = self.contrast
|
| 143 |
+
d = d[(d.arm == arm) & (d.statistic == "welch_top50_deg")]
|
| 144 |
+
assert len(d) == 5, (self.path, arm, len(d)) # T/B/Mono/NK/DC
|
| 145 |
+
return float(d[col].sum())
|
| 146 |
+
|
| 147 |
+
def deg_type(self, arm, ct, col="top50_overlap"):
|
| 148 |
+
d = self.contrast
|
| 149 |
+
d = d[(d.arm == arm) & (d.statistic == "welch_top50_deg") & (d.celltype == ct)]
|
| 150 |
+
assert len(d) == 1, (self.path, arm, ct, len(d))
|
| 151 |
+
return float(d[col].iloc[0])
|
| 152 |
+
|
| 153 |
+
def frac_r(self, arm, ct):
|
| 154 |
+
d = self.per_donor[self.per_donor.arm == arm]
|
| 155 |
+
return float(np.corrcoef(d[f"gen_{ct}"].astype(float), d[f"obs_{ct}"].astype(float))[0, 1])
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def load():
|
| 159 |
+
calls = {ds: Call(PLAN / "scores" / ds / "pooled") for ds in DSETS}
|
| 160 |
+
deg_call = Call(PLAN / "scores" / "ye2026_sepsis" / "pooled_deg")
|
| 161 |
+
for ds, c in calls.items():
|
| 162 |
+
for a in LORA_ARMS + [ZS, ZS_CAL, "zs__pseudo"]:
|
| 163 |
+
assert a in c.summary["arms"], (ds, a)
|
| 164 |
+
assert c.summary["per_arm"][a].get("receipt_verified", True) is not False, (ds, a)
|
| 165 |
+
# headline composition L1 equals the donor mean of per_donor.csv
|
| 166 |
+
assert close(c.per_donor.loc[c.per_donor.arm == a, "comp_l1"].mean(), c.head(a, "comp_l1"), 1e-9), a
|
| 167 |
+
# headline contrast means equal the per-type mean of contrast.csv
|
| 168 |
+
se = calls["ye2026_sepsis"]
|
| 169 |
+
for a in LORA_ARMS + [ZS, ZS_CAL, "zs__pseudo"]:
|
| 170 |
+
assert close(se.contrast_r(a), se.head(a, "contrast_mean_cp10k_r_gen"), 1e-9), a
|
| 171 |
+
assert close(deg_call.deg(a), deg_call.head(a, "deg_top50_sum"), 1e-9), a
|
| 172 |
+
# broadcast is the same for every arm conditioned on raw real bulk
|
| 173 |
+
bc = {a: se.contrast_r(a, "r_broadcast") for a in RAW_ARMS}
|
| 174 |
+
assert max(bc.values()) - min(bc.values()) < 1e-12, bc
|
| 175 |
+
bcd = {a: deg_call.deg(a, "top50_overlap_broadcast") for a in RAW_ARMS}
|
| 176 |
+
assert len(set(bcd.values())) == 1, bcd
|
| 177 |
+
assert close(bcd["real_lora__raw"], deg_call.head("real_lora__raw", "deg_top50_sum_broadcast"), 1e-9)
|
| 178 |
+
# non-DEG metrics agree between the two sepsis scoring calls (k-NN ties allow 1e-3)
|
| 179 |
+
for a in LORA_ARMS + [ZS, ZS_CAL]:
|
| 180 |
+
for k in ("comp_l1", "coverage"):
|
| 181 |
+
assert abs(se.head(a, k) - deg_call.head(a, k)) <= 1e-3, (a, k)
|
| 182 |
+
lens = {ds: Call(PLAN / "scores" / ds / LEN_SUB) for ds in DSETS}
|
| 183 |
+
for ds, lc in lens.items():
|
| 184 |
+
c = calls[ds]
|
| 185 |
+
assert ZS_LEN in lc.summary["arms"] and ZS in lc.summary["arms"], (ds, lc.summary["arms"])
|
| 186 |
+
assert int(lc.summary["n_donors"]) == int(c.summary["n_donors"]), ds
|
| 187 |
+
assert lc.summary["reference"]["reference_sha256"] == c.summary["reference"]["reference_sha256"], ds
|
| 188 |
+
for k in ("comp_l1", "coverage", "precision"): # the raw arm reproduces in the new call (k-NN ties: 1e-3)
|
| 189 |
+
assert abs(lc.head(ZS, k) - c.head(ZS, k)) <= 1e-3, (ds, k, lc.head(ZS, k), c.head(ZS, k))
|
| 190 |
+
assert close(lens["ye2026_sepsis"].contrast_r(ZS), se.contrast_r(ZS), 1e-9)
|
| 191 |
+
assert close(lens["ye2026_sepsis"].deg(ZS), deg_call.deg(ZS), 1e-9), (lens["ye2026_sepsis"].deg(ZS), deg_call.deg(ZS))
|
| 192 |
+
return calls, deg_call, lens
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def find_cal_budget(calls, deg_call):
|
| 196 |
+
"""Scan the scores folder for equal-budget calibration arms (see module docstring).
|
| 197 |
+
|
| 198 |
+
Returns (budget, log): budget[ds][n] = dict(arm, calls=[Call, ...]) for drawable arms (pooled call first, then
|
| 199 |
+
other calls over the same donors; the sepsis DEG call first for DEG); log = one dict per matching arm found."""
|
| 200 |
+
budget, log = {ds: {} for ds in DSETS}, []
|
| 201 |
+
cache = {c.path: c for c in list(calls.values()) + [deg_call]}
|
| 202 |
+
for ds in DSETS:
|
| 203 |
+
root = PLAN / "scores" / ds
|
| 204 |
+
pooled = calls[ds]
|
| 205 |
+
donors = set(pooled.per_donor.donor)
|
| 206 |
+
cands = {}
|
| 207 |
+
for sp in sorted(root.rglob("summary.json")):
|
| 208 |
+
rel = sp.relative_to(root)
|
| 209 |
+
if "arms" in rel.parts:
|
| 210 |
+
continue
|
| 211 |
+
try:
|
| 212 |
+
arms = json.loads(sp.read_text()).get("arms") or []
|
| 213 |
+
except (OSError, ValueError):
|
| 214 |
+
continue
|
| 215 |
+
for a in arms:
|
| 216 |
+
m = CAL_N_RE.search(a)
|
| 217 |
+
if "cal" not in a.lower() or m is None or any(t in a.lower() for t in FT_TAGS):
|
| 218 |
+
continue
|
| 219 |
+
n = int(m.group(1))
|
| 220 |
+
if sp.parent not in cache:
|
| 221 |
+
try:
|
| 222 |
+
cache[sp.parent] = Call(sp.parent)
|
| 223 |
+
except (OSError, ValueError) as e:
|
| 224 |
+
log.append(dict(dataset=ds, call=str(rel.parent), arm=a, n=n, drawn=False,
|
| 225 |
+
note=f"not drawn: cannot read the call ({e.__class__.__name__})"))
|
| 226 |
+
continue
|
| 227 |
+
call = cache[sp.parent]
|
| 228 |
+
same = set(call.per_donor.loc[call.per_donor.arm == a, "donor"]) == donors
|
| 229 |
+
ok = same and n in LC_N
|
| 230 |
+
why = ("drawn" if ok else "not drawn: " + ("n not in " + str(LC_N) if same else
|
| 231 |
+
"call does not score the pooled donor set"))
|
| 232 |
+
log.append(dict(dataset=ds, call=str(rel.parent), arm=a, n=n, drawn=ok, note=why))
|
| 233 |
+
if ok:
|
| 234 |
+
cands.setdefault(n, []).append((a, call))
|
| 235 |
+
for n, lst in cands.items():
|
| 236 |
+
names = sorted({a for a, _ in lst})
|
| 237 |
+
if len(names) > 1:
|
| 238 |
+
pref = sorted({a for a, c in lst if c is pooled})
|
| 239 |
+
if len(pref) != 1:
|
| 240 |
+
sys.exit(f"{ds}: several equal-budget calibration arms for n = {n}: {names}; pick one")
|
| 241 |
+
names = pref
|
| 242 |
+
arm = names[0]
|
| 243 |
+
cl = [c for a, c in lst if a == arm]
|
| 244 |
+
cl.sort(key=lambda c: (c is not pooled, c is not deg_call, str(c.path)))
|
| 245 |
+
for c in cl: # a call other than the pooled one must reproduce shared arms (k-NN ties allow 1e-3)
|
| 246 |
+
if c is pooled:
|
| 247 |
+
continue
|
| 248 |
+
for shared in (ZS_CAL, "real_lora__raw"):
|
| 249 |
+
if shared in c.summary["arms"]:
|
| 250 |
+
for k in ("comp_l1", "coverage"):
|
| 251 |
+
assert abs(c.head(shared, k) - pooled.head(shared, k)) <= 1e-3, (c.path, shared, k)
|
| 252 |
+
budget[ds][n] = dict(arm=arm, calls=cl)
|
| 253 |
+
return budget, log
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def find_scsemi(calls):
|
| 257 |
+
"""scSemiProfiler at n = 5..40 (equal-budget arms) and "all" (5-fold CV arm), see module docstring.
|
| 258 |
+
|
| 259 |
+
Returns (scs, log): scs[ds][pairs label] = dict(arm, calls=[Call, ...]) for accepted calls; log = one dict per
|
| 260 |
+
arm found (accepted or not)."""
|
| 261 |
+
scs, log = {ds: {} for ds in DSETS}, []
|
| 262 |
+
for ds in DSETS:
|
| 263 |
+
ref = calls[ds].summary
|
| 264 |
+
found = [(str(n), a, d) for n, lst in sorted(SR.budget_calls(ds).items()) for a, d in lst]
|
| 265 |
+
found += [("all", SR.CV_ARM, d) for d in SR.cv_calls(ds)]
|
| 266 |
+
for lab, a, d in found:
|
| 267 |
+
try:
|
| 268 |
+
c = Call(d)
|
| 269 |
+
except (OSError, ValueError) as e:
|
| 270 |
+
log.append(dict(dataset=ds, call=str(d), arm=a, pairs=lab, drawn=False,
|
| 271 |
+
note=f"not drawn: cannot read the call ({e.__class__.__name__})"))
|
| 272 |
+
continue
|
| 273 |
+
why = SR.accept(c.summary, ref, a)
|
| 274 |
+
if lab not in X_LAB[1:]:
|
| 275 |
+
why.append(f"n {lab} not in {X_LAB[1:]}")
|
| 276 |
+
ent = scs[ds].get(lab)
|
| 277 |
+
if ent is not None and ent["arm"] != a:
|
| 278 |
+
why.append(f"a different arm ({ent['arm']}) already gives n = {lab}")
|
| 279 |
+
log.append(dict(dataset=ds, call=str(d), arm=a, pairs=lab, drawn=not why,
|
| 280 |
+
note="drawn" if not why else "not drawn: " + "; ".join(why)))
|
| 281 |
+
if not why:
|
| 282 |
+
scs[ds].setdefault(lab, dict(arm=a, calls=[]))["calls"].append(c)
|
| 283 |
+
return scs, log
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def scsemi_series(scs, ds, getter):
|
| 287 |
+
"""[(pairs label, value, source)] of the scSemiProfiler line for one panel ([] when nothing is found)."""
|
| 288 |
+
out = []
|
| 289 |
+
for lab in X_LAB[1:]:
|
| 290 |
+
if lab in scs[ds]:
|
| 291 |
+
v, c = budget_value(scs[ds][lab], getter)
|
| 292 |
+
if v is not None:
|
| 293 |
+
out.append((lab, v, f"{c.path} arm {scs[ds][lab]['arm']}"))
|
| 294 |
+
return out
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def budget_value(entry, getter):
|
| 298 |
+
"""First call of a budget entry that provides the metric (None if no call does)."""
|
| 299 |
+
for c in entry["calls"]:
|
| 300 |
+
try:
|
| 301 |
+
return getter(c, entry["arm"]), c
|
| 302 |
+
except (AssertionError, KeyError, TypeError, AttributeError):
|
| 303 |
+
continue
|
| 304 |
+
return None, None
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def load_steps():
|
| 308 |
+
rows = []
|
| 309 |
+
for ds in DSETS:
|
| 310 |
+
for k in range(5):
|
| 311 |
+
for arm in RUN_ARMS:
|
| 312 |
+
p = PLAN / "runs" / ds / f"fold{k}" / arm / "RUN.json"
|
| 313 |
+
r = json.loads(p.read_text())
|
| 314 |
+
assert r["source_checkpoint"] == FINAL_CKPT, (p, r["source_checkpoint"])
|
| 315 |
+
assert r["mode"] == "lora", p
|
| 316 |
+
assert r["inner_val_rows"], p # every LoRA run early-stops on paired inner-val donors
|
| 317 |
+
hist = json.loads((p.parent / "history.json").read_text())
|
| 318 |
+
h = {int(e["step"]): float(e["inner_val_loss"]) for e in hist}
|
| 319 |
+
# cap-limited = ran to max_steps without the patience window closing
|
| 320 |
+
cap_limited = (r["steps_run"] >= r["max_steps"]
|
| 321 |
+
and r["steps_run"] - r["selected_step"] < r["patience"] * r["eval_every"])
|
| 322 |
+
last = max(h)
|
| 323 |
+
win = r["patience"] * r["eval_every"] # last patience window (2,000 steps)
|
| 324 |
+
drop_total = h[0] - h[last]
|
| 325 |
+
drop_last = h[last - win] - h[last]
|
| 326 |
+
rows.append({"dataset": ds, "fold": k, "arm": arm, "n_train": len(r["train_rows"]),
|
| 327 |
+
"n_inner_val": len(r["inner_val_rows"]), "selected_step": r["selected_step"],
|
| 328 |
+
"max_steps": r["max_steps"], "steps_run": r["steps_run"],
|
| 329 |
+
"patience_steps": win, "cap_limited": bool(cap_limited),
|
| 330 |
+
"val_loss_step0": h[0], "val_loss_last": h[last],
|
| 331 |
+
"val_loss_last_window_drop_frac": drop_last / drop_total,
|
| 332 |
+
"wall_seconds": r.get("wall_seconds"), "source": str(p),
|
| 333 |
+
"history": str(p.parent / "history.json")})
|
| 334 |
+
st = pd.DataFrame(rows)
|
| 335 |
+
# nested subsets: n_train equals the arm size for lora_n*
|
| 336 |
+
for n in LC_N:
|
| 337 |
+
assert (st[st.arm == f"lora_n{n}"].n_train == n).all(), n
|
| 338 |
+
return st
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def load_fold_sizes():
|
| 342 |
+
"""Test donors per fold (PREPARE.json); their sum must equal the donors in the pooled scoring call.
|
| 343 |
+
alpha = paired donors the zs__cal alpha is fitted on per fold (train + inner-val)."""
|
| 344 |
+
out = {}
|
| 345 |
+
for ds in DSETS:
|
| 346 |
+
p = PLAN / "data" / ds / "PREPARE.json"
|
| 347 |
+
fs = json.loads(p.read_text())["fold_sizes"]
|
| 348 |
+
out[ds] = dict(test=[int(v["test"]) for v in fs.values()],
|
| 349 |
+
alpha=[int(v["train"]) + int(v["inner_val"]) for v in fs.values()], source=str(p))
|
| 350 |
+
return out
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
def load_fewshot():
|
| 354 |
+
"""Few-pair call (5 draws): zero-shot + calibration with alpha from the same 5 pairs vs LoRA on those 5 pairs
|
| 355 |
+
(fixed 3k steps, no inner-val). Its own donor set, so it is only quoted in the notes, never drawn."""
|
| 356 |
+
out = {}
|
| 357 |
+
for ds in DSETS:
|
| 358 |
+
p = PLAN / "scores" / ds / "fewshot_n5" / "aggregate.json"
|
| 359 |
+
a = json.loads(p.read_text())["arms"]
|
| 360 |
+
out[ds] = dict(zs_cal=float(a["zs_cal"]["coverage"][0]), lora5=float(a["lora5"]["coverage"][0]),
|
| 361 |
+
source=str(p))
|
| 362 |
+
return out
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
def rng_txt(v):
|
| 366 |
+
v = sorted(int(x) for x in v)
|
| 367 |
+
return f"{v[0]}" if v[0] == v[-1] else f"{v[0]}–{v[-1]}"
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
def break_axis(ax, v0, lo, hi, x_txt=X_RAW, extra=()):
|
| 371 |
+
"""Shrink ax to lo..hi and add a short segment above it that shows v0 at the same data scale.
|
| 372 |
+
extra: further break values (2026-10-02, two zero-shot points at x = 0). When they do not fit at the main scale,
|
| 373 |
+
the segment gets its own scale and a tick at each value."""
|
| 374 |
+
p = ax.get_position()
|
| 375 |
+
h_top, gap = 0.22 * p.height, 0.08 * p.height
|
| 376 |
+
h_main = p.height - h_top - gap
|
| 377 |
+
ax.set_position([p.x0, p.y0, p.width, h_main])
|
| 378 |
+
ax.set_ylim(lo, hi)
|
| 379 |
+
half = (hi - lo) * h_top / h_main / 2
|
| 380 |
+
top = ax.figure.add_axes([p.x0, p.y0 + h_main + gap, p.width, h_top], sharex=ax)
|
| 381 |
+
vals = [v0] + list(extra)
|
| 382 |
+
if max(vals) - min(vals) > 1.6 * half: # own scale: ticks at the values
|
| 383 |
+
spread = max(vals) - min(vals)
|
| 384 |
+
top.set_ylim(min(vals) - 0.35 * spread, max(vals) + 0.35 * spread)
|
| 385 |
+
top.set_yticks(sorted(round(v, 2) for v in vals))
|
| 386 |
+
top.spines["bottom"].set_visible(False)
|
| 387 |
+
top.tick_params(axis="x", bottom=False, labelbottom=False)
|
| 388 |
+
mk = dict(marker=[(-1, -0.5), (1, 0.5)], markersize=10, ls="none", color=style.INK, mec=style.INK, mew=1.2,
|
| 389 |
+
clip_on=False)
|
| 390 |
+
top.plot([0], [0], transform=top.transAxes, **mk)
|
| 391 |
+
ax.plot([0], [1], transform=ax.transAxes, **mk)
|
| 392 |
+
return top
|
| 393 |
+
v0 = (max(vals) + min(vals)) / 2
|
| 394 |
+
top.set_ylim(v0 - half, v0 + half)
|
| 395 |
+
# one tick in the short segment: the nearest value on the main axis' tick grid that fits inside it
|
| 396 |
+
step = float(np.diff(ax.get_yticks()[:2])[0]) / 2
|
| 397 |
+
tick = round(round(v0 / step) * step, 10)
|
| 398 |
+
top.set_yticks([tick] if abs(tick - v0) < half else [])
|
| 399 |
+
if not len(top.get_yticks()): # no grid value fits: print the value next to the point instead
|
| 400 |
+
top.text(x_txt + 0.3, v0, f"{v0:.2f}", va="center", ha="left", fontsize=12)
|
| 401 |
+
top.spines["bottom"].set_visible(False)
|
| 402 |
+
top.tick_params(axis="x", bottom=False, labelbottom=False)
|
| 403 |
+
mk = dict(marker=[(-1, -0.5), (1, 0.5)], markersize=10, ls="none", color=style.INK, mec=style.INK, mew=1.2,
|
| 404 |
+
clip_on=False)
|
| 405 |
+
top.plot([0], [0], transform=top.transAxes, **mk)
|
| 406 |
+
ax.plot([0], [1], transform=ax.transAxes, **mk)
|
| 407 |
+
return top
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def curve(ax, z0, vl, refs, rows, panel, ds, srcl, ylim0=None, vb=None, vs=None):
|
| 411 |
+
"""Zero-shot points at x = 0 (z0: [(series, value, source)] for raw and calibrated), LoRA curve at 5..all,
|
| 412 |
+
optional equal-budget calibration line (vb: [(pairs label, value, source)]), reference lines.
|
| 413 |
+
Returns the axis that carries the panel title."""
|
| 414 |
+
vb = vb or []
|
| 415 |
+
vs = vs or [] # scSemiProfiler line (n = 5..all)
|
| 416 |
+
lo, hi = min(vl), max(vl)
|
| 417 |
+
for _, val, _ in list(refs) + [(None, v, None) for _, v, _ in vb + vs]:
|
| 418 |
+
lo, hi = min(lo, val), max(hi, val)
|
| 419 |
+
span = hi - lo
|
| 420 |
+
# a zero-shot point goes to the break segment when it sits > BREAK_RATIO spans beyond everything else
|
| 421 |
+
out = {ser for ser, v, _ in z0
|
| 422 |
+
if ylim0 is None and span > 0 and (v - hi > BREAK_RATIO * span or lo - v > BREAK_RATIO * span)}
|
| 423 |
+
for ser, v, _ in z0:
|
| 424 |
+
if ser in out:
|
| 425 |
+
assert v > hi, (panel, ds, ser, "axis break below the curve is not implemented")
|
| 426 |
+
else:
|
| 427 |
+
lo, hi = min(lo, v), max(hi, v)
|
| 428 |
+
broken = bool(out)
|
| 429 |
+
pad = (hi - lo) * 0.15
|
| 430 |
+
axes = [ax]
|
| 431 |
+
xz = {"zero_shot": X_RAW, "zs_len": X_CAL}
|
| 432 |
+
if broken:
|
| 433 |
+
zb = [z for z in z0 if z[0] in out]
|
| 434 |
+
top = break_axis(ax, zb[0][1], lo - pad, hi + pad, xz[zb[0][0]], extra=[v for _, v, _ in zb[1:]])
|
| 435 |
+
axes.append(top)
|
| 436 |
+
else:
|
| 437 |
+
ax.set_ylim(ylim0 if ylim0 is not None else lo - pad, hi + pad)
|
| 438 |
+
for ser, v, src in z0:
|
| 439 |
+
a = axes[-1] if ser in out else ax
|
| 440 |
+
if ser == "zero_shot":
|
| 441 |
+
a.scatter([X_RAW], [v], s=70, color=COL_RAW, edgecolor=RAW_EDGE, lw=1.0, zorder=5, clip_on=False)
|
| 442 |
+
else:
|
| 443 |
+
a.scatter([X_CAL], [v], s=70, color=COL_LEN, edgecolor=style.INK, lw=0.6, zorder=5, clip_on=False)
|
| 444 |
+
rows.append(dict(panel=panel, dataset=ds, series=ser, pairs=X_LAB[0], value=v, source=src,
|
| 445 |
+
y_axis_break=bool(broken)))
|
| 446 |
+
if vb:
|
| 447 |
+
xb = [X_POS[X_LAB.index(lab)] for lab, _, _ in vb]
|
| 448 |
+
ax.plot(xb, [v for _, v, _ in vb], color=COL_CAL, lw=1.8, zorder=3)
|
| 449 |
+
ax.scatter(xb, [v for _, v, _ in vb], s=60, marker="s", color=COL_CAL, edgecolor=style.INK, lw=0.6,
|
| 450 |
+
zorder=5)
|
| 451 |
+
for lab, v, src in vb:
|
| 452 |
+
rows.append(dict(panel=panel, dataset=ds, series="zs_cal_budget", pairs=lab, value=v, source=src,
|
| 453 |
+
y_axis_break=bool(broken)))
|
| 454 |
+
if vs:
|
| 455 |
+
xs = [X_POS[X_LAB.index(lab)] for lab, _, _ in vs]
|
| 456 |
+
ax.plot(xs, [v for _, v, _ in vs], color=COL_SC, lw=1.8, zorder=3)
|
| 457 |
+
ax.scatter(xs, [v for _, v, _ in vs], s=55, marker="D", color=COL_SC, edgecolor=style.INK, lw=0.6, zorder=5)
|
| 458 |
+
for lab, v, src in vs:
|
| 459 |
+
rows.append(dict(panel=panel, dataset=ds, series="scsemi", pairs=lab, value=v, source=src,
|
| 460 |
+
y_axis_break=bool(broken)))
|
| 461 |
+
ax.plot(X_POS[1:], vl, color=style.ARM["lora"], lw=2.0, zorder=3)
|
| 462 |
+
ax.scatter(X_POS[1:], vl, s=70, color=style.ARM["lora"], edgecolor=style.INK, lw=0.6, zorder=5)
|
| 463 |
+
for lab, v, s in zip(X_LAB[1:], vl, srcl):
|
| 464 |
+
rows.append(dict(panel=panel, dataset=ds, series="lora", pairs=lab, value=v, source=s,
|
| 465 |
+
y_axis_break=bool(broken)))
|
| 466 |
+
for key, val, src in refs:
|
| 467 |
+
r = REF[key]
|
| 468 |
+
for a in axes:
|
| 469 |
+
a.axhline(val, ls=r["ls"], color=r["color"], lw=r["lw"], zorder=2)
|
| 470 |
+
rows.append(dict(panel=panel, dataset=ds, series=f"ref_{key}", pairs="", value=val, source=src,
|
| 471 |
+
y_axis_break=bool(broken)))
|
| 472 |
+
ax.set_xlim(*XLIM)
|
| 473 |
+
ax.set_xticks(X_POS)
|
| 474 |
+
ax.set_xticklabels(xticks(ds))
|
| 475 |
+
# nothing is clipped: every plotted value is inside the y range of the axis that draws it
|
| 476 |
+
for v in list(vl) + [val for _, val, _ in refs] + [v for _, v, _ in vb + vs] + [v for ser, v, _ in z0
|
| 477 |
+
if ser not in out]:
|
| 478 |
+
assert ax.get_ylim()[0] <= v <= ax.get_ylim()[1], (panel, ds, v, ax.get_ylim())
|
| 479 |
+
for ser, v, _ in z0:
|
| 480 |
+
if ser in out:
|
| 481 |
+
assert axes[-1].get_ylim()[0] <= v <= axes[-1].get_ylim()[1], (panel, ds, ser, v)
|
| 482 |
+
return axes[-1]
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
def budget_series(budget, ds, getter, cal_all, src_all):
|
| 486 |
+
"""Equal-budget calibration line for one panel: [(pairs label, value, source)] at n = 5..40 (where present)
|
| 487 |
+
plus "all" = zs__cal (alpha from the same train + inner-val pairs LoRA "all" saw). [] when nothing is found."""
|
| 488 |
+
out = []
|
| 489 |
+
for n in LC_N:
|
| 490 |
+
if n not in budget[ds]:
|
| 491 |
+
continue
|
| 492 |
+
v, c = budget_value(budget[ds][n], getter)
|
| 493 |
+
if v is not None:
|
| 494 |
+
out.append((str(n), v, f"{c.path} arm {budget[ds][n]['arm']}"))
|
| 495 |
+
if out:
|
| 496 |
+
out.append(("all", cal_all, src_all + " arm zs__cal (alpha from every training pair of the fold = the rightmost LoRA point's pairs)"))
|
| 497 |
+
return out
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
def fig_realism(calls, lens, st, fold_sizes, rows, steprows, budget, scs):
|
| 501 |
+
has_budget = any(budget[ds] for ds in DSETS)
|
| 502 |
+
has_sc = any(scs[ds] for ds in DSETS)
|
| 503 |
+
n_leg = 6 + has_budget + has_sc
|
| 504 |
+
fig, axs = plt.subplots(2, 3, figsize=style.FULL, # a third legend row when an optional line is drawn
|
| 505 |
+
gridspec_kw=dict(left=0.168, right=0.99, top=0.79 if n_leg > 6 else 0.83,
|
| 506 |
+
bottom=0.12, hspace=0.36, wspace=0.30))
|
| 507 |
+
heads = ["Composition L1 ↓", "Coverage ↑", "Selected step (×1,000)"]
|
| 508 |
+
pos0 = {ri: axs[ri, 2].get_position() for ri in range(len(DSETS))} # row extents before any y-axis break
|
| 509 |
+
title_ax = {ci: axs[0, ci] for ci in range(3)}
|
| 510 |
+
for ri, ds in enumerate(DSETS):
|
| 511 |
+
c = calls[ds]
|
| 512 |
+
for ci, key in enumerate(["comp_l1", "coverage"]):
|
| 513 |
+
ax = axs[ri, ci]
|
| 514 |
+
refs = [("pseudo", c.head("zs__pseudo", key), c.src_summary)]
|
| 515 |
+
if key == "comp_l1":
|
| 516 |
+
refs.append(("null", c.head("real_lora__raw", "comp_l1_obs_loo_null"), c.src_summary))
|
| 517 |
+
z0 = [("zero_shot", c.head(ZS, key), c.src_summary),
|
| 518 |
+
("zs_len", lens[ds].head(ZS_LEN, key), lens[ds].src_summary)]
|
| 519 |
+
vb = budget_series(budget, ds, lambda cc, a, k=key: cc.head(a, k), c.head(ZS_CAL, key), c.src_summary)
|
| 520 |
+
vs = scsemi_series(scs, ds, lambda cc, a, k=key: cc.head(a, k))
|
| 521 |
+
tax = curve(ax, z0, [c.head(a, key) for a in LORA_ARMS], refs, rows,
|
| 522 |
+
f"{key}", ds, [c.src_summary] * 5, vb=vb, vs=vs)
|
| 523 |
+
if ri == 0:
|
| 524 |
+
title_ax[ci] = tax
|
| 525 |
+
# selected early-stopping step per fold
|
| 526 |
+
ax = axs[ri, 2]
|
| 527 |
+
s = st[st.dataset == ds]
|
| 528 |
+
for xi, arm in zip(X_POS[1:], RUN_ARMS):
|
| 529 |
+
f = s[s.arm == arm].sort_values("fold")
|
| 530 |
+
v = f.selected_step.astype(float).values / 1000
|
| 531 |
+
jit = np.linspace(-0.22, 0.22, len(v))
|
| 532 |
+
ax.scatter(xi + jit, v, s=36, color=style.ARM["lora"], edgecolor=style.INK, lw=0.5, zorder=4)
|
| 533 |
+
med = float(np.median(v))
|
| 534 |
+
ax.plot([xi - 0.36, xi + 0.36], [med, med], color=style.INK, lw=2.0, zorder=5)
|
| 535 |
+
steprows.append(dict(dataset=ds, arm=arm, pairs=X_LAB[X_POS.index(xi)], median_step=med * 1000,
|
| 536 |
+
min_step=v.min() * 1000, max_step=v.max() * 1000,
|
| 537 |
+
n_cap_limited=int(f.cap_limited.sum()),
|
| 538 |
+
max_last_window_drop_frac=(float(f[f.cap_limited].val_loss_last_window_drop_frac.max())
|
| 539 |
+
if f.cap_limited.any() else np.nan),
|
| 540 |
+
n_train=rng_txt(f.n_train), n_inner_val=rng_txt(f.n_inner_val),
|
| 541 |
+
source=";".join(f.source)))
|
| 542 |
+
cap = float(s.max_steps.max()) / 1000
|
| 543 |
+
ax.axhline(cap, color=style.GREY, lw=1.0, ls=(0, (2, 2)), zorder=1)
|
| 544 |
+
ax.text(X_POS[0] - 0.4, cap + 0.6, f"cap {cap:g}k", color=style.GREY, fontsize=12, va="bottom")
|
| 545 |
+
ax.text(X_POS[0], cap * 0.45, "no training", color=style.GREY, fontsize=12, ha="center",
|
| 546 |
+
va="center", rotation=90)
|
| 547 |
+
ax.set_ylim(0, cap * 1.18)
|
| 548 |
+
ax.set_xlim(-0.5, X_POS[-1] + 0.5)
|
| 549 |
+
ax.set_xticks(X_POS)
|
| 550 |
+
ax.set_xticklabels(xticks(ds))
|
| 551 |
+
n_all = rng_txt(s[s.arm == "real_lora"].n_train)
|
| 552 |
+
n_iv = rng_txt(s.n_inner_val)
|
| 553 |
+
n_scored = int(c.summary["n_donors"])
|
| 554 |
+
assert n_scored == sum(fold_sizes[ds]["test"]), (ds, n_scored, fold_sizes[ds]["test"])
|
| 555 |
+
n_alpha = rng_txt(fold_sizes[ds]["alpha"])
|
| 556 |
+
# zs__cal alpha uses the same donors LoRA "all" trains and early-stops on (train + inner-val)
|
| 557 |
+
lora_all_seen = sorted(int(a) + int(b) for a, b in zip(s[s.arm == "real_lora"].sort_values("fold").n_train,
|
| 558 |
+
s[s.arm == "real_lora"].sort_values("fold").n_inner_val))
|
| 559 |
+
assert lora_all_seen == sorted(fold_sizes[ds]["alpha"]), (ds, lora_all_seen, fold_sizes[ds]["alpha"])
|
| 560 |
+
ymid = (pos0[ri].y0 + pos0[ri].y1) / 2
|
| 561 |
+
fig.text(0.005, ymid + 0.075, DS_LABEL[ds], fontsize=15, fontweight="bold", va="bottom", ha="left")
|
| 562 |
+
fig.text(0.005, ymid + 0.065,
|
| 563 |
+
f"{n_scored} donors\ninner-val = {n_iv}\ntest fold\nnever trained on",
|
| 564 |
+
fontsize=12.5, va="top", ha="left", linespacing=1.35)
|
| 565 |
+
rows.append(dict(panel="meta", dataset=ds, series="n_scored_donors", pairs="", value=n_scored,
|
| 566 |
+
source=c.src_summary))
|
| 567 |
+
rows.append(dict(panel="meta", dataset=ds, series="n_pairs_all", pairs="all", value=n_all,
|
| 568 |
+
source="RUN.json train_rows: " + ";".join(s[s.arm == "real_lora"].source)))
|
| 569 |
+
rows.append(dict(panel="meta", dataset=ds, series="n_inner_val", pairs="", value=n_iv,
|
| 570 |
+
source="RUN.json inner_val_rows (all LoRA arms, 5 folds)"))
|
| 571 |
+
rows.append(dict(panel="meta", dataset=ds, series="n_test_donors_per_fold", pairs="",
|
| 572 |
+
value="/".join(map(str, fold_sizes[ds]["test"])),
|
| 573 |
+
source=fold_sizes[ds]["source"] + " fold_sizes test"))
|
| 574 |
+
rows.append(dict(panel="meta", dataset=ds, series="n_alpha_fit_pairs", pairs="0", value=n_alpha,
|
| 575 |
+
source=fold_sizes[ds]["source"] + " fold_sizes train+inner_val; prepare_dataset.py "
|
| 576 |
+
"fit = fold != f"))
|
| 577 |
+
for ci, h in enumerate(heads):
|
| 578 |
+
title_ax[ci].set_title(h, fontsize=14, pad=8)
|
| 579 |
+
x0, x1 = axs[1, 0].get_position().x0, axs[1, 2].get_position().x1
|
| 580 |
+
fig.text((x0 + x1) / 2, 0.005, xlabel(st), ha="center", va="bottom", fontsize=14)
|
| 581 |
+
handles = [ # column-wise fill: [raw, cal, (equal-budget cal)] | [LoRA, (scSemi), median] | [pseudo, null]
|
| 582 |
+
h_raw(), h_len()] + ([h_budget()] if has_budget else []) + ([h_scsemi()] if has_sc else []) + [
|
| 583 |
+
Line2D([0], [0], marker="o", color=style.ARM["lora"], lw=2.0, markeredgecolor=style.INK, markersize=8,
|
| 584 |
+
label="LoRA fine-tune (dots in step panel = folds)"),
|
| 585 |
+
Line2D([0], [0], color=style.INK, lw=2.0, label="Median of 5 folds"),
|
| 586 |
+
Line2D([0], [0], ls=REF["pseudo"]["ls"], color=REF["pseudo"]["color"], lw=REF["pseudo"]["lw"],
|
| 587 |
+
label=REF["pseudo"]["label"]),
|
| 588 |
+
Line2D([0], [0], ls=REF["null"]["ls"], color=REF["null"]["color"], lw=REF["null"]["lw"],
|
| 589 |
+
label=REF["null"]["label"]),
|
| 590 |
+
]
|
| 591 |
+
fig.legend(handles=handles, loc="upper left", bbox_to_anchor=(0.005, 1.0), ncol=3, frameon=False,
|
| 592 |
+
fontsize=12, handlelength=2.4, columnspacing=1.6, labelspacing=0.4, borderaxespad=0.0)
|
| 593 |
+
style.save(fig, "sec08_pairs_realism", FIGDIR)
|
| 594 |
+
|
| 595 |
+
|
| 596 |
+
def h_raw():
|
| 597 |
+
return Line2D([0], [0], marker="o", color=COL_RAW, lw=0, markeredgecolor=RAW_EDGE, markersize=8, label=LEG_ZS)
|
| 598 |
+
|
| 599 |
+
|
| 600 |
+
def h_len():
|
| 601 |
+
return Line2D([0], [0], marker="o", color=COL_LEN, lw=0, markeredgecolor=style.INK, markersize=8, label=LEG_LEN)
|
| 602 |
+
|
| 603 |
+
|
| 604 |
+
def h_scsemi():
|
| 605 |
+
return Line2D([0], [0], marker="D", color=COL_SC, lw=1.8, markeredgecolor=style.INK, markersize=7, label=LEG_SC)
|
| 606 |
+
|
| 607 |
+
|
| 608 |
+
def h_budget():
|
| 609 |
+
return Line2D([0], [0], marker="s", color=COL_CAL, lw=1.8, markeredgecolor=style.INK, markersize=7,
|
| 610 |
+
label=LEG_CAL_N)
|
| 611 |
+
|
| 612 |
+
|
| 613 |
+
def fig_signal(calls, deg_call, lens, st, rows, budget, scs):
|
| 614 |
+
has_budget = any(budget[ds] for ds in DSETS)
|
| 615 |
+
has_sc = any(scs[ds] for ds in DSETS)
|
| 616 |
+
leg_rows = -(-(5 + has_budget + has_sc) // 2)
|
| 617 |
+
fig, axs = plt.subplots(1, 3, figsize=style.TALL,
|
| 618 |
+
gridspec_kw=dict(left=0.085, right=0.99, top=0.755 - 0.055 * (leg_rows - 3), bottom=0.115,
|
| 619 |
+
wspace=0.42)) # 3 legend rows (4 with both optional lines)
|
| 620 |
+
im, se = calls["immicro"], calls["ye2026_sepsis"]
|
| 621 |
+
iml, sel = lens["immicro"], lens["ye2026_sepsis"]
|
| 622 |
+
tax = [None] * 3
|
| 623 |
+
# a: ImMicro across-donor NK fraction r
|
| 624 |
+
tax[0] = curve(axs[0], [("zero_shot", im.frac_r(ZS, "NK cell"), im.src_per_donor),
|
| 625 |
+
("zs_len", iml.frac_r(ZS_LEN, "NK cell"), iml.src_per_donor)],
|
| 626 |
+
[im.frac_r(a, "NK cell") for a in LORA_ARMS],
|
| 627 |
+
[("pseudo", im.frac_r("zs__pseudo", "NK cell"), im.src_per_donor)], rows, "nk_fraction_r",
|
| 628 |
+
"immicro", [im.src_per_donor] * 5,
|
| 629 |
+
vb=budget_series(budget, "immicro", lambda cc, a: cc.frac_r(a, "NK cell"),
|
| 630 |
+
im.frac_r(ZS_CAL, "NK cell"), im.src_per_donor),
|
| 631 |
+
vs=scsemi_series(scs, "immicro", lambda cc, a: cc.frac_r(a, "NK cell")))
|
| 632 |
+
# other cell types, recorded for the footnote ("0+cal" = zero-shot + calibration)
|
| 633 |
+
for ct in ["T cell", "B cell", "Monocyte"]:
|
| 634 |
+
for a, lab in zip([ZS, ZS_CAL] + LORA_ARMS, ["0", "0+cal"] + X_LAB[1:]):
|
| 635 |
+
rows.append(dict(panel="other_fraction_r", dataset="immicro", series=ct, pairs=lab,
|
| 636 |
+
value=im.frac_r(a, ct), source=im.src_per_donor))
|
| 637 |
+
# b: sepsis disease logFC r (mean of T/B/Mono/NK, mean_cp10k)
|
| 638 |
+
tax[1] = curve(axs[1], [("zero_shot", se.contrast_r(ZS), se.src_contrast),
|
| 639 |
+
("zs_len", sel.contrast_r(ZS_LEN), sel.src_contrast)],
|
| 640 |
+
[se.contrast_r(a) for a in LORA_ARMS],
|
| 641 |
+
[("pseudo", se.contrast_r("zs__pseudo"), se.src_contrast)], # no broadcast (2026-10-08)
|
| 642 |
+
rows, "logfc_r", "ye2026_sepsis", [se.src_contrast] * 5,
|
| 643 |
+
vb=budget_series(budget, "ye2026_sepsis", lambda cc, a: cc.contrast_r(a),
|
| 644 |
+
se.contrast_r(ZS_CAL), se.src_contrast),
|
| 645 |
+
vs=scsemi_series(scs, "ye2026_sepsis", lambda cc, a: cc.contrast_r(a)))
|
| 646 |
+
# c: sepsis top-50 DEG (Welch, sum over T/B/Mono/NK/DC)
|
| 647 |
+
tax[2] = curve(axs[2], [("zero_shot", deg_call.deg(ZS), deg_call.src_contrast),
|
| 648 |
+
("zs_len", sel.deg(ZS_LEN), sel.src_contrast)],
|
| 649 |
+
[deg_call.deg(a) for a in LORA_ARMS],
|
| 650 |
+
[("pseudo", deg_call.deg("zs__pseudo"), deg_call.src_contrast)], # no broadcast (2026-10-08)
|
| 651 |
+
rows, "top50_deg", "ye2026_sepsis", [deg_call.src_contrast] * 5, ylim0=0,
|
| 652 |
+
vb=budget_series(budget, "ye2026_sepsis", lambda cc, a: cc.deg(a),
|
| 653 |
+
deg_call.deg(ZS_CAL), deg_call.src_contrast),
|
| 654 |
+
vs=scsemi_series(scs, "ye2026_sepsis", lambda cc, a: cc.deg(a)))
|
| 655 |
+
# top-50 DEG overlap per cell type (footnote: which types carry the gain), incl. broadcast
|
| 656 |
+
for ct in DEG_TYPES:
|
| 657 |
+
for a, lab in zip([ZS, ZS_CAL] + LORA_ARMS + ["zs__pseudo"], ["0", "0+cal"] + X_LAB[1:] + ["pseudo"]):
|
| 658 |
+
rows.append(dict(panel="top50_deg_by_type", dataset="ye2026_sepsis", series=ct, pairs=lab,
|
| 659 |
+
value=deg_call.deg_type(a, ct), source=deg_call.src_contrast))
|
| 660 |
+
rows.append(dict(panel="top50_deg_by_type", dataset="ye2026_sepsis", series=ct, pairs="broadcast",
|
| 661 |
+
value=deg_call.deg_type("real_lora__raw", ct, "top50_overlap_broadcast"),
|
| 662 |
+
source=deg_call.src_contrast))
|
| 663 |
+
cd = se.summary["contrast_definition"]
|
| 664 |
+
grp = f"Sepsis {cd['n_case_donors']} vs {cd['n_control_donors']}"
|
| 665 |
+
heads = [f"ImMicro, {int(im.summary['n_donors'])} donors\ndonor NK fraction r",
|
| 666 |
+
f"{grp}\ndisease logFC r", f"{grp}\ntop-50 DEG overlap"]
|
| 667 |
+
for ax, h in zip(tax, heads):
|
| 668 |
+
ax.set_title(h, fontsize=14, pad=8, linespacing=1.3)
|
| 669 |
+
x0, x1 = axs[0].get_position().x0, axs[2].get_position().x1
|
| 670 |
+
fig.text((x0 + x1) / 2, 0.005, xlabel(st), ha="center", va="bottom", fontsize=13)
|
| 671 |
+
rows.append(dict(panel="meta", dataset="ye2026_sepsis", series="n_case_vs_control", pairs="",
|
| 672 |
+
value=f"{se.summary['contrast_definition']['n_case_donors']} vs "
|
| 673 |
+
f"{se.summary['contrast_definition']['n_control_donors']}", source=se.src_summary))
|
| 674 |
+
handles = [ # column-wise fill: [raw, cal, pseudo, ...] | [LoRA, (equal-budget cal), (scSemi), broadcast]
|
| 675 |
+
h_raw(), h_len(),
|
| 676 |
+
Line2D([0], [0], ls=REF["pseudo"]["ls"], color=REF["pseudo"]["color"], lw=REF["pseudo"]["lw"],
|
| 677 |
+
label=REF["pseudo"]["label"]),
|
| 678 |
+
Line2D([0], [0], marker="o", color=style.ARM["lora"], lw=2.0, markeredgecolor=style.INK, markersize=8,
|
| 679 |
+
label="LoRA fine-tune"),
|
| 680 |
+
] + ([h_budget()] if has_budget else []) + ([h_scsemi()] if has_sc else [])
|
| 681 |
+
fig.legend(handles=handles, loc="upper left", bbox_to_anchor=(0.005, 1.0), ncol=2, frameon=False,
|
| 682 |
+
fontsize=12, handlelength=2.4, columnspacing=1.2, labelspacing=0.4, borderaxespad=0.0)
|
| 683 |
+
style.save(fig, "sec08_pairs_signal", FIGDIR)
|
| 684 |
+
|
| 685 |
+
|
| 686 |
+
def slide_numbers(calls, deg_call, st, fold_sizes, fewshot, budget, budget_log, scs=None, sc_log=(), lens=None):
|
| 687 |
+
"""Numbers quoted in the slide keywords/footnote, each with its source file."""
|
| 688 |
+
im, se = calls["immicro"], calls["ye2026_sepsis"]
|
| 689 |
+
out = []
|
| 690 |
+
|
| 691 |
+
def add(key, value, src):
|
| 692 |
+
out.append(dict(key=key, value=value, source=src))
|
| 693 |
+
|
| 694 |
+
for ds, c in calls.items():
|
| 695 |
+
for key in ("coverage", "comp_l1"):
|
| 696 |
+
add(f"{ds}.{key}.zero_shot", round(c.head(ZS, key), 3), c.src_summary)
|
| 697 |
+
add(f"{ds}.{key}.zs_cal", round(c.head(ZS_CAL, key), 3), c.src_summary)
|
| 698 |
+
if lens:
|
| 699 |
+
add(f"{ds}.{key}.zs_len", round(lens[ds].head(ZS_LEN, key), 3), lens[ds].src_summary)
|
| 700 |
+
add(f"{ds}.{key}.lora_n5", round(c.head("lora_n5__raw", key), 3), c.src_summary)
|
| 701 |
+
add(f"{ds}.{key}.lora_all", round(c.head("real_lora__raw", key), 3), c.src_summary)
|
| 702 |
+
add(f"{ds}.{key}.zs_pseudo", round(c.head("zs__pseudo", key), 3), c.src_summary)
|
| 703 |
+
add(f"{ds}.comp_l1.null", round(c.head("real_lora__raw", "comp_l1_obs_loo_null"), 3), c.src_summary)
|
| 704 |
+
# donor-level composition L1, each LoRA size vs zero-shot (paired Wilcoxon, uncorrected)
|
| 705 |
+
piv = c.per_donor.pivot(index="donor", columns="arm", values="comp_l1")
|
| 706 |
+
for a, lab in zip(LORA_ARMS, X_LAB[1:]):
|
| 707 |
+
x = (piv[a] - piv[ZS]).dropna()
|
| 708 |
+
add(f"{ds}.comp_l1.lora_{lab}_minus_zero_shot.mean", round(float(x.mean()), 3), c.src_per_donor)
|
| 709 |
+
add(f"{ds}.comp_l1.lora_{lab}_minus_zero_shot.frac_donors_lower", round(float((x < 0).mean()), 2),
|
| 710 |
+
c.src_per_donor)
|
| 711 |
+
add(f"{ds}.comp_l1.lora_{lab}_vs_zero_shot.wilcoxon_p", float(f"{wilcoxon(x).pvalue:.2g}"),
|
| 712 |
+
c.src_per_donor)
|
| 713 |
+
# each LoRA size vs zero-shot + calibration (donor L1 and donor coverage; paired Wilcoxon, uncorrected)
|
| 714 |
+
for met in ("comp_l1", "coverage"):
|
| 715 |
+
pv = c.per_donor.pivot(index="donor", columns="arm", values=met)
|
| 716 |
+
for a, lab in zip(LORA_ARMS, X_LAB[1:]):
|
| 717 |
+
x = (pv[a] - pv[ZS_CAL]).dropna()
|
| 718 |
+
add(f"{ds}.{met}.lora_{lab}_minus_zs_cal.mean", round(float(x.mean()), 3), c.src_per_donor)
|
| 719 |
+
add(f"{ds}.{met}.lora_{lab}_minus_zs_cal.frac_donors_lower", round(float((x < 0).mean()), 2),
|
| 720 |
+
c.src_per_donor)
|
| 721 |
+
add(f"{ds}.{met}.lora_{lab}_vs_zs_cal.wilcoxon_p", float(f"{wilcoxon(x).pvalue:.2g}"),
|
| 722 |
+
c.src_per_donor)
|
| 723 |
+
# the raw -> calibrated zero-shot gap
|
| 724 |
+
x = (pv[ZS_CAL] - pv[ZS]).dropna()
|
| 725 |
+
add(f"{ds}.{met}.zs_cal_minus_zero_shot.mean", round(float(x.mean()), 3), c.src_per_donor)
|
| 726 |
+
add(f"{ds}.{met}.zs_cal_vs_zero_shot.wilcoxon_p", float(f"{wilcoxon(x).pvalue:.2g}"), c.src_per_donor)
|
| 727 |
+
add(f"{ds}.cal_alpha_fit_pairs", rng_txt(fold_sizes[ds]["alpha"]),
|
| 728 |
+
fold_sizes[ds]["source"] + " fold_sizes train+inner_val; tools/prepare_dataset.py fit = fold != f")
|
| 729 |
+
# few-pair call (its own donors): alpha from the same 5 pairs vs LoRA on them (fixed 3k steps, no inner-val)
|
| 730 |
+
add(f"{ds}.fewshot_n5.coverage.zs_cal_same5", round(fewshot[ds]["zs_cal"], 3), fewshot[ds]["source"])
|
| 731 |
+
add(f"{ds}.fewshot_n5.coverage.lora5_fixed3k", round(fewshot[ds]["lora5"], 3), fewshot[ds]["source"])
|
| 732 |
+
add(f"{ds}.n_scored_donors", int(c.summary["n_donors"]), c.src_summary)
|
| 733 |
+
s = st[st.dataset == ds]
|
| 734 |
+
add(f"{ds}.selected_step.lora_n5.range", rng_txt(s[s.arm == "lora_n5"].selected_step), "RUN.json: "
|
| 735 |
+
+ ";".join(s[s.arm == "lora_n5"].source))
|
| 736 |
+
add(f"{ds}.n_train.all", rng_txt(s[s.arm == "real_lora"].n_train), "RUN.json: "
|
| 737 |
+
+ ";".join(s[s.arm == "real_lora"].source))
|
| 738 |
+
add(f"{ds}.n_inner_val", rng_txt(s.n_inner_val), "RUN.json inner_val_rows (all LoRA arms, 5 folds)")
|
| 739 |
+
for arm in RUN_ARMS:
|
| 740 |
+
f = s[s.arm == arm]
|
| 741 |
+
add(f"{ds}.folds_cap_limited.{arm}", f"{int(f.cap_limited.sum())}/{len(f)}",
|
| 742 |
+
"RUN.json steps_run == max_steps and steps_run - selected_step < patience*eval_every: "
|
| 743 |
+
+ ";".join(f.source))
|
| 744 |
+
capped = s[s.cap_limited]
|
| 745 |
+
if len(capped):
|
| 746 |
+
add(f"{ds}.cap_limited.max_val_loss_drop_frac_last_2k_steps",
|
| 747 |
+
round(float(capped.val_loss_last_window_drop_frac.max()), 4),
|
| 748 |
+
"history.json inner_val_loss (drop over last patience window / drop from step 0): "
|
| 749 |
+
+ ";".join(capped.history))
|
| 750 |
+
for a, lab in zip([ZS, ZS_CAL] + LORA_ARMS + ["zs__pseudo"], KEY_LAB[:1] + ["zs_cal"] + KEY_LAB[1:] + ["pseudo"]):
|
| 751 |
+
add(f"immicro.nk_fraction_r.{lab}", round(im.frac_r(a, "NK cell"), 2), im.src_per_donor)
|
| 752 |
+
add(f"sepsis.logfc_r.{lab}", round(se.contrast_r(a), 2), se.src_contrast)
|
| 753 |
+
add(f"sepsis.top50_deg.{lab}", int(deg_call.deg(a)), deg_call.src_contrast)
|
| 754 |
+
add("sepsis.logfc_r.broadcast", round(se.contrast_r("real_lora__raw", "r_broadcast"), 2), se.src_contrast)
|
| 755 |
+
add("sepsis.top50_deg.broadcast", int(deg_call.deg("real_lora__raw", "top50_overlap_broadcast")),
|
| 756 |
+
deg_call.src_contrast)
|
| 757 |
+
|
| 758 |
+
def first_sustained(v, thr, strict=True):
|
| 759 |
+
"""First LoRA n from which every later n is above (or >=) thr."""
|
| 760 |
+
for i in range(len(v)):
|
| 761 |
+
if all((x > thr) if strict else (x >= thr) for x in v[i:]):
|
| 762 |
+
return X_LAB[1 + i]
|
| 763 |
+
return "never"
|
| 764 |
+
bc_r = se.contrast_r("real_lora__raw", "r_broadcast")
|
| 765 |
+
bc_d = deg_call.deg("real_lora__raw", "top50_overlap_broadcast")
|
| 766 |
+
vr = [se.contrast_r(a) for a in LORA_ARMS]
|
| 767 |
+
vd = [deg_call.deg(a) for a in LORA_ARMS]
|
| 768 |
+
add("sepsis.logfc_r.first_n_above_broadcast", first_sustained(vr, bc_r), se.src_contrast)
|
| 769 |
+
add("sepsis.logfc_r.first_n_above_zero_shot", first_sustained(vr, se.contrast_r(ZS)), se.src_contrast)
|
| 770 |
+
add("sepsis.top50_deg.first_n_at_or_above_broadcast", first_sustained(vd, bc_d, strict=False),
|
| 771 |
+
deg_call.src_contrast)
|
| 772 |
+
add("sepsis.top50_deg.first_n_above_zero_shot", first_sustained(vd, deg_call.deg(ZS)), deg_call.src_contrast)
|
| 773 |
+
add("sepsis.logfc_r.first_n_above_zs_cal", first_sustained(vr, se.contrast_r(ZS_CAL)), se.src_contrast)
|
| 774 |
+
add("sepsis.top50_deg.first_n_above_zs_cal", first_sustained(vd, deg_call.deg(ZS_CAL)), deg_call.src_contrast)
|
| 775 |
+
vn = [im.frac_r(a, "NK cell") for a in LORA_ARMS]
|
| 776 |
+
add("immicro.nk_fraction_r.first_n_above_zs_cal", first_sustained(vn, im.frac_r(ZS_CAL, "NK cell")),
|
| 777 |
+
im.src_per_donor)
|
| 778 |
+
for ds, c in calls.items():
|
| 779 |
+
for key in ("coverage", "comp_l1"):
|
| 780 |
+
v = [c.head(a, key) for a in LORA_ARMS]
|
| 781 |
+
thr = c.head(ZS_CAL, key)
|
| 782 |
+
first = first_sustained([-x for x in v], -thr) if key == "comp_l1" else first_sustained(v, thr)
|
| 783 |
+
add(f"{ds}.{key}.first_n_better_than_zs_cal", first, c.src_summary)
|
| 784 |
+
# across-donor fraction r per cell type: first n from which LoRA stays at/above zero-shot (footnote)
|
| 785 |
+
for ct, key in [("T cell", "T"), ("B cell", "B"), ("Monocyte", "Mono"), ("NK cell", "NK")]:
|
| 786 |
+
v = [im.frac_r(a, ct) for a in LORA_ARMS]
|
| 787 |
+
add(f"immicro.fraction_r.{key}.first_n_at_or_above_zero_shot",
|
| 788 |
+
first_sustained(v, im.frac_r(ZS, ct), strict=False), im.src_per_donor)
|
| 789 |
+
add(f"immicro.fraction_r.{key}.zero_shot", round(im.frac_r(ZS, ct), 2), im.src_per_donor)
|
| 790 |
+
add(f"immicro.fraction_r.{key}.zs_cal", round(im.frac_r(ZS_CAL, ct), 2), im.src_per_donor)
|
| 791 |
+
add(f"immicro.fraction_r.{key}.first_n_at_or_above_zs_cal",
|
| 792 |
+
first_sustained(v, im.frac_r(ZS_CAL, ct), strict=False), im.src_per_donor)
|
| 793 |
+
add(f"immicro.fraction_r.{key}.lora_5_10_20_40_all", "/".join(f"{x:.2f}" for x in v), im.src_per_donor)
|
| 794 |
+
# top-50 DEG overlap by cell type (which types carry the gain)
|
| 795 |
+
for ct, key in [("T cell", "T"), ("B cell", "B"), ("Monocyte", "Mono"), ("NK cell", "NK"), ("DC", "DC")]:
|
| 796 |
+
v = [deg_call.deg_type(a, ct) for a in [ZS] + LORA_ARMS]
|
| 797 |
+
add(f"sepsis.top50_deg.{key}.zero_shot_5_10_20_40_all", "/".join(f"{x:g}" for x in v),
|
| 798 |
+
deg_call.src_contrast)
|
| 799 |
+
add(f"sepsis.top50_deg.{key}.zs_cal", int(deg_call.deg_type(ZS_CAL, ct)), deg_call.src_contrast)
|
| 800 |
+
add(f"sepsis.top50_deg.{key}.broadcast", int(deg_call.deg_type("real_lora__raw", ct,
|
| 801 |
+
"top50_overlap_broadcast")),
|
| 802 |
+
deg_call.src_contrast)
|
| 803 |
+
add("sepsis.n_case", int(se.summary["contrast_definition"]["n_case_donors"]), se.src_summary)
|
| 804 |
+
add("sepsis.n_control", int(se.summary["contrast_definition"]["n_control_donors"]), se.src_summary)
|
| 805 |
+
add("final_checkpoint", FINAL_CKPT, "RUN.json source_checkpoint (all 50 LoRA runs)")
|
| 806 |
+
# equal-budget calibration scan (zero-shot + calibration with alpha from the n + inner-val pairs of lora_n*)
|
| 807 |
+
add("cal_budget.pattern", f"scores/<dataset>/**/summary.json arm names: 'cal' and regex {CAL_N_RE.pattern}, "
|
| 808 |
+
f"none of {list(FT_TAGS)}", str(PLAN / "scores"))
|
| 809 |
+
add("cal_budget.found", ";".join(f"{r['dataset']}:{r['call']}:{r['arm']}" for r in budget_log) or "none",
|
| 810 |
+
str(PLAN / "scores"))
|
| 811 |
+
for ds in DSETS:
|
| 812 |
+
add(f"{ds}.cal_budget.n_drawn", ",".join(str(n) for n in sorted(budget[ds])) or "none", str(PLAN / "scores"))
|
| 813 |
+
# scSemiProfiler line (equal-budget n + 5-fold CV "all")
|
| 814 |
+
add("scsemi.found", ";".join(f"{r['dataset']}:{r['call']}:{r['arm']}:{r['note']}" for r in sc_log) or "none",
|
| 815 |
+
f"{SR.plan_root()}/scores/<dataset>/{{{SR.BUDGET_EXP},{SR.CV_EXP}}}/pooled*")
|
| 816 |
+
for ds in DSETS:
|
| 817 |
+
sc = (scs or {}).get(ds, {})
|
| 818 |
+
add(f"{ds}.scsemi.pairs_drawn", ",".join(lab for lab in X_LAB[1:] if lab in sc) or "none",
|
| 819 |
+
f"{SR.plan_root()}/scores/{ds}")
|
| 820 |
+
for lab in X_LAB[1:]:
|
| 821 |
+
if lab in sc:
|
| 822 |
+
for key in ("coverage", "comp_l1"):
|
| 823 |
+
v, c = budget_value(sc[lab], lambda cc, a, k=key: cc.head(a, k))
|
| 824 |
+
if v is not None:
|
| 825 |
+
add(f"{ds}.{key}.scsemi_{lab}", round(v, 3), str(c.path / "summary.json"))
|
| 826 |
+
return pd.DataFrame(out)
|
| 827 |
+
|
| 828 |
+
|
| 829 |
+
def check_against_fig3(rows):
|
| 830 |
+
"""Cross-check the LoRA curve, the zero-shot + calibration point and the reference lines with the plan's own
|
| 831 |
+
fig3 source data (same numbers, independent code path; the plan's fig3 n=0 point is zs__cal). The zero-shot
|
| 832 |
+
real-bulk point is not in fig3; it is checked in load() instead (headline vs per_donor.csv / contrast.csv)."""
|
| 833 |
+
ref = pd.read_csv(PLAN / "figures" / "source_data" / "fig3_learning_curve.csv")
|
| 834 |
+
pmap = {("comp_l1", "immicro"): "3a", ("comp_l1", "ye2026_sepsis"): "3b",
|
| 835 |
+
("coverage", "immicro"): "3c", ("coverage", "ye2026_sepsis"): "3d",
|
| 836 |
+
("nk_fraction_r", "immicro"): "3e", ("logfc_r", "ye2026_sepsis"): "3f",
|
| 837 |
+
("top50_deg", "ye2026_sepsis"): "3h"}
|
| 838 |
+
n = 0
|
| 839 |
+
for r in rows:
|
| 840 |
+
p = pmap.get((r["panel"], r["dataset"]))
|
| 841 |
+
if p is None or r["series"] in ("zero_shot", "zs_cal_budget", "scsemi"):
|
| 842 |
+
continue
|
| 843 |
+
if r["series"] == "lora":
|
| 844 |
+
m = ref[(ref.panel == p) & (ref.series == r["series"]) & (ref.draw == f"n={r['pairs']}")]
|
| 845 |
+
elif r["series"] == "zs_cal":
|
| 846 |
+
m = ref[(ref.panel == p) & (ref.series == "zs_cal") & (ref.draw == "n=0")]
|
| 847 |
+
else:
|
| 848 |
+
m = ref[(ref.panel == p) & (ref.series == r["series"])]
|
| 849 |
+
assert len(m) == 1, (r, len(m))
|
| 850 |
+
assert abs(float(m.value.iloc[0]) - float(r["value"])) < 1e-5, (r, float(m.value.iloc[0]))
|
| 851 |
+
n += 1
|
| 852 |
+
return n
|
| 853 |
+
|
| 854 |
+
|
| 855 |
+
def main():
|
| 856 |
+
calls, deg_call, lens = load()
|
| 857 |
+
st = load_steps()
|
| 858 |
+
fold_sizes = load_fold_sizes()
|
| 859 |
+
fewshot = load_fewshot()
|
| 860 |
+
budget, budget_log = find_cal_budget(calls, deg_call)
|
| 861 |
+
scs, sc_log = find_scsemi(calls)
|
| 862 |
+
rows, steprows = [], []
|
| 863 |
+
fig_realism(calls, lens, st, fold_sizes, rows, steprows, budget, scs)
|
| 864 |
+
rows_sig = []
|
| 865 |
+
fig_signal(calls, deg_call, lens, st, rows_sig, budget, scs)
|
| 866 |
+
n_checked = check_against_fig3(rows + rows_sig)
|
| 867 |
+
pd.DataFrame(rows).to_csv(DATADIR / "sec08_pairs_realism.csv", index=False, float_format="%.6g")
|
| 868 |
+
pd.DataFrame(steprows).to_csv(DATADIR / "sec08_selected_steps.csv", index=False, float_format="%.6g")
|
| 869 |
+
st.to_csv(DATADIR / "sec08_selected_steps_per_fold.csv", index=False)
|
| 870 |
+
pd.DataFrame(rows_sig).to_csv(DATADIR / "sec08_pairs_signal.csv", index=False, float_format="%.6g")
|
| 871 |
+
nums = slide_numbers(calls, deg_call, st, fold_sizes, fewshot, budget, budget_log, scs, sc_log, lens)
|
| 872 |
+
nums.to_csv(DATADIR / "sec08_slide_numbers.csv", index=False)
|
| 873 |
+
print(nums.to_string(index=False, max_colwidth=70))
|
| 874 |
+
print(f"cross-checked {n_checked} plotted values against fig3_learning_curve.csv")
|
| 875 |
+
brk = [(r["panel"], r["dataset"]) for r in rows + rows_sig if r.get("series") == "zero_shot" and r["y_axis_break"]]
|
| 876 |
+
print(f"y-axis breaks: {brk}")
|
| 877 |
+
print(f"equal-budget calibration scan: arm names with 'cal' and regex {CAL_N_RE.pattern!r}, none of {FT_TAGS}, "
|
| 878 |
+
f"in {PLAN / 'scores'}/<dataset>/**/summary.json")
|
| 879 |
+
for r in budget_log:
|
| 880 |
+
print(f" found {r['dataset']} {r['call']} {r['arm']} (n {r['n']}): {r['note']}")
|
| 881 |
+
if not any(budget[ds] for ds in DSETS):
|
| 882 |
+
print(" NOTE: no equal-budget calibration arms found; only the two x = 0 zero-shot points are drawn.")
|
| 883 |
+
print(f"scSemiProfiler scan: {SR.plan_root()}/scores/<dataset>/{SR.BUDGET_EXP}/pooled* (scsemi_n<n>__raw) and "
|
| 884 |
+
f"{SR.CV_EXP}/pooled* ({SR.CV_ARM}, drawn at 'all')")
|
| 885 |
+
for r in sc_log:
|
| 886 |
+
print(f" found {r['dataset']} {r['call']} {r['arm']} (pairs {r['pairs']}): {r['note']}")
|
| 887 |
+
if not any(scs[ds] for ds in DSETS):
|
| 888 |
+
print(" NOTE: no scSemiProfiler equal-budget or 5-fold calls found; no scSemiProfiler line is drawn.")
|
| 889 |
+
|
| 890 |
+
|
| 891 |
+
if __name__ == "__main__":
|
| 892 |
+
main()
|
paper-releases/pbisc-diffusion/updates/20261008T121550Z-deck-fig4-rules-no-broadcast/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec09_cat_curves.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Section 9 of the 2026-09-30 paper-summary deck: CAT curves (correspondence at the top) of the disease genes
|
| 3 |
+
(added 2026-10-02, user request: a threshold-free DEG comparison with the random expectation drawn).
|
| 4 |
+
|
| 5 |
+
CPU only. Reads plans/paired_finetune_intradataset_20260927/scores_contrast/{fewshot,pooled}_cat.csv
|
| 6 |
+
(tools/contrast_extra.py): per cell type, all tested genes ranked by |limma moderated t| on the observed side and on the
|
| 7 |
+
predicted side; CAT(k) = fraction of the observed top-k genes that are also in the predicted top-k with the same logFC
|
| 8 |
+
sign (Irizarry et al. 2005); chance = k / (2 G) for G genes tested on both sides. Plotted: mean over T / B / Mono / NK;
|
| 9 |
+
5 donors = mean over the 5 draws of that per-draw mean (the main comparison); 5-fold = the pooled call (shown
|
| 10 |
+
separately). No bulk-broadcast curve (user decision 2026-10-08).
|
| 11 |
+
|
| 12 |
+
Outputs (deck folder; DECK_FIGDIR / DECK_OUTDATA override the folders):
|
| 13 |
+
figures/sec09_cat_curves.{png,pdf}
|
| 14 |
+
data/sec09_cat_curves.csv every plotted value with its source
|
| 15 |
+
data/sec09_cat_curves_slide_text.json title, keywords, footnotes (synced through text_source)
|
| 16 |
+
"""
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import os
|
| 20 |
+
|
| 21 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = ""
|
| 22 |
+
|
| 23 |
+
import json
|
| 24 |
+
import sys
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
|
| 27 |
+
import numpy as np
|
| 28 |
+
import pandas as pd
|
| 29 |
+
|
| 30 |
+
DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/"
|
| 31 |
+
"2026-09-30--paper-summary--r00")
|
| 32 |
+
sys.path.insert(0, str(DECK / "tools"))
|
| 33 |
+
import sec09_paired_validation as S9 # noqa: E402 (names, colours, labels; sets the deck rcParams)
|
| 34 |
+
import style # noqa: E402
|
| 35 |
+
import matplotlib.pyplot as plt # noqa: E402
|
| 36 |
+
from matplotlib.lines import Line2D # noqa: E402
|
| 37 |
+
|
| 38 |
+
CX = S9.T / "scores_contrast"
|
| 39 |
+
FIGDIR = Path(os.environ.get("DECK_FIGDIR", str(DECK / "figures")))
|
| 40 |
+
OUTDATA = Path(os.environ.get("DECK_OUTDATA", str(DECK / "data")))
|
| 41 |
+
DIS = S9.DISEASE
|
| 42 |
+
NAME = S9.NAME
|
| 43 |
+
TYPES = ["T cell", "B cell", "Monocyte", "NK cell"]
|
| 44 |
+
FS = style.FS
|
| 45 |
+
FEW = [("zs_raw", "zs_raw"), ("zs_cal", "zs_cal"), ("scsemi5", "scsemi5"), ("lora", "lora5")]
|
| 46 |
+
POOL = [("zs_raw", "zs__raw"), ("zs_cal", "zs__cal"), ("sconly_cal", "pseudo_full__cal"), ("lora", "real_lora__raw")]
|
| 47 |
+
LORA_ARM = {"fewshot": "lora5", "pooled": "real_lora__raw"}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def curves(cat: pd.DataFrame, design: str):
|
| 51 |
+
"""{(dataset, key): Series over k} for generated arms and 'chance' (chance of the LoRA arm's lists)."""
|
| 52 |
+
c = cat[cat.celltype.isin(TYPES)].copy()
|
| 53 |
+
c["kind"] = np.where(c.predictor.str.startswith("generated:"), "gen", "bc")
|
| 54 |
+
out = {}
|
| 55 |
+
arms = FEW if design == "fewshot" else POOL
|
| 56 |
+
for ds in DIS:
|
| 57 |
+
d = c[c.dataset == ds]
|
| 58 |
+
for key, arm in arms:
|
| 59 |
+
g = d[(d.arm == arm) & (d.kind == "gen")]
|
| 60 |
+
if g.empty:
|
| 61 |
+
continue
|
| 62 |
+
out[(ds, key)] = g.groupby(["unit", "k"]).cat_same_sign.mean().groupby("k").mean()
|
| 63 |
+
lo = d[d.arm == LORA_ARM[design]]
|
| 64 |
+
out[(ds, "chance")] = lo[lo.kind == "gen"].groupby(["unit", "k"]).chance_same_sign.mean().groupby("k").mean()
|
| 65 |
+
return out
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def main() -> int:
|
| 69 |
+
few = curves(pd.read_csv(CX / "fewshot_cat.csv"), "fewshot")
|
| 70 |
+
poo = curves(pd.read_csv(CX / "pooled_cat.csv"), "pooled")
|
| 71 |
+
fig, axs = plt.subplots(2, len(DIS), figsize=(12.3, 5.2), sharex=True,
|
| 72 |
+
gridspec_kw=dict(left=0.105, right=0.995, top=0.90, bottom=0.215, hspace=0.32, wspace=0.28))
|
| 73 |
+
rows = []
|
| 74 |
+
for ri, (lab, cv, keys, src) in enumerate([("5 donors", few, FEW, "fewshot_cat.csv"),
|
| 75 |
+
("5-fold CV\n(separate)", poo, POOL, "pooled_cat.csv")]):
|
| 76 |
+
for ci, ds in enumerate(DIS):
|
| 77 |
+
ax = axs[ri, ci]
|
| 78 |
+
hi = 0.0
|
| 79 |
+
for key, _ in keys:
|
| 80 |
+
if (ds, key) not in cv:
|
| 81 |
+
continue
|
| 82 |
+
s = cv[(ds, key)]
|
| 83 |
+
ax.plot(s.index, s.values, color=S9.COL[key], lw=2.2 if key == "lora" else 1.6, marker="o", ms=4,
|
| 84 |
+
mec=S9.EDGE, mew=0.5, zorder=4 if key == "lora" else 3)
|
| 85 |
+
hi = max(hi, s.max())
|
| 86 |
+
rows += [dict(design=lab, dataset=ds, series=key, k=int(k), cat=float(v), source=str(CX / src))
|
| 87 |
+
for k, v in s.items()]
|
| 88 |
+
ch = cv[(ds, "chance")]
|
| 89 |
+
ax.plot(ch.index, ch.values, ls=(0, (3, 2)), color=style.INK, lw=1.0, zorder=2)
|
| 90 |
+
rows += [dict(design=lab.split("\n")[0], dataset=ds, series="chance", k=int(k), cat=float(v),
|
| 91 |
+
source=str(CX / src)) for k, v in ch.items()]
|
| 92 |
+
ax.set_xscale("log")
|
| 93 |
+
ax.set_xticks([10, 50, 100, 500], ["10", "50", "100", "500"])
|
| 94 |
+
ax.set_ylim(0, max(0.12, hi * 1.15))
|
| 95 |
+
ax.yaxis.set_major_locator(plt.MaxNLocator(nbins=4))
|
| 96 |
+
ax.tick_params(labelsize=FS - 3)
|
| 97 |
+
if ri == 0:
|
| 98 |
+
ax.set_title(S9.ROWNAME[ds], fontsize=FS - 1, pad=6)
|
| 99 |
+
if ri == 1:
|
| 100 |
+
ax.set_xlabel("top-k genes (k)", fontsize=FS - 2)
|
| 101 |
+
axs[ri, 0].annotate(lab, xy=(0, 0.5), xycoords="axes fraction", xytext=(-58, 0), textcoords="offset points",
|
| 102 |
+
ha="right", va="center", fontsize=FS, fontweight="bold")
|
| 103 |
+
axs[ri, 0].set_ylabel("CAT, same sign", fontsize=FS - 3)
|
| 104 |
+
hk = [("zs_raw", S9.LAB["zs_raw"]), ("zs_cal", S9.LAB["zs_cal"]), ("scsemi5", "scSemiProfiler (5 donors)"),
|
| 105 |
+
("sconly_cal", "sc-only fine-tune (5-fold)"), ("lora", "LoRA")]
|
| 106 |
+
handles = [Line2D([0], [0], color=S9.COL[k], lw=2.0, marker="o", ms=5, mec=S9.EDGE, mew=0.5, label=l) for k, l in hk]
|
| 107 |
+
handles += [Line2D([0], [0], ls=(0, (3, 2)), color=style.INK, lw=1.0, label="Chance (k / 2G)")]
|
| 108 |
+
fig.legend(handles=handles, loc="lower center", ncol=4, bbox_to_anchor=(0.53, -0.01), fontsize=FS - 3,
|
| 109 |
+
frameon=False, columnspacing=1.4, handlelength=2.2)
|
| 110 |
+
style.save(fig, "sec09_cat_curves", FIGDIR)
|
| 111 |
+
d = pd.DataFrame(rows)
|
| 112 |
+
OUTDATA.mkdir(exist_ok=True)
|
| 113 |
+
d.to_csv(OUTDATA / "sec09_cat_curves.csv", index=False, float_format="%.6g")
|
| 114 |
+
|
| 115 |
+
# slide text, from the plotted values at k = 100
|
| 116 |
+
def at(cv, ds, key, k=100):
|
| 117 |
+
s = cv.get((ds, key))
|
| 118 |
+
return np.nan if s is None or k not in s.index else float(s.loc[k])
|
| 119 |
+
|
| 120 |
+
top_few = [ds for ds in DIS if at(few, ds, "lora") >= max(at(few, ds, k) for k, _ in FEW if k != "lora")]
|
| 121 |
+
top_poo = [ds for ds in DIS if at(poo, ds, "lora") >= max(at(poo, ds, k) for k, _ in POOL if k != "lora")]
|
| 122 |
+
vs_sc = [ds for ds in DIS if at(few, ds, "lora") > at(few, ds, "scsemi5")]
|
| 123 |
+
kw = [f"LoRA top model: {len(top_few)}/4 (5 donors), {len(top_poo)}/4 (5-fold)",
|
| 124 |
+
f"LoRA-5 above scSemiProfiler-5: {len(vs_sc)}/4 cohorts (k = 100)",
|
| 125 |
+
f"Chance at k = 100: {min(at(few, ds, 'chance') for ds in DIS):.3f}–{max(at(few, ds, 'chance') for ds in DIS):.3f}"]
|
| 126 |
+
for k in kw:
|
| 127 |
+
if len(k) > 52:
|
| 128 |
+
raise ValueError(f"keyword too long: {k!r}")
|
| 129 |
+
vals = "; ".join(
|
| 130 |
+
f"{NAME[ds]} CAT100 5 donors LoRA {at(few, ds, 'lora'):.3f} / scSemi {at(few, ds, 'scsemi5'):.3f} / "
|
| 131 |
+
f"calibration {at(few, ds, 'zs_cal'):.3f} / raw {at(few, ds, 'zs_raw'):.3f}"
|
| 132 |
+
f" / chance {at(few, ds, 'chance'):.3f}; 5-fold LoRA {at(poo, ds, 'lora'):.3f}"
|
| 133 |
+
for ds in DIS)
|
| 134 |
+
full = ("Correspondence at the top (Irizarry et al. 2005): per cell type, every gene tested on both sides is ranked by "
|
| 135 |
+
"|limma-voom moderated t| (case vs control, same donor x type pseudobulks as the DEG panels); CAT(k) = share of "
|
| 136 |
+
"the observed top-k genes that are also in the generated top-k with the same logFC sign. Mean over T / B / Mono "
|
| 137 |
+
"/ NK; 5 donors = mean over 5 draws (scSemiProfiler: its 25 draws), the main comparison; 5-fold = pooled call, "
|
| 138 |
+
"shown separately. Chance = k / (2G), G = genes tested on both sides ("
|
| 139 |
+
f"{min(at(few, ds, 'chance') for ds in DIS):.3f}–{max(at(few, ds, 'chance') for ds in DIS):.3f} at k = 100). "
|
| 140 |
+
"No significance threshold, so cohorts where few genes pass FDR (Giroux, Ji) still get a curve. "
|
| 141 |
+
"Rank-biased overlap (Webber et al. 2010, p = 0.98) gives the same order: scores_contrast/{fewshot,pooled}_rbo.csv. "
|
| 142 |
+
"Giroux: sex-linked genes excluded. " + vals + ".")
|
| 143 |
+
txt = {"title": "Disease genes at every list length (CAT)", "layout": "full",
|
| 144 |
+
"figures": [str(FIGDIR / "sec09_cat_curves.png")], "keywords": kw,
|
| 145 |
+
"footnote_short": "Same-sign overlap of observed and generated top-k genes per cell type; no FDR cut-off.",
|
| 146 |
+
"footnote": full,
|
| 147 |
+
"numbers": [{"value": vals, "source": str(CX / "fewshot_cat.csv") + "; " + str(CX / "pooled_cat.csv")}]}
|
| 148 |
+
(OUTDATA / "sec09_cat_curves_slide_text.json").write_text(json.dumps(
|
| 149 |
+
{"section": "09-cat", "scripts": [str(Path(__file__).resolve())],
|
| 150 |
+
"generated_from": "tools/sec09_cat_curves.py (rerun to refresh; do not edit by hand)", "slides": [txt]},
|
| 151 |
+
indent=1, ensure_ascii=False))
|
| 152 |
+
print("\n".join(kw))
|
| 153 |
+
return 0
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
if __name__ == "__main__":
|
| 157 |
+
sys.exit(main())
|