Archive 4 checkpoints (1-4)
Browse files- paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec04_metrics_overview.py +89 -0
- paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec04_sle_benchmark.py +441 -0
- paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec05_shift_cohorts.py +95 -0
- paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec07_rank_sweep.py +268 -0
paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec04_metrics_overview.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Section 4 of the 2026-09-30 paper-summary deck: how generated cells are scored (metric overview; added 2026-10-02).
|
| 3 |
+
|
| 4 |
+
CPU only; draws a plain table figure. One row per metric used anywhere in the deck: what it asks, what it is compared
|
| 5 |
+
against (control, null or ceiling), and the paper the definition comes from. The definitions match the scorers:
|
| 6 |
+
plans/paired_finetune_intradataset_20260927/tools/score_ft.py (composition, precision/coverage, logFC r, top-50 DEG),
|
| 7 |
+
tools/extra_metrics.py (classifier AUC, MMD^2, E_N) and tools/contrast_extra.py (Spearman, split-half ceiling,
|
| 8 |
+
limma-voom DEG, CAT). References are the PDFs in paper-release-20260928/reference-papers/ (INDEX.md).
|
| 9 |
+
|
| 10 |
+
Outputs: figures/sec04_metrics_overview.{png,pdf}; data/sec04_metrics_overview.csv (the table as text).
|
| 11 |
+
"""
|
| 12 |
+
import os
|
| 13 |
+
|
| 14 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = ""
|
| 15 |
+
import sys
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
import pandas as pd
|
| 19 |
+
|
| 20 |
+
DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/"
|
| 21 |
+
"2026-09-30--paper-summary--r00")
|
| 22 |
+
sys.path.insert(0, str(DECK / "tools"))
|
| 23 |
+
import style # noqa: E402
|
| 24 |
+
import matplotlib.pyplot as plt # noqa: E402
|
| 25 |
+
|
| 26 |
+
FIGDIR = Path(os.environ.get("DECK_FIGDIR", str(DECK / "figures")))
|
| 27 |
+
OUTDATA = Path(os.environ.get("DECK_OUTDATA", str(DECK / "data")))
|
| 28 |
+
|
| 29 |
+
# group, metric, question, compared against, reference
|
| 30 |
+
ROWS = [
|
| 31 |
+
("Cells", "Precision / coverage", "Land on real cells? Cover all real cells?",
|
| 32 |
+
"held-out real cells (R2)", "Kynkäänniemi 2019; Naeem 2020"),
|
| 33 |
+
("Cells", "Classifier AUC", "Can a classifier tell generated from real cells?",
|
| 34 |
+
"0.5 = indistinguishable", "Lopez-Paz & Oquab 2017"),
|
| 35 |
+
("Cells", "MMD²", "How far apart are the two cell distributions?",
|
| 36 |
+
"real vs real", "Gretton 2012"),
|
| 37 |
+
("Cells", "E_N", "scSemiProfiler's own nearest-neighbour error",
|
| 38 |
+
"within-sample split", "Wang 2024"),
|
| 39 |
+
("Composition", "Cell-type L1", "Right mix of the six scANVI cell types?",
|
| 40 |
+
"other donors' mean (null)", "—"),
|
| 41 |
+
("Disease", "logFC r (Pearson / Spearman)", "Same case-vs-control change in each cell type?",
|
| 42 |
+
"broadcast; split-half ceiling", "Roohani 2024; Viñas Torné 2026"),
|
| 43 |
+
("Disease", "Top-50 DEG overlap", "Same top disease genes per cell type?",
|
| 44 |
+
"chance; limma-voom check", "Li 2026; Squair 2021; Law 2014"),
|
| 45 |
+
("Disease", "CAT curve", "Same genes at every list length k?",
|
| 46 |
+
"chance = k / 2G", "Irizarry 2005"),
|
| 47 |
+
("Cost", "GPU time", "How long to apply to a new cohort?",
|
| 48 |
+
"same donors, same GPU", "—"),
|
| 49 |
+
]
|
| 50 |
+
HEAD = ("", "Metric", "Question", "Compared against", "Definition from")
|
| 51 |
+
COLX = (0.0, 0.103, 0.29, 0.607, 0.80)
|
| 52 |
+
GROUP_COL = {"Cells": style.ARM["lora"], "Composition": style.ARM["zs_cal"], "Disease": style.ARM["sconly"],
|
| 53 |
+
"Cost": style.GREY}
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def main() -> int:
|
| 57 |
+
fig = plt.figure(figsize=(12.3, 5.0))
|
| 58 |
+
ax = fig.add_axes([0.0, 0.0, 1.0, 1.0])
|
| 59 |
+
ax.set_axis_off()
|
| 60 |
+
n = len(ROWS)
|
| 61 |
+
top, step = 0.93, 0.093
|
| 62 |
+
fs = style.FS - 2
|
| 63 |
+
for x, h in zip(COLX, HEAD):
|
| 64 |
+
ax.text(x + 0.005, top + 0.045, h, fontsize=fs, fontweight="bold", color=style.INK, va="center")
|
| 65 |
+
ax.plot([0, 1], [top + 0.012, top + 0.012], color=style.INK, lw=1.0)
|
| 66 |
+
prev = None
|
| 67 |
+
for i, (g, m, q, c, r) in enumerate(ROWS):
|
| 68 |
+
y = top - (i + 0.5) * step
|
| 69 |
+
if g != prev:
|
| 70 |
+
if prev is not None:
|
| 71 |
+
ax.plot([0, 1], [y + step / 2, y + step / 2], color="#C8C8C8", lw=0.8)
|
| 72 |
+
ax.text(COLX[0] + 0.005, y, g, fontsize=fs + 1, fontweight="bold", color=GROUP_COL[g], va="center")
|
| 73 |
+
prev = g
|
| 74 |
+
ax.text(COLX[1] + 0.005, y, m, fontsize=fs, color=style.INK, va="center")
|
| 75 |
+
ax.text(COLX[2] + 0.005, y, q, fontsize=fs, color=style.SUBINK, va="center")
|
| 76 |
+
ax.text(COLX[3] + 0.005, y, c, fontsize=fs, color=style.SUBINK, va="center")
|
| 77 |
+
ax.text(COLX[4] + 0.005, y, r, fontsize=fs - 1, color=style.SUBINK, va="center", style="italic")
|
| 78 |
+
ax.plot([0, 1], [top - n * step, top - n * step], color=style.INK, lw=1.0)
|
| 79 |
+
ax.set_xlim(0, 1)
|
| 80 |
+
ax.set_ylim(top - n * step - 0.01, top + 0.08)
|
| 81 |
+
style.save(fig, "sec04_metrics_overview", FIGDIR)
|
| 82 |
+
OUTDATA.mkdir(exist_ok=True)
|
| 83 |
+
pd.DataFrame(ROWS, columns=["group", "metric", "question", "compared_against", "reference"]).to_csv(
|
| 84 |
+
OUTDATA / "sec04_metrics_overview.csv", index=False)
|
| 85 |
+
return 0
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
if __name__ == "__main__":
|
| 89 |
+
sys.exit(main())
|
paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec04_sle_benchmark.py
ADDED
|
@@ -0,0 +1,441 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Section 4 figures: final PBISC on the held-out SLE single-cell benchmark (GSE135779).
|
| 2 |
+
|
| 3 |
+
CPU only. Reads existing score tables; recomputes nothing heavy.
|
| 4 |
+
Model: runs/f01_6k_1x_seed20260627/checkpoint_epoch_016.pt (6k genes, 1x, part 16, Bernoulli read-out,
|
| 5 |
+
DDIM 50, EMA). Input = sc pseudobulk of 42 held-out donors. Scoring = frozen f01common scANVI, six-type gate.
|
| 6 |
+
scSemiProfiler run = sle_primary_cap1500_default_budget (14 in-cohort representative donors with real sc,
|
| 7 |
+
capped at 1,500 cells each); PBISC sees only the target pseudobulk.
|
| 8 |
+
Methods drawn: PBISC, scSemiProfiler and the bulk-broadcast baseline only (the source tables carry more
|
| 9 |
+
rows; they are not read into the figures or the data CSVs).
|
| 10 |
+
|
| 11 |
+
Figures (all 12.3 x 4.6 in so they fit under a keyword line on a 5.7-in content area)
|
| 12 |
+
sec04_sle_benchmark logFC r, top-50 DEG, comp L1: PBISC (5 seeds) vs scSemiProfiler,
|
| 13 |
+
on the 1,006-gene axis (shared by all panels) and the 2,279-gene axis (6k panel
|
| 14 |
+
intersect the published 2,980 list). Grey dashed = input bulk logFC copied to every
|
| 15 |
+
cell type (broadcast baseline slide).
|
| 16 |
+
sec04_sle_per_celltype per-type logFC r and top-50 overlap, 1,006-gene axis, all six types incl. Other.
|
| 17 |
+
sec04_sle_broadcast section 4: bulk-broadcast baseline and partial r given bulk, 1,006-gene axis.
|
| 18 |
+
"""
|
| 19 |
+
import json
|
| 20 |
+
import sys
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
|
| 23 |
+
import numpy as np
|
| 24 |
+
import pandas as pd
|
| 25 |
+
|
| 26 |
+
DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/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 |
+
|
| 31 |
+
FIG = DECK / "figures"
|
| 32 |
+
DATA = DECK / "data"
|
| 33 |
+
SLE = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/utility_studies_final6k_20260925/sle")
|
| 34 |
+
BCAST = SLE.parent / "sle_broadcast" / "tables"
|
| 35 |
+
SCSEMI_RES = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/bulk2sc-paper/results/scsemiprofiler_vs_pbisc_heldout_20260629")
|
| 36 |
+
SCSEMI_INPUT = SCSEMI_RES / "inputs/004_A_GSE135779_SLE_PBMC/primary_kmeans/input_manifest.json"
|
| 37 |
+
|
| 38 |
+
FIGSIZE = (12.3, 4.6)
|
| 39 |
+
VFS = 12 # value-label font size (pt on the slide)
|
| 40 |
+
AXES = ["1006", "2279"]
|
| 41 |
+
AXIS_LABEL = {"1006": "1,006 genes", "2279": "2,279 genes"}
|
| 42 |
+
SEED_TAGS = ["diffusion_f016k_e16", "diffusion_f016ks1_e16", "diffusion_f016ks2_e16",
|
| 43 |
+
"diffusion_f016ks3_e16", "diffusion_f016ks4_e16"]
|
| 44 |
+
TYPES = ["T cell", "B cell", "Monocyte", "NK cell", "DC", "Other"]
|
| 45 |
+
TYPE_SHORT = {"T cell": "T", "B cell": "B", "Monocyte": "Mono", "NK cell": "NK", "DC": "DC", "Other": "Other"}
|
| 46 |
+
C_P, C_S, C_B = style.ARM["pbisc"], style.ARM["scsemi"], style.ARM["broadcast"]
|
| 47 |
+
LBL_P = "PBISC 6k (5 seeds)"
|
| 48 |
+
LBL_S = "scSemiProfiler"
|
| 49 |
+
W2 = 0.34 # bar width when a group has two bars (PBISC, scSemiProfiler)
|
| 50 |
+
GAP = 1.05 # centre-to-centre spacing of neighbouring bars, in bar widths
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def pair_x(x, w=W2):
|
| 54 |
+
"""Centres of the two bars (PBISC, scSemiProfiler) of a group centred on x."""
|
| 55 |
+
return x - w * GAP / 2, x + w * GAP / 2
|
| 56 |
+
|
| 57 |
+
numbers = [] # (key, value, source)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def note(key, value, source):
|
| 61 |
+
numbers.append({"key": key, "value": value, "source": str(source)})
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def base_dir(axis):
|
| 65 |
+
return SLE / f"metrics_{axis}" / "panel_2980_diffusion_f016k_e16" / "pbmc5_other"
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
# ------------------------------------------------------------------ inputs
|
| 69 |
+
def load_summary(axis):
|
| 70 |
+
"""Headline rows from tables_<axis>.csv (5-seed mean/SD, per-seed values, baselines)."""
|
| 71 |
+
path = SLE / f"tables_{axis}.csv"
|
| 72 |
+
t = pd.read_csv(path).set_index("row")
|
| 73 |
+
seeds = t.loc[["base (seed 20260913)", "seed s1", "seed s2", "seed s3", "seed s4"]]
|
| 74 |
+
out = {
|
| 75 |
+
"path": path,
|
| 76 |
+
"seed_r": seeds["logfc_r"].to_numpy(), "seed_deg": seeds["top50"].to_numpy(),
|
| 77 |
+
"seed_l1": seeds["comp_l1"].to_numpy(),
|
| 78 |
+
"mean": t.loc["seed mean (5 seeds)"], "sd": t.loc["seed SD (ddof=1)"],
|
| 79 |
+
"scsemi": t.loc["scSemiProfiler"],
|
| 80 |
+
}
|
| 81 |
+
# sanity: the stored mean/SD equal the per-seed values
|
| 82 |
+
assert np.isclose(out["seed_r"].mean(), out["mean"]["logfc_r"])
|
| 83 |
+
assert np.isclose(out["seed_r"].std(ddof=1), out["sd"]["logfc_r"])
|
| 84 |
+
return out
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def load_broadcast_summary():
|
| 88 |
+
"""Mean r (6 types) and total top-50 of the input-bulk broadcast per axis; cross-checked vs tables_<axis>."""
|
| 89 |
+
sm = BCAST / "summary_mean_r_top50.csv"
|
| 90 |
+
s = pd.read_csv(sm)
|
| 91 |
+
out = {}
|
| 92 |
+
for a in AXES:
|
| 93 |
+
d = s[s["axis"] == int(a)].set_index("method")
|
| 94 |
+
t = load_summary(a)
|
| 95 |
+
assert np.isclose(d.loc["diffusion_5seed_mean", "mean_logFC_pearson"], t["mean"]["logfc_r"])
|
| 96 |
+
assert np.isclose(d.loc["diffusion_5seed_mean", "total_top50_overlap"], t["mean"]["top50"])
|
| 97 |
+
assert np.isclose(d.loc["scSemiProfiler", "mean_logFC_pearson"], t["scsemi"]["logfc_r"])
|
| 98 |
+
out[a] = (float(d.loc["broadcast_input_bulk", "mean_logFC_pearson"]),
|
| 99 |
+
float(d.loc["broadcast_input_bulk", "total_top50_overlap"]))
|
| 100 |
+
return out, sm
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def truth_list_size(axis):
|
| 104 |
+
p = base_dir(axis) / "top50_deg_overlap.csv"
|
| 105 |
+
d = pd.read_csv(p)
|
| 106 |
+
d = d[d["method"] == "diffusion_f016k_e16"]
|
| 107 |
+
return int(d["truth_top_list_size"].sum()), p
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def donor_counts():
|
| 111 |
+
p = base_dir("1006") / "pseudobulk_row_manifest.csv"
|
| 112 |
+
m = pd.read_csv(p)
|
| 113 |
+
m = m[m["method"] == "real"].drop_duplicates("sample_id")
|
| 114 |
+
c = m["condition"].value_counts()
|
| 115 |
+
return int(len(m)), int(c.get("SLE", 0)), int(c.get("HC", 0)), p
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def scsemi_setting():
|
| 119 |
+
"""Representative donors that give scSemiProfiler real sc, and its per-donor cell cap."""
|
| 120 |
+
inp = json.loads(SCSEMI_INPUT.read_text())
|
| 121 |
+
man = json.loads((SLE / "MANIFEST.json").read_text())
|
| 122 |
+
runs = [f["path"] for group in man["files"].values() if isinstance(group, list) for f in group
|
| 123 |
+
if isinstance(f, dict) and "/outputs/scsemiprofiler/004_A_GSE135779_SLE_PBMC/" in f.get("path", "")]
|
| 124 |
+
assert len(runs) == 1, runs
|
| 125 |
+
run_dir = Path(runs[0]).parent
|
| 126 |
+
cfg_path = run_dir / "run_config.json"
|
| 127 |
+
cfg = json.loads(cfg_path.read_text())
|
| 128 |
+
rep = inp["condition_counts"]["representative"]
|
| 129 |
+
n_rep = len(inp["representative_donors"])
|
| 130 |
+
note("scSemiProfiler run used in SLE benchmark", run_dir.name, SLE / "MANIFEST.json")
|
| 131 |
+
note("scSemiProfiler representative donors with real sc", f"{n_rep} ({rep['SLE']} SLE / {rep['HC']} HC)",
|
| 132 |
+
SCSEMI_INPUT)
|
| 133 |
+
note("scSemiProfiler representative-cell cap per donor", cfg["max_rep_cells_per_donor"], cfg_path)
|
| 134 |
+
return n_rep, cfg["max_rep_cells_per_donor"]
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def cell_shares():
|
| 138 |
+
"""Share of each type among real target cells (evaluation manifest) and generated DC per donor."""
|
| 139 |
+
em = base_dir("1006") / "evaluation_manifest.json"
|
| 140 |
+
counts = json.loads(em.read_text())["truth_labels_override"]["raw_label_counts"]
|
| 141 |
+
total = sum(counts.values())
|
| 142 |
+
share = {k: v / total for k, v in counts.items()}
|
| 143 |
+
note("real target cells total", total, em)
|
| 144 |
+
for k in TYPES:
|
| 145 |
+
note(f"real cells {k}", f"{counts[k]} ({100 * share[k]:.1f}%)", em)
|
| 146 |
+
cl = base_dir("1006") / "composition_long.csv"
|
| 147 |
+
c = pd.read_csv(cl)
|
| 148 |
+
for meth in ["diffusion_f016k_e16", "scSemiProfiler", "real"]:
|
| 149 |
+
d = c[(c["method"] == meth) & (c["celltype"] == "DC")]
|
| 150 |
+
note(f"DC cells per donor, {meth} (base seed for diffusion)",
|
| 151 |
+
f"mean {d['n_cells_celltype'].mean():.1f} of {d['n_cells_total'].mean():.0f}; "
|
| 152 |
+
f"{int((d['n_cells_celltype'] > 0).sum())}/{len(d)} donors with any", cl)
|
| 153 |
+
return share, counts, total
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
# ------------------------------------------------------------------ helpers
|
| 157 |
+
def seed_dots(ax, x, vals, width):
|
| 158 |
+
rng = np.random.default_rng(0)
|
| 159 |
+
jit = (rng.random(len(vals)) - 0.5) * width * 0.55
|
| 160 |
+
ax.scatter(x + jit, vals, s=18, color="white", edgecolor=style.INK, linewidth=0.8, zorder=4, clip_on=False)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def bar(ax, x, h, color, width, label=None, err=None):
|
| 164 |
+
ax.bar(x, h, width=width, color=color, edgecolor="none", label=label, zorder=2)
|
| 165 |
+
if err is not None:
|
| 166 |
+
ax.errorbar(x, h, yerr=err, fmt="none", ecolor=style.INK, elinewidth=1.2, capsize=4, zorder=3)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def base_label(ax, x, text, y0):
|
| 170 |
+
"""Value written inside the bar near its base: same height for every bar, so no bar looks ahead."""
|
| 171 |
+
ax.text(x, y0, text, ha="center", va="bottom", fontsize=VFS, color=style.INK, zorder=5)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def seed_legend(fig, ax, ncol, extra=None):
|
| 175 |
+
h, l = ax.get_legend_handles_labels()
|
| 176 |
+
h.append(plt.Line2D([], [], marker="o", ls="none", mfc="white", mec=style.INK, ms=6))
|
| 177 |
+
l.append("single seed")
|
| 178 |
+
if extra:
|
| 179 |
+
h.append(extra[0])
|
| 180 |
+
l.append(extra[1])
|
| 181 |
+
fig.legend(h, l, loc="upper center", ncol=ncol, bbox_to_anchor=(0.5, 1.01), handlelength=1.4,
|
| 182 |
+
columnspacing=1.4)
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
# ------------------------------------------------------------------ figure (a)
|
| 186 |
+
def fig_benchmark():
|
| 187 |
+
S = {a: load_summary(a) for a in AXES}
|
| 188 |
+
n_donor, n_sle, n_hc, p_donor = donor_counts()
|
| 189 |
+
note("donors", f"{n_donor} ({n_sle} SLE / {n_hc} HC)", p_donor)
|
| 190 |
+
lists = {a: truth_list_size(a) for a in AXES}
|
| 191 |
+
bc, p_bc = load_broadcast_summary()
|
| 192 |
+
|
| 193 |
+
fig = plt.figure(figsize=FIGSIZE)
|
| 194 |
+
gs = fig.add_gridspec(1, 3, width_ratios=[2.0, 2.0, 1.1], wspace=0.42, top=0.86)
|
| 195 |
+
axr, axd, axl = (fig.add_subplot(gs[0, i]) for i in range(3))
|
| 196 |
+
w = W2
|
| 197 |
+
rows = []
|
| 198 |
+
for gi, a in enumerate(AXES):
|
| 199 |
+
s = S[a]
|
| 200 |
+
for ax, key, seedkey, fmt_p, fmt_b, y0, bidx in [
|
| 201 |
+
(axr, "logfc_r", "seed_r", "{:.2f}", "{:.2f}", 0.012, 0),
|
| 202 |
+
(axd, "top50", "seed_deg", "{:.1f}", "{:.0f}", 2.0, 1)]:
|
| 203 |
+
xs = pair_x(gi, w)
|
| 204 |
+
m, sd = s["mean"][key], s["sd"][key]
|
| 205 |
+
bar(ax, xs[0], m, C_P, w, LBL_P if gi == 0 else None, err=sd)
|
| 206 |
+
seed_dots(ax, xs[0], s[seedkey], w)
|
| 207 |
+
bar(ax, xs[1], s["scsemi"][key], C_S, w, LBL_S if gi == 0 else None)
|
| 208 |
+
base_label(ax, xs[0], fmt_p.format(m), y0)
|
| 209 |
+
base_label(ax, xs[1], fmt_b.format(s["scsemi"][key]), y0)
|
| 210 |
+
# broadcast reference: input bulk logFC copied to every cell type
|
| 211 |
+
bv = bc[a][bidx]
|
| 212 |
+
ax.plot([gi - 0.44, gi + 0.44], [bv, bv], color=C_B, lw=1.6, ls=(0, (4, 2.5)), zorder=1)
|
| 213 |
+
ax.text(gi, bv + (0.012 if key == "logfc_r" else 2.0),
|
| 214 |
+
"bulk copied " + (f"{bv:.2f}" if key == "logfc_r" else f"{bv:.0f}"),
|
| 215 |
+
ha="center", va="bottom", fontsize=VFS, color=style.GREY)
|
| 216 |
+
note(f"{key} {a}: broadcast (input bulk logFC copied to every type)",
|
| 217 |
+
round(bv, 3) if key == "logfc_r" else int(bv), p_bc)
|
| 218 |
+
for meth, v, sdv in [("PBISC 6k 5-seed mean", m, sd), ("scSemiProfiler", s["scsemi"][key], np.nan)]:
|
| 219 |
+
rows.append({"axis_genes": a, "metric": key, "method": meth, "value": v, "seed_sd": sdv,
|
| 220 |
+
"source": s["path"]})
|
| 221 |
+
rows.append({"axis_genes": a, "metric": key, "method": "broadcast (input bulk)", "value": bv,
|
| 222 |
+
"seed_sd": np.nan, "source": p_bc})
|
| 223 |
+
for tag, v in zip(SEED_TAGS, s[seedkey]):
|
| 224 |
+
rows.append({"axis_genes": a, "metric": key, "method": tag, "value": v, "seed_sd": np.nan,
|
| 225 |
+
"source": s["path"]})
|
| 226 |
+
note(f"{key} {a}: PBISC 5-seed mean", round(float(m), 3 if key == "logfc_r" else 1), s["path"])
|
| 227 |
+
note(f"{key} {a}: PBISC 5-seed SD", round(float(sd), 3 if key == "logfc_r" else 1), s["path"])
|
| 228 |
+
note(f"{key} {a}: scSemiProfiler", round(float(s["scsemi"][key]), 3), s["path"])
|
| 229 |
+
axr.set_xticks([0, 1], [AXIS_LABEL[a] for a in AXES])
|
| 230 |
+
axd.set_xticks([0, 1], [f"{AXIS_LABEL[a]}\n(of {lists[a][0]})" for a in AXES])
|
| 231 |
+
axr.set_ylabel("Disease logFC r (higher better)")
|
| 232 |
+
axd.set_ylabel("Top-50 DEG overlap (higher better)")
|
| 233 |
+
axr.set_ylim(0, 0.78)
|
| 234 |
+
axd.set_ylim(0, 135)
|
| 235 |
+
for a in AXES:
|
| 236 |
+
note(f"top-50 truth list size {a}", lists[a][0], lists[a][1])
|
| 237 |
+
|
| 238 |
+
# composition L1: labels only, identical on both axes (check it)
|
| 239 |
+
s = S["1006"]
|
| 240 |
+
for k in ["mean", "sd", "scsemi"]:
|
| 241 |
+
assert np.isclose(S["1006"][k]["comp_l1"], S["2279"][k]["comp_l1"])
|
| 242 |
+
xs = pair_x(0, w)
|
| 243 |
+
m, sd = s["mean"]["comp_l1"], s["sd"]["comp_l1"]
|
| 244 |
+
bar(axl, xs[0], m, C_P, w, err=sd)
|
| 245 |
+
seed_dots(axl, xs[0], s["seed_l1"], w)
|
| 246 |
+
bar(axl, xs[1], s["scsemi"]["comp_l1"], C_S, w)
|
| 247 |
+
y0 = 0.006
|
| 248 |
+
base_label(axl, xs[0], f"{m:.2f}", y0)
|
| 249 |
+
base_label(axl, xs[1], f"{s['scsemi']['comp_l1']:.2f}", y0)
|
| 250 |
+
axl.set_xticks([0], ["labels only,\nboth axes"])
|
| 251 |
+
axl.set_xlim(-0.6, 0.6)
|
| 252 |
+
axl.set_ylim(0, 0.3)
|
| 253 |
+
axl.set_ylabel("Composition L1 (lower better)")
|
| 254 |
+
for meth, v, sdv in [("PBISC 6k 5-seed mean", m, sd), ("scSemiProfiler", s["scsemi"]["comp_l1"], np.nan)]:
|
| 255 |
+
rows.append({"axis_genes": "labels only", "metric": "comp_l1", "method": meth, "value": v,
|
| 256 |
+
"seed_sd": sdv, "source": s["path"]})
|
| 257 |
+
note("comp_l1: PBISC 5-seed mean", round(float(m), 3), s["path"])
|
| 258 |
+
note("comp_l1: PBISC 5-seed SD", round(float(sd), 4), s["path"])
|
| 259 |
+
note("comp_l1: scSemiProfiler", round(float(s["scsemi"]["comp_l1"]), 3), s["path"])
|
| 260 |
+
for ax in (axr, axd):
|
| 261 |
+
ax.set_xlim(-0.6, 1.6)
|
| 262 |
+
|
| 263 |
+
seed_legend(fig, axr, ncol=4,
|
| 264 |
+
extra=(plt.Line2D([], [], color=C_B, lw=1.6, ls=(0, (4, 2.5))), "bulk logFC copied (broadcast)"))
|
| 265 |
+
style.save(fig, "sec04_sle_benchmark", FIG)
|
| 266 |
+
pd.DataFrame(rows).to_csv(DATA / "sec04_sle_benchmark.csv", index=False)
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
# ------------------------------------------------------------------ figure (b)
|
| 270 |
+
def per_type_tables(axis):
|
| 271 |
+
ps = SLE / f"per_celltype_seed_{axis}.csv"
|
| 272 |
+
seeds = pd.read_csv(ps)
|
| 273 |
+
pr = base_dir(axis) / "pseudobulk_logfc_metrics.csv"
|
| 274 |
+
pt = base_dir(axis) / "top50_deg_overlap.csv"
|
| 275 |
+
r = pd.read_csv(pr)
|
| 276 |
+
t = pd.read_csv(pt)
|
| 277 |
+
return seeds, r, t, ps, pr, pt
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def type_ticks(share):
|
| 281 |
+
out = []
|
| 282 |
+
for c in TYPES:
|
| 283 |
+
pct = round(100 * share[c], 1)
|
| 284 |
+
out.append(f"{TYPE_SHORT[c]}\n{pct:.0f}%" if pct >= 10 else f"{TYPE_SHORT[c]}\n{pct:.1f}%")
|
| 285 |
+
return out
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def fig_per_celltype(share, axis="1006"):
|
| 289 |
+
seeds, r, t, ps, pr, pt = per_type_tables(axis)
|
| 290 |
+
fig, (a1, a2) = plt.subplots(1, 2, figsize=FIGSIZE, gridspec_kw={"wspace": 0.18, "top": 0.86})
|
| 291 |
+
w = W2
|
| 292 |
+
x = np.arange(len(TYPES))
|
| 293 |
+
rows = []
|
| 294 |
+
sds = {}
|
| 295 |
+
drawn_top = {} # tallest drawn element per type on the top-50 panel (bar or seed dot)
|
| 296 |
+
for ax, skey, btab, bsrc in [(a1, "logFC_pearson", r, pr), (a2, "top50_overlap_count", t, pt)]:
|
| 297 |
+
for i, ct in enumerate(TYPES):
|
| 298 |
+
sv = seeds[(seeds["celltype"] == ct) & (seeds["set"].isin(SEED_TAGS))][skey].to_numpy(float)
|
| 299 |
+
assert len(sv) == 5
|
| 300 |
+
scs = float(btab[(btab["method"] == "scSemiProfiler") & (btab["celltype"] == ct)][skey].iloc[0])
|
| 301 |
+
# the base-seed row of the seed table must equal the evaluator's own per-type file
|
| 302 |
+
base = float(btab[(btab["method"] == "diffusion_f016k_e16") & (btab["celltype"] == ct)][skey].iloc[0])
|
| 303 |
+
assert np.isclose(base, seeds[(seeds["celltype"] == ct) & (seeds["set"] == SEED_TAGS[0])][skey].iloc[0])
|
| 304 |
+
xp, xs_ = pair_x(x[i], w)
|
| 305 |
+
bar(ax, xp, sv.mean(), C_P, w, LBL_P if i == 0 else None, err=sv.std(ddof=1))
|
| 306 |
+
seed_dots(ax, xp, sv, w)
|
| 307 |
+
bar(ax, xs_, scs, C_S, w, LBL_S if i == 0 else None)
|
| 308 |
+
sds[(skey, ct)] = sv.std(ddof=1)
|
| 309 |
+
if skey == "top50_overlap_count":
|
| 310 |
+
drawn_top[ct] = max(sv.max(), sv.mean() + sv.std(ddof=1), scs)
|
| 311 |
+
for meth, v, sd, src in [("PBISC 6k 5-seed mean", sv.mean(), sv.std(ddof=1), ps),
|
| 312 |
+
("scSemiProfiler", scs, np.nan, bsrc)]:
|
| 313 |
+
rows.append({"axis_genes": axis, "metric": skey, "celltype": ct, "method": meth,
|
| 314 |
+
"value": v, "seed_sd": sd, "real_cell_share": share[ct], "source": src})
|
| 315 |
+
note(f"{skey} {ct} {axis}: PBISC 5-seed mean / scSemiProfiler",
|
| 316 |
+
f"{sv.mean():.3f} / {scs:.3f}" if skey == "logFC_pearson"
|
| 317 |
+
else f"{sv.mean():.1f} / {scs:.0f}", f"{ps} ; {bsrc}")
|
| 318 |
+
ax.set_xticks(x, type_ticks(share))
|
| 319 |
+
ax.set_xlim(-0.6, len(TYPES) - 0.4)
|
| 320 |
+
# Other has a truth top list of 12 genes, not 50 -- say so where it is drawn
|
| 321 |
+
n_other = int(t[(t["method"] == "diffusion_f016k_e16") & (t["celltype"] == "Other")]["truth_top_list_size"].iloc[0])
|
| 322 |
+
other_top = max(float(drawn_top["Other"]), 0)
|
| 323 |
+
a2.text(x[-1], other_top + 1.2, f"of {n_other}", ha="center", va="bottom", fontsize=VFS, color=style.GREY)
|
| 324 |
+
note("Other truth top list size (top-50 panel)", n_other, pt)
|
| 325 |
+
for ct in TYPES:
|
| 326 |
+
note(f"logFC r seed SD {ct} {axis}", round(float(sds[("logFC_pearson", ct)]), 4), ps)
|
| 327 |
+
a1.set_ylabel("Disease logFC r (higher better)")
|
| 328 |
+
a2.set_ylabel("Top-50 DEG overlap (of 50)")
|
| 329 |
+
a1.set_ylim(0, 0.7)
|
| 330 |
+
a2.set_ylim(0, 30)
|
| 331 |
+
a1.text(-0.02, -0.035, "% of real cells", transform=a1.transAxes, ha="right", va="top",
|
| 332 |
+
fontsize=11, color=style.GREY)
|
| 333 |
+
seed_legend(fig, a1, ncol=3)
|
| 334 |
+
style.save(fig, "sec04_sle_per_celltype", FIG)
|
| 335 |
+
pd.DataFrame(rows).to_csv(DATA / "sec04_sle_per_celltype.csv", index=False)
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
# ------------------------------------------------------------------ figure (c) backup
|
| 339 |
+
def fig_broadcast(axis="1006"):
|
| 340 |
+
pc = BCAST / "per_celltype_logfc_top50.csv"
|
| 341 |
+
sm = BCAST / "summary_mean_r_top50.csv"
|
| 342 |
+
rs = BCAST / "residual_specificity_summary.csv"
|
| 343 |
+
per = pd.read_csv(pc)
|
| 344 |
+
per = per[per["axis"] == int(axis)]
|
| 345 |
+
summ = pd.read_csv(sm)
|
| 346 |
+
summ = summ[summ["axis"] == int(axis)].set_index("method")
|
| 347 |
+
res = pd.read_csv(rs)
|
| 348 |
+
res = res[(res["axis"] == int(axis)) & (res["gene_space"] == "full_axis")].set_index("method")
|
| 349 |
+
|
| 350 |
+
def per_val(method, ct, col="logFC_pearson"):
|
| 351 |
+
return float(per[(per["method"] == method) & (per["celltype"] == ct)][col].iloc[0])
|
| 352 |
+
|
| 353 |
+
# the 6-type mean in the summary table is the mean over exactly the six drawn types
|
| 354 |
+
assert int(summ.loc["broadcast_input_bulk", "n_celltypes"]) == len(TYPES)
|
| 355 |
+
assert np.isclose(np.mean([per_val("broadcast_input_bulk", g) for g in TYPES]),
|
| 356 |
+
summ.loc["broadcast_input_bulk", "mean_logFC_pearson"])
|
| 357 |
+
|
| 358 |
+
fig = plt.figure(figsize=FIGSIZE)
|
| 359 |
+
gs = fig.add_gridspec(1, 2, width_ratios=[3.4, 1.2], wspace=0.26, top=0.86)
|
| 360 |
+
a1, a2 = fig.add_subplot(gs[0, 0]), fig.add_subplot(gs[0, 1])
|
| 361 |
+
groups = TYPES + ["mean"]
|
| 362 |
+
x = np.arange(len(groups), dtype=float)
|
| 363 |
+
x[-1] += 0.3 # small gap before the mean group
|
| 364 |
+
w = 0.26
|
| 365 |
+
off = np.array([-1.0, 0.0, 1.0]) * w * GAP # broadcast, PBISC, scSemiProfiler
|
| 366 |
+
rows = []
|
| 367 |
+
for i, g in enumerate(groups):
|
| 368 |
+
if g == "mean":
|
| 369 |
+
b = float(summ.loc["broadcast_input_bulk", "mean_logFC_pearson"])
|
| 370 |
+
sv = np.array([float(summ.loc[t, "mean_logFC_pearson"]) for t in SEED_TAGS])
|
| 371 |
+
scs = float(summ.loc["scSemiProfiler", "mean_logFC_pearson"])
|
| 372 |
+
src = sm
|
| 373 |
+
else:
|
| 374 |
+
b = per_val("broadcast_input_bulk", g)
|
| 375 |
+
sv = np.array([per_val(t, g) for t in SEED_TAGS])
|
| 376 |
+
scs = per_val("scSemiProfiler", g)
|
| 377 |
+
src = pc
|
| 378 |
+
bar(a1, x[i] + off[0], b, C_B, w, "Bulk logFC copied to every type" if i == 0 else None)
|
| 379 |
+
bar(a1, x[i] + off[1], sv.mean(), C_P, w, LBL_P if i == 0 else None, err=sv.std(ddof=1))
|
| 380 |
+
seed_dots(a1, x[i] + off[1], sv, w)
|
| 381 |
+
bar(a1, x[i] + off[2], scs, C_S, w, LBL_S if i == 0 else None)
|
| 382 |
+
for meth, v, sd in [("broadcast (input bulk)", b, np.nan), ("PBISC 6k 5-seed mean", sv.mean(), sv.std(ddof=1)),
|
| 383 |
+
("scSemiProfiler", scs, np.nan)]:
|
| 384 |
+
rows.append({"panel": "logFC r", "axis_genes": axis, "group": g, "method": meth, "value": v,
|
| 385 |
+
"seed_sd": sd, "source": src})
|
| 386 |
+
if g == "mean":
|
| 387 |
+
note(f"mean logFC r {axis} (6 types incl. Other): broadcast / PBISC 5-seed / scSemiProfiler",
|
| 388 |
+
f"{b:.3f} / {sv.mean():.3f} / {scs:.3f}", src)
|
| 389 |
+
a1.text(x[i] + off[0], b + 0.02, f"{b:.2f}", ha="center", va="bottom", fontsize=VFS)
|
| 390 |
+
a1.text(x[i] + off[1], max(sv.max(), sv.mean() + sv.std(ddof=1)) + 0.03, f"{sv.mean():.2f}",
|
| 391 |
+
ha="center", va="bottom", fontsize=VFS)
|
| 392 |
+
elif g == "Other":
|
| 393 |
+
note(f"Other logFC r {axis}: broadcast / PBISC 5-seed / scSemiProfiler",
|
| 394 |
+
f"{b:.3f} / {sv.mean():.3f} / {scs:.3f}", src)
|
| 395 |
+
bvals = [per_val("broadcast_input_bulk", g) for g in TYPES[:5]]
|
| 396 |
+
note(f"broadcast r per type {axis} (T,B,Mono,NK,DC) range", f"{min(bvals):.2f}-{max(bvals):.2f}", pc)
|
| 397 |
+
a1.axvline(len(TYPES) - 0.35, color=style.GREY, lw=0.8, ls=":")
|
| 398 |
+
a1.set_xticks(x, [TYPE_SHORT.get(g, "Mean of 6\n(incl. Other)") for g in groups])
|
| 399 |
+
a1.set_xlim(-0.6, x[-1] + 0.6)
|
| 400 |
+
a1.set_ylim(0, 0.95)
|
| 401 |
+
a1.set_ylabel("Disease logFC r vs real cells")
|
| 402 |
+
|
| 403 |
+
# partial r given the bulk logFC (cell-type-specific part)
|
| 404 |
+
sv = np.array([float(res.loc[t, "partial_r"]) for t in SEED_TAGS])
|
| 405 |
+
scs = float(res.loc["scSemiProfiler", "partial_r"])
|
| 406 |
+
mean_row = float(res.loc["diffusion_5seed_mean", "partial_r"])
|
| 407 |
+
assert np.isclose(mean_row, sv.mean())
|
| 408 |
+
assert "broadcast_input_bulk" not in res.index # broadcast has no residual, so it is not scored
|
| 409 |
+
pw = 0.3 # same bar width and centre spacing (0.34) as before; the two bars sit centred on the panel
|
| 410 |
+
xs = np.array([-0.17, 0.17])
|
| 411 |
+
bar(a2, xs[0], sv.mean(), C_P, pw, err=sv.std(ddof=1))
|
| 412 |
+
seed_dots(a2, xs[0], sv, pw)
|
| 413 |
+
bar(a2, xs[1], scs, C_S, pw)
|
| 414 |
+
for xx, v in zip(xs, [mean_row, scs]):
|
| 415 |
+
a2.text(xx, 0.006, f"{v:.3f}", ha="center", va="bottom", fontsize=VFS, color=style.INK, zorder=5)
|
| 416 |
+
a2.set_xticks(xs, ["PBISC", "scSemi"])
|
| 417 |
+
a2.set_xlim(-0.6, 0.6)
|
| 418 |
+
a2.set_ylim(0, 0.3)
|
| 419 |
+
a2.set_ylabel("Partial r, given bulk logFC")
|
| 420 |
+
a2.text(0.5, 1.0, "broadcast: no type-\nspecific part, not scored", transform=a2.transAxes, ha="center",
|
| 421 |
+
va="top", fontsize=11, color=style.GREY)
|
| 422 |
+
note(f"partial r {axis}: PBISC 5-seed mean / scSemiProfiler", f"{mean_row:.3f} / {scs:.3f}", rs)
|
| 423 |
+
for meth, v in [("PBISC 6k 5-seed mean", mean_row), ("scSemiProfiler", scs)]:
|
| 424 |
+
rows.append({"panel": "partial r", "axis_genes": axis, "group": "mean", "method": meth, "value": v,
|
| 425 |
+
"seed_sd": sv.std(ddof=1) if meth.startswith("PBISC 6k") else np.nan, "source": rs})
|
| 426 |
+
h, l = a1.get_legend_handles_labels()
|
| 427 |
+
fig.legend(h, l, loc="upper center", ncol=4, bbox_to_anchor=(0.5, 1.01), handlelength=1.2,
|
| 428 |
+
columnspacing=1.4)
|
| 429 |
+
style.save(fig, "sec04_sle_broadcast", FIG)
|
| 430 |
+
pd.DataFrame(rows).to_csv(DATA / "sec04_sle_broadcast.csv", index=False)
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
if __name__ == "__main__":
|
| 434 |
+
scsemi_setting()
|
| 435 |
+
share, counts, total = cell_shares()
|
| 436 |
+
fig_benchmark()
|
| 437 |
+
fig_per_celltype(share, "1006")
|
| 438 |
+
fig_broadcast("1006")
|
| 439 |
+
pd.DataFrame(numbers).to_csv(DATA / "sec04_sle_numbers.csv", index=False)
|
| 440 |
+
for n in numbers:
|
| 441 |
+
print(f"{n['key']}: {n['value']} <- {n['source']}")
|
paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec05_shift_cohorts.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Section 5 slide: the raw-bulk vs pseudobulk shift in three paired cohorts (condition vectors only).
|
| 2 |
+
|
| 3 |
+
For each cohort's primary setting (ImMicro native, Randolph fixed, Arunachalam raw5000_pseudoNative), PCA fitted on
|
| 4 |
+
the real sc pseudobulks (30 PCs; Arunachalam 11 because n = 12):
|
| 5 |
+
(1) median distance of real bulk (raw) to its own donor's pseudobulk, in D (median distance between the pseudobulks
|
| 6 |
+
of different donors; Randolph and Arunachalam: same-condition pairs only),
|
| 7 |
+
(2) shared fraction: share of the summed squared raw-minus-pseudobulk offset removed by one common (mean) vector,
|
| 8 |
+
(3) own-donor top-1 retrieval as measured and after leave-one-out shift removal, with chance.
|
| 9 |
+
All numbers are read from umap/sample_level/<cohort>/metrics_<cohort>.json. CPU only.
|
| 10 |
+
"""
|
| 11 |
+
import sys
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
import json
|
| 15 |
+
import pandas as pd
|
| 16 |
+
|
| 17 |
+
DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/2026-09-30--paper-summary--r00")
|
| 18 |
+
sys.path.insert(0, str(DECK / "tools"))
|
| 19 |
+
import style # noqa: E402
|
| 20 |
+
import matplotlib.pyplot as plt # noqa: E402
|
| 21 |
+
|
| 22 |
+
SRC = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/utility_studies_final6k_20260925/umap/sample_level")
|
| 23 |
+
COHORTS = ["ImMicro", "Randolph", "Arunachalam"]
|
| 24 |
+
FIG = DECK / "figures"
|
| 25 |
+
DATA = DECK / "data"
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def main():
|
| 29 |
+
rows = []
|
| 30 |
+
for c in COHORTS:
|
| 31 |
+
path = SRC / c / f"metrics_{c}.json"
|
| 32 |
+
m = json.load(open(path))
|
| 33 |
+
p = m["settings"][m["primary_setting"]]["sum"]["pca30"]
|
| 34 |
+
rows.append({
|
| 35 |
+
"cohort": c, "setting": m["primary_setting"], "pca_components": m["pca_components"],
|
| 36 |
+
"n": p["retrieval"]["raw"]["n"],
|
| 37 |
+
"dist_to_own_pseudo_D": p["distance_D"]["raw->obs"]["median"],
|
| 38 |
+
"shared_fraction": p["shared_shift"]["raw"]["shared_fraction"],
|
| 39 |
+
"top1": p["retrieval"]["raw"]["top1_own_sample"],
|
| 40 |
+
"top1_shift_removed": p["retrieval_shift_removed"]["raw"]["top1_own_sample"],
|
| 41 |
+
"chance": p["retrieval"]["raw"]["chance"],
|
| 42 |
+
"source": str(path),
|
| 43 |
+
})
|
| 44 |
+
df = pd.DataFrame(rows)
|
| 45 |
+
df.to_csv(DATA / "sec05_shift_cohorts.csv", index=False)
|
| 46 |
+
|
| 47 |
+
c_raw, edge = style.ARM["zs_raw"], "#5E8FB5"
|
| 48 |
+
fig, axes = plt.subplots(1, 3, figsize=style.FULL, gridspec_kw={"width_ratios": [1.12, 1.12, 1.4]})
|
| 49 |
+
x = range(len(df))
|
| 50 |
+
ticks = [f"{r.cohort}\nn = {r.n}" for r in df.itertuples()]
|
| 51 |
+
|
| 52 |
+
ax = axes[0]
|
| 53 |
+
ax.bar(x, df["dist_to_own_pseudo_D"], 0.6, color=c_raw, edgecolor=edge)
|
| 54 |
+
for i, v in enumerate(df["dist_to_own_pseudo_D"]):
|
| 55 |
+
ax.text(i, v + 0.04, f"{v:.2f}", ha="center", va="bottom", fontsize=style.FS - 2)
|
| 56 |
+
ax.axhline(1.0, color=style.GREY, lw=1.0, ls="--")
|
| 57 |
+
ax.text(2.45, 2.95, "dashed: 1 D = median\ndonor-to-donor distance", ha="right", va="top", fontsize=style.FS - 3,
|
| 58 |
+
color=style.GREY)
|
| 59 |
+
ax.set_ylabel("Real bulk (raw) to own pseudobulk (D)")
|
| 60 |
+
ax.set_ylim(0, 3.1)
|
| 61 |
+
|
| 62 |
+
ax = axes[1]
|
| 63 |
+
ax.bar(x, df["shared_fraction"], 0.6, color=c_raw, edgecolor=edge)
|
| 64 |
+
for i, v in enumerate(df["shared_fraction"]):
|
| 65 |
+
ax.text(i, v + 0.015, f"{v:.2f}", ha="center", va="bottom", fontsize=style.FS - 2)
|
| 66 |
+
ax.set_ylabel("Squared offset in one shared shift")
|
| 67 |
+
ax.set_ylim(0, 1.1)
|
| 68 |
+
|
| 69 |
+
ax = axes[2]
|
| 70 |
+
w = 0.36
|
| 71 |
+
for i, r in enumerate(df.itertuples()):
|
| 72 |
+
ax.bar(i - w / 2, 100 * r.top1, w, color="white", edgecolor=edge, lw=1.2,
|
| 73 |
+
label="as measured" if i == 0 else None)
|
| 74 |
+
ax.bar(i + w / 2, 100 * r.top1_shift_removed, w, color=c_raw, edgecolor=edge, lw=1.2,
|
| 75 |
+
label="shift removed" if i == 0 else None)
|
| 76 |
+
ax.text(i - w / 2, 100 * r.top1 + 1.5, f"{100 * r.top1:.1f}", ha="center", va="bottom", fontsize=style.FS - 3)
|
| 77 |
+
ax.text(i + w / 2, 100 * r.top1_shift_removed + 1.5, f"{100 * r.top1_shift_removed:.1f}", ha="center",
|
| 78 |
+
va="bottom", fontsize=style.FS - 3)
|
| 79 |
+
ax.hlines(100 * r.chance, i - 0.45, i + 0.45, color=style.GREY, lw=1.2, ls="--",
|
| 80 |
+
label="chance" if i == 0 else None)
|
| 81 |
+
ax.set_ylabel("Own donor = nearest pseudobulk (%)")
|
| 82 |
+
ax.set_ylim(0, 118)
|
| 83 |
+
ax.set_yticks([0, 25, 50, 75, 100])
|
| 84 |
+
ax.legend(loc="upper left", ncol=3, handlelength=1.2, columnspacing=1.0, handletextpad=0.3, borderaxespad=0.0)
|
| 85 |
+
for ax in axes:
|
| 86 |
+
ax.set_xticks(list(x))
|
| 87 |
+
ax.set_xticklabels(ticks, fontsize=style.FS - 3)
|
| 88 |
+
ax.tick_params(axis="x", length=0)
|
| 89 |
+
fig.subplots_adjust(left=0.06, right=0.995, top=0.98, bottom=0.14, wspace=0.34)
|
| 90 |
+
style.save(fig, "sec05_shift_cohorts", FIG)
|
| 91 |
+
print(df.drop(columns=["source"]).to_string())
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
if __name__ == "__main__":
|
| 95 |
+
main()
|
paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec07_rank_sweep.py
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Section 7 slide (LoRA ablations) of the 2026-09-30 paper-summary deck: LoRA rank r = 4 / 16 / 64 at
|
| 3 |
+
n = 5, 20 and all training pairs (ImMicro, sepsis; donor-level 5-fold CV, pooled cross-fitted scoring).
|
| 4 |
+
|
| 5 |
+
CPU only. Reads plans/paired_finetune_intradataset_20260927/scores/<ds>/rankcal_20261001.json (written by
|
| 6 |
+
tools/aggregate_rankcal.py) and checks every plotted value against the pooled scoring calls it came from:
|
| 7 |
+
r = 16 scores/<ds>/pooled (sepsis: pooled_deg) arms lora_n5__raw, lora_n20__raw, real_lora__raw
|
| 8 |
+
r = 4, 64 scores/<ds>/lora_rank_20261001/pooled arms lora_r{4,64}_n5__raw, lora_r{4,64}_n20__raw, lora_r{4,64}__raw
|
| 9 |
+
Composition L1 / precision / coverage = summary.json headline; logFC r = mean of contrast.csv mean_cp10k r over
|
| 10 |
+
T, B, Monocyte, NK; top-50 DEG = headline deg_top50_sum. Per-donor L1 Wilcoxon vs r = 16 as aggregate_rankcal.py.
|
| 11 |
+
Each LoRA run's rank and checkpoint are checked in runs/<ds>/fold<k>/<arm>/RUN.json.
|
| 12 |
+
|
| 13 |
+
Outputs (deck folder; DECK_FIGDIR / DECK_OUTDATA override):
|
| 14 |
+
figures/sec07_rank_sweep.{png,pdf}, data/sec07_rank_sweep.csv, data/sec07_rank_sweep_slide_text.json
|
| 15 |
+
"""
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import os
|
| 19 |
+
|
| 20 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = "" # plotting only
|
| 21 |
+
|
| 22 |
+
import json
|
| 23 |
+
import re
|
| 24 |
+
import sys
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
|
| 27 |
+
import numpy as np
|
| 28 |
+
import pandas as pd
|
| 29 |
+
from scipy.stats import wilcoxon
|
| 30 |
+
|
| 31 |
+
DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/"
|
| 32 |
+
"2026-09-30--paper-summary--r00")
|
| 33 |
+
sys.path.insert(0, str(DECK / "tools"))
|
| 34 |
+
import style # noqa: E402
|
| 35 |
+
import fold_sizes as FZ # noqa: E402 (the 'all' point is shown as its training-pair count)
|
| 36 |
+
import matplotlib.pyplot as plt # noqa: E402
|
| 37 |
+
from matplotlib.lines import Line2D # noqa: E402
|
| 38 |
+
|
| 39 |
+
PLAN = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/"
|
| 40 |
+
"paired_finetune_intradataset_20260927")
|
| 41 |
+
FINAL_CKPT = ("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/runs/"
|
| 42 |
+
"f01_6k_1x_seed20260627/checkpoint_epoch_016.pt")
|
| 43 |
+
FIGDIR = Path(os.environ.get("DECK_FIGDIR", str(DECK / "figures")))
|
| 44 |
+
OUTDATA = Path(os.environ.get("DECK_OUTDATA", str(DECK / "data")))
|
| 45 |
+
SCRIPT = DECK / "tools" / "sec07_rank_sweep.py"
|
| 46 |
+
DSETS = ["immicro", "ye2026_sepsis"]
|
| 47 |
+
NAME = {"immicro": "ImMicro", "ye2026_sepsis": "Sepsis"}
|
| 48 |
+
RANKS = (4, 16, 64)
|
| 49 |
+
NS = ("5", "20", "all")
|
| 50 |
+
RANK_EXP = "lora_rank_20261001"
|
| 51 |
+
TYPES = ["T cell", "B cell", "Monocyte", "NK cell"]
|
| 52 |
+
FS = style.FS
|
| 53 |
+
# r = 16 is the deck's LoRA (orange); 4 and 64 are lighter / darker shades of it, with their own markers
|
| 54 |
+
RCOL = {4: "#F2AE7B", 16: style.ARM["lora"], 64: "#6E2E00"}
|
| 55 |
+
RMK = {4: "v", 16: "o", 64: "s"}
|
| 56 |
+
PANELS = [("comp_l1", "Composition L1 ↓"), ("coverage", "Coverage ↑"), ("precision", "Precision ↑"),
|
| 57 |
+
("logfc_r", "Disease logFC r ↑"), ("deg", "Top-50 DEG ↑")]
|
| 58 |
+
OFF_STORY = re.compile(r"refcal|reference[ -]calibrat|\bVAE\b|\bTPM\b|\bAIFI\b|\bAIDA\b", re.I)
|
| 59 |
+
KW_MAX, FOOT_MAX = 45, 110
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def arm(r: int, n: str) -> str:
|
| 63 |
+
if r == 16:
|
| 64 |
+
return "real_lora__raw" if n == "all" else f"lora_n{n}__raw"
|
| 65 |
+
return f"lora_r{r}__raw" if n == "all" else f"lora_r{r}_n{n}__raw"
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def call_dir(ds: str, r: int) -> Path:
|
| 69 |
+
S = PLAN / "scores" / ds
|
| 70 |
+
if r != 16:
|
| 71 |
+
return S / RANK_EXP / "pooled"
|
| 72 |
+
return S / "pooled_deg" if (S / "pooled_deg" / "summary.json").exists() else S / "pooled"
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def load():
|
| 76 |
+
rows, pdl, runs = [], {}, []
|
| 77 |
+
for ds in DSETS:
|
| 78 |
+
js_path = PLAN / "scores" / ds / "rankcal_20261001.json"
|
| 79 |
+
js = json.loads(js_path.read_text())
|
| 80 |
+
for r in RANKS:
|
| 81 |
+
d = call_dir(ds, r)
|
| 82 |
+
s = json.loads((d / "summary.json").read_text())
|
| 83 |
+
con = pd.read_csv(d / "contrast.csv") if (d / "contrast.csv").exists() else None
|
| 84 |
+
per = pd.read_csv(d / "per_donor.csv")
|
| 85 |
+
for n in NS:
|
| 86 |
+
a = arm(r, n)
|
| 87 |
+
h, pj = s["headline"][a], js[a]["pooled"]
|
| 88 |
+
v = {"comp_l1": float(h["comp_l1"]), "coverage": float(h["coverage"]), "precision": float(h["precision"]),
|
| 89 |
+
"logfc_r": np.nan, "deg": np.nan}
|
| 90 |
+
if con is not None and s.get("contrast_definition", {}).get("enabled"):
|
| 91 |
+
c = con[(con.arm == a) & (con.statistic == "mean_cp10k") & con.celltype.isin(TYPES)]
|
| 92 |
+
assert set(c.celltype) == set(TYPES), (d, a)
|
| 93 |
+
v["logfc_r"] = float(c.r_generated.mean())
|
| 94 |
+
if h.get("deg_top50_sum") is not None:
|
| 95 |
+
v["deg"] = float(h["deg_top50_sum"])
|
| 96 |
+
# the aggregated JSON must equal the scoring call
|
| 97 |
+
for k, kj in (("comp_l1", "comp_l1"), ("coverage", "coverage"), ("precision", "precision"),
|
| 98 |
+
("logfc_r", "logfc_r"), ("deg", "deg_top50_sum")):
|
| 99 |
+
x = pj.get(kj)
|
| 100 |
+
if x is None:
|
| 101 |
+
assert np.isnan(v[k]), (ds, a, k)
|
| 102 |
+
else:
|
| 103 |
+
assert abs(float(x) - v[k]) < 1e-9, (ds, a, k, x, v[k])
|
| 104 |
+
for k, val in v.items():
|
| 105 |
+
rows.append({"dataset": ds, "rank": r, "pairs": n, "arm": a, "metric": k, "value": val,
|
| 106 |
+
"source": str(d / ("contrast.csv" if k == "logfc_r" else "summary.json")),
|
| 107 |
+
"aggregate": str(js_path)})
|
| 108 |
+
pdl[(ds, r, n)] = per[per.arm == a].set_index("donor")["comp_l1"]
|
| 109 |
+
for k in range(5):
|
| 110 |
+
rp = PLAN / "runs" / ds / f"fold{k}" / a.removesuffix("__raw") / "RUN.json"
|
| 111 |
+
if not rp.exists():
|
| 112 |
+
continue
|
| 113 |
+
R = json.loads(rp.read_text())
|
| 114 |
+
assert R["source_checkpoint"] == FINAL_CKPT, rp
|
| 115 |
+
assert R["mode"] == "lora" and int(R["trainable"]["lora_rank"]) == r, (rp, R["trainable"].get("lora_rank"))
|
| 116 |
+
runs.append({"dataset": ds, "rank": r, "pairs": n, "fold": k, "n_train": len(R["train_rows"]),
|
| 117 |
+
"n_inner_val": len(R["inner_val_rows"]), "selected_step": R["selected_step"],
|
| 118 |
+
"n_trainable": R["trainable"]["n_trainable"], "source": str(rp)})
|
| 119 |
+
return pd.DataFrame(rows), pdl, pd.DataFrame(runs)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def wil(pdl, ds, r, n):
|
| 123 |
+
x, y = pdl[(ds, r, n)], pdl[(ds, 16, n)]
|
| 124 |
+
j = x.to_frame("a").join(y.to_frame("b"), how="inner")
|
| 125 |
+
d = j["a"] - j["b"]
|
| 126 |
+
return float(d.mean()), float(wilcoxon(j["a"], j["b"]).pvalue), len(j)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def fig(df, runs):
|
| 130 |
+
fig, axs = plt.subplots(2, len(PANELS), figsize=style.FULL,
|
| 131 |
+
gridspec_kw=dict(left=0.135, right=0.995, top=0.855, bottom=0.17, hspace=0.42,
|
| 132 |
+
wspace=0.42))
|
| 133 |
+
xs = np.arange(len(NS))
|
| 134 |
+
for i, ds in enumerate(DSETS):
|
| 135 |
+
for j, (mk, lab) in enumerate(PANELS):
|
| 136 |
+
ax = axs[i, j]
|
| 137 |
+
sub = df[(df.dataset == ds) & (df.metric == mk)]
|
| 138 |
+
if sub.value.isna().all():
|
| 139 |
+
for sp in ax.spines.values():
|
| 140 |
+
sp.set_visible(False)
|
| 141 |
+
ax.set_xticks([])
|
| 142 |
+
ax.set_yticks([])
|
| 143 |
+
if j == len(PANELS) - 1: # centred over the empty disease columns, in figure coordinates
|
| 144 |
+
p0, p1 = axs[i, j - 1].get_position(), ax.get_position()
|
| 145 |
+
fig.text((p0.x0 + p1.x1) / 2, (p1.y0 + p1.y1) / 2, "healthy cohort: no contrast", ha="center",
|
| 146 |
+
va="center", fontsize=FS - 2, color="#595959", style="italic")
|
| 147 |
+
else:
|
| 148 |
+
for r in RANKS:
|
| 149 |
+
v = [float(sub[(sub["rank"] == r) & (sub.pairs == n)].value.iloc[0]) for n in NS]
|
| 150 |
+
ax.plot(xs, v, color=RCOL[r], lw=2.2 if r == 16 else 1.8, marker=RMK[r], ms=7,
|
| 151 |
+
mec=style.INK, mew=0.6, zorder=4 if r == 16 else 3)
|
| 152 |
+
ax.set_xticks(xs)
|
| 153 |
+
ax.set_xticklabels([n if n != "all" else FZ.all_label(ds) for n in NS])
|
| 154 |
+
ax.set_xlim(-0.35, len(NS) - 0.65)
|
| 155 |
+
ax.tick_params(axis="both", labelsize=FS - 3)
|
| 156 |
+
ax.yaxis.set_major_locator(plt.MaxNLocator(nbins=4))
|
| 157 |
+
if mk == "deg":
|
| 158 |
+
ax.set_ylim(0, max(sub.value) * 1.15)
|
| 159 |
+
if i == 0:
|
| 160 |
+
ax.set_title(lab, fontsize=FS - 1, pad=8)
|
| 161 |
+
n_d = int(json.loads((call_dir(ds, 16) / "summary.json").read_text())["n_donors"])
|
| 162 |
+
y = (axs[i, 0].get_position().y0 + axs[i, 0].get_position().y1) / 2
|
| 163 |
+
fig.text(0.005, y + 0.02, NAME[ds], fontsize=FS + 1, fontweight="bold", va="bottom", ha="left")
|
| 164 |
+
fig.text(0.005, y + 0.01, f"{n_d} donors", fontsize=FS - 2, va="top", ha="left", color="#4D4D4D")
|
| 165 |
+
iv = sorted(set(runs.n_inner_val))
|
| 166 |
+
ivt = f"{iv[0]}" if len(iv) == 1 else f"{iv[0]}–{iv[-1]}"
|
| 167 |
+
x0, x1 = axs[1, 0].get_position().x0, axs[1, -1].get_position().x1
|
| 168 |
+
fig.text((x0 + x1) / 2, 0.01, f"LoRA training pairs per fold (5-fold CV; +{ivt} inner-val pairs for early stopping; test fold never trained on)",
|
| 169 |
+
ha="center", va="bottom", fontsize=FS - 1)
|
| 170 |
+
handles = [Line2D([0], [0], color=RCOL[r], lw=2.2 if r == 16 else 1.8, marker=RMK[r], ms=7, mec=style.INK,
|
| 171 |
+
mew=0.6, label=f"LoRA rank r = {r}" + (" (used in the deck)" if r == 16 else ""))
|
| 172 |
+
for r in RANKS]
|
| 173 |
+
fig.legend(handles=handles, loc="upper center", bbox_to_anchor=(0.55, 1.0), ncol=3, frameon=False,
|
| 174 |
+
fontsize=FS - 2, handlelength=2.4, columnspacing=2.0, borderaxespad=0.0)
|
| 175 |
+
style.save(fig, "sec07_rank_sweep", FIGDIR)
|
| 176 |
+
return ivt
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def words(s):
|
| 180 |
+
return sum(1 for t in s.split() if re.search(r"[A-Za-z0-9]", t))
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def check(s, what, maxlen=None, maxwords=None):
|
| 184 |
+
if re.search(r"[가-힣]", s) or OFF_STORY.search(s):
|
| 185 |
+
raise ValueError(f"Korean / off-story text in {what}: {s!r}")
|
| 186 |
+
if maxlen and len(s) > maxlen:
|
| 187 |
+
raise ValueError(f"{what} over {maxlen} characters ({len(s)}): {s!r}")
|
| 188 |
+
if maxwords and words(s) > maxwords:
|
| 189 |
+
raise ValueError(f"{what} over {maxwords} words: {s!r}")
|
| 190 |
+
return s
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def main():
|
| 194 |
+
FIGDIR.mkdir(parents=True, exist_ok=True)
|
| 195 |
+
OUTDATA.mkdir(parents=True, exist_ok=True)
|
| 196 |
+
df, pdl, runs = load()
|
| 197 |
+
ivt = fig(df, runs)
|
| 198 |
+
df.to_csv(OUTDATA / "sec07_rank_sweep.csv", index=False, float_format="%.6g")
|
| 199 |
+
runs.to_csv(OUTDATA / "sec07_rank_sweep_runs.csv", index=False)
|
| 200 |
+
|
| 201 |
+
def v(ds, r, n, mk):
|
| 202 |
+
return float(df[(df.dataset == ds) & (df["rank"] == r) & (df.pairs == n) & (df.metric == mk)].value.iloc[0])
|
| 203 |
+
|
| 204 |
+
im, se = "immicro", "ye2026_sepsis"
|
| 205 |
+
c16, c64 = v(im, 16, "all", "coverage"), v(im, 64, "all", "coverage")
|
| 206 |
+
l16, l4 = v(im, 16, "all", "comp_l1"), v(im, 4, "all", "comp_l1")
|
| 207 |
+
p16, p64 = v(im, 16, "all", "precision"), v(im, 64, "all", "precision")
|
| 208 |
+
kw = [f"ImMicro r64 vs r16: coverage {c16:.2f} → {c64:.2f}",
|
| 209 |
+
f"ImMicro r4 vs r16: L1 {l16:.3f} → {l4:.3f}",
|
| 210 |
+
f"Kept r16; r64 precision {p16:.2f} → {p64:.2f}"]
|
| 211 |
+
for k in kw:
|
| 212 |
+
check(k, "keyword", KW_MAX, 7)
|
| 213 |
+
r16, r64, r4 = (v(se, r, "all", "logfc_r") for r in (16, 64, 4))
|
| 214 |
+
d16, d64, d4 = (int(v(se, r, "all", "deg")) for r in (16, 64, 4))
|
| 215 |
+
fs = check(f"Sepsis, {FZ.all_label(se)} pairs/fold: r64 logFC r {r16:.2f} → {r64:.2f}, DEG {d16} → {d64}; "
|
| 216 |
+
f"r4 {r4:.2f}, DEG {d4}. Pooled 5-fold scores.", "footnote_short", FOOT_MAX)
|
| 217 |
+
# footnote_full: every value and the per-donor tests
|
| 218 |
+
parts = []
|
| 219 |
+
for ds in DSETS:
|
| 220 |
+
for n in NS:
|
| 221 |
+
cells = []
|
| 222 |
+
for r in RANKS:
|
| 223 |
+
t = (f"r{r}: L1 {v(ds, r, n, 'comp_l1'):.3f}, P/C {v(ds, r, n, 'precision'):.3f} / "
|
| 224 |
+
f"{v(ds, r, n, 'coverage'):.3f}")
|
| 225 |
+
if not np.isnan(v(ds, r, n, "logfc_r")):
|
| 226 |
+
t += f", logFC r {v(ds, r, n, 'logfc_r'):.2f}, DEG {int(v(ds, r, n, 'deg'))}"
|
| 227 |
+
if r != 16:
|
| 228 |
+
m, p, nn = wil(pdl, ds, r, n)
|
| 229 |
+
t += f" (L1 vs r16 {m:+.3f}, Wilcoxon p {p:.2g}, {nn} donors)"
|
| 230 |
+
cells.append(t)
|
| 231 |
+
parts.append(f"{NAME[ds]} n = {n if n != 'all' else FZ.all_label(ds) + ' (every training donor of the fold)'}: "
|
| 232 |
+
+ "; ".join(cells))
|
| 233 |
+
ntr = runs.groupby(["dataset", "rank"]).n_trainable.first()
|
| 234 |
+
full = (f"LoRA fine-tune of the final model (f01 6k·1x·E16) with rank r and alpha = r, same recipe as the deck's "
|
| 235 |
+
f"r = 16 runs (early stop on {ivt} inner-val pairs, 20k step cap); n = training pairs, nested subsets; "
|
| 236 |
+
f"donor-level 5-fold CV, each pair scored once by its fold model (pooled call). Trainable parameters "
|
| 237 |
+
+ ", ".join(f"r{r} {ntr.loc[(im, r)]:,}" for r in RANKS) + ". "
|
| 238 |
+
+ " | ".join(parts)
|
| 239 |
+
+ ". r64 vs r16 brings small gains in coverage and disease signal but slightly lower precision and no "
|
| 240 |
+
"composition change; r4 is worse with many pairs; at n = 5 the ranks are mixed. r = 16 is kept. "
|
| 241 |
+
"Scores: scores/<cohort>/lora_rank_20261001/pooled (r4, r64) and scores/<cohort>/pooled{,_deg} (r16); "
|
| 242 |
+
"table: scores/<cohort>/rankcal_20261001.md.")
|
| 243 |
+
check(full, "footnote")
|
| 244 |
+
nums = [{"value": f"ImMicro {FZ.all_label(im)} pairs/fold coverage r16 {c16:.3f} -> r64 {c64:.3f}; precision {p16:.3f} -> {p64:.3f}; "
|
| 245 |
+
f"L1 r16 {l16:.3f}, r4 {l4:.3f} (Wilcoxon p {wil(pdl, im, 4, 'all')[1]:.2g})",
|
| 246 |
+
"source": f"{call_dir(im, 16)}/summary.json; {call_dir(im, 4)}/summary.json, per_donor.csv"},
|
| 247 |
+
{"value": f"Sepsis {FZ.all_label(se)} pairs/fold logFC r r16 {r16:.3f}, r64 {r64:.3f}, r4 {r4:.3f}; DEG {d16} / {d64} / {d4}",
|
| 248 |
+
"source": f"{call_dir(se, 16)}/summary.json, contrast.csv; {call_dir(se, 4)}/summary.json, contrast.csv"},
|
| 249 |
+
{"value": "trainable parameters: " + ", ".join(f"r{r} {ntr.loc[(im, r)]}" for r in RANKS),
|
| 250 |
+
"source": "runs/<cohort>/fold<k>/<arm>/RUN.json (trainable.n_trainable)"}]
|
| 251 |
+
spec = {"section": "07-rank", "slides": [{
|
| 252 |
+
"title": "LoRA rank: r = 4, 16, 64", "layout": "full", "figures": [str(FIGDIR / "sec07_rank_sweep.png")],
|
| 253 |
+
"keywords": kw, "footnote": full, "footnote_short": fs, "numbers": nums}],
|
| 254 |
+
"scripts": [str(SCRIPT)], "generated_from": "tools/sec07_rank_sweep.py (rerun to refresh; do not edit by hand)"}
|
| 255 |
+
(OUTDATA / "sec07_rank_sweep_slide_text.json").write_text(json.dumps(spec, indent=1, ensure_ascii=False))
|
| 256 |
+
for p in (OUTDATA / "sec07_rank_sweep_slide_text.json", OUTDATA / "sec07_rank_sweep.csv"):
|
| 257 |
+
m = OFF_STORY.search(p.read_text(encoding="utf-8"))
|
| 258 |
+
if m:
|
| 259 |
+
raise ValueError(f"{p}: off-story text {m.group(0)!r}")
|
| 260 |
+
for k in kw:
|
| 261 |
+
print(" *", k, f"({words(k)} words, {len(k)} chars)")
|
| 262 |
+
print(" footnote_short:", fs, f"({len(fs)} chars)")
|
| 263 |
+
print(" footnote:", full)
|
| 264 |
+
return 0
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
if __name__ == "__main__":
|
| 268 |
+
sys.exit(main())
|