Archive 4 checkpoints (1-4)
Browse files- paper-releases/pbisc-diffusion/updates/20260930T090852Z-summary-deck-final-path-story/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec07_ft_modes.py +327 -0
- paper-releases/pbisc-diffusion/updates/20260930T090852Z-summary-deck-final-path-story/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec08_pairs_needed.py +525 -0
- paper-releases/pbisc-diffusion/updates/20260930T090852Z-summary-deck-final-path-story/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec09_paired_validation.py +1251 -0
- paper-releases/pbisc-diffusion/updates/20260930T090852Z-summary-deck-final-path-story/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/style.py +65 -0
paper-releases/pbisc-diffusion/updates/20260930T090852Z-summary-deck-final-path-story/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec07_ft_modes.py
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Section 7, slide (a): full FT vs LoRA vs condition-encoder-only vs sc-only FT vs zero-shot,
|
| 2 |
+
plus the compute cost (trainable parameters, wall-clock time per training step).
|
| 3 |
+
|
| 4 |
+
Every arm is conditioned on the real bulk as measured (score arms *__raw): the zero-shot baseline is the
|
| 5 |
+
pretrained model fed real bulk (zs__raw), and the sc-only control is the sc-only fine-tune fed real bulk
|
| 6 |
+
(pseudo_full__raw). The condition-encoder-only arm exists only as real_condenc__raw (fold-0 call).
|
| 7 |
+
Accuracy: ImMicro and sepsis, 5-fold cross-fitted, pooled scoring (one call over all donors).
|
| 8 |
+
The condition-encoder-only arm exists only in the fold-0 pilot, so the L1 and coverage panels also show
|
| 9 |
+
every arm from the fold-0 scoring call (open diamonds). Metrics are only comparable within one scoring call,
|
| 10 |
+
so filled circles (pooled call) and open diamonds (fold-0 call) are never compared with each other.
|
| 11 |
+
The sepsis-vs-control logFC r is shown for the pooled call only: the fold-0 contrast rests on 5 controls
|
| 12 |
+
and the source README calls the per-fold contrast too noisy to use.
|
| 13 |
+
|
| 14 |
+
Compute: time per training step (median over runs), not minutes per run, because runs early-stop at
|
| 15 |
+
different steps (sepsis full 5.75k-20k, LoRA 5.75k-15k). All three modes use batch 256 and validate every
|
| 16 |
+
250 steps (asserted from RUN.json), so wall seconds / steps_run is a like-for-like per-step cost.
|
| 17 |
+
|
| 18 |
+
Every number is read from the score summaries / RUN.json receipts below. CPU only.
|
| 19 |
+
"""
|
| 20 |
+
import json
|
| 21 |
+
import sys
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
|
| 24 |
+
import numpy as np
|
| 25 |
+
import pandas as pd
|
| 26 |
+
from scipy.stats import wilcoxon
|
| 27 |
+
|
| 28 |
+
DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/"
|
| 29 |
+
"2026-09-30--paper-summary--r00")
|
| 30 |
+
sys.path.insert(0, str(DECK / "tools"))
|
| 31 |
+
import style # noqa: E402
|
| 32 |
+
import matplotlib.pyplot as plt # noqa: E402
|
| 33 |
+
from matplotlib.lines import Line2D # noqa: E402
|
| 34 |
+
|
| 35 |
+
PLAN = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/"
|
| 36 |
+
"paired_finetune_intradataset_20260927")
|
| 37 |
+
FIGDIR, DATADIR = DECK / "figures", DECK / "data"
|
| 38 |
+
DATASETS = {"immicro": "ImMicro", "ye2026_sepsis": "Sepsis"}
|
| 39 |
+
CELLTYPES = ["T cell", "B cell", "Monocyte", "NK cell"]
|
| 40 |
+
|
| 41 |
+
# rows top -> bottom: (score arm key, run dir name or None, label, colour)
|
| 42 |
+
ARMS = [
|
| 43 |
+
("real_full__raw", "real_full", "full FT", style.ARM["full_ft"]),
|
| 44 |
+
("real_lora__raw", "real_lora", "LoRA FT (r 16)", style.ARM["lora"]),
|
| 45 |
+
("real_condenc__raw", "real_condenc", "cond.-encoder-only FT", style.ARM["other"]),
|
| 46 |
+
("pseudo_full__raw", None, "sc-only FT", style.ARM["sconly"]),
|
| 47 |
+
("zs__raw", None, "zero-shot, real bulk", style.ARM["zs"]),
|
| 48 |
+
]
|
| 49 |
+
COMPUTE_ARMS = ARMS[:3]
|
| 50 |
+
ZS = "zs__raw"
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def fit_lim(vals, lo, hi, step, pad_frac=0.05):
|
| 54 |
+
"""Default axis limits, widened (to a multiple of step) only when a value would sit on or past an edge."""
|
| 55 |
+
vals = np.asarray(vals, float)
|
| 56 |
+
pad = pad_frac * (hi - lo)
|
| 57 |
+
if vals.min() - pad < lo:
|
| 58 |
+
lo = round(float(np.floor((vals.min() - pad) / step) * step), 10)
|
| 59 |
+
if vals.max() + pad > hi:
|
| 60 |
+
hi = round(float(np.ceil((vals.max() + pad) / step) * step), 10)
|
| 61 |
+
return lo, hi
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def load_call(ds, call):
|
| 65 |
+
root = PLAN / "scores" / ds / call
|
| 66 |
+
summ = json.loads((root / "summary.json").read_text())
|
| 67 |
+
con = pd.read_csv(root / "contrast.csv") if (root / "contrast.csv").exists() else None
|
| 68 |
+
per = pd.read_csv(root / "per_donor.csv")
|
| 69 |
+
return root, summ, con, per
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def arm_metrics(ds, call):
|
| 73 |
+
root, summ, con, per = load_call(ds, call)
|
| 74 |
+
rows = []
|
| 75 |
+
for arm, _, label, _ in ARMS:
|
| 76 |
+
if arm not in summ["arms"]:
|
| 77 |
+
continue
|
| 78 |
+
h = summ["headline"][arm]
|
| 79 |
+
r = {"dataset": ds, "call": call, "arm": arm, "label": label, "n_donors": summ["n_donors"],
|
| 80 |
+
"comp_l1": h["comp_l1"], "coverage": h["coverage"], "precision": h["precision"],
|
| 81 |
+
"source_summary": str(root / "summary.json")}
|
| 82 |
+
if con is not None:
|
| 83 |
+
c = con[(con["arm"] == arm) & (con["statistic"] == "mean_cp10k") & con["celltype"].isin(CELLTYPES)]
|
| 84 |
+
assert set(c["celltype"]) == set(CELLTYPES), (ds, call, arm)
|
| 85 |
+
r["logfc_r"] = float(c["r_generated"].mean())
|
| 86 |
+
assert abs(r["logfc_r"] - h["contrast_mean_cp10k_r_gen"]) < 1e-9
|
| 87 |
+
r["n_case"] = int(c["n_case_donors_obs"].iloc[0])
|
| 88 |
+
r["n_control"] = int(c["n_control_donors_obs"].iloc[0])
|
| 89 |
+
r["source_contrast"] = str(root / "contrast.csv")
|
| 90 |
+
rows.append(r)
|
| 91 |
+
return pd.DataFrame(rows), per
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def compute_receipts():
|
| 95 |
+
rows = []
|
| 96 |
+
for ds in DATASETS:
|
| 97 |
+
for arm, run, label, _ in COMPUTE_ARMS:
|
| 98 |
+
for f in sorted((PLAN / "runs" / ds).glob(f"fold[0-9]/{run}/RUN.json")):
|
| 99 |
+
d = json.loads(f.read_text())
|
| 100 |
+
rows.append({"dataset": ds, "arm": arm, "label": label, "fold": d["fold"], "mode": d["mode"],
|
| 101 |
+
"lr": d["lr"], "batch_size": d["batch_size"], "eval_every": d["eval_every"],
|
| 102 |
+
"n_trainable": d["trainable"]["n_trainable"],
|
| 103 |
+
"n_total_base": d["trainable"]["n_total_base"],
|
| 104 |
+
"wall_seconds": d["wall_seconds"], "steps_run": d["steps_run"],
|
| 105 |
+
"sec_per_step": d["wall_seconds"] / d["steps_run"],
|
| 106 |
+
"selected_step": d["selected_step"],
|
| 107 |
+
"selected_inner_val_loss": d["selected_inner_val_loss"],
|
| 108 |
+
"pretrained_inner_val_loss": d["pretrained_inner_val_loss"],
|
| 109 |
+
"source_checkpoint": d["source_checkpoint"], "run_json": str(f)})
|
| 110 |
+
return pd.DataFrame(rows)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def main():
|
| 114 |
+
acc, pers = [], {}
|
| 115 |
+
for ds in DATASETS:
|
| 116 |
+
for call in ("pooled", "fold0"):
|
| 117 |
+
df, per = arm_metrics(ds, call)
|
| 118 |
+
acc.append(df)
|
| 119 |
+
pers[(ds, call)] = per
|
| 120 |
+
acc = pd.concat(acc, ignore_index=True)
|
| 121 |
+
# sanity: the condition-encoder arm is only in the fold-0 call; every plotted arm is a real-bulk (raw) arm
|
| 122 |
+
assert not ((acc["call"] == "pooled") & (acc["arm"] == "real_condenc__raw")).any()
|
| 123 |
+
assert acc["arm"].str.endswith("__raw").all()
|
| 124 |
+
# every plotted arm is present in both calls (except cond.-encoder-only, fold-0 call only)
|
| 125 |
+
for (ds, call), g in acc.groupby(["dataset", "call"]):
|
| 126 |
+
want = {a[0] for a in ARMS} - ({"real_condenc__raw"} if call == "pooled" else set())
|
| 127 |
+
assert set(g["arm"]) == want, (ds, call, set(g["arm"]))
|
| 128 |
+
|
| 129 |
+
# paired Wilcoxon of donor-level L1 (uncorrected): full vs LoRA and each fine-tune vs zero-shot (pooled call);
|
| 130 |
+
# cond.-encoder-only vs LoRA / zero-shot (fold-0 call, the only call with that arm)
|
| 131 |
+
wil = []
|
| 132 |
+
tests = [("pooled", "real_full__raw", "real_lora__raw", "full - LoRA"),
|
| 133 |
+
("pooled", "real_full__raw", ZS, "full - zero-shot"),
|
| 134 |
+
("pooled", "real_lora__raw", ZS, "LoRA - zero-shot"),
|
| 135 |
+
("fold0", "real_condenc__raw", "real_lora__raw", "cond.-encoder-only - LoRA"),
|
| 136 |
+
("fold0", "real_condenc__raw", ZS, "cond.-encoder-only - zero-shot")]
|
| 137 |
+
for ds in DATASETS:
|
| 138 |
+
for call, a, b, name in tests:
|
| 139 |
+
per = pers[(ds, call)]
|
| 140 |
+
for arm in (a, b): # donor mean must reproduce the headline L1
|
| 141 |
+
h = float(acc[(acc["dataset"] == ds) & (acc["call"] == call) & (acc["arm"] == arm)]["comp_l1"].iloc[0])
|
| 142 |
+
assert abs(per.loc[per["arm"] == arm, "comp_l1"].mean() - h) < 1e-9, (ds, call, arm)
|
| 143 |
+
p = per.pivot(index="donor", columns="arm", values="comp_l1")
|
| 144 |
+
x = (p[a] - p[b]).dropna()
|
| 145 |
+
wil.append({"dataset": ds, "call": call, "comparison": f"{name} comp_l1", "arm_a": a, "arm_b": b,
|
| 146 |
+
"mean_diff": float(x.mean()), "frac_donors_a_lower": float((x < 0).mean()),
|
| 147 |
+
"wilcoxon_p": float(wilcoxon(x).pvalue), "n": int(len(x)),
|
| 148 |
+
"source": str(PLAN / "scores" / ds / call / "per_donor.csv")})
|
| 149 |
+
wil = pd.DataFrame(wil)
|
| 150 |
+
|
| 151 |
+
rec = compute_receipts()
|
| 152 |
+
# per-step cost is like-for-like only if batch size and validation cadence match across modes
|
| 153 |
+
assert rec["batch_size"].nunique() == 1 and rec["eval_every"].nunique() == 1
|
| 154 |
+
agg = dict(n_runs=("fold", "size"), folds=("fold", lambda s: ",".join(map(str, sorted(s)))),
|
| 155 |
+
n_trainable=("n_trainable", "first"), n_trainable_nunique=("n_trainable", "nunique"),
|
| 156 |
+
lr=("lr", "first"),
|
| 157 |
+
wall_min_median=("wall_seconds", lambda s: float(np.median(s)) / 60.0),
|
| 158 |
+
wall_min_min=("wall_seconds", lambda s: float(np.min(s)) / 60.0),
|
| 159 |
+
wall_min_max=("wall_seconds", lambda s: float(np.max(s)) / 60.0),
|
| 160 |
+
steps_run_median=("steps_run", "median"), steps_run_min=("steps_run", "min"),
|
| 161 |
+
steps_run_max=("steps_run", "max"),
|
| 162 |
+
sec_per_step_median=("sec_per_step", "median"))
|
| 163 |
+
comp = rec.groupby(["dataset", "arm", "label"]).agg(**agg).reset_index()
|
| 164 |
+
comp_all = rec.groupby(["arm", "label"]).agg(**agg).reset_index().assign(dataset="both")
|
| 165 |
+
comp = pd.concat([comp, comp_all], ignore_index=True)
|
| 166 |
+
assert (comp["n_trainable_nunique"] == 1).all()
|
| 167 |
+
n_full = int(rec.loc[rec["arm"] == "real_full__raw", "n_trainable"].iloc[0])
|
| 168 |
+
n_lora = int(rec.loc[rec["arm"] == "real_lora__raw", "n_trainable"].iloc[0])
|
| 169 |
+
ratio = n_full / n_lora
|
| 170 |
+
sps = comp[comp["dataset"] == "both"].set_index("arm")["sec_per_step_median"]
|
| 171 |
+
step_ratio = float(sps["real_full__raw"] / sps["real_lora__raw"])
|
| 172 |
+
|
| 173 |
+
acc.to_csv(DATADIR / "sec07_ft_modes_accuracy.csv", index=False)
|
| 174 |
+
rec.to_csv(DATADIR / "sec07_ft_modes_compute_runs.csv", index=False)
|
| 175 |
+
comp.to_csv(DATADIR / "sec07_ft_modes_compute.csv", index=False)
|
| 176 |
+
wil.to_csv(DATADIR / "sec07_ft_modes_wilcoxon.csv", index=False)
|
| 177 |
+
|
| 178 |
+
# ------------------------------------------------------------------ figure
|
| 179 |
+
W, H = 12.2, 4.95
|
| 180 |
+
fig = plt.figure(figsize=(W, H))
|
| 181 |
+
|
| 182 |
+
def ax_in(x, y, w, h):
|
| 183 |
+
return fig.add_axes([x / W, y / H, w / W, h / H])
|
| 184 |
+
|
| 185 |
+
ny = len(ARMS)
|
| 186 |
+
ypos = {a[0]: ny - 1 - i for i, a in enumerate(ARMS)}
|
| 187 |
+
x0, gap, ggap = 2.3, 0.36, 0.62
|
| 188 |
+
pw = (W - x0 - ggap - 3 * gap) / 5
|
| 189 |
+
top_y, top_h = 2.3, 2.1
|
| 190 |
+
# (dataset, metric, x label, xlim, ticks, show fold-0 diamonds)
|
| 191 |
+
# last tick sits inside the axis so it never touches the next panel's "0" (logFC r is the last panel).
|
| 192 |
+
# Default limits are widened from the data (fit_lim) so the zero-shot real-bulk point is never clipped;
|
| 193 |
+
# the L1 limit is shared by both cohorts so the two L1 panels stay comparable.
|
| 194 |
+
def vals(ds_list, met, calls):
|
| 195 |
+
s = acc[acc["dataset"].isin(ds_list) & acc["call"].isin(calls)][met]
|
| 196 |
+
return s.dropna().to_numpy(float)
|
| 197 |
+
l1_lim = fit_lim(vals(list(DATASETS), "comp_l1", ["pooled", "fold0"]), 0, 0.5, 0.1)
|
| 198 |
+
cov_lim = fit_lim(vals(list(DATASETS), "coverage", ["pooled", "fold0"]), 0, 1.0, 0.1)
|
| 199 |
+
r_lim = fit_lim(vals(["ye2026_sepsis"], "logfc_r", ["pooled"]), 0, 0.65, 0.05)
|
| 200 |
+
panels = [("immicro", "comp_l1", "L1 ↓", l1_lim, [0, 0.2, 0.4], True),
|
| 201 |
+
("immicro", "coverage", "coverage ↑", cov_lim, [0, 0.4, 0.8], True),
|
| 202 |
+
("ye2026_sepsis", "comp_l1", "L1 ↓", l1_lim, [0, 0.2, 0.4], True),
|
| 203 |
+
("ye2026_sepsis", "coverage", "coverage ↑", cov_lim, [0, 0.4, 0.8], True),
|
| 204 |
+
("ye2026_sepsis", "logfc_r", "logFC r ↑", r_lim, [0, 0.2, 0.4, 0.6], False)]
|
| 205 |
+
for _, _, _, lim, ticks, _ in panels:
|
| 206 |
+
assert lim[0] <= min(ticks) and max(ticks) < lim[1], (lim, ticks)
|
| 207 |
+
xs = []
|
| 208 |
+
x = x0
|
| 209 |
+
for i in range(len(panels)):
|
| 210 |
+
xs.append(x)
|
| 211 |
+
x += pw + (ggap if i == 1 else gap)
|
| 212 |
+
for i, (ds, met, xlabel, xlim, ticks, show_f0) in enumerate(panels):
|
| 213 |
+
ax = ax_in(xs[i], top_y, pw, top_h)
|
| 214 |
+
for arm, _, label, col in ARMS:
|
| 215 |
+
y = ypos[arm]
|
| 216 |
+
ax.axhline(y, color="#E6E6E6", lw=0.8, zorder=0)
|
| 217 |
+
calls = (("pooled", 0.14, "o", True), ("fold0", -0.14, "D", False)) if show_f0 else \
|
| 218 |
+
(("pooled", 0.0, "o", True),)
|
| 219 |
+
drawn = False
|
| 220 |
+
for call, dy, mk, fill in calls:
|
| 221 |
+
s = acc[(acc["dataset"] == ds) & (acc["call"] == call) & (acc["arm"] == arm)]
|
| 222 |
+
if len(s) == 0:
|
| 223 |
+
continue
|
| 224 |
+
v = float(s[met].iloc[0])
|
| 225 |
+
ax.plot([v], [y + dy], marker=mk, ms=9 if mk == "o" else 7.5, mec=col,
|
| 226 |
+
mfc=col if fill else "white", mew=1.8, ls="none", zorder=3)
|
| 227 |
+
drawn = True
|
| 228 |
+
if not drawn:
|
| 229 |
+
x_txt = max(0.0, (0 - xlim[0]) / (xlim[1] - xlim[0])) + 0.02 # right of the r = 0 line
|
| 230 |
+
ax.text(x_txt, y, "no pooled contrast", ha="left", va="center", fontsize=style.FS - 3,
|
| 231 |
+
color="#6E6E6E", transform=ax.get_yaxis_transform())
|
| 232 |
+
if xlim[0] < 0: # the axis extends below 0 (zero-shot logFC r); mark r = 0
|
| 233 |
+
ax.axvline(0, color="#BDBDBD", lw=0.8, zorder=1)
|
| 234 |
+
ax.set_xlim(*xlim)
|
| 235 |
+
ax.set_xticks(ticks)
|
| 236 |
+
ax.set_xticklabels([f"{t:g}" for t in ticks])
|
| 237 |
+
ax.set_ylim(-0.6, ny - 0.4)
|
| 238 |
+
ax.set_yticks([ypos[a[0]] for a in ARMS])
|
| 239 |
+
if i == 0:
|
| 240 |
+
ax.set_yticklabels([a[2] for a in ARMS], fontsize=style.FS - 1)
|
| 241 |
+
else:
|
| 242 |
+
ax.set_yticklabels([])
|
| 243 |
+
ax.tick_params(axis="y", length=0)
|
| 244 |
+
ax.spines["left"].set_visible(False)
|
| 245 |
+
ax.set_xlabel(xlabel, labelpad=3)
|
| 246 |
+
# dataset headers (group labels, not figure titles)
|
| 247 |
+
im_n = int(acc[(acc["dataset"] == "immicro") & (acc["call"] == "pooled")]["n_donors"].iloc[0])
|
| 248 |
+
im_n0 = int(acc[(acc["dataset"] == "immicro") & (acc["call"] == "fold0")]["n_donors"].iloc[0])
|
| 249 |
+
se = acc[(acc["dataset"] == "ye2026_sepsis") & (acc["call"] == "pooled")].iloc[0]
|
| 250 |
+
se_n0 = int(acc[(acc["dataset"] == "ye2026_sepsis") & (acc["call"] == "fold0")]["n_donors"].iloc[0])
|
| 251 |
+
hy = (top_y + top_h + 0.12) / H
|
| 252 |
+
fig.text((xs[0] + (xs[1] + pw)) / 2 / W, hy, f"ImMicro, healthy (n {im_n})", ha="center", va="bottom",
|
| 253 |
+
fontsize=style.FS, color=style.INK)
|
| 254 |
+
fig.text((xs[2] + (xs[4] + pw)) / 2 / W, hy,
|
| 255 |
+
f"Sepsis {int(se['n_case'])} vs control {int(se['n_control'])} (n {int(se['n_donors'])})",
|
| 256 |
+
ha="center", va="bottom", fontsize=style.FS, color=style.INK)
|
| 257 |
+
for xa, xb in ((xs[0], xs[1] + pw), (xs[2], xs[4] + pw)):
|
| 258 |
+
fig.add_artist(Line2D([xa / W, xb / W], [hy - 0.005, hy - 0.005], color=style.GREY, lw=0.8))
|
| 259 |
+
|
| 260 |
+
# ------------------------------------------------------------------ compute row
|
| 261 |
+
cy, ch = 0.45, 1.0
|
| 262 |
+
carms = COMPUTE_ARMS
|
| 263 |
+
cpos = {a[0]: len(carms) - 1 - i for i, a in enumerate(carms)}
|
| 264 |
+
bx = [x0, x0 + 2.75]
|
| 265 |
+
bw = [2.15, 2.0]
|
| 266 |
+
# trainable params (log)
|
| 267 |
+
ax = ax_in(bx[0], cy, bw[0], ch)
|
| 268 |
+
for arm, _, label, col in carms:
|
| 269 |
+
n = int(comp.loc[comp["arm"] == arm, "n_trainable"].iloc[0])
|
| 270 |
+
ax.barh(cpos[arm], n / 1e6, height=0.62, color=col, lw=0)
|
| 271 |
+
ax.text(n / 1e6 * 1.12, cpos[arm], f"{n / 1e6:.1f} M", va="center", ha="left", fontsize=style.FS - 2)
|
| 272 |
+
ax.set_xscale("log")
|
| 273 |
+
ax.set_xlim(0.5, 400)
|
| 274 |
+
ax.set_xticks([1, 10, 100])
|
| 275 |
+
ax.set_xticklabels(["1 M", "10 M", "100 M"])
|
| 276 |
+
ax.minorticks_off()
|
| 277 |
+
ax.set_yticks([cpos[a[0]] for a in carms])
|
| 278 |
+
ax.set_yticklabels([a[2] for a in carms], fontsize=style.FS - 1)
|
| 279 |
+
ax.tick_params(axis="y", length=0)
|
| 280 |
+
ax.spines["left"].set_visible(False)
|
| 281 |
+
ax.set_ylim(-0.6, len(carms) - 0.4)
|
| 282 |
+
ax.set_xlabel("trainable params (log)", labelpad=3)
|
| 283 |
+
# wall-clock ms per training step, median over all runs of both cohorts
|
| 284 |
+
ax = ax_in(bx[1], cy, bw[1], ch)
|
| 285 |
+
both = comp[comp["dataset"] == "both"].set_index("arm")
|
| 286 |
+
for arm, _, label, col in carms:
|
| 287 |
+
s = both.loc[arm]
|
| 288 |
+
v = 1000.0 * s["sec_per_step_median"]
|
| 289 |
+
ax.barh(cpos[arm], v, height=0.62, color=col, lw=0)
|
| 290 |
+
txt = f"{v:.0f} ms" if s["n_runs"] > 2 else f"{v:.0f} ms (fold 0)"
|
| 291 |
+
ax.text(v + 1.2, cpos[arm], txt, va="center", ha="left", fontsize=style.FS - 2)
|
| 292 |
+
ax.set_xlim(0, 80)
|
| 293 |
+
ax.set_xticks([0, 25, 50])
|
| 294 |
+
ax.set_yticks([cpos[a[0]] for a in carms])
|
| 295 |
+
ax.set_yticklabels([])
|
| 296 |
+
ax.tick_params(axis="y", length=0)
|
| 297 |
+
ax.spines["left"].set_visible(False)
|
| 298 |
+
ax.set_ylim(-0.6, len(carms) - 0.4)
|
| 299 |
+
ax.set_xlabel("wall ms / step", labelpad=3)
|
| 300 |
+
|
| 301 |
+
# legend for the two scoring calls (bottom right)
|
| 302 |
+
lx = (bx[1] + bw[1] + 0.75) / W
|
| 303 |
+
handles = [Line2D([], [], marker="o", ms=9, mfc=style.INK, mec=style.INK, ls="none",
|
| 304 |
+
label=f"5-fold pooled (n {im_n} / {int(se['n_donors'])})"),
|
| 305 |
+
Line2D([], [], marker="D", ms=7.5, mfc="white", mec=style.INK, mew=1.8, ls="none",
|
| 306 |
+
label=f"fold-0 pilot (n {im_n0} / {se_n0})")]
|
| 307 |
+
fig.legend(handles=handles, loc="lower left", bbox_to_anchor=(lx, (cy + 0.42) / H), frameon=False,
|
| 308 |
+
fontsize=style.FS - 2, handletextpad=0.4, labelspacing=0.5)
|
| 309 |
+
fig.text(lx + 0.004, (cy - 0.02) / H,
|
| 310 |
+
"compare same marker only\ncond.-encoder-only: fold 0 only\nlogFC r: pooled only",
|
| 311 |
+
ha="left", va="bottom", fontsize=style.FS - 3, color="#4D4D4D", linespacing=1.3)
|
| 312 |
+
|
| 313 |
+
style.save(fig, "sec07_ft_modes", FIGDIR)
|
| 314 |
+
|
| 315 |
+
# print the numbers used on the slide
|
| 316 |
+
print(f"trainable full {n_full} lora {n_lora} ratio {ratio:.2f}; per-step full/LoRA {step_ratio:.2f}")
|
| 317 |
+
print(comp[["dataset", "label", "n_runs", "folds", "lr", "n_trainable", "wall_min_median", "wall_min_min",
|
| 318 |
+
"wall_min_max", "steps_run_min", "steps_run_max", "sec_per_step_median"]]
|
| 319 |
+
.round(4).to_string(index=False))
|
| 320 |
+
print(acc[["dataset", "call", "label", "n_donors", "comp_l1", "coverage", "precision", "logfc_r",
|
| 321 |
+
"n_case", "n_control"]].round(3).to_string(index=False))
|
| 322 |
+
print(f"x limits: L1 {l1_lim}, coverage {cov_lim}, logFC r {r_lim}")
|
| 323 |
+
print(wil.drop(columns=["source"]).to_string(index=False))
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
if __name__ == "__main__":
|
| 327 |
+
main()
|
paper-releases/pbisc-diffusion/updates/20260930T090852Z-summary-deck-final-path-story/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec08_pairs_needed.py
ADDED
|
@@ -0,0 +1,525 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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" = zero-shot, the pretrained model fed the real bulk as measured (score arm zs__raw; uses no pair);
|
| 10 |
+
LoRA n = training pairs, and every LoRA run also early-stops on 7-8 paired inner-val donors
|
| 11 |
+
(RUN.json inner_val_rows). Every plotted arm is conditioned on the same real bulk (*__raw), so they share one
|
| 12 |
+
real-bulk broadcast. Cap-limited = ran to max_steps before the patience window closed; its late inner-val loss
|
| 13 |
+
drop is read from history.json.
|
| 14 |
+
When the zero-shot point lies far outside every other value of a panel (BREAK_RATIO), that panel gets a y-axis
|
| 15 |
+
break with a short segment at the same data scale, instead of squeezing the LoRA curve.
|
| 16 |
+
"""
|
| 17 |
+
import json
|
| 18 |
+
import sys
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
import pandas as pd
|
| 23 |
+
from scipy.stats import wilcoxon
|
| 24 |
+
|
| 25 |
+
DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/"
|
| 26 |
+
"2026-09-30--paper-summary--r00")
|
| 27 |
+
sys.path.insert(0, str(DECK / "tools"))
|
| 28 |
+
import style # noqa: E402
|
| 29 |
+
import matplotlib.pyplot as plt # noqa: E402
|
| 30 |
+
from matplotlib.lines import Line2D # noqa: E402
|
| 31 |
+
|
| 32 |
+
PLAN = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/"
|
| 33 |
+
"paired_finetune_intradataset_20260927")
|
| 34 |
+
FINAL_CKPT = ("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/runs/"
|
| 35 |
+
"f01_6k_1x_seed20260627/checkpoint_epoch_016.pt")
|
| 36 |
+
FIGDIR, DATADIR = DECK / "figures", DECK / "data"
|
| 37 |
+
FIGDIR.mkdir(exist_ok=True)
|
| 38 |
+
DATADIR.mkdir(exist_ok=True)
|
| 39 |
+
|
| 40 |
+
DSETS = ["immicro", "ye2026_sepsis"]
|
| 41 |
+
DS_LABEL = {"immicro": "ImMicro", "ye2026_sepsis": "Sepsis"}
|
| 42 |
+
LC_N = [5, 10, 20, 40]
|
| 43 |
+
LORA_ARMS = [f"lora_n{n}__raw" for n in LC_N] + ["real_lora__raw"]
|
| 44 |
+
RUN_ARMS = [f"lora_n{n}" for n in LC_N] + ["real_lora"]
|
| 45 |
+
ZS = "zs__raw" # zero-shot on the real bulk as measured: 0 pairs
|
| 46 |
+
X_LAB = ["0", "5", "10", "20", "40", "all"]
|
| 47 |
+
KEY_LAB = ["zero_shot", "5", "10", "20", "40", "all"] # the same points, as keys in sec08_slide_numbers.csv
|
| 48 |
+
X_POS = [0.0, 1.3, 2.3, 3.3, 4.3, 5.3] # small gap after the zero-shot point (no fine-tuning)
|
| 49 |
+
BREAK_RATIO = 1.5 # y-axis break when the zero-shot point sits > 1.5 spans of the other values beyond them
|
| 50 |
+
CELLTYPES = ["T cell", "B cell", "Monocyte", "NK cell"]
|
| 51 |
+
DEG_TYPES = ["T cell", "B cell", "Monocyte", "NK cell", "DC"]
|
| 52 |
+
RAW_ARMS = LORA_ARMS + ["zs__raw", "real_full__raw", "pseudo_full__raw"] # all conditioned on raw real bulk
|
| 53 |
+
|
| 54 |
+
REF = { # reference-line styles; pseudo/broadcast copied from sec09 REFSTYLE so the deck is consistent
|
| 55 |
+
"pseudo": dict(ls=(0, (4, 2)), color=style.ARM["pseudo"], lw=1.6, label="Zero-shot from sc pseudobulk"),
|
| 56 |
+
"broadcast": dict(ls=(0, (1, 1.2)), color=style.ARM["broadcast"], lw=2.4, label="Real-bulk broadcast"),
|
| 57 |
+
"null": dict(ls=(0, (6, 2, 1.5, 2)), color=style.GREY, lw=1.4, label="Cohort-mean null"),
|
| 58 |
+
}
|
| 59 |
+
LEG_ZS = "Zero-shot, real bulk"
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def xlabel(st):
|
| 63 |
+
"""x-axis label; the inner-val range is read from the RUN.json files."""
|
| 64 |
+
return f"LoRA training pairs (each run +{rng_txt(st.n_inner_val)} inner-val pairs for early stopping)"
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def close(a, b, tol=1e-6):
|
| 68 |
+
return abs(float(a) - float(b)) <= tol
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class Call:
|
| 72 |
+
"""One pooled score_ft.py scoring call."""
|
| 73 |
+
|
| 74 |
+
def __init__(self, path: Path):
|
| 75 |
+
self.path = path
|
| 76 |
+
self.summary = json.loads((path / "summary.json").read_text())
|
| 77 |
+
self.contrast = pd.read_csv(path / "contrast.csv") if (path / "contrast.csv").exists() else None
|
| 78 |
+
self.per_donor = pd.read_csv(path / "per_donor.csv")
|
| 79 |
+
self.src_summary = str(path / "summary.json")
|
| 80 |
+
self.src_contrast = str(path / "contrast.csv")
|
| 81 |
+
self.src_per_donor = str(path / "per_donor.csv")
|
| 82 |
+
|
| 83 |
+
def head(self, arm, key):
|
| 84 |
+
return float(self.summary["headline"][arm][key])
|
| 85 |
+
|
| 86 |
+
def contrast_r(self, arm, col="r_generated"):
|
| 87 |
+
c = self.contrast
|
| 88 |
+
c = c[(c.arm == arm) & (c.statistic == "mean_cp10k") & (c.celltype.isin(CELLTYPES))]
|
| 89 |
+
assert set(c.celltype) == set(CELLTYPES), (self.path, arm)
|
| 90 |
+
return float(c[col].mean())
|
| 91 |
+
|
| 92 |
+
def deg(self, arm, col="top50_overlap"):
|
| 93 |
+
d = self.contrast
|
| 94 |
+
d = d[(d.arm == arm) & (d.statistic == "welch_top50_deg")]
|
| 95 |
+
assert len(d) == 5, (self.path, arm, len(d)) # T/B/Mono/NK/DC
|
| 96 |
+
return float(d[col].sum())
|
| 97 |
+
|
| 98 |
+
def deg_type(self, arm, ct, col="top50_overlap"):
|
| 99 |
+
d = self.contrast
|
| 100 |
+
d = d[(d.arm == arm) & (d.statistic == "welch_top50_deg") & (d.celltype == ct)]
|
| 101 |
+
assert len(d) == 1, (self.path, arm, ct, len(d))
|
| 102 |
+
return float(d[col].iloc[0])
|
| 103 |
+
|
| 104 |
+
def frac_r(self, arm, ct):
|
| 105 |
+
d = self.per_donor[self.per_donor.arm == arm]
|
| 106 |
+
return float(np.corrcoef(d[f"gen_{ct}"].astype(float), d[f"obs_{ct}"].astype(float))[0, 1])
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def load():
|
| 110 |
+
calls = {ds: Call(PLAN / "scores" / ds / "pooled") for ds in DSETS}
|
| 111 |
+
deg_call = Call(PLAN / "scores" / "ye2026_sepsis" / "pooled_deg")
|
| 112 |
+
for ds, c in calls.items():
|
| 113 |
+
for a in LORA_ARMS + [ZS, "zs__pseudo"]:
|
| 114 |
+
assert a in c.summary["arms"], (ds, a)
|
| 115 |
+
assert c.summary["per_arm"][a].get("receipt_verified", True) is not False, (ds, a)
|
| 116 |
+
# headline composition L1 equals the donor mean of per_donor.csv
|
| 117 |
+
assert close(c.per_donor.loc[c.per_donor.arm == a, "comp_l1"].mean(), c.head(a, "comp_l1"), 1e-9), a
|
| 118 |
+
# headline contrast means equal the per-type mean of contrast.csv
|
| 119 |
+
se = calls["ye2026_sepsis"]
|
| 120 |
+
for a in LORA_ARMS + [ZS, "zs__pseudo"]:
|
| 121 |
+
assert close(se.contrast_r(a), se.head(a, "contrast_mean_cp10k_r_gen"), 1e-9), a
|
| 122 |
+
assert close(deg_call.deg(a), deg_call.head(a, "deg_top50_sum"), 1e-9), a
|
| 123 |
+
# broadcast is the same for every arm conditioned on raw real bulk
|
| 124 |
+
bc = {a: se.contrast_r(a, "r_broadcast") for a in RAW_ARMS}
|
| 125 |
+
assert max(bc.values()) - min(bc.values()) < 1e-12, bc
|
| 126 |
+
bcd = {a: deg_call.deg(a, "top50_overlap_broadcast") for a in RAW_ARMS}
|
| 127 |
+
assert len(set(bcd.values())) == 1, bcd
|
| 128 |
+
assert close(bcd["real_lora__raw"], deg_call.head("real_lora__raw", "deg_top50_sum_broadcast"), 1e-9)
|
| 129 |
+
# non-DEG metrics agree between the two sepsis scoring calls (k-NN ties allow 1e-3)
|
| 130 |
+
for a in LORA_ARMS + [ZS]:
|
| 131 |
+
for k in ("comp_l1", "coverage"):
|
| 132 |
+
assert abs(se.head(a, k) - deg_call.head(a, k)) <= 1e-3, (a, k)
|
| 133 |
+
return calls, deg_call
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def load_steps():
|
| 137 |
+
rows = []
|
| 138 |
+
for ds in DSETS:
|
| 139 |
+
for k in range(5):
|
| 140 |
+
for arm in RUN_ARMS:
|
| 141 |
+
p = PLAN / "runs" / ds / f"fold{k}" / arm / "RUN.json"
|
| 142 |
+
r = json.loads(p.read_text())
|
| 143 |
+
assert r["source_checkpoint"] == FINAL_CKPT, (p, r["source_checkpoint"])
|
| 144 |
+
assert r["mode"] == "lora", p
|
| 145 |
+
assert r["inner_val_rows"], p # every LoRA run early-stops on paired inner-val donors
|
| 146 |
+
hist = json.loads((p.parent / "history.json").read_text())
|
| 147 |
+
h = {int(e["step"]): float(e["inner_val_loss"]) for e in hist}
|
| 148 |
+
# cap-limited = ran to max_steps without the patience window closing
|
| 149 |
+
cap_limited = (r["steps_run"] >= r["max_steps"]
|
| 150 |
+
and r["steps_run"] - r["selected_step"] < r["patience"] * r["eval_every"])
|
| 151 |
+
last = max(h)
|
| 152 |
+
win = r["patience"] * r["eval_every"] # last patience window (2,000 steps)
|
| 153 |
+
drop_total = h[0] - h[last]
|
| 154 |
+
drop_last = h[last - win] - h[last]
|
| 155 |
+
rows.append({"dataset": ds, "fold": k, "arm": arm, "n_train": len(r["train_rows"]),
|
| 156 |
+
"n_inner_val": len(r["inner_val_rows"]), "selected_step": r["selected_step"],
|
| 157 |
+
"max_steps": r["max_steps"], "steps_run": r["steps_run"],
|
| 158 |
+
"patience_steps": win, "cap_limited": bool(cap_limited),
|
| 159 |
+
"val_loss_step0": h[0], "val_loss_last": h[last],
|
| 160 |
+
"val_loss_last_window_drop_frac": drop_last / drop_total,
|
| 161 |
+
"wall_seconds": r.get("wall_seconds"), "source": str(p),
|
| 162 |
+
"history": str(p.parent / "history.json")})
|
| 163 |
+
st = pd.DataFrame(rows)
|
| 164 |
+
# nested subsets: n_train equals the arm size for lora_n*
|
| 165 |
+
for n in LC_N:
|
| 166 |
+
assert (st[st.arm == f"lora_n{n}"].n_train == n).all(), n
|
| 167 |
+
return st
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def load_fold_sizes():
|
| 171 |
+
"""Test donors per fold (PREPARE.json); their sum must equal the donors in the pooled scoring call."""
|
| 172 |
+
out = {}
|
| 173 |
+
for ds in DSETS:
|
| 174 |
+
p = PLAN / "data" / ds / "PREPARE.json"
|
| 175 |
+
fs = json.loads(p.read_text())["fold_sizes"]
|
| 176 |
+
out[ds] = dict(test=[int(v["test"]) for v in fs.values()], source=str(p))
|
| 177 |
+
return out
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def rng_txt(v):
|
| 181 |
+
v = sorted(int(x) for x in v)
|
| 182 |
+
return f"{v[0]}" if v[0] == v[-1] else f"{v[0]}–{v[-1]}"
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def break_axis(ax, v0, lo, hi):
|
| 186 |
+
"""Shrink ax to lo..hi and add a short segment above it that shows v0 at the same data scale."""
|
| 187 |
+
p = ax.get_position()
|
| 188 |
+
h_top, gap = 0.22 * p.height, 0.08 * p.height
|
| 189 |
+
h_main = p.height - h_top - gap
|
| 190 |
+
ax.set_position([p.x0, p.y0, p.width, h_main])
|
| 191 |
+
ax.set_ylim(lo, hi)
|
| 192 |
+
half = (hi - lo) * h_top / h_main / 2
|
| 193 |
+
top = ax.figure.add_axes([p.x0, p.y0 + h_main + gap, p.width, h_top], sharex=ax)
|
| 194 |
+
top.set_ylim(v0 - half, v0 + half)
|
| 195 |
+
# one tick in the short segment: the nearest value on the main axis' tick grid that fits inside it
|
| 196 |
+
step = float(np.diff(ax.get_yticks()[:2])[0]) / 2
|
| 197 |
+
tick = round(round(v0 / step) * step, 10)
|
| 198 |
+
top.set_yticks([tick] if abs(tick - v0) < half else [])
|
| 199 |
+
if not len(top.get_yticks()): # no grid value fits: print the value next to the point instead
|
| 200 |
+
top.text(X_POS[0] + 0.3, v0, f"{v0:.2f}", va="center", ha="left", fontsize=12)
|
| 201 |
+
top.spines["bottom"].set_visible(False)
|
| 202 |
+
top.tick_params(axis="x", bottom=False, labelbottom=False)
|
| 203 |
+
mk = dict(marker=[(-1, -0.5), (1, 0.5)], markersize=10, ls="none", color=style.INK, mec=style.INK, mew=1.2,
|
| 204 |
+
clip_on=False)
|
| 205 |
+
top.plot([0], [0], transform=top.transAxes, **mk)
|
| 206 |
+
ax.plot([0], [1], transform=ax.transAxes, **mk)
|
| 207 |
+
return top
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def curve(ax, v0, vl, refs, rows, panel, ds, src0, srcl, ylim0=None):
|
| 211 |
+
"""Zero-shot (real bulk) point at x=0, LoRA curve at 5..all, reference lines. Returns the axis for the title."""
|
| 212 |
+
lo, hi = min(vl), max(vl)
|
| 213 |
+
for key, val, src in refs:
|
| 214 |
+
lo, hi = min(lo, val), max(hi, val)
|
| 215 |
+
span = hi - lo
|
| 216 |
+
broken = ylim0 is None and span > 0 and (v0 - hi > BREAK_RATIO * span or lo - v0 > BREAK_RATIO * span)
|
| 217 |
+
if broken:
|
| 218 |
+
assert v0 > hi, (panel, ds, "axis break below the curve is not implemented")
|
| 219 |
+
else:
|
| 220 |
+
lo, hi = min(lo, v0), max(hi, v0)
|
| 221 |
+
pad = (hi - lo) * 0.15
|
| 222 |
+
axes = [ax]
|
| 223 |
+
if broken:
|
| 224 |
+
top = break_axis(ax, v0, lo - pad, hi + pad)
|
| 225 |
+
axes.append(top)
|
| 226 |
+
else:
|
| 227 |
+
ax.set_ylim(ylim0 if ylim0 is not None else lo - pad, hi + pad)
|
| 228 |
+
(axes[-1] if broken else ax).scatter([X_POS[0]], [v0], s=70, color=style.ARM["zs"], edgecolor=style.INK,
|
| 229 |
+
lw=0.6, zorder=5, clip_on=False)
|
| 230 |
+
ax.plot(X_POS[1:], vl, color=style.ARM["lora"], lw=2.0, zorder=3)
|
| 231 |
+
ax.scatter(X_POS[1:], vl, s=70, color=style.ARM["lora"], edgecolor=style.INK, lw=0.6, zorder=5)
|
| 232 |
+
rows.append(dict(panel=panel, dataset=ds, series="zero_shot", pairs=X_LAB[0], value=v0, source=src0,
|
| 233 |
+
y_axis_break=bool(broken)))
|
| 234 |
+
for lab, v, s in zip(X_LAB[1:], vl, srcl):
|
| 235 |
+
rows.append(dict(panel=panel, dataset=ds, series="lora", pairs=lab, value=v, source=s,
|
| 236 |
+
y_axis_break=bool(broken)))
|
| 237 |
+
for key, val, src in refs:
|
| 238 |
+
r = REF[key]
|
| 239 |
+
for a in axes:
|
| 240 |
+
a.axhline(val, ls=r["ls"], color=r["color"], lw=r["lw"], zorder=2)
|
| 241 |
+
rows.append(dict(panel=panel, dataset=ds, series=f"ref_{key}", pairs="", value=val, source=src,
|
| 242 |
+
y_axis_break=bool(broken)))
|
| 243 |
+
ax.set_xlim(-0.5, X_POS[-1] + 0.5)
|
| 244 |
+
ax.set_xticks(X_POS)
|
| 245 |
+
ax.set_xticklabels(X_LAB)
|
| 246 |
+
# nothing is clipped: every plotted value is inside the y range of the axis that draws it
|
| 247 |
+
for v in list(vl) + [val for _, val, _ in refs] + ([] if broken else [v0]):
|
| 248 |
+
assert ax.get_ylim()[0] <= v <= ax.get_ylim()[1], (panel, ds, v, ax.get_ylim())
|
| 249 |
+
if broken:
|
| 250 |
+
assert axes[-1].get_ylim()[0] <= v0 <= axes[-1].get_ylim()[1]
|
| 251 |
+
return axes[-1]
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def fig_realism(calls, st, fold_sizes, rows, steprows):
|
| 255 |
+
fig, axs = plt.subplots(2, 3, figsize=style.FULL,
|
| 256 |
+
gridspec_kw=dict(left=0.168, right=0.99, top=0.83, bottom=0.12,
|
| 257 |
+
hspace=0.36, wspace=0.30))
|
| 258 |
+
heads = ["Composition L1 ↓", "Coverage ↑", "Selected step (×1,000)"]
|
| 259 |
+
pos0 = {ri: axs[ri, 2].get_position() for ri in range(len(DSETS))} # row extents before any y-axis break
|
| 260 |
+
title_ax = {ci: axs[0, ci] for ci in range(3)}
|
| 261 |
+
for ri, ds in enumerate(DSETS):
|
| 262 |
+
c = calls[ds]
|
| 263 |
+
for ci, key in enumerate(["comp_l1", "coverage"]):
|
| 264 |
+
ax = axs[ri, ci]
|
| 265 |
+
refs = [("pseudo", c.head("zs__pseudo", key), c.src_summary)]
|
| 266 |
+
if key == "comp_l1":
|
| 267 |
+
refs.append(("null", c.head("real_lora__raw", "comp_l1_obs_loo_null"), c.src_summary))
|
| 268 |
+
tax = curve(ax, c.head(ZS, key), [c.head(a, key) for a in LORA_ARMS], refs, rows,
|
| 269 |
+
f"{key}", ds, c.src_summary, [c.src_summary] * 5)
|
| 270 |
+
if ri == 0:
|
| 271 |
+
title_ax[ci] = tax
|
| 272 |
+
# selected early-stopping step per fold
|
| 273 |
+
ax = axs[ri, 2]
|
| 274 |
+
s = st[st.dataset == ds]
|
| 275 |
+
for xi, arm in zip(X_POS[1:], RUN_ARMS):
|
| 276 |
+
f = s[s.arm == arm].sort_values("fold")
|
| 277 |
+
v = f.selected_step.astype(float).values / 1000
|
| 278 |
+
jit = np.linspace(-0.22, 0.22, len(v))
|
| 279 |
+
ax.scatter(xi + jit, v, s=36, color=style.ARM["lora"], edgecolor=style.INK, lw=0.5, zorder=4)
|
| 280 |
+
med = float(np.median(v))
|
| 281 |
+
ax.plot([xi - 0.36, xi + 0.36], [med, med], color=style.INK, lw=2.0, zorder=5)
|
| 282 |
+
steprows.append(dict(dataset=ds, arm=arm, pairs=X_LAB[X_POS.index(xi)], median_step=med * 1000,
|
| 283 |
+
min_step=v.min() * 1000, max_step=v.max() * 1000,
|
| 284 |
+
n_cap_limited=int(f.cap_limited.sum()),
|
| 285 |
+
max_last_window_drop_frac=(float(f[f.cap_limited].val_loss_last_window_drop_frac.max())
|
| 286 |
+
if f.cap_limited.any() else np.nan),
|
| 287 |
+
n_train=rng_txt(f.n_train), n_inner_val=rng_txt(f.n_inner_val),
|
| 288 |
+
source=";".join(f.source)))
|
| 289 |
+
cap = float(s.max_steps.max()) / 1000
|
| 290 |
+
ax.axhline(cap, color=style.GREY, lw=1.0, ls=(0, (2, 2)), zorder=1)
|
| 291 |
+
ax.text(X_POS[0] - 0.4, cap + 0.6, f"cap {cap:g}k", color=style.GREY, fontsize=12, va="bottom")
|
| 292 |
+
ax.text(X_POS[0], cap * 0.45, "no training", color=style.GREY, fontsize=12, ha="center",
|
| 293 |
+
va="center", rotation=90)
|
| 294 |
+
ax.set_ylim(0, cap * 1.18)
|
| 295 |
+
ax.set_xlim(-0.5, X_POS[-1] + 0.5)
|
| 296 |
+
ax.set_xticks(X_POS)
|
| 297 |
+
ax.set_xticklabels(X_LAB)
|
| 298 |
+
n_all = rng_txt(s[s.arm == "real_lora"].n_train)
|
| 299 |
+
n_iv = rng_txt(s.n_inner_val)
|
| 300 |
+
n_scored = int(c.summary["n_donors"])
|
| 301 |
+
assert n_scored == sum(fold_sizes[ds]["test"]), (ds, n_scored, fold_sizes[ds]["test"])
|
| 302 |
+
ymid = (pos0[ri].y0 + pos0[ri].y1) / 2
|
| 303 |
+
fig.text(0.005, ymid + 0.075, DS_LABEL[ds], fontsize=15, fontweight="bold", va="bottom", ha="left")
|
| 304 |
+
fig.text(0.005, ymid + 0.065, f"{n_scored} donors\nall = {n_all} pairs\ninner-val = {n_iv}",
|
| 305 |
+
fontsize=12.5, va="top", ha="left", linespacing=1.35)
|
| 306 |
+
rows.append(dict(panel="meta", dataset=ds, series="n_scored_donors", pairs="", value=n_scored,
|
| 307 |
+
source=c.src_summary))
|
| 308 |
+
rows.append(dict(panel="meta", dataset=ds, series="n_pairs_all", pairs="all", value=n_all,
|
| 309 |
+
source="RUN.json train_rows: " + ";".join(s[s.arm == "real_lora"].source)))
|
| 310 |
+
rows.append(dict(panel="meta", dataset=ds, series="n_inner_val", pairs="", value=n_iv,
|
| 311 |
+
source="RUN.json inner_val_rows (all LoRA arms, 5 folds)"))
|
| 312 |
+
rows.append(dict(panel="meta", dataset=ds, series="n_test_donors_per_fold", pairs="",
|
| 313 |
+
value="/".join(map(str, fold_sizes[ds]["test"])),
|
| 314 |
+
source=fold_sizes[ds]["source"] + " fold_sizes test"))
|
| 315 |
+
for ci, h in enumerate(heads):
|
| 316 |
+
title_ax[ci].set_title(h, fontsize=14, pad=8)
|
| 317 |
+
x0, x1 = axs[1, 0].get_position().x0, axs[1, 2].get_position().x1
|
| 318 |
+
fig.text((x0 + x1) / 2, 0.005, xlabel(st), ha="center", va="bottom", fontsize=14)
|
| 319 |
+
handles = [
|
| 320 |
+
Line2D([0], [0], marker="o", color=style.ARM["zs"], lw=0, markeredgecolor=style.INK, markersize=8,
|
| 321 |
+
label=LEG_ZS),
|
| 322 |
+
Line2D([0], [0], marker="o", color=style.ARM["lora"], lw=2.0, markeredgecolor=style.INK, markersize=8,
|
| 323 |
+
label="LoRA fine-tune (dots in step panel = folds)"),
|
| 324 |
+
Line2D([0], [0], color=style.INK, lw=2.0, label="Median of 5 folds"),
|
| 325 |
+
Line2D([0], [0], ls=REF["pseudo"]["ls"], color=REF["pseudo"]["color"], lw=REF["pseudo"]["lw"],
|
| 326 |
+
label=REF["pseudo"]["label"]),
|
| 327 |
+
Line2D([0], [0], ls=REF["null"]["ls"], color=REF["null"]["color"], lw=REF["null"]["lw"],
|
| 328 |
+
label=REF["null"]["label"]),
|
| 329 |
+
]
|
| 330 |
+
fig.legend(handles=handles, loc="upper left", bbox_to_anchor=(0.005, 1.0), ncol=3, frameon=False,
|
| 331 |
+
fontsize=12, handlelength=2.4, columnspacing=1.6, labelspacing=0.4, borderaxespad=0.0)
|
| 332 |
+
style.save(fig, "sec08_pairs_realism", FIGDIR)
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
def fig_signal(calls, deg_call, st, rows):
|
| 336 |
+
fig, axs = plt.subplots(1, 3, figsize=style.TALL,
|
| 337 |
+
gridspec_kw=dict(left=0.085, right=0.99, top=0.79, bottom=0.115, wspace=0.42))
|
| 338 |
+
im, se = calls["immicro"], calls["ye2026_sepsis"]
|
| 339 |
+
tax = [None] * 3
|
| 340 |
+
# a: ImMicro across-donor NK fraction r
|
| 341 |
+
tax[0] = curve(axs[0], im.frac_r(ZS, "NK cell"), [im.frac_r(a, "NK cell") for a in LORA_ARMS],
|
| 342 |
+
[("pseudo", im.frac_r("zs__pseudo", "NK cell"), im.src_per_donor)], rows, "nk_fraction_r",
|
| 343 |
+
"immicro", im.src_per_donor, [im.src_per_donor] * 5)
|
| 344 |
+
# other cell types, recorded for the footnote
|
| 345 |
+
for ct in ["T cell", "B cell", "Monocyte"]:
|
| 346 |
+
for a, lab in zip([ZS] + LORA_ARMS, X_LAB):
|
| 347 |
+
rows.append(dict(panel="other_fraction_r", dataset="immicro", series=ct, pairs=lab,
|
| 348 |
+
value=im.frac_r(a, ct), source=im.src_per_donor))
|
| 349 |
+
# b: sepsis disease logFC r (mean of T/B/Mono/NK, mean_cp10k)
|
| 350 |
+
tax[1] = curve(axs[1], se.contrast_r(ZS), [se.contrast_r(a) for a in LORA_ARMS],
|
| 351 |
+
[("pseudo", se.contrast_r("zs__pseudo"), se.src_contrast),
|
| 352 |
+
("broadcast", se.contrast_r("real_lora__raw", "r_broadcast"), se.src_contrast)],
|
| 353 |
+
rows, "logfc_r", "ye2026_sepsis", se.src_contrast, [se.src_contrast] * 5)
|
| 354 |
+
# c: sepsis top-50 DEG (Welch, sum over T/B/Mono/NK/DC)
|
| 355 |
+
tax[2] = curve(axs[2], deg_call.deg(ZS), [deg_call.deg(a) for a in LORA_ARMS],
|
| 356 |
+
[("pseudo", deg_call.deg("zs__pseudo"), deg_call.src_contrast),
|
| 357 |
+
("broadcast", deg_call.deg("real_lora__raw", "top50_overlap_broadcast"), deg_call.src_contrast)],
|
| 358 |
+
rows, "top50_deg", "ye2026_sepsis", deg_call.src_contrast, [deg_call.src_contrast] * 5, ylim0=0)
|
| 359 |
+
# top-50 DEG overlap per cell type (footnote: which types carry the gain), incl. broadcast
|
| 360 |
+
for ct in DEG_TYPES:
|
| 361 |
+
for a, lab in zip([ZS] + LORA_ARMS + ["zs__pseudo"], X_LAB + ["pseudo"]):
|
| 362 |
+
rows.append(dict(panel="top50_deg_by_type", dataset="ye2026_sepsis", series=ct, pairs=lab,
|
| 363 |
+
value=deg_call.deg_type(a, ct), source=deg_call.src_contrast))
|
| 364 |
+
rows.append(dict(panel="top50_deg_by_type", dataset="ye2026_sepsis", series=ct, pairs="broadcast",
|
| 365 |
+
value=deg_call.deg_type("real_lora__raw", ct, "top50_overlap_broadcast"),
|
| 366 |
+
source=deg_call.src_contrast))
|
| 367 |
+
cd = se.summary["contrast_definition"]
|
| 368 |
+
grp = f"Sepsis {cd['n_case_donors']} vs {cd['n_control_donors']}"
|
| 369 |
+
heads = [f"ImMicro, {int(im.summary['n_donors'])} donors\ndonor NK fraction r",
|
| 370 |
+
f"{grp}\ndisease logFC r", f"{grp}\ntop-50 DEG overlap"]
|
| 371 |
+
for ax, h in zip(tax, heads):
|
| 372 |
+
ax.set_title(h, fontsize=14, pad=8, linespacing=1.3)
|
| 373 |
+
x0, x1 = axs[0].get_position().x0, axs[2].get_position().x1
|
| 374 |
+
fig.text((x0 + x1) / 2, 0.005, xlabel(st), ha="center", va="bottom", fontsize=13)
|
| 375 |
+
rows.append(dict(panel="meta", dataset="ye2026_sepsis", series="n_case_vs_control", pairs="",
|
| 376 |
+
value=f"{se.summary['contrast_definition']['n_case_donors']} vs "
|
| 377 |
+
f"{se.summary['contrast_definition']['n_control_donors']}", source=se.src_summary))
|
| 378 |
+
handles = [ # column-wise fill: [zero-shot, pseudo] | [LoRA, broadcast]
|
| 379 |
+
Line2D([0], [0], marker="o", color=style.ARM["zs"], lw=0, markeredgecolor=style.INK, markersize=8,
|
| 380 |
+
label=LEG_ZS),
|
| 381 |
+
Line2D([0], [0], ls=REF["pseudo"]["ls"], color=REF["pseudo"]["color"], lw=REF["pseudo"]["lw"],
|
| 382 |
+
label=REF["pseudo"]["label"]),
|
| 383 |
+
Line2D([0], [0], marker="o", color=style.ARM["lora"], lw=2.0, markeredgecolor=style.INK, markersize=8,
|
| 384 |
+
label="LoRA fine-tune"),
|
| 385 |
+
Line2D([0], [0], ls=REF["broadcast"]["ls"], color=REF["broadcast"]["color"], lw=REF["broadcast"]["lw"],
|
| 386 |
+
label=REF["broadcast"]["label"]),
|
| 387 |
+
]
|
| 388 |
+
fig.legend(handles=handles, loc="upper left", bbox_to_anchor=(0.005, 1.0), ncol=2, frameon=False,
|
| 389 |
+
fontsize=12, handlelength=2.4, columnspacing=1.2, labelspacing=0.4, borderaxespad=0.0)
|
| 390 |
+
style.save(fig, "sec08_pairs_signal", FIGDIR)
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
def slide_numbers(calls, deg_call, st):
|
| 394 |
+
"""Numbers quoted in the slide keywords/footnote, each with its source file."""
|
| 395 |
+
im, se = calls["immicro"], calls["ye2026_sepsis"]
|
| 396 |
+
out = []
|
| 397 |
+
|
| 398 |
+
def add(key, value, src):
|
| 399 |
+
out.append(dict(key=key, value=value, source=src))
|
| 400 |
+
|
| 401 |
+
for ds, c in calls.items():
|
| 402 |
+
for key in ("coverage", "comp_l1"):
|
| 403 |
+
add(f"{ds}.{key}.zero_shot", round(c.head(ZS, key), 3), c.src_summary)
|
| 404 |
+
add(f"{ds}.{key}.lora_n5", round(c.head("lora_n5__raw", key), 3), c.src_summary)
|
| 405 |
+
add(f"{ds}.{key}.lora_all", round(c.head("real_lora__raw", key), 3), c.src_summary)
|
| 406 |
+
add(f"{ds}.{key}.zs_pseudo", round(c.head("zs__pseudo", key), 3), c.src_summary)
|
| 407 |
+
add(f"{ds}.comp_l1.null", round(c.head("real_lora__raw", "comp_l1_obs_loo_null"), 3), c.src_summary)
|
| 408 |
+
# donor-level composition L1, each LoRA size vs zero-shot (paired Wilcoxon, uncorrected)
|
| 409 |
+
piv = c.per_donor.pivot(index="donor", columns="arm", values="comp_l1")
|
| 410 |
+
for a, lab in zip(LORA_ARMS, X_LAB[1:]):
|
| 411 |
+
x = (piv[a] - piv[ZS]).dropna()
|
| 412 |
+
add(f"{ds}.comp_l1.lora_{lab}_minus_zero_shot.mean", round(float(x.mean()), 3), c.src_per_donor)
|
| 413 |
+
add(f"{ds}.comp_l1.lora_{lab}_minus_zero_shot.frac_donors_lower", round(float((x < 0).mean()), 2),
|
| 414 |
+
c.src_per_donor)
|
| 415 |
+
add(f"{ds}.comp_l1.lora_{lab}_vs_zero_shot.wilcoxon_p", float(f"{wilcoxon(x).pvalue:.2g}"),
|
| 416 |
+
c.src_per_donor)
|
| 417 |
+
add(f"{ds}.n_scored_donors", int(c.summary["n_donors"]), c.src_summary)
|
| 418 |
+
s = st[st.dataset == ds]
|
| 419 |
+
add(f"{ds}.selected_step.lora_n5.range", rng_txt(s[s.arm == "lora_n5"].selected_step), "RUN.json: "
|
| 420 |
+
+ ";".join(s[s.arm == "lora_n5"].source))
|
| 421 |
+
add(f"{ds}.n_train.all", rng_txt(s[s.arm == "real_lora"].n_train), "RUN.json: "
|
| 422 |
+
+ ";".join(s[s.arm == "real_lora"].source))
|
| 423 |
+
add(f"{ds}.n_inner_val", rng_txt(s.n_inner_val), "RUN.json inner_val_rows (all LoRA arms, 5 folds)")
|
| 424 |
+
for arm in RUN_ARMS:
|
| 425 |
+
f = s[s.arm == arm]
|
| 426 |
+
add(f"{ds}.folds_cap_limited.{arm}", f"{int(f.cap_limited.sum())}/{len(f)}",
|
| 427 |
+
"RUN.json steps_run == max_steps and steps_run - selected_step < patience*eval_every: "
|
| 428 |
+
+ ";".join(f.source))
|
| 429 |
+
capped = s[s.cap_limited]
|
| 430 |
+
if len(capped):
|
| 431 |
+
add(f"{ds}.cap_limited.max_val_loss_drop_frac_last_2k_steps",
|
| 432 |
+
round(float(capped.val_loss_last_window_drop_frac.max()), 4),
|
| 433 |
+
"history.json inner_val_loss (drop over last patience window / drop from step 0): "
|
| 434 |
+
+ ";".join(capped.history))
|
| 435 |
+
for a, lab in zip([ZS] + LORA_ARMS + ["zs__pseudo"], KEY_LAB + ["pseudo"]):
|
| 436 |
+
add(f"immicro.nk_fraction_r.{lab}", round(im.frac_r(a, "NK cell"), 2), im.src_per_donor)
|
| 437 |
+
add(f"sepsis.logfc_r.{lab}", round(se.contrast_r(a), 2), se.src_contrast)
|
| 438 |
+
add(f"sepsis.top50_deg.{lab}", int(deg_call.deg(a)), deg_call.src_contrast)
|
| 439 |
+
add("sepsis.logfc_r.broadcast", round(se.contrast_r("real_lora__raw", "r_broadcast"), 2), se.src_contrast)
|
| 440 |
+
add("sepsis.top50_deg.broadcast", int(deg_call.deg("real_lora__raw", "top50_overlap_broadcast")),
|
| 441 |
+
deg_call.src_contrast)
|
| 442 |
+
|
| 443 |
+
def first_sustained(v, thr, strict=True):
|
| 444 |
+
"""First LoRA n from which every later n is above (or >=) thr."""
|
| 445 |
+
for i in range(len(v)):
|
| 446 |
+
if all((x > thr) if strict else (x >= thr) for x in v[i:]):
|
| 447 |
+
return X_LAB[1 + i]
|
| 448 |
+
return "never"
|
| 449 |
+
bc_r = se.contrast_r("real_lora__raw", "r_broadcast")
|
| 450 |
+
bc_d = deg_call.deg("real_lora__raw", "top50_overlap_broadcast")
|
| 451 |
+
vr = [se.contrast_r(a) for a in LORA_ARMS]
|
| 452 |
+
vd = [deg_call.deg(a) for a in LORA_ARMS]
|
| 453 |
+
add("sepsis.logfc_r.first_n_above_broadcast", first_sustained(vr, bc_r), se.src_contrast)
|
| 454 |
+
add("sepsis.logfc_r.first_n_above_zero_shot", first_sustained(vr, se.contrast_r(ZS)), se.src_contrast)
|
| 455 |
+
add("sepsis.top50_deg.first_n_at_or_above_broadcast", first_sustained(vd, bc_d, strict=False),
|
| 456 |
+
deg_call.src_contrast)
|
| 457 |
+
add("sepsis.top50_deg.first_n_above_zero_shot", first_sustained(vd, deg_call.deg(ZS)), deg_call.src_contrast)
|
| 458 |
+
# across-donor fraction r per cell type: first n from which LoRA stays at/above zero-shot (footnote)
|
| 459 |
+
for ct, key in [("T cell", "T"), ("B cell", "B"), ("Monocyte", "Mono"), ("NK cell", "NK")]:
|
| 460 |
+
v = [im.frac_r(a, ct) for a in LORA_ARMS]
|
| 461 |
+
add(f"immicro.fraction_r.{key}.first_n_at_or_above_zero_shot",
|
| 462 |
+
first_sustained(v, im.frac_r(ZS, ct), strict=False), im.src_per_donor)
|
| 463 |
+
add(f"immicro.fraction_r.{key}.zero_shot", round(im.frac_r(ZS, ct), 2), im.src_per_donor)
|
| 464 |
+
add(f"immicro.fraction_r.{key}.lora_5_10_20_40_all", "/".join(f"{x:.2f}" for x in v), im.src_per_donor)
|
| 465 |
+
# top-50 DEG overlap by cell type (which types carry the gain)
|
| 466 |
+
for ct, key in [("T cell", "T"), ("B cell", "B"), ("Monocyte", "Mono"), ("NK cell", "NK"), ("DC", "DC")]:
|
| 467 |
+
v = [deg_call.deg_type(a, ct) for a in [ZS] + LORA_ARMS]
|
| 468 |
+
add(f"sepsis.top50_deg.{key}.zero_shot_5_10_20_40_all", "/".join(f"{x:g}" for x in v),
|
| 469 |
+
deg_call.src_contrast)
|
| 470 |
+
add(f"sepsis.top50_deg.{key}.broadcast", int(deg_call.deg_type("real_lora__raw", ct,
|
| 471 |
+
"top50_overlap_broadcast")),
|
| 472 |
+
deg_call.src_contrast)
|
| 473 |
+
add("sepsis.n_case", int(se.summary["contrast_definition"]["n_case_donors"]), se.src_summary)
|
| 474 |
+
add("sepsis.n_control", int(se.summary["contrast_definition"]["n_control_donors"]), se.src_summary)
|
| 475 |
+
add("final_checkpoint", FINAL_CKPT, "RUN.json source_checkpoint (all 50 LoRA runs)")
|
| 476 |
+
return pd.DataFrame(out)
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
def check_against_fig3(rows):
|
| 480 |
+
"""Cross-check the LoRA curve and reference lines with the plan's own fig3 source data (same numbers,
|
| 481 |
+
independent code path). The plan's fig3 n=0 point is a different zero-shot arm, so the zero-shot real-bulk
|
| 482 |
+
point is checked in load() instead (headline vs per_donor.csv / contrast.csv)."""
|
| 483 |
+
ref = pd.read_csv(PLAN / "figures" / "source_data" / "fig3_learning_curve.csv")
|
| 484 |
+
pmap = {("comp_l1", "immicro"): "3a", ("comp_l1", "ye2026_sepsis"): "3b",
|
| 485 |
+
("coverage", "immicro"): "3c", ("coverage", "ye2026_sepsis"): "3d",
|
| 486 |
+
("nk_fraction_r", "immicro"): "3e", ("logfc_r", "ye2026_sepsis"): "3f",
|
| 487 |
+
("top50_deg", "ye2026_sepsis"): "3h"}
|
| 488 |
+
n = 0
|
| 489 |
+
for r in rows:
|
| 490 |
+
p = pmap.get((r["panel"], r["dataset"]))
|
| 491 |
+
if p is None or r["series"] == "zero_shot":
|
| 492 |
+
continue
|
| 493 |
+
if r["series"] == "lora":
|
| 494 |
+
m = ref[(ref.panel == p) & (ref.series == r["series"]) & (ref.draw == f"n={r['pairs']}")]
|
| 495 |
+
else:
|
| 496 |
+
m = ref[(ref.panel == p) & (ref.series == r["series"])]
|
| 497 |
+
assert len(m) == 1, (r, len(m))
|
| 498 |
+
assert abs(float(m.value.iloc[0]) - float(r["value"])) < 1e-5, (r, float(m.value.iloc[0]))
|
| 499 |
+
n += 1
|
| 500 |
+
return n
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
def main():
|
| 504 |
+
calls, deg_call = load()
|
| 505 |
+
st = load_steps()
|
| 506 |
+
fold_sizes = load_fold_sizes()
|
| 507 |
+
rows, steprows = [], []
|
| 508 |
+
fig_realism(calls, st, fold_sizes, rows, steprows)
|
| 509 |
+
rows_sig = []
|
| 510 |
+
fig_signal(calls, deg_call, st, rows_sig)
|
| 511 |
+
n_checked = check_against_fig3(rows + rows_sig)
|
| 512 |
+
pd.DataFrame(rows).to_csv(DATADIR / "sec08_pairs_realism.csv", index=False, float_format="%.6g")
|
| 513 |
+
pd.DataFrame(steprows).to_csv(DATADIR / "sec08_selected_steps.csv", index=False, float_format="%.6g")
|
| 514 |
+
st.to_csv(DATADIR / "sec08_selected_steps_per_fold.csv", index=False)
|
| 515 |
+
pd.DataFrame(rows_sig).to_csv(DATADIR / "sec08_pairs_signal.csv", index=False, float_format="%.6g")
|
| 516 |
+
nums = slide_numbers(calls, deg_call, st)
|
| 517 |
+
nums.to_csv(DATADIR / "sec08_slide_numbers.csv", index=False)
|
| 518 |
+
print(nums.to_string(index=False, max_colwidth=70))
|
| 519 |
+
print(f"cross-checked {n_checked} plotted values against fig3_learning_curve.csv")
|
| 520 |
+
brk = [(r["panel"], r["dataset"]) for r in rows + rows_sig if r.get("series") == "zero_shot" and r["y_axis_break"]]
|
| 521 |
+
print(f"y-axis breaks: {brk}")
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
if __name__ == "__main__":
|
| 525 |
+
main()
|
paper-releases/pbisc-diffusion/updates/20260930T090852Z-summary-deck-final-path-story/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec09_paired_validation.py
ADDED
|
@@ -0,0 +1,1251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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2 |
+
"""Section 9 of the 2026-09-30 paper-summary deck: the final method in five paired cohorts,
|
| 3 |
+
and scSemiProfiler trained on the same 5 donors.
|
| 4 |
+
|
| 5 |
+
CPU only: reads score files, draws slide-sized figures. No torch, no CUDA, no generation, no scANVI.
|
| 6 |
+
|
| 7 |
+
Data loading is imported unchanged from the benchmark's own figure script
|
| 8 |
+
(plans/paired_finetune_intradataset_20260927/figures/make_figures.py: load_fewpair, load_pooled),
|
| 9 |
+
so every plotted number and every scSemiProfiler acceptance check (same donor set, same reference
|
| 10 |
+
sha, receipt verified) is the same as in the paper figures. Only the drawing is new.
|
| 11 |
+
|
| 12 |
+
Outputs (deck folder):
|
| 13 |
+
figures/sec09_cohorts.{png,pdf} slide a: five paired cohorts (table)
|
| 14 |
+
figures/sec09_fewpair_cells.{png,pdf} slide b: 5 donors, cell-level metrics
|
| 15 |
+
figures/sec09_fewpair_disease.{png,pdf} slide c: 5 donors, disease signal
|
| 16 |
+
figures/sec09_fivefold.{png,pdf} slide d: all pairs, 5-fold pooled
|
| 17 |
+
data/sec09_*.csv every plotted number with its source file
|
| 18 |
+
data/sec09_slide_text.json slide titles, keywords, footnotes (long "footnote" for the speaker
|
| 19 |
+
notes + one-line "footnote_short") and quoted numbers (+ sources),
|
| 20 |
+
all built by this script from the same data as the figures
|
| 21 |
+
data/sec09_quoted_numbers.csv the quoted numbers as a flat table
|
| 22 |
+
|
| 23 |
+
Baselines (paper story, user decision 2026-09-30): the no-fine-tune baseline is zero-shot on the real bulk as
|
| 24 |
+
measured (few-pair arm zs_raw, pooled arm zs__raw); the sc-only control is the sc-only fine-tune fed the real bulk
|
| 25 |
+
as measured (pooled arm pseudo_full__raw). The benchmark's input-adjusted arms (zs_cal, zs__cal, pseudo_full__cal)
|
| 26 |
+
are dropped right after loading and never reach a figure, table or slide text; OFF_STORY guards the outputs.
|
| 27 |
+
|
| 28 |
+
RERUN CHECKLIST (all 25 scSemiProfiler draws are scored; rerun whenever a score file changes):
|
| 29 |
+
1. /home/sj_server_1/miniforge3/bin/python3 tools/sec09_paired_validation.py (no edits needed; must exit 0)
|
| 30 |
+
2. Rebuild the four slides from data/sec09_slide_text.json: every title, keyword line, footnote and quoted
|
| 31 |
+
number there is regenerated. Do not keep hand-copied slide text.
|
| 32 |
+
3. Look at the four PNGs again.
|
| 33 |
+
"""
|
| 34 |
+
from __future__ import annotations
|
| 35 |
+
|
| 36 |
+
import os
|
| 37 |
+
|
| 38 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = "" # plotting only
|
| 39 |
+
|
| 40 |
+
import gzip
|
| 41 |
+
import importlib
|
| 42 |
+
import importlib.util
|
| 43 |
+
import json
|
| 44 |
+
import re
|
| 45 |
+
import sys
|
| 46 |
+
from pathlib import Path
|
| 47 |
+
|
| 48 |
+
import numpy as np
|
| 49 |
+
import pandas as pd
|
| 50 |
+
from scipy.stats import wilcoxon
|
| 51 |
+
|
| 52 |
+
DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/"
|
| 53 |
+
"2026-09-30--paper-summary--r00")
|
| 54 |
+
T = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/"
|
| 55 |
+
"paired_finetune_intradataset_20260927")
|
| 56 |
+
SCORES = T / "scores"
|
| 57 |
+
DATA = T / "data"
|
| 58 |
+
FIGDIR = DECK / "figures"
|
| 59 |
+
OUTDATA = DECK / "data"
|
| 60 |
+
SCRIPT = DECK / "tools" / "sec09_paired_validation.py"
|
| 61 |
+
DATALAKE = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc")
|
| 62 |
+
|
| 63 |
+
# 1) the benchmark's loaders (this import sets print-size rcParams) ...
|
| 64 |
+
_spec = importlib.util.spec_from_file_location("pf_make_figures", T / "figures" / "make_figures.py")
|
| 65 |
+
mf = importlib.util.module_from_spec(_spec)
|
| 66 |
+
_spec.loader.exec_module(mf)
|
| 67 |
+
# 2) ... then the deck style, which must win the rcParams
|
| 68 |
+
sys.path.insert(0, str(DECK / "tools"))
|
| 69 |
+
import style # noqa: E402
|
| 70 |
+
|
| 71 |
+
importlib.reload(style)
|
| 72 |
+
import matplotlib.pyplot as plt # noqa: E402
|
| 73 |
+
from matplotlib.lines import Line2D # noqa: E402
|
| 74 |
+
from matplotlib.patches import Patch # noqa: E402
|
| 75 |
+
from matplotlib.ticker import MaxNLocator # noqa: E402
|
| 76 |
+
|
| 77 |
+
# deck order: healthy first, whole-blood cohort last
|
| 78 |
+
ORDER = ["immicro", "ye2026_sepsis", "imperial_eskd", "giroux2022", "ji2025_chili"]
|
| 79 |
+
DISEASE = [d for d in ORDER if d != "immicro"]
|
| 80 |
+
NAME = {"immicro": "ImMicro", "ye2026_sepsis": "Sepsis", "imperial_eskd": "Imperial",
|
| 81 |
+
"giroux2022": "Giroux", "ji2025_chili": "Ji"}
|
| 82 |
+
ROWNAME = {**NAME, "ji2025_chili": "Ji (whole blood)"}
|
| 83 |
+
COL = {"zs_raw": style.ARM["zs"], "scsemi5": style.ARM["scsemi"], "lora": style.ARM["lora"],
|
| 84 |
+
"sconly": style.ARM["sconly"]}
|
| 85 |
+
LAB = {"zs_raw": "Zero-shot, real bulk", "scsemi5": "scSemiProfiler, 5 donors",
|
| 86 |
+
"lora": "LoRA, 5 donors", "sconly": "sc-only fine-tune",
|
| 87 |
+
"lora_all": "LoRA, all training pairs"}
|
| 88 |
+
# few-pair arms kept from load_fewpair (canonical key -> arm name in summary.json); everything else is dropped
|
| 89 |
+
ARM_FILE = {"lora": "lora5", "scsemi5": "scsemi5", "zs_raw": "zs_raw", "pseudo": "zs_pseudo"}
|
| 90 |
+
# pooled 5-fold arms (plot key -> arm name in scores/<cohort>/pooled/summary.json)
|
| 91 |
+
POOLED_ARMS = {"zs_raw": "zs__raw", "sconly": "pseudo_full__raw", "lora": "real_lora__raw"}
|
| 92 |
+
# text that must not appear in any figure, CSV label or slide text of this section
|
| 93 |
+
OFF_STORY = re.compile(r"calibrat|refcal|\bcal\b|_cal\b|__cal\b|α|alpha|paired cal", re.I)
|
| 94 |
+
KW_MAX_CHARS = 45 # keyword line length on the slide
|
| 95 |
+
FOOT_SHORT_MAX = 110 # one-line on-slide footnote
|
| 96 |
+
REFSTYLE = {"pseudo": dict(ls=(0, (4, 2)), color=style.ARM["pseudo"], lw=1.6, label="Zero-shot, sc pseudobulk input"),
|
| 97 |
+
"broadcast": dict(ls=(0, (1, 1.2)), color=style.ARM["broadcast"], lw=2.4, label="Real-bulk broadcast")}
|
| 98 |
+
EDGE = "#333333"
|
| 99 |
+
SUB = "#595959"
|
| 100 |
+
FS = style.FS
|
| 101 |
+
HILITE = "#FFF3D1"
|
| 102 |
+
LEFT_IN = 2.25 # room for the row labels (cohort + train/test pairs)
|
| 103 |
+
WIN_FRAC = 0.8 # a cohort verdict needs one method better in >= 80 % of the shared draws
|
| 104 |
+
QC = {d: DATA / d / "QC_REPORT.md" for d in DISEASE}
|
| 105 |
+
ARGS = T / "tools" / "contrast_args.sh"
|
| 106 |
+
README = T / "README.md"
|
| 107 |
+
SCORE_FT = T / "tools" / "score_ft.py"
|
| 108 |
+
PREPARE = T / "tools" / "prepare_dataset.py"
|
| 109 |
+
INV = DATALAKE / "docs" / "dataset_inventory.csv"
|
| 110 |
+
SOFT_SC = DATALAKE / "datasets" / "GSE314416" / "metadata" / "GSE314416_family.soft.gz"
|
| 111 |
+
SOFT_BULK = DATALAKE / "datasets" / "GSE314922" / "metadata" / "GSE314922_family.soft.gz"
|
| 112 |
+
|
| 113 |
+
CKPT = "runs/f01_6k_1x_seed20260627/checkpoint_epoch_016.pt"
|
| 114 |
+
NUMS = {k: [] for k in "abcd"} # slide -> [{"value", "source"}] quoted on the slide
|
| 115 |
+
EXTRA = [] # further numbers written to the CSV only
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def num(slide, value, source):
|
| 119 |
+
NUMS[slide].append({"value": str(value), "source": str(source)})
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def extra(slide, item, value, source):
|
| 123 |
+
EXTRA.append({"slide": slide, "item": item, "value": str(value), "source": str(source)})
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def rng(vals, fmt="{:d}"):
|
| 127 |
+
vals = sorted(set(vals))
|
| 128 |
+
return fmt.format(vals[0]) if len(vals) == 1 else f"{fmt.format(vals[0])}–{fmt.format(vals[-1])}"
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
# ------------------------------------------------------------------------------------------
|
| 132 |
+
# Evidence: every label on the cohort table must match ONE line of its source file
|
| 133 |
+
# ------------------------------------------------------------------------------------------
|
| 134 |
+
_TEXT_CACHE: dict = {}
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def _read_text(p: Path) -> str:
|
| 138 |
+
if p not in _TEXT_CACHE:
|
| 139 |
+
if p.suffix == ".gz":
|
| 140 |
+
with gzip.open(p, "rt", encoding="utf-8", errors="replace") as fh:
|
| 141 |
+
_TEXT_CACHE[p] = fh.read()
|
| 142 |
+
else:
|
| 143 |
+
_TEXT_CACHE[p] = p.read_text(encoding="utf-8", errors="replace")
|
| 144 |
+
return _TEXT_CACHE[p]
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def evidence(p: Path, pattern: str) -> str:
|
| 148 |
+
"""The full source line (with its number) that contains a match of `pattern`; the match may not span lines."""
|
| 149 |
+
text = _read_text(p)
|
| 150 |
+
m = re.search(pattern, text, flags=re.M)
|
| 151 |
+
if not m:
|
| 152 |
+
raise ValueError(f"evidence not found: /{pattern}/ in {p}")
|
| 153 |
+
if "\n" in m.group(0):
|
| 154 |
+
raise ValueError(f"evidence /{pattern}/ spans lines in {p}")
|
| 155 |
+
a = text.rfind("\n", 0, m.start()) + 1
|
| 156 |
+
b = text.find("\n", m.end())
|
| 157 |
+
line = text[a:(len(text) if b < 0 else b)].strip()
|
| 158 |
+
return f"L{text.count(chr(10), 0, m.start()) + 1}: {line[:240]}"
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def match_text(p: Path, pattern: str) -> str:
|
| 162 |
+
"""Only the matched text (one line) of `pattern` in p, after the same checks as evidence()."""
|
| 163 |
+
evidence(p, pattern)
|
| 164 |
+
return re.search(pattern, _read_text(p), flags=re.M).group(0)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def evidences(pairs) -> tuple[str, str]:
|
| 168 |
+
ev = [evidence(p, pat) for p, pat in pairs]
|
| 169 |
+
return " || ".join(ev), " ; ".join(sorted({str(p) for p, _ in pairs}))
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
# display text -> [(file, one-line regex), ...]; each regex must match a single line of its file
|
| 173 |
+
COHORT_TEXT = {
|
| 174 |
+
"immicro": {
|
| 175 |
+
"study": ("ImMicro 2026", [(INV, r"Babdor et al\., Cell 2026 ImMicro")]),
|
| 176 |
+
"disease": ("healthy", [(INV, r'Babdor et al\., Cell 2026 ImMicro",Healthy humans')]),
|
| 177 |
+
"bulk": ("PBMC, mRNA-Seq", [(SOFT_BULK, r"^!Sample_source_name_ch1 = PBMC *$"),
|
| 178 |
+
(SOFT_BULK, r"Universal Plus mRNA-Seq with NuQuant kit")]),
|
| 179 |
+
"sc": ("10x 5′ v1.1 CITE-seq", [(SOFT_SC, r"Chromium Next GEM Single Cell 5.{1,2} v1\.1 Library Kit"),
|
| 180 |
+
(SOFT_SC, r"Library strategy: CITE-seq")]),
|
| 181 |
+
},
|
| 182 |
+
"ye2026_sepsis": {
|
| 183 |
+
"study": ("Ye 2026", [(QC["ye2026_sepsis"], r"Ye Q et al\., Nat Immunol 2026")]),
|
| 184 |
+
"disease": ("sepsis", [(QC["ye2026_sepsis"], r"^# Ye 2026 sepsis")]),
|
| 185 |
+
# extraction is total RNA (Trizol) but the library (polyA vs rRNA depletion) is not stated -> show PBMC only
|
| 186 |
+
"bulk": ("PBMC", [(QC["ye2026_sepsis"], r"GEO protocol: PBMC total RNA \(Trizol\).*polyA vs rRNA depletion not stated")]),
|
| 187 |
+
"sc": ("10x 5′", [(QC["ye2026_sepsis"], r"Chemistry: GEO says .*but the data show 5'")]),
|
| 188 |
+
},
|
| 189 |
+
"imperial_eskd": {
|
| 190 |
+
"study": ("Imperial ESKD", [(QC["imperial_eskd"], r"patients with COVID-19, Imperial cohort")]),
|
| 191 |
+
"disease": ("COVID-19, dialysis", [(QC["imperial_eskd"], r"haemodialysis \(end-stage kidney disease\) patients with COVID-19")]),
|
| 192 |
+
"bulk": ("PBMC", [(QC["imperial_eskd"], r"^- Bulk: .*PBMC RNA-seq")]),
|
| 193 |
+
"sc": ("10x 5′ v2 CITE-seq", [(QC["imperial_eskd"], r"^- scRNA: .*PBMC CITE-seq"),
|
| 194 |
+
(QC["imperial_eskd"], r"Chemistry: 10x 5′ v2")]),
|
| 195 |
+
},
|
| 196 |
+
"giroux2022": {
|
| 197 |
+
"study": ("Giroux 2022", [(QC["giroux2022"], r"Giroux NS et al\., Sci Rep 2022")]),
|
| 198 |
+
"disease": ("COVID-19, outpatient", [(QC["giroux2022"], r"Duke outpatients, early COVID-19")]),
|
| 199 |
+
"bulk": ("PBMC, total RNA (SoLo)", [(QC["giroux2022"], r"^# Giroux 2022 COVID-19: paired PBMC bulk and scRNA"),
|
| 200 |
+
(QC["giroux2022"], r"GEO protocol: Zymo Direct-zol total RNA, NuGEN Ovation SoLo")]),
|
| 201 |
+
"sc": ("10x 5′ v1", [(QC["giroux2022"], r"10x library per subject-day \(5' v1")]),
|
| 202 |
+
},
|
| 203 |
+
"ji2025_chili": {
|
| 204 |
+
"study": ("Ji 2025", [(QC["ji2025_chili"], r"Ji C et al\., Cancer Immunol Immunother 2025")]),
|
| 205 |
+
"disease": ("ICI liver injury", [(QC["ji2025_chili"], r"liver injury on checkpoint inhibitors \(ChILI\)")]),
|
| 206 |
+
"bulk": ("whole blood, 3′ QuantSeq", [(QC["ji2025_chili"], r"\*\*PAXgene whole-blood tubes\*\*"),
|
| 207 |
+
(QC["ji2025_chili"], r"Protocol: Lexogen QuantSeq 3′ FWD")]),
|
| 208 |
+
"sc": ("10x 5′", [(QC["ji2025_chili"], r"Chemistry: 10x 5′ GEX")]),
|
| 209 |
+
},
|
| 210 |
+
}
|
| 211 |
+
# display labels of the scorer's case / control groups; the group lists are asserted against summary.json and
|
| 212 |
+
# contrast_args.sh; `neither` = groups scored in neither arm of the contrast
|
| 213 |
+
CONTRAST = {
|
| 214 |
+
"ye2026_sepsis": dict(case="sepsis", control="control", case_groups=["adult_sepsis", "ped_sepsis"],
|
| 215 |
+
control_groups=["adult_HC", "adult_ICU_ctrl", "ped_HC", "ped_ICU_ctrl"], neither=[],
|
| 216 |
+
ev=[(ARGS, r'ye2026_sepsis\) echo "--case-groups adult_sepsis,ped_sepsis '
|
| 217 |
+
r'--control-groups adult_HC,adult_ICU_ctrl,ped_HC,ped_ICU_ctrl"')]),
|
| 218 |
+
"imperial_eskd": dict(case="COVID+", control="COVID−", case_groups=["covid_positive"],
|
| 219 |
+
control_groups=["covid_negative"], neither=["recovery"],
|
| 220 |
+
ev=[(ARGS, r"COVID-positive vs COVID-negative haemodialysis patients \(recovery samples in neither group\)"),
|
| 221 |
+
(ARGS, r'imperial_eskd\) echo "--case-groups covid_positive --control-groups covid_negative"')]),
|
| 222 |
+
# the GEO label is "severe"; the paper and the author sheet call this group "moderate" (all are outpatients)
|
| 223 |
+
"giroux2022": dict(case="moderate", control="mild", case_groups=["severe"], control_groups=["mild"], neither=[],
|
| 224 |
+
ev=[(QC["giroux2022"], r'The paper and the author sheet call the "severe" group "moderate"'),
|
| 225 |
+
(ARGS, r'giroux2022\) echo "--case-groups severe --control-groups mild"')]),
|
| 226 |
+
"ji2025_chili": dict(case="ChILI", control="ICI control", case_groups=["TOL", "FU1"], control_groups=["BC", "AC"],
|
| 227 |
+
neither=[],
|
| 228 |
+
ev=[(ARGS, r"ChILI patients \(liver injury and its follow-up\) vs checkpoint-inhibitor controls"),
|
| 229 |
+
(ARGS, r'ji2025_chili\) echo "--case-groups TOL,FU1 --control-groups BC,AC"')]),
|
| 230 |
+
}
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def usable_folds(ds):
|
| 234 |
+
f = pd.read_csv(DATA / ds / "folds.csv")
|
| 235 |
+
f["donor_id"] = f["donor_id"].astype(str)
|
| 236 |
+
f["sample_id"] = f["sample_id"].astype(str)
|
| 237 |
+
return f[f.fold >= 0].copy()
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def min_cells() -> int:
|
| 241 |
+
return int(re.search(r"^MIN_CELLS = (\d+)", _read_text(PREPARE), flags=re.M).group(1))
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def cohort_rows():
|
| 245 |
+
mc = min_cells()
|
| 246 |
+
rows = []
|
| 247 |
+
for ds in ORDER:
|
| 248 |
+
r = {"dataset": ds}
|
| 249 |
+
for key, (txt, pairs) in COHORT_TEXT[ds].items():
|
| 250 |
+
r[key] = txt
|
| 251 |
+
r[f"{key}_evidence"], r[f"{key}_source"] = evidences(pairs)
|
| 252 |
+
dj = DATA / ds / "fewshot_n5" / "DRAWS.json"
|
| 253 |
+
draws = json.loads(dj.read_text())
|
| 254 |
+
used = usable_folds(ds)
|
| 255 |
+
if len(used) != draws["n_usable_rows"] or used.donor_id.nunique() != draws["n_usable_donors"]:
|
| 256 |
+
raise ValueError(f"{ds}: folds.csv and DRAWS.json disagree on usable rows/donors")
|
| 257 |
+
# exclusion tally, re-derived with prepare_dataset.py's rule: identity_pass & n_cells >= MIN_CELLS
|
| 258 |
+
feats = np.load(DATA / ds / "features.npz", allow_pickle=False)
|
| 259 |
+
samples = pd.read_csv(DATA / ds / "samples.csv")
|
| 260 |
+
n_all = int(feats["bulk_raw"].shape[0])
|
| 261 |
+
idp = feats["identity_pass"].astype(bool) if "identity_pass" in feats.files else np.ones(n_all, bool)
|
| 262 |
+
chk = (pd.Series(feats["identity_check"].astype(str)).str.split(":").str[0].str.strip()
|
| 263 |
+
if "identity_check" in feats.files else pd.Series(["(no flag)"] * n_all))
|
| 264 |
+
low = (samples["n_cells"].to_numpy() < mc)
|
| 265 |
+
n_fail, n_border = int((chk == "fail").sum()), int((chk == "borderline").sum())
|
| 266 |
+
if int((~idp).sum()) != n_fail + n_border:
|
| 267 |
+
raise ValueError(f"{ds}: identity_pass False rows != fail + borderline")
|
| 268 |
+
n_low = int((idp & low).sum())
|
| 269 |
+
if n_all - n_fail - n_border - n_low != draws["n_usable_rows"]:
|
| 270 |
+
raise ValueError(f"{ds}: exclusion tally does not reproduce the usable rows")
|
| 271 |
+
pooled_sum = json.loads((SCORES / ds / "pooled" / "summary.json").read_text())
|
| 272 |
+
if pooled_sum["n_donors"] != draws["n_usable_rows"]:
|
| 273 |
+
raise ValueError(f"{ds}: pooled scored n {pooled_sum['n_donors']} != usable rows {draws['n_usable_rows']}")
|
| 274 |
+
r.update(n_pairs_all=n_all, n_identity_fail=n_fail, n_identity_borderline=n_border,
|
| 275 |
+
n_low_cells=n_low, min_cells=mc, identity_flag=("identity_pass" in feats.files),
|
| 276 |
+
n_rows=draws["n_usable_rows"], n_donors=draws["n_usable_donors"], n_rows_source=str(dj),
|
| 277 |
+
exclusion_source=f"{DATA / ds / 'features.npz'} (identity_pass, identity_check); "
|
| 278 |
+
f"{DATA / ds / 'samples.csv'} (n_cells); {PREPARE} (MIN_CELLS)")
|
| 279 |
+
cd = pooled_sum["contrast_definition"]
|
| 280 |
+
psrc = str(SCORES / ds / "pooled" / "summary.json")
|
| 281 |
+
if ds in CONTRAST:
|
| 282 |
+
C = CONTRAST[ds]
|
| 283 |
+
if list(cd["case_groups"]) != C["case_groups"] or list(cd["control_groups"]) != C["control_groups"]:
|
| 284 |
+
raise ValueError(f"{ds}: contrast groups changed: {cd['case_groups']} / {cd['control_groups']}")
|
| 285 |
+
neither = sorted({g for g, a, b in zip(cd["groups"], cd["case"], cd["ctrl"]) if not a and not b})
|
| 286 |
+
if neither != sorted(C["neither"]) or (int(cd.get("n_donors_in_neither", 0)) > 0) != bool(neither):
|
| 287 |
+
raise ValueError(f"{ds}: groups in neither arm {neither} != expected {C['neither']}")
|
| 288 |
+
ev, evsrc = evidences(C["ev"])
|
| 289 |
+
r.update(case_label=C["case"], control_label=C["control"], n_case=int(cd["n_case_donors"]),
|
| 290 |
+
n_control=int(cd["n_control_donors"]), n_neither=int(cd.get("n_donors_in_neither", 0)),
|
| 291 |
+
neither_label=",".join(neither), contrast_source=psrc, contrast_label_evidence=ev,
|
| 292 |
+
contrast_label_source=evsrc)
|
| 293 |
+
else:
|
| 294 |
+
if cd.get("enabled"):
|
| 295 |
+
raise ValueError(f"{ds}: expected no contrast")
|
| 296 |
+
r.update(case_label="", control_label="", n_case=np.nan, n_control=np.nan, n_neither=0,
|
| 297 |
+
neither_label="", contrast_source=psrc)
|
| 298 |
+
rows.append(r)
|
| 299 |
+
return pd.DataFrame(rows)
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def fig_cohorts(tab: pd.DataFrame):
|
| 303 |
+
"""Plain table: columns are placed by measuring the rendered text, so nothing overlaps."""
|
| 304 |
+
headers = ["Cohort", "Condition", "Bulk", "scRNA-seq", "Pairs (donors)", "Case vs control"]
|
| 305 |
+
center = {4}
|
| 306 |
+
body = []
|
| 307 |
+
for r in tab.itertuples():
|
| 308 |
+
pd_txt = f"{r.n_rows}" if r.n_rows == r.n_donors else f"{r.n_rows} ({r.n_donors})"
|
| 309 |
+
ctxt = (f"{r.case_label} {int(r.n_case)} vs {r.control_label} {int(r.n_control)}" if r.case_label
|
| 310 |
+
else "none (healthy)")
|
| 311 |
+
csub = f"+{r.n_neither} {r.neither_label} (neither)" if r.n_neither else None
|
| 312 |
+
body.append([(r.study, {}, None), (r.disease, {}, None),
|
| 313 |
+
(r.bulk, {"fontweight": "bold"} if r.dataset == "ji2025_chili" else {}, None),
|
| 314 |
+
(r.sc, {}, None), (pd_txt, {}, None), (ctxt, {} if r.case_label else {"color": SUB}, csub)])
|
| 315 |
+
W, H = style.FULL[0], 3.7
|
| 316 |
+
fig = plt.figure(figsize=(W, H))
|
| 317 |
+
ax = fig.add_axes([0.0, 0.0, 1.0, 1.0])
|
| 318 |
+
ax.set_axis_off()
|
| 319 |
+
ax.set_xlim(0, 1)
|
| 320 |
+
ax.set_ylim(0, 1)
|
| 321 |
+
n = len(body)
|
| 322 |
+
top, rowh = 0.87, 0.84 / n
|
| 323 |
+
texts = [[] for _ in headers]
|
| 324 |
+
for j, h in enumerate(headers):
|
| 325 |
+
texts[j].append(ax.text(0, top + 0.055, h, ha="left", va="center", fontsize=FS, fontweight="bold",
|
| 326 |
+
color=style.INK))
|
| 327 |
+
for i, row in enumerate(body):
|
| 328 |
+
y = top - rowh * (i + 0.5)
|
| 329 |
+
for j, (txt, kw, sub) in enumerate(row):
|
| 330 |
+
if sub:
|
| 331 |
+
texts[j].append(ax.text(0, y + 0.03, txt, ha="left", va="center", fontsize=FS,
|
| 332 |
+
**{"color": style.INK, **kw}))
|
| 333 |
+
texts[j].append(ax.text(0, y - 0.035, sub, ha="left", va="center", fontsize=FS - 3, color=SUB))
|
| 334 |
+
else:
|
| 335 |
+
texts[j].append(ax.text(0, y, txt, ha="left", va="center", fontsize=FS,
|
| 336 |
+
**{"color": style.INK, **kw}))
|
| 337 |
+
fig.canvas.draw()
|
| 338 |
+
rend = fig.canvas.get_renderer()
|
| 339 |
+
widths = [max(t.get_window_extent(rend).width for t in col) / (fig.dpi * W) for col in texts]
|
| 340 |
+
gap = (1.0 - sum(widths)) / (len(headers) - 1)
|
| 341 |
+
if gap < 0.012:
|
| 342 |
+
raise ValueError(f"cohort table too wide for the slide (gap {gap:.3f})")
|
| 343 |
+
x = 0.0
|
| 344 |
+
for j, col in enumerate(texts):
|
| 345 |
+
for t in col:
|
| 346 |
+
if j in center:
|
| 347 |
+
t.set_x(x + widths[j] / 2)
|
| 348 |
+
t.set_ha("center")
|
| 349 |
+
else:
|
| 350 |
+
t.set_x(x)
|
| 351 |
+
x += widths[j] + gap
|
| 352 |
+
ax.plot([0, 1], [top + 0.005] * 2, color=style.INK, lw=1.2)
|
| 353 |
+
for i in range(1, n):
|
| 354 |
+
ax.plot([0, 1], [top - rowh * i] * 2, color="#C8C8C8", lw=0.7)
|
| 355 |
+
ax.plot([0, 1], [top - rowh * n] * 2, color=style.INK, lw=1.2)
|
| 356 |
+
style.save(fig, "sec09_cohorts", FIGDIR)
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
# ------------------------------------------------------------------------------------------
|
| 360 |
+
# Shared drawing helpers: rows = cohorts, columns = metrics, horizontal bars
|
| 361 |
+
# ------------------------------------------------------------------------------------------
|
| 362 |
+
BAR_H = 0.72
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
def jitter(n, seed):
|
| 366 |
+
r = np.random.default_rng(seed)
|
| 367 |
+
return (r.random(n) - 0.5) * BAR_H * 0.6
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
def hbars(ax, arms, vals_of, seed=0, dots=True):
|
| 371 |
+
"""arms drawn top to bottom at y = 0..na-1. vals_of(arm) -> list of floats. Returns stats."""
|
| 372 |
+
out = {}
|
| 373 |
+
for i, arm in enumerate(arms):
|
| 374 |
+
vals = np.asarray([v for v in vals_of(arm) if not np.isnan(v)], float)
|
| 375 |
+
if len(vals) == 0:
|
| 376 |
+
ax.text(0.01, i, "not run", transform=ax.get_yaxis_transform(), va="center", fontsize=FS - 3,
|
| 377 |
+
color=SUB)
|
| 378 |
+
out[arm] = (np.nan, np.nan, 0)
|
| 379 |
+
continue
|
| 380 |
+
m = float(vals.mean())
|
| 381 |
+
sd = float(vals.std(ddof=1)) if len(vals) > 1 else 0.0
|
| 382 |
+
ax.barh(i, m, height=BAR_H, color=COL[arm], edgecolor=EDGE, linewidth=0.6, zorder=2)
|
| 383 |
+
if dots and len(vals) > 1:
|
| 384 |
+
ax.errorbar(m, i, xerr=sd, fmt="none", ecolor="#111111", elinewidth=1.0, capsize=3, capthick=1.0,
|
| 385 |
+
zorder=4)
|
| 386 |
+
# dots unclipped so a draw at an axis end (precision 1.0) stays whole; check_inside() asserts that every
|
| 387 |
+
# dot and bar lies within the final x-limits. SD whiskers stay clipped (a count's SD can reach below 0).
|
| 388 |
+
ax.scatter(vals, i + jitter(len(vals), seed + i), s=16, facecolor="white", edgecolor="#111111",
|
| 389 |
+
linewidth=0.7, zorder=5, clip_on=False)
|
| 390 |
+
out[arm] = (m, sd, len(vals))
|
| 391 |
+
ax.set_ylim(len(arms) - 0.5, -0.5)
|
| 392 |
+
ax.set_yticks([])
|
| 393 |
+
return out
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
def check_inside(fig, name):
|
| 397 |
+
"""Every draw dot, bar end and reference line lies within its panel's final x-limits (nothing cut off)."""
|
| 398 |
+
from matplotlib.collections import PathCollection
|
| 399 |
+
from matplotlib.patches import Rectangle
|
| 400 |
+
for ax in fig.axes:
|
| 401 |
+
lo, hi = sorted(ax.get_xlim())
|
| 402 |
+
eps = 1e-9 * max(1.0, abs(hi - lo))
|
| 403 |
+
xs = [float(x) for c in ax.collections if isinstance(c, PathCollection) for x in c.get_offsets()[:, 0]]
|
| 404 |
+
xs += [x for p in ax.patches if isinstance(p, Rectangle) for x in (p.get_x(), p.get_x() + p.get_width())]
|
| 405 |
+
xs += [float(x) for ln in ax.lines for x in np.atleast_1d(ln.get_xdata()) if ln.get_linestyle() != "None"]
|
| 406 |
+
bad = [x for x in xs if not (lo - eps <= x <= hi + eps)]
|
| 407 |
+
if bad:
|
| 408 |
+
raise ValueError(f"{name}: value(s) {bad[:3]} outside the x-limits ({lo:.3g}, {hi:.3g})")
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
def ref_line(ax, x, kind, na):
|
| 412 |
+
"""Reference line above the bars (zorder 2) but below error bars (4) and draw dots (5)."""
|
| 413 |
+
if x is None or np.isnan(x):
|
| 414 |
+
return
|
| 415 |
+
s = REFSTYLE[kind]
|
| 416 |
+
ax.plot([x, x], [-0.5, na - 0.5], ls=s["ls"], color=s["color"], lw=s["lw"], zorder=3,
|
| 417 |
+
solid_capstyle="butt")
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
def row_label(ax, name, subs):
|
| 421 |
+
"""Cohort name (FS) with grey sub-lines (FS-3) stacked below it, the block centred on the row."""
|
| 422 |
+
lines = [(name, FS, style.INK)] + [(s, FS - 3, SUB) for s in subs]
|
| 423 |
+
y = sum(fs * 1.3 for _, fs, _ in lines) / 2
|
| 424 |
+
for txt, fs, col in lines:
|
| 425 |
+
h = fs * 1.3
|
| 426 |
+
ax.annotate(txt, xy=(0, 0.5), xycoords="axes fraction", xytext=(-12, y - h / 2), textcoords="offset points",
|
| 427 |
+
ha="right", va="center", fontsize=fs, color=col)
|
| 428 |
+
y -= h
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
def label_header(ax, text):
|
| 432 |
+
ax.annotate(text, xy=(0, 1), xycoords="axes fraction", xytext=(-12, 10), textcoords="offset points",
|
| 433 |
+
ha="right", va="bottom", fontsize=FS - 3, color=SUB, style="italic")
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
def blank(ax, text):
|
| 437 |
+
for sp in ax.spines.values():
|
| 438 |
+
sp.set_visible(False)
|
| 439 |
+
ax.set_xticks([])
|
| 440 |
+
ax.set_yticks([])
|
| 441 |
+
ax.text(0.5, 0.5, text, transform=ax.transAxes, ha="center", va="center", fontsize=FS - 3, color=SUB,
|
| 442 |
+
style="italic")
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
def grid(nrows, ncols, figsize, left, right, top, bottom, hspace, wspace):
|
| 446 |
+
fig = plt.figure(figsize=figsize)
|
| 447 |
+
gs = fig.add_gridspec(nrows, ncols, left=left / figsize[0], right=1 - right / figsize[0],
|
| 448 |
+
top=1 - top / figsize[1], bottom=bottom / figsize[1], hspace=hspace, wspace=wspace)
|
| 449 |
+
axs = np.empty((nrows, ncols), dtype=object)
|
| 450 |
+
for i in range(nrows):
|
| 451 |
+
for j in range(ncols):
|
| 452 |
+
axs[i, j] = fig.add_subplot(gs[i, j])
|
| 453 |
+
return fig, axs
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
def shared_x(axs_col, lo, hi, xlabel, ticks=None):
|
| 457 |
+
for k, ax in enumerate(axs_col):
|
| 458 |
+
ax.set_xlim(lo, hi)
|
| 459 |
+
if ticks is not None:
|
| 460 |
+
ax.set_xticks(ticks)
|
| 461 |
+
if k < len(axs_col) - 1:
|
| 462 |
+
ax.tick_params(axis="x", labelbottom=False, length=0)
|
| 463 |
+
ax.spines["bottom"].set_visible(False)
|
| 464 |
+
axs_col[-1].set_xlabel(xlabel)
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
def legend_bottom(fig, handles, ncol, y=0.0):
|
| 468 |
+
fig.legend(handles=handles, loc="lower center", bbox_to_anchor=(0.5, y), ncol=ncol, frameon=False,
|
| 469 |
+
fontsize=FS - 2, handlelength=2.2, columnspacing=1.6, borderaxespad=0.0)
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
def patch(key, label=None):
|
| 473 |
+
return Patch(facecolor=COL[key], edgecolor=EDGE, linewidth=0.6, label=label or LAB[key])
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
def refh(kind):
|
| 477 |
+
s = REFSTYLE[kind]
|
| 478 |
+
return Line2D([0], [0], ls=s["ls"], color=s["color"], lw=s["lw"], label=s["label"])
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
def dot_handle(n_draws):
|
| 482 |
+
lab = "one draw; bar = mean ± SD" + (f" of {n_draws}" if n_draws else "")
|
| 483 |
+
return Line2D([0], [0], marker="o", lw=0, markerfacecolor="white", markeredgecolor="#111111",
|
| 484 |
+
markersize=5, label=lab)
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
# ------------------------------------------------------------------------------------------
|
| 488 |
+
# Few-pair (5 donors) data
|
| 489 |
+
# ------------------------------------------------------------------------------------------
|
| 490 |
+
_JSON: dict = {}
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
def jload(p: Path):
|
| 494 |
+
if p not in _JSON:
|
| 495 |
+
_JSON[p] = json.loads(Path(p).read_text())
|
| 496 |
+
return _JSON[p]
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
def fewpair():
|
| 500 |
+
few, status = mf.load_fewpair(SCORES)
|
| 501 |
+
few = few[few.arm.isin(ARM_FILE)].reset_index(drop=True) # zero-shot baseline = raw real bulk (zs_raw) only
|
| 502 |
+
status.to_csv(OUTDATA / "sec09_scsemi_status.csv", index=False)
|
| 503 |
+
# depth-matched precision / coverage are in each call's summary.json headline (not in load_fewpair's metrics)
|
| 504 |
+
for k in ("precision_dm", "coverage_dm"):
|
| 505 |
+
few[k] = [float(jload(T / s)["headline"][ARM_FILE[a]][k]) for s, a in zip(few.source, few.arm)]
|
| 506 |
+
return few, status
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
def few_vals(few, ds, arm, metric):
|
| 510 |
+
s = few[(few.dataset == ds) & (few.arm == arm)].sort_values("draw")
|
| 511 |
+
return s[metric].astype(float).tolist(), s["draw"].tolist(), s["source"].tolist()
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
def few_ref(few, ds, kind, metric):
|
| 515 |
+
"""pseudo = zero-shot from sc pseudobulk (zs_pseudo arm); broadcast = raw real bulk logFC/DEG; mean over draws."""
|
| 516 |
+
if kind == "pseudo":
|
| 517 |
+
s = few[(few.dataset == ds) & (few.arm == "pseudo")]
|
| 518 |
+
v = s[metric]
|
| 519 |
+
else:
|
| 520 |
+
s = few[(few.dataset == ds) & (few.arm == "lora")]
|
| 521 |
+
v = s["broadcast_r" if metric == "contrast_r" else "deg_broadcast"]
|
| 522 |
+
v = v.dropna()
|
| 523 |
+
return (float(v.mean()) if len(v) else np.nan), ";".join(sorted(set(s["source"])))
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
def n_draws(few, ds, arm):
|
| 527 |
+
return int(few[(few.dataset == ds) & (few.arm == arm)]["draw"].nunique())
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
def draw_info(few, ds):
|
| 531 |
+
"""Training / test pairs of the scored LoRA draws (DRAWS.json), and test subjects per contrast arm."""
|
| 532 |
+
dj = DATA / ds / "fewshot_n5" / "DRAWS.json"
|
| 533 |
+
D = jload(dj)["draw"]
|
| 534 |
+
u = usable_folds(ds)
|
| 535 |
+
lora = few[(few.dataset == ds) & (few.arm == "lora")].sort_values("draw")
|
| 536 |
+
tr, te, n_sub, sub_cc = [], [], [], []
|
| 537 |
+
for r in lora.itertuples():
|
| 538 |
+
v = D[str(int(r.draw))] if str(int(r.draw)) in D else D[int(r.draw)]
|
| 539 |
+
if int(r.n_scored) != int(v["n_test_rows"]):
|
| 540 |
+
raise ValueError(f"{ds} draw {r.draw}: scored n {r.n_scored} != DRAWS n_test_rows {v['n_test_rows']}")
|
| 541 |
+
train = {str(x) for x in v["train_donors"]}
|
| 542 |
+
if int(u[u.donor_id.isin(train)].shape[0]) != int(v["n_train_rows"]):
|
| 543 |
+
raise ValueError(f"{ds} draw {r.draw}: train rows in folds.csv != DRAWS n_train_rows")
|
| 544 |
+
tr.append(int(v["n_train_rows"]))
|
| 545 |
+
te.append(int(r.n_scored))
|
| 546 |
+
test = u[~u.donor_id.isin(train)]
|
| 547 |
+
n_sub.append(int(test.donor_id.nunique()))
|
| 548 |
+
if ds in CONTRAST:
|
| 549 |
+
C = CONTRAST[ds]
|
| 550 |
+
cs = set(test[test.group.isin(C["case_groups"])].donor_id)
|
| 551 |
+
ct = set(test[test.group.isin(C["control_groups"])].donor_id)
|
| 552 |
+
sub_cc.append((len(cs), len(ct)))
|
| 553 |
+
return {"train": rng(tr), "test": rng(te), "n_train": tr, "n_test": te, "n_test_subjects": n_sub,
|
| 554 |
+
"subjects_cc": sub_cc, "n_draws": len(tr), "source": str(dj)}
|
| 555 |
+
|
| 556 |
+
|
| 557 |
+
def subjects_text(info):
|
| 558 |
+
"""'2 vs 2' when a cohort's test set holds few subjects (< 10) per draw; else ''."""
|
| 559 |
+
if not info["subjects_cc"] or max(info["n_test_subjects"]) >= 10:
|
| 560 |
+
return ""
|
| 561 |
+
a = rng([c for c, _ in info["subjects_cc"]])
|
| 562 |
+
b = rng([t for _, t in info["subjects_cc"]])
|
| 563 |
+
return f"{a} vs {b}"
|
| 564 |
+
|
| 565 |
+
|
| 566 |
+
def row_subs(info, per_row_draws):
|
| 567 |
+
subs = [f"train {info['train']} / test {info['test']}"]
|
| 568 |
+
st = subjects_text(info)
|
| 569 |
+
if st:
|
| 570 |
+
subs.append(f"test = {st} subjects")
|
| 571 |
+
if per_row_draws:
|
| 572 |
+
subs.append(f"{info['n_draws']} draws")
|
| 573 |
+
return subs
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
def long_rows(fig, few, datasets, arms, metrics, refs):
|
| 577 |
+
rows = []
|
| 578 |
+
for ds in datasets:
|
| 579 |
+
for metric in metrics:
|
| 580 |
+
for arm in arms:
|
| 581 |
+
vals, draws, srcs = few_vals(few, ds, arm, metric)
|
| 582 |
+
for v, d, s in zip(vals, draws, srcs):
|
| 583 |
+
rows.append({"figure": fig, "dataset": ds, "metric": metric, "series": arm, "kind": "draw",
|
| 584 |
+
"draw": d, "value": v, "source": s})
|
| 585 |
+
vv = [v for v in vals if not np.isnan(v)]
|
| 586 |
+
if vv:
|
| 587 |
+
rows.append({"figure": fig, "dataset": ds, "metric": metric, "series": arm, "kind": "mean",
|
| 588 |
+
"draw": "", "value": float(np.mean(vv)),
|
| 589 |
+
"sd": float(np.std(vv, ddof=1)) if len(vv) > 1 else 0.0, "n_draws": len(vv),
|
| 590 |
+
"source": "derived: mean/SD of the draw rows"})
|
| 591 |
+
for kind in refs.get(metric, []):
|
| 592 |
+
v, s = few_ref(few, ds, kind, metric)
|
| 593 |
+
rows.append({"figure": fig, "dataset": ds, "metric": metric, "series": f"ref_{kind}",
|
| 594 |
+
"kind": "reference (mean over draws)", "draw": "", "value": v, "source": s})
|
| 595 |
+
return rows
|
| 596 |
+
|
| 597 |
+
|
| 598 |
+
def same_draw_compare(few, status, datasets, metric, lower_better=False, min_margin=0.0, other="scsemi5"):
|
| 599 |
+
"""LoRA-5 vs another arm (scSemi-5 by default, or zero-shot zs_raw) draw by draw, on the draws where both
|
| 600 |
+
exist (same test pairs; scSemi-5 draws only when load_fewpair accepted them).
|
| 601 |
+
|
| 602 |
+
Per draw: LoRA better / other better / tie (equal values). Cohort verdict:
|
| 603 |
+
'tie' if at least half the shared draws tie, or |mean difference| < min_margin;
|
| 604 |
+
'lora' if LoRA is better in >= WIN_FRAC of the shared draws;
|
| 605 |
+
'other' if the other arm is better in >= WIN_FRAC of the shared draws;
|
| 606 |
+
'split' otherwise.
|
| 607 |
+
"""
|
| 608 |
+
used = status[status.status == "used"]
|
| 609 |
+
res = {}
|
| 610 |
+
for ds in datasets:
|
| 611 |
+
a = few[(few.dataset == ds) & (few.arm == "lora")].set_index("draw")[metric].astype(float)
|
| 612 |
+
b = few[(few.dataset == ds) & (few.arm == other)].set_index("draw")[metric].astype(float)
|
| 613 |
+
cand = sorted(used[used.dataset == ds]["draw"]) if other == "scsemi5" else sorted(a.index)
|
| 614 |
+
dr = [d for d in cand if d in a.index and d in b.index and not (np.isnan(a[d]) or np.isnan(b[d]))]
|
| 615 |
+
if not dr:
|
| 616 |
+
continue
|
| 617 |
+
d = (a[dr] - b[dr]) * (-1.0 if lower_better else 1.0) # > 0: LoRA better
|
| 618 |
+
nL, nO = int((d > 0).sum()), int((d < 0).sum())
|
| 619 |
+
nT = len(dr) - nL - nO
|
| 620 |
+
mdiff = float(a[dr].mean() - b[dr].mean())
|
| 621 |
+
if 2 * nT >= len(dr) or abs(mdiff) < min_margin:
|
| 622 |
+
verdict = "tie"
|
| 623 |
+
elif nL >= WIN_FRAC * len(dr):
|
| 624 |
+
verdict = "lora"
|
| 625 |
+
elif nO >= WIN_FRAC * len(dr):
|
| 626 |
+
verdict = "other"
|
| 627 |
+
else:
|
| 628 |
+
verdict = "split"
|
| 629 |
+
res[ds] = dict(lora=float(a[dr].mean()), other=float(b[dr].mean()), n=len(dr), n_lora=nL, n_other=nO,
|
| 630 |
+
n_tie=nT, verdict=verdict, draws=dr)
|
| 631 |
+
return res
|
| 632 |
+
|
| 633 |
+
|
| 634 |
+
def l1_vs_zeroshot_per_donor(ds):
|
| 635 |
+
"""LoRA-5 minus zero-shot (raw real bulk, arm zs_raw) composition L1, averaged per donor over every draw the
|
| 636 |
+
donor was tested in, then a Wilcoxon signed-rank test over donors (units repeat across draws, so donor-draw
|
| 637 |
+
rows are not independent). The donor-draw row test is returned too, for the CSV only."""
|
| 638 |
+
s2d = dict(zip(usable_folds(ds).sample_id, usable_folds(ds).donor_id))
|
| 639 |
+
parts = []
|
| 640 |
+
for j, p in mf.draw_dirs(SCORES / ds / "fewshot_n5"):
|
| 641 |
+
pdn = pd.read_csv(p / "per_donor.csv", usecols=["arm", "donor", "comp_l1"])
|
| 642 |
+
w = pdn[pdn.arm.isin(["lora5", "zs_raw"])].pivot(index="donor", columns="arm", values="comp_l1")
|
| 643 |
+
if w[["lora5", "zs_raw"]].isna().any().any():
|
| 644 |
+
raise ValueError(f"{p}: per_donor.csv lacks lora5 or zs_raw rows for some donors")
|
| 645 |
+
x = (w["lora5"] - w["zs_raw"]).rename("diff").reset_index()
|
| 646 |
+
x["draw"] = j
|
| 647 |
+
parts.append(x)
|
| 648 |
+
x = pd.concat(parts)
|
| 649 |
+
x["donor_id"] = x["donor"].astype(str).map(s2d)
|
| 650 |
+
if x["donor_id"].isna().any():
|
| 651 |
+
raise ValueError(f"{ds}: per_donor units missing from folds.csv")
|
| 652 |
+
per = x.groupby("donor_id")["diff"].mean()
|
| 653 |
+
return dict(n_donors=int(len(per)), n_rows=int(len(x)), mean_diff=float(per.mean()),
|
| 654 |
+
frac_better=float((per < 0).mean()), p=float(wilcoxon(per).pvalue),
|
| 655 |
+
row_mean_diff=float(x["diff"].mean()), row_p=float(wilcoxon(x["diff"]).pvalue),
|
| 656 |
+
source=f"{SCORES / ds / 'fewshot_n5'}/draw<j>/per_donor.csv (comp_l1, arms lora5 / zs_raw); "
|
| 657 |
+
f"{DATA / ds / 'folds.csv'} (sample -> donor)")
|
| 658 |
+
|
| 659 |
+
|
| 660 |
+
# ------------------------------------------------------------------------------------------
|
| 661 |
+
# Slide b: 5 donors, cells
|
| 662 |
+
# ------------------------------------------------------------------------------------------
|
| 663 |
+
def fig_fewpair_cells(few, info):
|
| 664 |
+
arms = ["zs_raw", "scsemi5", "lora"]
|
| 665 |
+
metrics = [("coverage", "Coverage ↑", (0, 1.0), [0, 0.5, 1.0]),
|
| 666 |
+
("precision", "Precision ↑", (0, 1.0), [0, 0.5, 1.0]),
|
| 667 |
+
("comp_l1", "Composition L1 ↓", None, None)]
|
| 668 |
+
nd_all = {info[d]["n_draws"] for d in ORDER}
|
| 669 |
+
per_row = len(nd_all) > 1
|
| 670 |
+
fig, axs = grid(len(ORDER), len(metrics), style.FULL, left=LEFT_IN, right=0.15, top=0.45, bottom=1.25,
|
| 671 |
+
hspace=0.22, wspace=0.10)
|
| 672 |
+
l1max = 0.0
|
| 673 |
+
for i, ds in enumerate(ORDER):
|
| 674 |
+
nl = n_draws(few, ds, "lora")
|
| 675 |
+
ns = n_draws(few, ds, "scsemi5")
|
| 676 |
+
for j, (mk, _, _, _) in enumerate(metrics):
|
| 677 |
+
ax = axs[i, j]
|
| 678 |
+
st = hbars(ax, arms, lambda a: few_vals(few, ds, a, mk)[0], seed=17 * i + j)
|
| 679 |
+
ref = few_ref(few, ds, "pseudo", mk)[0]
|
| 680 |
+
ref_line(ax, ref, "pseudo", len(arms))
|
| 681 |
+
if mk == "comp_l1":
|
| 682 |
+
allv = [v for a in arms for v in few_vals(few, ds, a, mk)[0] if not np.isnan(v)] + [ref]
|
| 683 |
+
l1max = max([l1max, np.nanmax(allv)] + [m + sd for m, sd, n in st.values() if n])
|
| 684 |
+
elif max([v for a in arms for v in few_vals(few, ds, a, mk)[0] if not np.isnan(v)] + [ref]) > 1.0:
|
| 685 |
+
raise ValueError(f"{ds} {mk}: value above the fixed 0-1 axis")
|
| 686 |
+
if j == 0 and 0 < ns < nl:
|
| 687 |
+
m, sd, n = st["scsemi5"]
|
| 688 |
+
ax.text(max(m + sd, max(few_vals(few, ds, "scsemi5", mk)[0])) + 0.03, 1, f"{ns} of {nl} draws",
|
| 689 |
+
va="center", ha="left", fontsize=FS - 3, color="#8A5A00")
|
| 690 |
+
row_label(axs[i, 0], ROWNAME[ds], row_subs(info[ds], per_row))
|
| 691 |
+
label_header(axs[0, 0], "pairs per draw")
|
| 692 |
+
for j, (mk, lab, lim, ticks) in enumerate(metrics):
|
| 693 |
+
if lim is None: # raw zero-shot L1 reaches ~0.8: the axis follows the data (every draw dot and SD bar)
|
| 694 |
+
lim = (0, np.ceil(l1max * 1.08 * 10) / 10)
|
| 695 |
+
ticks = [round(t, 1) for t in np.arange(0, lim[1] + 1e-9, 0.2)]
|
| 696 |
+
shared_x(axs[:, j], lim[0], lim[1], lab, ticks)
|
| 697 |
+
handles = [patch("zs_raw"), patch("scsemi5"), patch("lora"), refh("pseudo"),
|
| 698 |
+
dot_handle(None if per_row else nd_all.pop())]
|
| 699 |
+
legend_bottom(fig, handles, ncol=3)
|
| 700 |
+
check_inside(fig, "sec09_fewpair_cells")
|
| 701 |
+
style.save(fig, "sec09_fewpair_cells", FIGDIR)
|
| 702 |
+
rows = long_rows("sec09_fewpair_cells", few, ORDER, arms, [m[0] for m in metrics] + ["precision_dm", "coverage_dm"],
|
| 703 |
+
{"coverage": ["pseudo"], "precision": ["pseudo"], "comp_l1": ["pseudo"]})
|
| 704 |
+
pd.DataFrame(rows).to_csv(OUTDATA / "sec09_fewpair_cells.csv", index=False, float_format="%.6g")
|
| 705 |
+
|
| 706 |
+
|
| 707 |
+
# ------------------------------------------------------------------------------------------
|
| 708 |
+
# Slide c: 5 donors, disease signal
|
| 709 |
+
# ------------------------------------------------------------------------------------------
|
| 710 |
+
def fmt_deg(v):
|
| 711 |
+
return f"{v:.1f}" if v < 10 else f"{v:.0f}"
|
| 712 |
+
|
| 713 |
+
|
| 714 |
+
def fig_fewpair_disease(few, info):
|
| 715 |
+
arms = ["zs_raw", "scsemi5", "lora"]
|
| 716 |
+
nd_all = {info[d]["n_draws"] for d in DISEASE}
|
| 717 |
+
per_row = len(nd_all) > 1
|
| 718 |
+
fig, axs = grid(len(DISEASE), 2, style.TALL, left=LEFT_IN, right=0.25, top=0.45, bottom=1.55,
|
| 719 |
+
hspace=0.45, wspace=0.12)
|
| 720 |
+
rmin, rmax = 0.0, 0.0
|
| 721 |
+
for i, ds in enumerate(DISEASE):
|
| 722 |
+
nl = n_draws(few, ds, "lora")
|
| 723 |
+
ns = n_draws(few, ds, "scsemi5")
|
| 724 |
+
# logFC r
|
| 725 |
+
ax = axs[i, 0]
|
| 726 |
+
hbars(ax, arms, lambda a: few_vals(few, ds, a, "contrast_r")[0], seed=31 * i)
|
| 727 |
+
bc = few_ref(few, ds, "broadcast", "contrast_r")[0]
|
| 728 |
+
ref_line(ax, bc, "broadcast", len(arms))
|
| 729 |
+
ax.axvline(0, color="#555555", lw=0.8, zorder=1)
|
| 730 |
+
ax.spines["left"].set_visible(False)
|
| 731 |
+
allv = [v for a in arms for v in few_vals(few, ds, a, "contrast_r")[0] if not np.isnan(v)] + [bc]
|
| 732 |
+
rmin, rmax = min(rmin, min(allv)), max(rmax, max(allv))
|
| 733 |
+
if ns < nl:
|
| 734 |
+
ax.text(1.0, 1, f"{ns} of {nl} draws", transform=ax.get_yaxis_transform(), va="center", ha="right",
|
| 735 |
+
fontsize=FS - 3, color="#8A5A00")
|
| 736 |
+
# top-50 DEG, own scale per cohort
|
| 737 |
+
ax = axs[i, 1]
|
| 738 |
+
st = hbars(ax, arms, lambda a: few_vals(few, ds, a, "deg")[0], seed=37 * i)
|
| 739 |
+
bcd = few_ref(few, ds, "broadcast", "deg")[0]
|
| 740 |
+
ref_line(ax, bcd, "broadcast", len(arms))
|
| 741 |
+
hi = max([bcd] + [v for a in arms for v in few_vals(few, ds, a, "deg")[0] if not np.isnan(v)])
|
| 742 |
+
hi = max(hi, 4.0)
|
| 743 |
+
ax.set_xlim(0, hi * 1.40)
|
| 744 |
+
ax.xaxis.set_major_locator(MaxNLocator(nbins=3, integer=True))
|
| 745 |
+
for k, a in enumerate(arms):
|
| 746 |
+
m, sd, n = st[a]
|
| 747 |
+
if n:
|
| 748 |
+
ax.text(0.995, k, fmt_deg(m), transform=ax.get_yaxis_transform(), va="center", ha="right",
|
| 749 |
+
fontsize=FS - 3, color=SUB)
|
| 750 |
+
row_label(axs[i, 0], ROWNAME[ds], row_subs(info[ds], per_row))
|
| 751 |
+
label_header(axs[0, 0], "pairs per draw")
|
| 752 |
+
lo = min(-0.1, np.floor(rmin * 10) / 10)
|
| 753 |
+
hi = max(0.9, np.ceil(rmax * 10) / 10 + 0.05)
|
| 754 |
+
shared_x(axs[:, 0], lo, hi, "Disease logFC r ↑", [0, 0.4, 0.8])
|
| 755 |
+
axs[-1, 1].set_xlabel("Top-50 DEG overlap ↑")
|
| 756 |
+
for ax in axs[:, 1]:
|
| 757 |
+
ax.tick_params(axis="x", labelsize=FS - 3)
|
| 758 |
+
handles = [patch("zs_raw"), patch("scsemi5"), patch("lora"), refh("broadcast"),
|
| 759 |
+
dot_handle(None if per_row else nd_all.pop())]
|
| 760 |
+
legend_bottom(fig, handles, ncol=2)
|
| 761 |
+
check_inside(fig, "sec09_fewpair_disease")
|
| 762 |
+
style.save(fig, "sec09_fewpair_disease", FIGDIR)
|
| 763 |
+
rows = long_rows("sec09_fewpair_disease", few, DISEASE, arms, ["contrast_r", "deg"],
|
| 764 |
+
{"contrast_r": ["broadcast"], "deg": ["broadcast"]})
|
| 765 |
+
pd.DataFrame(rows).to_csv(OUTDATA / "sec09_fewpair_disease.csv", index=False, float_format="%.6g")
|
| 766 |
+
|
| 767 |
+
|
| 768 |
+
# ------------------------------------------------------------------------------------------
|
| 769 |
+
# Slide d: all pairs, 5-fold pooled
|
| 770 |
+
# ------------------------------------------------------------------------------------------
|
| 771 |
+
def baselines_text(vals):
|
| 772 |
+
"""'0.11' when both baselines round to the same 2 decimals, else '0.10–0.12'."""
|
| 773 |
+
s = sorted({f"{v:.2f}" for v in vals})
|
| 774 |
+
return s[0] if len(s) == 1 else f"{s[0]}–{s[-1]}"
|
| 775 |
+
|
| 776 |
+
|
| 777 |
+
def fig_fivefold(pooled, tab):
|
| 778 |
+
arms = ["zs_raw", "sconly", "lora"]
|
| 779 |
+
metrics = [("coverage", "Coverage ↑"), ("contrast_r", "Disease logFC r ↑"), ("deg", "Top-50 DEG overlap ↑")]
|
| 780 |
+
fig, axs = grid(len(ORDER), 3, style.FULL, left=LEFT_IN, right=0.35, top=0.45, bottom=1.25,
|
| 781 |
+
hspace=0.40, wspace=0.12)
|
| 782 |
+
rows = []
|
| 783 |
+
ji_note = None
|
| 784 |
+
tabi = tab.set_index("dataset")
|
| 785 |
+
|
| 786 |
+
def src(m, mk):
|
| 787 |
+
return m.get("deg_source", m["source"]) if mk == "deg" else m["source"]
|
| 788 |
+
|
| 789 |
+
for i, ds in enumerate(ORDER):
|
| 790 |
+
P = pooled[ds]
|
| 791 |
+
for j, (mk, _) in enumerate(metrics):
|
| 792 |
+
ax = axs[i, j]
|
| 793 |
+
if ds == "ji2025_chili":
|
| 794 |
+
ax.set_facecolor(HILITE)
|
| 795 |
+
if mk in ("contrast_r", "deg") and ds == "immicro":
|
| 796 |
+
blank(ax, "healthy cohort: no contrast")
|
| 797 |
+
continue
|
| 798 |
+
hbars(ax, arms, lambda a: [P[POOLED_ARMS[a]][mk]], dots=False)
|
| 799 |
+
for a in arms:
|
| 800 |
+
rows.append({"figure": "sec09_fivefold", "dataset": ds, "metric": mk, "series": a,
|
| 801 |
+
"arm_file": POOLED_ARMS[a], "value": P[POOLED_ARMS[a]][mk],
|
| 802 |
+
"n_scored": P[POOLED_ARMS[a]]["n_scored"], "source": src(P[POOLED_ARMS[a]], mk)})
|
| 803 |
+
if mk == "coverage":
|
| 804 |
+
ref = P["zs__pseudo"]["coverage"]
|
| 805 |
+
ref_line(ax, ref, "pseudo", len(arms))
|
| 806 |
+
rows.append({"figure": "sec09_fivefold", "dataset": ds, "metric": mk, "series": "ref_pseudo",
|
| 807 |
+
"arm_file": "zs__pseudo", "value": ref, "source": P["zs__pseudo"]["source"]})
|
| 808 |
+
else:
|
| 809 |
+
m = P["real_lora__raw"]
|
| 810 |
+
ref = m["broadcast_r"] if mk == "contrast_r" else m["deg_broadcast"]
|
| 811 |
+
ref_line(ax, ref, "broadcast", len(arms))
|
| 812 |
+
rows.append({"figure": "sec09_fivefold", "dataset": ds, "metric": mk, "series": "ref_broadcast",
|
| 813 |
+
"arm_file": "real_lora__raw (raw real bulk)", "value": ref, "source": src(m, mk)})
|
| 814 |
+
if mk == "deg":
|
| 815 |
+
hi = max([ref] + [P[POOLED_ARMS[a]]["deg"] for a in arms] + [4.0])
|
| 816 |
+
ax.set_xlim(0, hi * 1.25)
|
| 817 |
+
ax.xaxis.set_major_locator(MaxNLocator(nbins=3, integer=True))
|
| 818 |
+
ax.tick_params(axis="x", labelsize=FS - 3)
|
| 819 |
+
for k, a in enumerate(arms):
|
| 820 |
+
v = P[POOLED_ARMS[a]]["deg"]
|
| 821 |
+
ax.text(v + hi * 0.03, k, f"{v:.0f}", va="center", ha="left", fontsize=FS - 3, color=SUB)
|
| 822 |
+
if mk == "contrast_r":
|
| 823 |
+
ax.axvline(0, color="#555555", lw=0.8, zorder=1)
|
| 824 |
+
ax.spines["left"].set_visible(False)
|
| 825 |
+
if ds == "ji2025_chili" and mk == "coverage":
|
| 826 |
+
v_zs = P[POOLED_ARMS["zs_raw"]]["coverage"]
|
| 827 |
+
v_sc = P[POOLED_ARMS["sconly"]]["coverage"]
|
| 828 |
+
v_lo = P[POOLED_ARMS["lora"]]["coverage"]
|
| 829 |
+
txt = ax.text(max(v_zs, v_sc) + 0.03, 0.5, f"baselines {baselines_text([v_zs, v_sc])}",
|
| 830 |
+
va="center", ha="left", fontsize=FS - 2, color="#5A5A5A")
|
| 831 |
+
ji_note = (txt, ax, P["zs__pseudo"]["coverage"])
|
| 832 |
+
ax.text(v_lo + 0.02, 2, f"{v_lo:.2f}", va="center", ha="left", fontsize=FS - 3, color=SUB)
|
| 833 |
+
n = P["real_lora__raw"]["n_scored"]
|
| 834 |
+
nd = int(tabi.loc[ds, "n_donors"])
|
| 835 |
+
if int(tabi.loc[ds, "n_rows"]) != int(n):
|
| 836 |
+
raise ValueError(f"{ds}: pooled n {n} != usable rows")
|
| 837 |
+
row_label(axs[i, 0], ROWNAME[ds], [f"n={n}" + (f" ({nd} donors)" if nd != n else "")])
|
| 838 |
+
shared_x(axs[:, 0], 0, 1.0, metrics[0][1], [0, 0.5, 1.0])
|
| 839 |
+
# the Ji annotation must end left of the pseudobulk reference line (checked on the final x scale)
|
| 840 |
+
txt, ax, ref = ji_note
|
| 841 |
+
fig.canvas.draw()
|
| 842 |
+
x1 = ax.transData.inverted().transform(txt.get_window_extent(fig.canvas.get_renderer()))[1, 0]
|
| 843 |
+
if x1 >= ref - 0.01:
|
| 844 |
+
raise ValueError(f"Ji annotation ends at {x1:.2f}, over the pseudobulk reference line at {ref:.2f}")
|
| 845 |
+
rvals = [r["value"] for r in rows if r["metric"] == "contrast_r"]
|
| 846 |
+
shared_x(axs[1:, 1], min(-0.1, np.floor(min(rvals) * 10) / 10), max(0.9, np.ceil(max(rvals) * 10) / 10),
|
| 847 |
+
metrics[1][1], [0, 0.4, 0.8])
|
| 848 |
+
axs[-1, 2].set_xlabel(metrics[2][1])
|
| 849 |
+
handles = [patch("zs_raw"), patch("sconly"), patch("lora", LAB["lora_all"]), refh("pseudo"),
|
| 850 |
+
refh("broadcast")]
|
| 851 |
+
legend_bottom(fig, handles, ncol=3)
|
| 852 |
+
check_inside(fig, "sec09_fivefold")
|
| 853 |
+
style.save(fig, "sec09_fivefold", FIGDIR)
|
| 854 |
+
pd.DataFrame(rows).to_csv(OUTDATA / "sec09_fivefold.csv", index=False, float_format="%.6g")
|
| 855 |
+
return rows
|
| 856 |
+
|
| 857 |
+
|
| 858 |
+
# ------------------------------------------------------------------------------------------
|
| 859 |
+
# Slide text: every keyword / footnote / quoted number is built here from the same data
|
| 860 |
+
# ------------------------------------------------------------------------------------------
|
| 861 |
+
BANNED = ("novel", "powerful", "robust", "state-of-the-art", "seamless", "leverage")
|
| 862 |
+
|
| 863 |
+
|
| 864 |
+
def n_words(s):
|
| 865 |
+
return sum(1 for t in s.split() if re.search(r"[A-Za-z0-9]", t))
|
| 866 |
+
|
| 867 |
+
|
| 868 |
+
def check_text(s, what):
|
| 869 |
+
if any(b in s.lower() for b in BANNED) or re.search(r"[가-힣]", s):
|
| 870 |
+
raise ValueError(f"banned word / Korean in {what}: {s!r}")
|
| 871 |
+
if OFF_STORY.search(s):
|
| 872 |
+
raise ValueError(f"off-story (input adjustment) wording in {what}: {s!r}")
|
| 873 |
+
return s
|
| 874 |
+
|
| 875 |
+
|
| 876 |
+
def check_keywords(kws):
|
| 877 |
+
if len(kws) > 3:
|
| 878 |
+
raise ValueError(f"more than 3 keyword lines: {kws}")
|
| 879 |
+
for k in kws:
|
| 880 |
+
if n_words(k) > 7:
|
| 881 |
+
raise ValueError(f"keyword over 7 words: {k!r}")
|
| 882 |
+
if len(k) > KW_MAX_CHARS:
|
| 883 |
+
raise ValueError(f"keyword over {KW_MAX_CHARS} characters ({len(k)}): {k!r}")
|
| 884 |
+
check_text(k, "keyword")
|
| 885 |
+
return kws
|
| 886 |
+
|
| 887 |
+
|
| 888 |
+
def check_foot_short(s):
|
| 889 |
+
"""One on-slide line: <= FOOT_SHORT_MAX characters, no file paths."""
|
| 890 |
+
if len(s) > FOOT_SHORT_MAX or "\n" in s:
|
| 891 |
+
raise ValueError(f"footnote_short over {FOOT_SHORT_MAX} characters ({len(s)}): {s!r}")
|
| 892 |
+
if re.search(r"/home|\b(scores|data|runs|tools|figures)/|\.(json|csv|npz|md|py|pt)\b", s):
|
| 893 |
+
raise ValueError(f"file path in footnote_short: {s!r}")
|
| 894 |
+
return check_text(s, "footnote_short")
|
| 895 |
+
|
| 896 |
+
|
| 897 |
+
def keyword_or_short(long, short):
|
| 898 |
+
"""The long wording when it fits a keyword line, else the short one (both computed from the same numbers)."""
|
| 899 |
+
return long if len(long) <= KW_MAX_CHARS else short
|
| 900 |
+
|
| 901 |
+
|
| 902 |
+
def names(dss):
|
| 903 |
+
return ", ".join(NAME[d] for d in dss)
|
| 904 |
+
|
| 905 |
+
|
| 906 |
+
def fmt_p(p):
|
| 907 |
+
return f"{p:.0e}" if p < 0.01 else f"{p:.2f}"
|
| 908 |
+
|
| 909 |
+
|
| 910 |
+
def main():
|
| 911 |
+
FIGDIR.mkdir(parents=True, exist_ok=True)
|
| 912 |
+
OUTDATA.mkdir(parents=True, exist_ok=True)
|
| 913 |
+
|
| 914 |
+
tab = cohort_rows()
|
| 915 |
+
tab.to_csv(OUTDATA / "sec09_cohorts.csv", index=False)
|
| 916 |
+
fig_cohorts(tab)
|
| 917 |
+
|
| 918 |
+
few, status = fewpair()
|
| 919 |
+
info = {ds: draw_info(few, ds) for ds in ORDER}
|
| 920 |
+
pooled, calls = mf.load_pooled(SCORES)
|
| 921 |
+
fig_fewpair_cells(few, info)
|
| 922 |
+
fig_fewpair_disease(few, info)
|
| 923 |
+
fig_fivefold(pooled, tab)
|
| 924 |
+
|
| 925 |
+
used = status[status.status == "used"]
|
| 926 |
+
run_json = T / "runs" / "immicro" / "fewshot_n5" / "draw0" / "lora" / "RUN.json"
|
| 927 |
+
evidence(run_json, re.escape(CKPT)) # the few-pair LoRA runs start from the final checkpoint
|
| 928 |
+
steps = int(re.search(r'"fixed_steps": (\d+)', evidence(run_json, r'"fixed_steps": \d+')).group(1))
|
| 929 |
+
lora_r = re.search(r"LoRA r = (\d+)", evidence(README, r"LoRA r = \d+ \(1\.3 M")).group(1)
|
| 930 |
+
sampling = match_text(README, r"test donors only, 1,500 cells each, seed \d+, DDIM 50, EMA, Bernoulli read-out")
|
| 931 |
+
early = match_text(README, r"About 10 % of each fold's training donors are inner-validation, used only for early stopping")
|
| 932 |
+
pc_def = match_text(SCORE_FT, r"precision/coverage/density \(PCA-50 \+ k = 10 balls fitted on the scored donors' observed R1 cells\)")
|
| 933 |
+
pca_n = {int(jload(SCORES / ds / "fewshot_n5" / "draw0" / "summary.json")["reference"]["pca"]["n_components"])
|
| 934 |
+
for ds in ORDER}
|
| 935 |
+
if pca_n != {50}:
|
| 936 |
+
raise ValueError(f"PCA components differ from the footnote: {pca_n}")
|
| 937 |
+
ddef = jload(SCORES / "ji2025_chili" / "fewshot_n5" / "draw0" / "summary.json")["deg_definition"]
|
| 938 |
+
if not ("welch_bh_deg" in ddef["functions"] and ddef["top_n"] == 50 and len(ddef["types"]) == 5):
|
| 939 |
+
raise ValueError("DEG definition differs from the footnote")
|
| 940 |
+
n_types = len(ddef["types"])
|
| 941 |
+
base_src = f"{run_json}; {README}"
|
| 942 |
+
slides = []
|
| 943 |
+
|
| 944 |
+
# ---------------- slide a ----------------
|
| 945 |
+
tot_rows, tot_donors = int(tab.n_rows.sum()), int(tab.n_donors.sum())
|
| 946 |
+
n_all = int(tab.n_pairs_all.sum())
|
| 947 |
+
n_fail, n_bord, n_low = int(tab.n_identity_fail.sum()), int(tab.n_identity_borderline.sum()), int(tab.n_low_cells.sum())
|
| 948 |
+
ji = tab.set_index("dataset").loc["ji2025_chili"]
|
| 949 |
+
if not ji.bulk.startswith("whole blood"):
|
| 950 |
+
raise ValueError("Ji bulk label changed")
|
| 951 |
+
noflag = [NAME[d] for d in tab[~tab.identity_flag].dataset]
|
| 952 |
+
multi = [NAME[d] for d in tab[tab.n_rows != tab.n_donors].dataset]
|
| 953 |
+
kw_a = check_keywords([f"{tot_rows} paired samples, {tot_donors} donors",
|
| 954 |
+
"Only identity-pass pairs; donor-level splits",
|
| 955 |
+
"Ji bulk: whole blood, not PBMC"])
|
| 956 |
+
foot_a = (f"Usable pair = passed the pairing identity check and >= {int(tab.min_cells.iloc[0])} cells "
|
| 957 |
+
f"(fold >= 0 in data/<cohort>/folds.csv); dropped {n_fail} identity-fail, {n_bord} borderline and "
|
| 958 |
+
f"{n_low} low-cell pairs of {n_all}. {', '.join(noflag)}: no identity flag, all used. "
|
| 959 |
+
f"{', '.join(multi)}: several pairs per donor. Case vs control = samples in "
|
| 960 |
+
f"scores/<cohort>/pooled/summary.json. Giroux 'moderate' = GEO 'severe' (paper term). "
|
| 961 |
+
f"Labels: data/<cohort>/QC_REPORT.md; ImMicro: GEO GSE314922/GSE314416.")
|
| 962 |
+
num("a", f"{tot_rows} paired samples (sum of usable rows)", f"{DATA}/<cohort>/fewshot_n5/DRAWS.json (n_usable_rows)")
|
| 963 |
+
num("a", f"{tot_donors} donors (sum of usable donors)", f"{DATA}/<cohort>/fewshot_n5/DRAWS.json (n_usable_donors)")
|
| 964 |
+
num("a", f"dropped {n_fail} identity-fail, {n_bord} borderline, {n_low} < {int(tab.min_cells.iloc[0])} cells, of {n_all}",
|
| 965 |
+
f"{DATA}/<cohort>/features.npz (identity_pass, identity_check); samples.csv (n_cells); {PREPARE} (MIN_CELLS)")
|
| 966 |
+
for r in tab.itertuples():
|
| 967 |
+
v = f"{NAME[r.dataset]} {r.n_rows} pairs / {r.n_donors} donors"
|
| 968 |
+
s = r.n_rows_source
|
| 969 |
+
if r.case_label:
|
| 970 |
+
v += f"; {r.case_label} {int(r.n_case)} vs {r.control_label} {int(r.n_control)}"
|
| 971 |
+
if r.n_neither:
|
| 972 |
+
v += f" (+{r.n_neither} {r.neither_label}, neither)"
|
| 973 |
+
s += f"; {r.contrast_source}"
|
| 974 |
+
num("a", v, s)
|
| 975 |
+
fs_a = check_foot_short(f"Usable pair = passed identity check and ≥ {int(tab.min_cells.iloc[0])} cells: "
|
| 976 |
+
f"{tot_rows} of {n_all} pairs; donor-level splits.")
|
| 977 |
+
slides.append({"title": "Five paired cohorts", "layout": "full",
|
| 978 |
+
"figures": [str(FIGDIR / "sec09_cohorts.png")], "keywords": kw_a, "footnote": foot_a,
|
| 979 |
+
"footnote_short": fs_a, "numbers": NUMS["a"]})
|
| 980 |
+
|
| 981 |
+
# ---------------- slide b ----------------
|
| 982 |
+
mk_b = (("coverage", False), ("precision", False), ("comp_l1", True), ("coverage_dm", False),
|
| 983 |
+
("precision_dm", False))
|
| 984 |
+
cmp_b = {mk: same_draw_compare(few, status, ORDER, mk, lower) for mk, lower in mk_b}
|
| 985 |
+
cmp_bz = {mk: same_draw_compare(few, status, ORDER, mk, lower, other="zs_raw") for mk, lower in mk_b}
|
| 986 |
+
wins = {mk: sum(v["verdict"] == "lora" for v in c.values()) for mk, c in cmp_b.items()}
|
| 987 |
+
wins_z = {mk: sum(v["verdict"] == "lora" for v in c.values()) for mk, c in cmp_bz.items()}
|
| 988 |
+
ncoh = {mk: len(c) for mk, c in cmp_b.items()}
|
| 989 |
+
if ncoh["coverage"] != len(ORDER):
|
| 990 |
+
raise ValueError("a cohort has no shared scSemiProfiler draw")
|
| 991 |
+
if any(len(c) != len(ORDER) for c in cmp_bz.values()):
|
| 992 |
+
raise ValueError("a cohort has no zero-shot draw")
|
| 993 |
+
nb = len(ORDER)
|
| 994 |
+
if wins["coverage"] == wins["precision"]:
|
| 995 |
+
kw_b1 = f"LoRA-5 > scSemi-5: coverage, precision {wins['coverage']}/{nb}"
|
| 996 |
+
else:
|
| 997 |
+
kw_b1 = f"Beats scSemi-5: coverage {wins['coverage']}/{nb}, precision {wins['precision']}/{nb}"
|
| 998 |
+
|
| 999 |
+
def span(v):
|
| 1000 |
+
return f"{min(v):.2f}–{max(v):.2f}"
|
| 1001 |
+
|
| 1002 |
+
cov_mean = {a: [float(np.mean(few_vals(few, d, a, "coverage")[0])) for d in ORDER]
|
| 1003 |
+
for a in ("lora", "scsemi5", "zs_raw")}
|
| 1004 |
+
kw_b2 = f"LoRA-5 coverage {span(cov_mean['lora'])}; scSemi-5 {span(cov_mean['scsemi5'])}"
|
| 1005 |
+
l1t = {ds: l1_vs_zeroshot_per_donor(ds) for ds in ORDER}
|
| 1006 |
+
gain = [d for d in ORDER if l1t[d]["p"] < 0.05 and l1t[d]["mean_diff"] < 0]
|
| 1007 |
+
others = [d for d in ORDER if d not in gain]
|
| 1008 |
+
if not gain:
|
| 1009 |
+
kw_b3 = "No composition gain vs zero-shot"
|
| 1010 |
+
elif not others:
|
| 1011 |
+
kw_b3 = "Lower L1 than zero-shot: all cohorts"
|
| 1012 |
+
elif len(gain) >= len(others):
|
| 1013 |
+
kw_b3 = keyword_or_short(f"Lower L1 than zero-shot: all but {names(others)}",
|
| 1014 |
+
f"Lower L1 than zero-shot: {len(gain)}/{nb}")
|
| 1015 |
+
else:
|
| 1016 |
+
kw_b3 = keyword_or_short(f"Lower L1 than zero-shot: {names(gain)} only",
|
| 1017 |
+
f"Lower L1 than zero-shot: {len(gain)}/{nb}")
|
| 1018 |
+
kw_b = check_keywords([kw_b1, kw_b2, kw_b3])
|
| 1019 |
+
l1_split = [d for d, v in cmp_b["comp_l1"].items() if v["verdict"] != "lora"]
|
| 1020 |
+
dm_c = {a: [cmp_b["coverage_dm"][d][k] for d in ORDER] for a, k in (("lora", "lora"), ("scsemi5", "other"))}
|
| 1021 |
+
if wins["coverage_dm"] != wins["coverage"] or wins["precision_dm"] != wins["precision"]:
|
| 1022 |
+
raise ValueError("depth-matched ranking differs from raw P/C: rewrite the 'same ranking' footnote")
|
| 1023 |
+
tr_all = [x for d in ORDER for x in info[d]["n_train"]]
|
| 1024 |
+
missing = status[status.status != "used"]
|
| 1025 |
+
miss_txt = ", ".join(f"{NAME[r.dataset]} draw{r.draw}" for r in missing.itertuples())
|
| 1026 |
+
ns_used, ns_all = len(used), len(status)
|
| 1027 |
+
zs_pc = (f"coverage {wins_z['coverage']}/{nb}, precision {wins_z['precision']}/{nb}, "
|
| 1028 |
+
f"depth-matched {wins_z['coverage_dm']}/{nb} and {wins_z['precision_dm']}/{nb}")
|
| 1029 |
+
foot_b = (f"Base f01 6k·1x·E16 (EMA, DDIM 50) + LoRA r={lora_r}, {steps:,} steps. LoRA-5 / scSemi-5 = LoRA / "
|
| 1030 |
+
f"scSemiProfiler trained on the same 5 donors ({min(tr_all)}–{max(tr_all)} pairs); test = all other usable "
|
| 1031 |
+
f"pairs. Zero-shot = base model without fine-tuning, fed each test pair's real bulk as measured (same "
|
| 1032 |
+
f"call as LoRA-5). scSemi-5 scored in a separate call, same test set and reference (sha-checked); "
|
| 1033 |
+
f"{ns_used}/{ns_all} draws" + (f" (missing: {miss_txt})" if len(missing) else "") + ". "
|
| 1034 |
+
f"Verdict = better in >= 80% of shared draws. LoRA-5 lower L1 than scSemi-5 in {wins['comp_l1']}/{nb}"
|
| 1035 |
+
+ (f" ({', '.join(f'{NAME[d]} {cmp_b['comp_l1'][d]['verdict']} {cmp_b['comp_l1'][d]['n_lora']}/{cmp_b['comp_l1'][d]['n']}' for d in l1_split)})"
|
| 1036 |
+
if l1_split else "")
|
| 1037 |
+
+ f". LoRA-5 > zero-shot: {zs_pc} cohorts. Depth-matched P/C vs scSemi-5: same ranking, coverage "
|
| 1038 |
+
f"LoRA-5 {span(dm_c['lora'])} vs scSemi-5 {span(dm_c['scsemi5'])}. L1 LoRA-5 minus zero-shot, per-donor "
|
| 1039 |
+
f"Wilcoxon (gain = p < 0.05): " + ", ".join(f"{NAME[d]} {l1t[d]['mean_diff']:+.2f} (p {fmt_p(l1t[d]['p'])})"
|
| 1040 |
+
for d in ORDER)
|
| 1041 |
+
+ ". scANVI labels; P/C = PCA-50, k=10 balls. Scores: scores/<cohort>/fewshot_n5/.")
|
| 1042 |
+
nd_b = sorted({info[d]["n_draws"] for d in ORDER})
|
| 1043 |
+
fs_b = check_foot_short(f"{rng(nd_b)} draws per cohort; test = all other usable pairs. Zero-shot = base model "
|
| 1044 |
+
f"on real bulk. scANVI labels.")
|
| 1045 |
+
scs = f"{SCORES}/<cohort>/fewshot_n5/draw<j>/summary.json and draw<j>_scsemi5/summary.json"
|
| 1046 |
+
for mk in ("coverage", "precision", "comp_l1", "coverage_dm", "precision_dm"):
|
| 1047 |
+
c = cmp_b[mk]
|
| 1048 |
+
num("b", f"LoRA-5 vs scSemi-5 {mk} (shared-draw means; LoRA-better draws/n; verdict): " +
|
| 1049 |
+
"; ".join(f"{NAME[d]} {v['lora']:.3f} vs {v['other']:.3f} ({v['n_lora']}/{v['n']}, {v['verdict']})"
|
| 1050 |
+
for d, v in c.items()) + f" -> LoRA verdicts {wins[mk]}/{ncoh[mk]}", scs)
|
| 1051 |
+
for mk in ("coverage", "precision", "comp_l1", "coverage_dm", "precision_dm"):
|
| 1052 |
+
c = cmp_bz[mk]
|
| 1053 |
+
num("b", f"LoRA-5 vs zero-shot (real bulk) {mk} (same-draw means; LoRA-better draws/n; verdict): " +
|
| 1054 |
+
"; ".join(f"{NAME[d]} {v['lora']:.3f} vs {v['other']:.3f} ({v['n_lora']}/{v['n']}, {v['verdict']})"
|
| 1055 |
+
for d, v in c.items()) + f" -> LoRA verdicts {wins_z[mk]}/{len(c)}",
|
| 1056 |
+
f"{SCORES}/<cohort>/fewshot_n5/draw<j>/summary.json (arms lora5, zs_raw)")
|
| 1057 |
+
num("b", "coverage cohort means over all draws: " + "; ".join(
|
| 1058 |
+
f"{lab} " + ", ".join(f"{NAME[d]} {v:.3f}" for d, v in zip(ORDER, cov_mean[a]))
|
| 1059 |
+
for a, lab in (("lora", "LoRA-5"), ("scsemi5", "scSemi-5"), ("zs_raw", "zero-shot"))), scs)
|
| 1060 |
+
num("b", "LoRA-5 minus zero-shot (real bulk) composition L1, per-donor Wilcoxon (draw-averaged): " +
|
| 1061 |
+
"; ".join(f"{NAME[d]} {v['mean_diff']:+.3f}, n={v['n_donors']}, p={v['p']:.2g}" for d, v in l1t.items()) +
|
| 1062 |
+
f" -> gain in {len(gain)}/{nb}",
|
| 1063 |
+
f"{SCORES}/<cohort>/fewshot_n5/draw<j>/per_donor.csv; {DATA}/<cohort>/folds.csv")
|
| 1064 |
+
num("b", "scSemiProfiler draws used / LoRA draws: " +
|
| 1065 |
+
", ".join(f"{NAME[d]} {int((used.dataset == d).sum())}/{n_draws(few, d, 'lora')}" for d in ORDER),
|
| 1066 |
+
OUTDATA / "sec09_scsemi_status.csv")
|
| 1067 |
+
num("b", "training pairs per draw: " + ", ".join(f"{NAME[d]} {info[d]['train']}" for d in ORDER) +
|
| 1068 |
+
"; test pairs: " + ", ".join(f"{NAME[d]} {info[d]['test']}" for d in ORDER),
|
| 1069 |
+
f"{DATA}/<cohort>/fewshot_n5/DRAWS.json (n_train_rows, n_test_rows)")
|
| 1070 |
+
num("b", f"LoRA r = {lora_r}; {steps} fixed steps; base {CKPT}; sampling: {sampling}", base_src)
|
| 1071 |
+
num("b", f"P/C definition: {pc_def}; PCA components in every summary.json = 50", SCORE_FT)
|
| 1072 |
+
for ds in ORDER:
|
| 1073 |
+
extra("b", f"{ds} LoRA-5 minus zero-shot (real bulk) L1, Wilcoxon over donor-draw rows (pseudo-replicated; "
|
| 1074 |
+
f"not quoted, replaced by the per-donor test)",
|
| 1075 |
+
f"{l1t[ds]['row_mean_diff']:+.3f}, n={l1t[ds]['n_rows']}, p {l1t[ds]['row_p']:.2g}", l1t[ds]["source"])
|
| 1076 |
+
slides.append({"title": "5 donors: LoRA vs scSemiProfiler — cells", "layout": "full",
|
| 1077 |
+
"figures": [str(FIGDIR / "sec09_fewpair_cells.png")], "keywords": kw_b, "footnote": foot_b,
|
| 1078 |
+
"footnote_short": fs_b, "numbers": NUMS["b"]})
|
| 1079 |
+
|
| 1080 |
+
# ---------------- slide c ----------------
|
| 1081 |
+
cmp_r = same_draw_compare(few, status, DISEASE, "contrast_r")
|
| 1082 |
+
cmp_d = same_draw_compare(few, status, DISEASE, "deg", min_margin=1.0)
|
| 1083 |
+
cmp_rz = same_draw_compare(few, status, DISEASE, "contrast_r", other="zs_raw")
|
| 1084 |
+
cmp_dz = same_draw_compare(few, status, DISEASE, "deg", min_margin=1.0, other="zs_raw")
|
| 1085 |
+
deg_l = [d for d, v in cmp_d.items() if v["verdict"] == "lora"]
|
| 1086 |
+
deg_tie = [d for d, v in cmp_d.items() if v["verdict"] == "tie"]
|
| 1087 |
+
deg_other = [d for d, v in cmp_d.items() if v["verdict"] not in ("lora", "tie")]
|
| 1088 |
+
near0 = [d for d in deg_tie if max(cmp_d[d]["lora"], cmp_d[d]["other"]) < 1.0]
|
| 1089 |
+
kw_c1 = f"Top-50 DEG: LoRA-5 > scSemi-5 {len(deg_l)}/{len(cmp_d)}"
|
| 1090 |
+
kw_c1_short = kw_c1 + (f", tied {len(deg_tie)}" if deg_tie else "")
|
| 1091 |
+
if near0:
|
| 1092 |
+
kw_c1 += f"; {names(near0)} ~0"
|
| 1093 |
+
if [d for d in deg_tie if d not in near0]:
|
| 1094 |
+
kw_c1 += f"; {names([d for d in deg_tie if d not in near0])} tied"
|
| 1095 |
+
if deg_other:
|
| 1096 |
+
kw_c1 += f"; {names(deg_other)} not"
|
| 1097 |
+
kw_c1 = keyword_or_short(kw_c1, kw_c1_short)
|
| 1098 |
+
r_s = [d for d, v in cmp_r.items() if v["verdict"] == "other"]
|
| 1099 |
+
r_split = [d for d, v in cmp_r.items() if v["verdict"] in ("split", "tie")]
|
| 1100 |
+
r_l = [d for d, v in cmp_r.items() if v["verdict"] == "lora"]
|
| 1101 |
+
parts = []
|
| 1102 |
+
if r_s:
|
| 1103 |
+
parts.append(f"scSemi-5 wins {names(r_s)}")
|
| 1104 |
+
if r_split:
|
| 1105 |
+
parts.append(f"{names(r_split)} split")
|
| 1106 |
+
kw_c2_short = f"logFC r: LoRA-5 > scSemi-5 {len(r_l)}/{len(cmp_r)}"
|
| 1107 |
+
kw_c2 = keyword_or_short(("logFC r: " + "; ".join(parts)) if parts else kw_c2_short, kw_c2_short)
|
| 1108 |
+
arms3 = ("zs_raw", "scsemi5", "lora")
|
| 1109 |
+
|
| 1110 |
+
def arm_mean(ds, a, mk):
|
| 1111 |
+
v = [x for x in few_vals(few, ds, a, mk)[0] if not np.isnan(x)]
|
| 1112 |
+
return float(np.mean(v)) if v else np.nan
|
| 1113 |
+
|
| 1114 |
+
bc_all = [d for d in DISEASE
|
| 1115 |
+
if few_ref(few, d, "broadcast", "contrast_r")[0] > np.nanmax([arm_mean(d, a, "contrast_r") for a in arms3])
|
| 1116 |
+
and few_ref(few, d, "broadcast", "deg")[0] > np.nanmax([arm_mean(d, a, "deg") for a in arms3])]
|
| 1117 |
+
kw_c3 = (keyword_or_short(f"{names(bc_all)}: real-bulk broadcast beats all arms",
|
| 1118 |
+
f"Broadcast beats all arms: {len(bc_all)}/{len(DISEASE)}")
|
| 1119 |
+
if bc_all else "Every cohort: some arm beats broadcast")
|
| 1120 |
+
kw_c = check_keywords([kw_c1, kw_c2, kw_c3])
|
| 1121 |
+
dmax = {d: sorted({int(x) for x in few[(few.dataset == d) & (few.arm == "lora")]["deg_max"].dropna()}) for d in DISEASE}
|
| 1122 |
+
small = [d for d in DISEASE if subjects_text(info[d])]
|
| 1123 |
+
|
| 1124 |
+
def vz(c):
|
| 1125 |
+
return ", ".join(f"{NAME[d]} {v['verdict'].replace('other', 'zero-shot')} {v['n_lora']}/{v['n']}"
|
| 1126 |
+
for d, v in c.items())
|
| 1127 |
+
|
| 1128 |
+
foot_c = (f"Same draws and verdict rule as the previous slide; DEG tie = half the draws equal or mean gap < 1 gene. "
|
| 1129 |
+
f"logFC r = mean over T/B/Mono/NK of case-vs-control log2FC r (generated vs observed); top-50 DEG = "
|
| 1130 |
+
f"Welch+BH overlap summed over {n_types} types (max 250; "
|
| 1131 |
+
+ ", ".join(f"{NAME[d]} {rng(dmax[d])}" for d in DISEASE if dmax[d] != [250]) + " per draw). "
|
| 1132 |
+
+ "".join(f"{NAME[d]} test = {subjects_text(info[d])} subjects per draw. " for d in small)
|
| 1133 |
+
+ f"LoRA-5 vs zero-shot (real bulk), LoRA-better draws: logFC r {vz(cmp_rz)}; DEG {vz(cmp_dz)}. "
|
| 1134 |
+
+ "Broadcast = the input real bulk's own logFC. Scores: scores/<cohort>/fewshot_n5/draw<j>{,_scsemi5}/.")
|
| 1135 |
+
fs_c = check_foot_short(f"Same draws as previous slide. Top-50 DEG = Welch + BH overlap, summed over {n_types} "
|
| 1136 |
+
f"cell types.")
|
| 1137 |
+
srcc = f"{SCORES}/<cohort>/fewshot_n5/draw<j>{{,_scsemi5}}/summary.json and contrast.csv"
|
| 1138 |
+
num("c", "Top-50 DEG LoRA-5 vs scSemi-5 (shared-draw means; LoRA-better / tied draws; verdict): " +
|
| 1139 |
+
"; ".join(f"{NAME[d]} {v['lora']:.1f} vs {v['other']:.1f} ({v['n_lora']}/{v['n']}, {v['n_tie']} tied, {v['verdict']})"
|
| 1140 |
+
for d, v in cmp_d.items()), srcc)
|
| 1141 |
+
num("c", "logFC r LoRA-5 vs scSemi-5 (shared-draw means; LoRA-better draws; verdict): " +
|
| 1142 |
+
"; ".join(f"{NAME[d]} {v['lora']:.3f} vs {v['other']:.3f} ({v['n_lora']}/{v['n']}, {v['verdict']})"
|
| 1143 |
+
for d, v in cmp_r.items()), srcc)
|
| 1144 |
+
num("c", "Top-50 DEG LoRA-5 vs zero-shot (real bulk) (same-draw means; LoRA-better / tied draws; verdict): " +
|
| 1145 |
+
"; ".join(f"{NAME[d]} {v['lora']:.1f} vs {v['other']:.1f} ({v['n_lora']}/{v['n']}, {v['n_tie']} tied, {v['verdict']})"
|
| 1146 |
+
for d, v in cmp_dz.items()), f"{SCORES}/<cohort>/fewshot_n5/draw<j>/summary.json (arms lora5, zs_raw)")
|
| 1147 |
+
num("c", "logFC r LoRA-5 vs zero-shot (real bulk) (same-draw means; LoRA-better draws; verdict): " +
|
| 1148 |
+
"; ".join(f"{NAME[d]} {v['lora']:.3f} vs {v['other']:.3f} ({v['n_lora']}/{v['n']}, {v['verdict']})"
|
| 1149 |
+
for d, v in cmp_rz.items()), f"{SCORES}/<cohort>/fewshot_n5/draw<j>/contrast.csv (arms lora5, zs_raw)")
|
| 1150 |
+
for d in bc_all:
|
| 1151 |
+
num("c", f"{NAME[d]} broadcast logFC r {few_ref(few, d, 'broadcast', 'contrast_r')[0]:.3f} vs best arm "
|
| 1152 |
+
f"{max(arm_mean(d, a, 'contrast_r') for a in arms3):.3f}; broadcast DEG "
|
| 1153 |
+
f"{few_ref(few, d, 'broadcast', 'deg')[0]:.1f} vs best arm {max(arm_mean(d, a, 'deg') for a in arms3):.1f} "
|
| 1154 |
+
f"(means over all draws)", f"{SCORES}/{d}/fewshot_n5/draw<j>{{,_scsemi5}}/summary.json")
|
| 1155 |
+
num("c", "DEG maximum per draw: " + ", ".join(f"{NAME[d]} {rng(dmax[d])}" for d in DISEASE),
|
| 1156 |
+
f"{SCORES}/<cohort>/fewshot_n5/draw<j>/summary.json (deg_top50_max)")
|
| 1157 |
+
for d in small:
|
| 1158 |
+
num("c", f"{NAME[d]} test subjects per draw: {subjects_text(info[d])} ({CONTRAST[d]['case']} vs "
|
| 1159 |
+
f"{CONTRAST[d]['control']}); test pairs {info[d]['test']}",
|
| 1160 |
+
f"{info[d]['source']} (train_donors); {DATA / d / 'folds.csv'} (group)")
|
| 1161 |
+
slides.append({"title": "5 donors: LoRA vs scSemiProfiler — disease signal", "layout": "figure_keywords",
|
| 1162 |
+
"figures": [str(FIGDIR / "sec09_fewpair_disease.png")], "keywords": kw_c, "footnote": foot_c,
|
| 1163 |
+
"footnote_short": fs_c, "numbers": NUMS["c"]})
|
| 1164 |
+
|
| 1165 |
+
# ---------------- slide d ----------------
|
| 1166 |
+
L = {d: pooled[d][POOLED_ARMS["lora"]] for d in ORDER}
|
| 1167 |
+
Z = {d: pooled[d][POOLED_ARMS["zs_raw"]] for d in ORDER}
|
| 1168 |
+
S = {d: pooled[d][POOLED_ARMS["sconly"]] for d in ORDER}
|
| 1169 |
+
B = {d: [Z[d], S[d]] for d in ORDER}
|
| 1170 |
+
best = {mk: [d for d in (ORDER if mk == "coverage" else DISEASE) if L[d][mk] >= max(b[mk] for b in B[d])]
|
| 1171 |
+
for mk in ("coverage", "contrast_r", "deg")}
|
| 1172 |
+
kw_d1 = f"LoRA tops coverage {len(best['coverage'])}/{len(ORDER)}, logFC r {len(best['contrast_r'])}/{len(DISEASE)}"
|
| 1173 |
+
jb = baselines_text([b["coverage"] for b in B["ji2025_chili"]])
|
| 1174 |
+
jl = f"{L['ji2025_chili']['coverage']:.2f}"
|
| 1175 |
+
kw_d2 = keyword_or_short(f"Ji whole blood: baselines {jb}, LoRA {jl}", f"Ji whole blood: LoRA {jl}, others {jb}")
|
| 1176 |
+
bc_win = [d for d in DISEASE if L[d]["broadcast_r"] > L[d]["contrast_r"]]
|
| 1177 |
+
kw_d3 = ("; ".join(f"{NAME[d]}: broadcast r {L[d]['broadcast_r']:.2f} > LoRA {L[d]['contrast_r']:.2f}" for d in bc_win)
|
| 1178 |
+
if bc_win else "LoRA above broadcast in every cohort")
|
| 1179 |
+
kw_d3 = keyword_or_short(kw_d3, f"Broadcast r above LoRA: {names(bc_win)}")
|
| 1180 |
+
kw_d = check_keywords([kw_d1, kw_d2, kw_d3])
|
| 1181 |
+
foot_d = (f"Donor-level 5-fold CV; each pair scored once, by the fold model that never trained on its donor "
|
| 1182 |
+
f"(one pooled call per cohort). LoRA r={lora_r} on all training donors' real bulk, early stop on "
|
| 1183 |
+
f"inner-val donors. Zero-shot = base model without fine-tuning; sc-only = full fine-tune on training "
|
| 1184 |
+
f"donors' sc pseudobulk; both are fed the test pair's real bulk as measured. Base f01 6k·1x·E16. "
|
| 1185 |
+
f"Top-50 DEG: LoRA best {len(best['deg'])}/{len(DISEASE)}. Sepsis DEG from pooled_deg. "
|
| 1186 |
+
f"Scores: scores/<cohort>/pooled/summary.json.")
|
| 1187 |
+
fs_d = check_foot_short("Donor-level 5-fold CV; each pair scored by a model that never saw its donor. "
|
| 1188 |
+
"sc-only: tuned on sc pseudobulk.")
|
| 1189 |
+
psrc = f"{SCORES}/<cohort>/pooled/summary.json (Sepsis DEG: {SCORES}/ye2026_sepsis/pooled_deg/summary.json)"
|
| 1190 |
+
num("d", f"LoRA best of 3 arms: coverage {len(best['coverage'])}/{len(ORDER)}, logFC r "
|
| 1191 |
+
f"{len(best['contrast_r'])}/{len(DISEASE)}, top-50 DEG {len(best['deg'])}/{len(DISEASE)}", psrc)
|
| 1192 |
+
num("d", f"Ji coverage: zero-shot {Z['ji2025_chili']['coverage']:.3f}, sc-only "
|
| 1193 |
+
f"{S['ji2025_chili']['coverage']:.3f}, LoRA {L['ji2025_chili']['coverage']:.3f}",
|
| 1194 |
+
SCORES / "ji2025_chili" / "pooled" / "summary.json")
|
| 1195 |
+
for d in bc_win:
|
| 1196 |
+
num("d", f"{NAME[d]} logFC r: broadcast {L[d]['broadcast_r']:.3f} vs LoRA {L[d]['contrast_r']:.3f}; "
|
| 1197 |
+
f"DEG broadcast {L[d]['deg_broadcast']:.0f} vs LoRA {L[d]['deg']:.0f}", SCORES / d / "pooled" / "summary.json")
|
| 1198 |
+
num("d", "LoRA logFC r vs broadcast: " + ", ".join(f"{NAME[d]} {L[d]['contrast_r']:.3f} vs {L[d]['broadcast_r']:.3f}"
|
| 1199 |
+
for d in DISEASE), psrc)
|
| 1200 |
+
for mk, lab in (("coverage", "coverage"), ("contrast_r", "logFC r"), ("deg", "top-50 DEG")):
|
| 1201 |
+
dd = ORDER if mk == "coverage" else DISEASE
|
| 1202 |
+
f = "{:.3f}" if mk != "deg" else "{:.0f}"
|
| 1203 |
+
num("d", f"{lab} LoRA / zero-shot / sc-only: " +
|
| 1204 |
+
", ".join(f"{NAME[d]} {f.format(L[d][mk])} / {f.format(Z[d][mk])} / {f.format(S[d][mk])}" for d in dd), psrc)
|
| 1205 |
+
num("d", "Pooled n (pairs / donors): " + ", ".join(f"{NAME[r.dataset]} {r.n_rows}/{r.n_donors}" for r in tab.itertuples()),
|
| 1206 |
+
f"{SCORES}/<cohort>/pooled/summary.json (n_donors); {DATA}/<cohort>/fewshot_n5/DRAWS.json")
|
| 1207 |
+
num("d", f"early stopping: {early}", README)
|
| 1208 |
+
for d in ORDER:
|
| 1209 |
+
for a, f in POOLED_ARMS.items():
|
| 1210 |
+
extra("d", f"{d} pooled {a} ({f}) coverage / precision / L1 / r / DEG",
|
| 1211 |
+
f"{pooled[d][f]['coverage']:.3f} / {pooled[d][f]['precision']:.3f} / {pooled[d][f]['comp_l1']:.3f} / "
|
| 1212 |
+
f"{pooled[d][f]['contrast_r']:.3f} / {pooled[d][f]['deg']:.0f}",
|
| 1213 |
+
pooled[d][f]["source"] + (f"; DEG: {pooled[d][f]['deg_source']}" if "deg_source" in pooled[d][f] else ""))
|
| 1214 |
+
slides.append({"title": "All pairs, 5-fold", "layout": "full", "figures": [str(FIGDIR / "sec09_fivefold.png")],
|
| 1215 |
+
"keywords": kw_d, "footnote": foot_d, "footnote_short": fs_d, "numbers": NUMS["d"]})
|
| 1216 |
+
|
| 1217 |
+
for s in slides:
|
| 1218 |
+
for k in ("title", "footnote"):
|
| 1219 |
+
check_text(s[k], k)
|
| 1220 |
+
for n in s["numbers"]:
|
| 1221 |
+
check_text(n["value"], "quoted number")
|
| 1222 |
+
spec = {"section": "09", "slides": slides, "scripts": [str(SCRIPT)],
|
| 1223 |
+
"generated_from": "tools/sec09_paired_validation.py (rerun to refresh; do not edit by hand)",
|
| 1224 |
+
"scsemi_draws_used": f"{ns_used}/{ns_all}"}
|
| 1225 |
+
(OUTDATA / "sec09_slide_text.json").write_text(json.dumps(spec, indent=1, ensure_ascii=False))
|
| 1226 |
+
flat = [{"slide": k, "item": "quoted on slide", "value": n["value"], "source": n["source"]}
|
| 1227 |
+
for k in "abcd" for n in NUMS[k]] + EXTRA
|
| 1228 |
+
pd.DataFrame(flat).to_csv(OUTDATA / "sec09_quoted_numbers.csv", index=False)
|
| 1229 |
+
# nothing written by this script may carry the input-adjustment wording
|
| 1230 |
+
for p in [OUTDATA / "sec09_slide_text.json"] + sorted(OUTDATA.glob("sec09_*.csv")):
|
| 1231 |
+
m = OFF_STORY.search(p.read_text(encoding="utf-8"))
|
| 1232 |
+
if m:
|
| 1233 |
+
raise ValueError(f"{p}: off-story text {m.group(0)!r}")
|
| 1234 |
+
|
| 1235 |
+
print("scSemiProfiler draws used per dataset:",
|
| 1236 |
+
{NAME[d]: f"{int((used.dataset == d).sum())}/{n_draws(few, d, 'lora')}" for d in ORDER})
|
| 1237 |
+
for s in slides:
|
| 1238 |
+
print(f"\n== {s['title']} [{s['layout']}]")
|
| 1239 |
+
for k in s["keywords"]:
|
| 1240 |
+
print(" *", k, f"({n_words(k)} words, {len(k)} chars)")
|
| 1241 |
+
print(" footnote_short:", s["footnote_short"], f"({len(s['footnote_short'])} chars)")
|
| 1242 |
+
print(" footnote:", s["footnote"])
|
| 1243 |
+
for n in s["numbers"]:
|
| 1244 |
+
print(" #", n["value"])
|
| 1245 |
+
for p in sorted(FIGDIR.glob("sec09_*.png")):
|
| 1246 |
+
print("wrote", p)
|
| 1247 |
+
return 0
|
| 1248 |
+
|
| 1249 |
+
|
| 1250 |
+
if __name__ == "__main__":
|
| 1251 |
+
sys.exit(main())
|
paper-releases/pbisc-diffusion/updates/20260930T090852Z-summary-deck-final-path-story/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/style.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared matplotlib style for every figure of the 2026-09-30 paper-summary deck.
|
| 2 |
+
|
| 3 |
+
Figures are drawn at their on-slide size (inches), so font sizes are the sizes seen on the slide.
|
| 4 |
+
Slide: 13.333 x 7.5 in (16:9). Content area below the title: about 12.3 x 5.7 in.
|
| 5 |
+
Use FULL, HALF or TALL for figsize unless a figure needs something else.
|
| 6 |
+
Plain look: white background, no top/right spines, no titles inside figures (the slide title says it),
|
| 7 |
+
no shadows, no gradients, no decorative elements. Colour carries meaning only.
|
| 8 |
+
"""
|
| 9 |
+
import matplotlib
|
| 10 |
+
matplotlib.use("Agg")
|
| 11 |
+
import matplotlib.pyplot as plt
|
| 12 |
+
|
| 13 |
+
FULL = (12.3, 5.6) # figure fills the content area
|
| 14 |
+
HALF = (6.0, 5.4) # one of two side-by-side figures
|
| 15 |
+
TALL = (7.8, 5.6) # figure + a keyword column on the right
|
| 16 |
+
DPI = 200
|
| 17 |
+
|
| 18 |
+
FS = 14 # base font size on the slide (pt)
|
| 19 |
+
plt.rcParams.update({
|
| 20 |
+
"font.family": "sans-serif",
|
| 21 |
+
"font.sans-serif": ["Arial", "Liberation Sans", "DejaVu Sans"],
|
| 22 |
+
"font.size": FS, "axes.titlesize": FS, "axes.labelsize": FS,
|
| 23 |
+
"xtick.labelsize": FS - 2, "ytick.labelsize": FS - 2, "legend.fontsize": FS - 2,
|
| 24 |
+
"axes.spines.top": False, "axes.spines.right": False,
|
| 25 |
+
"axes.linewidth": 1.0, "xtick.major.width": 1.0, "ytick.major.width": 1.0,
|
| 26 |
+
"legend.frameon": False, "figure.facecolor": "white", "axes.facecolor": "white",
|
| 27 |
+
"savefig.facecolor": "white", "savefig.bbox": "tight", "savefig.pad_inches": 0.05,
|
| 28 |
+
"pdf.fonttype": 42, "ps.fonttype": 42,
|
| 29 |
+
})
|
| 30 |
+
|
| 31 |
+
# One colour per method, identical across every figure (Okabe-Ito, same as the paper's paired figures)
|
| 32 |
+
ARM = {
|
| 33 |
+
"pbisc": "#D55E00", # PBISC (final model, or LoRA fine-tune)
|
| 34 |
+
"lora": "#D55E00",
|
| 35 |
+
"full_ft": "#E07B39",
|
| 36 |
+
"zs_cal": "#0072B2", # zero-shot, paired calibration
|
| 37 |
+
"zs_raw": "#A6CBE3", # zero-shot, raw bulk (old pale shade; kept for the archived scripts)
|
| 38 |
+
"zs": "#0072B2", # zero-shot, real bulk as measured: the no-fine-tune baseline (story without calibration)
|
| 39 |
+
"pseudo": "#1A1A1A", # zero-shot from sc pseudobulk (reference line)
|
| 40 |
+
"scsemi": "#E69F00", # scSemiProfiler
|
| 41 |
+
"vae": "#56B4E9", # PBISC-VAE
|
| 42 |
+
"sconly": "#CC79A7", # sc-only fine-tune
|
| 43 |
+
"broadcast": "#9A9A9A", # real-bulk broadcast baseline
|
| 44 |
+
"other": "#009E73",
|
| 45 |
+
"refcal": "#D55E00", # zero-shot + reference calibration (PBISC's no-pair real-bulk path; = sec04 PBISC colour)
|
| 46 |
+
"tpm": "#DDCC77", # zero-shot, TPM (length-corrected) bulk input (sec05; not used by any other key)
|
| 47 |
+
}
|
| 48 |
+
# Architecture variants (section 3 only). trunk4x / prop avoid the PBISC-VAE (#56B4E9) and
|
| 49 |
+
# scSemiProfiler (#E69F00) reference-line colours drawn on the same slide.
|
| 50 |
+
VARIANT = {"1x": "#D55E00", "4x": "#0072B2", "trunk4x": "#332288", "ctx4x": "#009E73", "16x": "#CC79A7", "prop": "#999933"}
|
| 51 |
+
# Gene panels (section 3 only); 3k avoids the PBISC-VAE line colour
|
| 52 |
+
PANEL = {"2k": "#A6CBE3", "3k": "#882255", "6k": "#D55E00", "15k": "#0072B2"}
|
| 53 |
+
GREY = "#8C8C8C"
|
| 54 |
+
INK = "#1A1A1A"
|
| 55 |
+
SUBINK = "#4D4D4D" # secondary text (sub-lines under bars)
|
| 56 |
+
PBISC_PALE = "#F3C9A8" # light PBISC orange: planned / not yet generated (outlined in ARM["pbisc"])
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def save(fig, name, figdir):
|
| 60 |
+
"""Save PNG (slide) and PDF (vector) with the same stem."""
|
| 61 |
+
from pathlib import Path
|
| 62 |
+
figdir = Path(figdir)
|
| 63 |
+
fig.savefig(figdir / f"{name}.png", dpi=DPI)
|
| 64 |
+
fig.savefig(figdir / f"{name}.pdf")
|
| 65 |
+
plt.close(fig)
|