junidude14 commited on
Commit
4ee2286
·
verified ·
1 Parent(s): 89f2ab3

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20260930T065633Z-summary-deck-scsemi-final/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec05_cells_offmanifold.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Section 5, slide (b): cells generated from real bulk (raw) vs other inputs vs real cells (ImMicro, final model).
2
+
3
+ Figure 1 (HALF): cell UMAP (fitted on real R1 cells; other sets placed with umap.transform), 3,000 held-out real
4
+ R2 cells and the same 3,000 matched generated cells from real bulk (raw) and from the donor's own sc pseudobulk,
5
+ coloured by the frozen f01common six-type label. Source: umap/cell_immicro_5arm/interactive/cells_5arm.json.
6
+ Figure 2 (HALF): monocyte %, precision and coverage per input arm (PCA-50, k = 10, 150 cells x 107 donors per set,
7
+ one scoring call) from input_path_compare/immicro_behcet/tables/immicro_table.csv. Arms: real bulk (raw), TPM,
8
+ reference calibration with the AIFI and with the AIDA reference, sc pseudobulk, real R2 cells.
9
+ CPU only.
10
+ """
11
+ import json
12
+ import sys
13
+ from pathlib import Path
14
+
15
+ import numpy as np
16
+ import pandas as pd
17
+
18
+ DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/2026-09-30--paper-summary--r00")
19
+ sys.path.insert(0, str(DECK / "tools"))
20
+ import style # noqa: E402
21
+ import matplotlib.pyplot as plt # noqa: E402
22
+ from matplotlib.lines import Line2D # noqa: E402
23
+
24
+ U = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/utility_studies_final6k_20260925")
25
+ CELLS = U / "umap/cell_immicro_5arm/interactive/cells_5arm.json"
26
+ TABLE = U / "input_path_compare/immicro_behcet/tables/immicro_table.csv"
27
+ TRANS = U / "umap/cell_immicro_5arm/tables/c_label_transition_pseudo_to_raw_counts.csv"
28
+ FIG = DECK / "figures"
29
+ DATA = DECK / "data"
30
+
31
+ RAW_EDGE, TPM_EDGE = "#5E8FB5", "#9C8B3B"
32
+ # (arm key in immicro_table.csv, tick label, fill colour, edge colour)
33
+ ARMS = [
34
+ ("raw", "real bulk (raw)", style.ARM["zs_raw"], RAW_EDGE),
35
+ ("tpm", "TPM", style.ARM["tpm"], TPM_EDGE),
36
+ ("refcal", "refcal, AIFI ref.", style.ARM["refcal"], style.ARM["refcal"]),
37
+ ("refcal_aida", "refcal, AIDA ref.", style.ARM["refcal"], style.ARM["refcal"]),
38
+ ("pseudo", "sc pseudobulk", style.ARM["pseudo"], style.ARM["pseudo"]),
39
+ ("real_R2", "real cells (R2)", style.GREY, style.GREY),
40
+ ]
41
+
42
+
43
+ def umap_figure():
44
+ d = json.load(open(CELLS))
45
+ sets, labels = d["sets"], d["labels_l1"]
46
+ lab_col = d["meta"]["colours"]["labels_l1"]
47
+ c = pd.DataFrame({k: d["cells"][k] for k in ("set", "pair_id", "donor_index", "l1", "x", "y")})
48
+ c["set_name"] = [sets[i] for i in c["set"]]
49
+ c["label"] = [labels[i] for i in c["l1"]]
50
+ keep = c[c["set_name"].isin(["R2", "raw", "pseudo"])].copy()
51
+ keep[["set_name", "pair_id", "donor_index", "label", "x", "y"]].to_csv(DATA / "sec05_cells_umap_coords.csv", index=False)
52
+ real = keep[keep["set_name"] == "R2"]
53
+ n_per = keep.groupby("set_name").size().to_dict()
54
+ assert n_per["R2"] == n_per["raw"] == n_per["pseudo"], n_per
55
+
56
+ fig, axes = plt.subplots(2, 2, figsize=style.HALF)
57
+ panels = [("R2", "Real cells"), ("raw", "From real bulk (raw)"), ("pseudo", "From sc pseudobulk")]
58
+ rng = np.random.default_rng(0)
59
+ for ax, (key, title) in zip(axes.flat[:3], panels):
60
+ s = keep[keep["set_name"] == key]
61
+ if key != "R2":
62
+ ax.scatter(real["x"], real["y"], s=1.2, color="#D9D9D9", lw=0, rasterized=True)
63
+ order = rng.permutation(len(s))
64
+ s = s.iloc[order]
65
+ ax.scatter(s["x"], s["y"], s=1.6, c=[lab_col[l] for l in s["label"]], lw=0, rasterized=True)
66
+ ax.text(0.02, 0.99, title, transform=ax.transAxes, ha="left", va="top", fontsize=style.FS - 2)
67
+ ax.set_xticks([])
68
+ ax.set_yticks([])
69
+ for sp in ax.spines.values():
70
+ sp.set_visible(False)
71
+ xs = np.r_[keep["x"]]
72
+ ys = np.r_[keep["y"]]
73
+ for ax in axes.flat[:3]:
74
+ ax.set_xlim(xs.min() - 0.5, xs.max() + 0.5)
75
+ ax.set_ylim(ys.min() - 0.5, ys.max() + 2.5)
76
+ lg = axes.flat[3]
77
+ lg.axis("off")
78
+ handles = [Line2D([], [], marker="o", ls="", color=lab_col[l], markersize=8) for l in labels]
79
+ handles.append(Line2D([], [], marker="o", ls="", color="#D9D9D9", markersize=8))
80
+ names = list(labels) + ["real cells"]
81
+ lg.legend(handles, names, loc="center left", handletextpad=0.2, labelspacing=0.45, borderaxespad=0.0,
82
+ fontsize=style.FS - 2)
83
+ fig.subplots_adjust(left=0.01, right=0.99, top=0.99, bottom=0.01, wspace=0.04, hspace=0.04)
84
+ style.save(fig, "sec05_cells_umap", FIG)
85
+
86
+ mono = {k: 100 * float((keep[keep["set_name"] == k]["label"] == "Monocyte").mean()) for k in ("R2", "raw", "pseudo")}
87
+ return n_per, mono
88
+
89
+
90
+ def metrics_figure():
91
+ t = pd.read_csv(TABLE).set_index("arm")
92
+ vals = {}
93
+ for arm, *_ in ARMS:
94
+ vals[arm] = {"monocyte_pct": float(t.loc[arm, "monocyte_pct_150"]),
95
+ "precision": float(t.loc[arm, "precision"]),
96
+ "coverage": float(t.loc[arm, "coverage"])}
97
+ if arm != "real_R2":
98
+ vals[arm]["comp_L1"] = float(t.loc[arm, "comp_L1"])
99
+ # the real_R2 row's comp_L1 is the cohort-mean leave-one-out null, not a property of the R2 cells
100
+ null = float(t.loc["raw", "comp_L1_obs_LOO_null"])
101
+ assert abs(null - float(t.loc["real_R2", "comp_L1"])) < 1e-12, "null differs between rows"
102
+ out = []
103
+ for arm, *_ in ARMS:
104
+ for k, v in vals[arm].items():
105
+ out.append({"arm": arm, "metric": k, "value": v, "source": str(TABLE)})
106
+ out.append({"arm": "null", "metric": "comp_L1_LOO_null", "value": null,
107
+ "source": f"{TABLE} (column comp_L1_obs_LOO_null)"})
108
+ tr = pd.read_csv(TRANS, index_col=0)
109
+ t_row = tr.loc["T cell"]
110
+ t_to_mono = float(t_row["Monocyte"] / t_row.sum())
111
+ n_t, n_t_mono, n_all = int(t_row.sum()), int(t_row["Monocyte"]), int(tr.to_numpy().sum())
112
+ out.append({"arm": "raw", "metric": "pseudo_T_cells_labelled_monocyte_under_raw", "value": t_to_mono,
113
+ "source": str(TRANS)})
114
+ out.append({"arm": "raw", "metric": "n_pseudo_T_cells", "value": n_t, "source": str(TRANS)})
115
+ out.append({"arm": "raw", "metric": "n_pseudo_T_to_monocyte", "value": n_t_mono, "source": str(TRANS)})
116
+ out.append({"arm": "raw", "metric": "n_cells_in_transition_table", "value": n_all, "source": str(TRANS)})
117
+ pd.DataFrame(out).to_csv(DATA / "sec05_cells_metrics.csv", index=False)
118
+
119
+ fig, axes = plt.subplots(1, 3, figsize=style.HALF, sharey=True)
120
+ specs = [("monocyte_pct", "Monocytes (%)", 48, "{:.1f}", [0, 20, 40]),
121
+ ("precision", "Precision", 1.5, "{:.2f}", [0, 0.5, 1.0]),
122
+ ("coverage", "Coverage", 1.5, "{:.2f}", [0, 0.5, 1.0])]
123
+ ys = np.arange(len(ARMS))
124
+ for ax, (k, xlab, xmax, fmt, ticks) in zip(axes, specs):
125
+ for y, (arm, lab, col, edge) in zip(ys, ARMS):
126
+ v = vals[arm][k]
127
+ ax.barh(y, v, 0.68, color=col, edgecolor=edge, lw=0.9)
128
+ ax.text(v + xmax * 0.025, y, fmt.format(v), ha="left", va="center", fontsize=style.FS - 3)
129
+ ax.set_xlim(0, xmax)
130
+ ax.set_xticks(ticks)
131
+ ax.set_xticklabels([f"{x:g}" for x in ticks])
132
+ ax.set_xlabel(xlab, labelpad=2)
133
+ ax.tick_params(axis="y", length=0)
134
+ axes[0].set_yticks(ys)
135
+ axes[0].set_yticklabels([a[1] for a in ARMS])
136
+ axes[0].set_ylim(len(ARMS) - 0.45, -0.55)
137
+ fig.subplots_adjust(left=0.30, right=0.99, top=0.99, bottom=0.11, wspace=0.12)
138
+ style.save(fig, "sec05_cells_metrics", FIG)
139
+ return vals, null, (t_to_mono, n_t_mono, n_t, n_all)
140
+
141
+
142
+ def main():
143
+ n_per, mono_json = umap_figure()
144
+ vals, null, tm = metrics_figure()
145
+ print("cells per UMAP panel", n_per)
146
+ print("monocyte % in the 3,000-cell UMAP subsample", {k: round(v, 1) for k, v in mono_json.items()})
147
+ for arm, d in vals.items():
148
+ print(arm, {k: round(v, 4) for k, v in d.items()})
149
+ print("composition L1 LOO null", round(null, 4))
150
+ print("pseudo T cells that become monocytes under raw: %.4f (%d / %d; %d cells in table)" % tm)
151
+
152
+
153
+ if __name__ == "__main__":
154
+ main()
paper-releases/pbisc-diffusion/updates/20260930T065633Z-summary-deck-scsemi-final/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec05_condition_space.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Section 5, slide (a): real bulk vs sc pseudobulk of the same donors as MODEL INPUT vectors (ImMicro, 107 donors).
2
+
3
+ These are the bulk-side input vectors (log1p CPM over the 5,508 shared panel genes), not the model's learned
4
+ condition embedding (ctx).
5
+
6
+ Left: PC1/PC2 of PCA-30 fitted on the 107 sc pseudobulks; each donor's real bulk (raw) is joined to its own
7
+ pseudobulk. Pseudobulk markers split by sc pool block (DB1-3 vs DB4-7), because pseudobulk PC1 is almost entirely
8
+ sc pool batch; the pool R^2 on PC1 is computed here from the plotted coordinates and the pool labels in the
9
+ datalake features.npz (same file the sample-level study loads), and written to data/sec05_condition_space_numbers.csv.
10
+ Right: own-donor top-1 retrieval as measured vs after leave-one-out shift removal (a diagnostic that uses the other
11
+ donors' paired pseudobulks), read from metrics_ImMicro.json.
12
+ CPU only; reads existing coordinates, recomputes nothing heavy.
13
+ """
14
+ import csv
15
+ import json
16
+ import sys
17
+ from pathlib import Path
18
+
19
+ import numpy as np
20
+ import pandas as pd
21
+
22
+ DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/2026-09-30--paper-summary--r00")
23
+ sys.path.insert(0, str(DECK / "tools"))
24
+ import style # noqa: E402
25
+ import matplotlib.pyplot as plt # noqa: E402
26
+ from matplotlib.lines import Line2D # noqa: E402
27
+
28
+ SRC = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/utility_studies_final6k_20260925/umap/sample_level")
29
+ COORDS = SRC / "ImMicro" / "coords_ImMicro_native.csv"
30
+ METRICS = SRC / "ImMicro" / "metrics_ImMicro.json"
31
+ BATCH = SRC / "ImMicro" / "batch_structure_ImMicro.json"
32
+ # pool labels: the source npz that build_realbulk_conditions.load_cohort("ImMicro") reads (groups = pools)
33
+ FEATURES = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/analyses/offset_sample_size_20260914/features.npz")
34
+ FIG = DECK / "figures"
35
+ DATA = DECK / "data"
36
+
37
+ RAW_LABEL = "real bulk (raw)"
38
+
39
+
40
+ def r2(z, lab):
41
+ """Between-group SS / total SS (same definition as sample_level/tools/batch_structure.py)."""
42
+ z = np.asarray(z, float).reshape(len(z), -1)
43
+ mu = z.mean(0)
44
+ tot = ((z - mu) ** 2).sum()
45
+ between = sum(((z[lab == g].mean(0) - mu) ** 2).sum() * (lab == g).sum() for g in np.unique(lab))
46
+ return float(between / tot)
47
+
48
+
49
+ def main():
50
+ c = pd.read_csv(COORDS)
51
+ c = c[c["space"] == "pca"]
52
+ raw = c[c["group"] == "raw"].set_index("donor_id")[["x", "y"]]
53
+ obs = c[c["group"] == "obs"].set_index("donor_id")[["x", "y"]]
54
+ donors = list(obs.index)
55
+ assert set(raw.index) == set(donors) and len(donors) == 107, (len(donors), len(raw))
56
+ raw = raw.loc[donors].to_numpy()
57
+ obs = obs.loc[donors].to_numpy()
58
+ n = len(donors)
59
+
60
+ # pool labels (small members only)
61
+ f = np.load(FEATURES, allow_pickle=False)
62
+ pool_of = dict(zip(f["donor_ids"].astype(str).tolist(), f["pools"].astype(str).tolist()))
63
+ assert set(donors) <= set(pool_of), "donor ids missing from features.npz"
64
+ pools = np.array([pool_of[d] for d in donors])
65
+ pool_pc1_mean = {p: float(obs[pools == p, 0].mean()) for p in sorted(np.unique(pools))}
66
+ block_lo = sorted(p for p, v in pool_pc1_mean.items() if v < 0) # data-driven split on pseudobulk PC1
67
+ block_hi = sorted(p for p, v in pool_pc1_mean.items() if v >= 0)
68
+ in_lo = np.isin(pools, block_lo)
69
+ pc1_r2 = {"pseudobulk": r2(obs[:, 0], pools), "raw": r2(raw[:, 0], pools)}
70
+
71
+ off = raw - obs
72
+ mean_off = off.mean(0)
73
+
74
+ m = json.load(open(METRICS))
75
+ evr = m["pca_explained_variance_ratio"]
76
+ pca = m["settings"]["native"]["sum"]["pca30"]
77
+ full = m["settings"]["native"]["sum"]["full"]
78
+ nums = {
79
+ "D_pca30": pca["unit"]["D"],
80
+ "raw_to_own_pseudo_median_D_pca30": pca["distance_D"]["raw->obs"]["median"],
81
+ "raw_to_own_pseudo_median_D_full": full["distance_D"]["raw->obs"]["median"],
82
+ "shared_fraction_sq_offset_pca30": pca["shared_shift"]["raw"]["shared_fraction"],
83
+ "shared_fraction_sq_offset_full": full["shared_shift"]["raw"]["shared_fraction"],
84
+ "pca30_captured_fraction_of_raw_offset_sq": pca["pca_captured_fraction_of_offset_sq"]["raw"],
85
+ "top1_plain_pca30": pca["retrieval"]["raw"]["top1_own_sample"],
86
+ "top1_shift_removed_pca30": pca["retrieval_shift_removed"]["raw"]["top1_own_sample"],
87
+ "top1_plain_full": full["retrieval"]["raw"]["top1_own_sample"],
88
+ "top1_shift_removed_full": full["retrieval_shift_removed"]["raw"]["top1_own_sample"],
89
+ "top1_chance": pca["retrieval"]["raw"]["chance"],
90
+ "n_donors": m["n_samples"],
91
+ "n_genes": m["n_genes"],
92
+ "pc1_evr": evr[0],
93
+ "pc2_evr": evr[1],
94
+ # for the speaker notes: summed generated cells vs real pseudobulk (two biases partly cancel)
95
+ "gen_raw_to_obs_median_D_pca30": pca["distance_D"]["gen_raw->obs"]["median"],
96
+ "gen_pseudo_to_obs_median_D_pca30": pca["distance_D"]["gen_pseudo->obs"]["median"],
97
+ }
98
+ assert nums["n_donors"] == n
99
+ bs = json.load(open(BATCH))
100
+ bnums = {
101
+ "pool_R2_pseudobulk_pca30": bs["settings"]["native"]["pca30"]["obs"],
102
+ "pool_R2_raw_pca30": bs["settings"]["native"]["pca30"]["raw"],
103
+ "pool_R2_permutation_null_median": bs["pca30_obs_permutation_null"]["median"],
104
+ }
105
+ lnums = {
106
+ "pool_R2_pseudobulk_PC1": pc1_r2["pseudobulk"],
107
+ "pool_R2_raw_PC1": pc1_r2["raw"],
108
+ "pseudobulk_PC1_mean_block_" + "+".join(block_lo): float(obs[in_lo, 0].mean()),
109
+ "pseudobulk_PC1_mean_block_" + "+".join(block_hi): float(obs[~in_lo, 0].mean()),
110
+ "n_donors_block_" + "+".join(block_lo): int(in_lo.sum()),
111
+ "n_donors_block_" + "+".join(block_hi): int((~in_lo).sum()),
112
+ }
113
+
114
+ # panel source tables
115
+ pd.DataFrame({
116
+ "donor_id": donors, "pool": pools,
117
+ "pseudo_pc1": obs[:, 0], "pseudo_pc2": obs[:, 1],
118
+ "raw_pc1": raw[:, 0], "raw_pc2": raw[:, 1],
119
+ }).to_csv(DATA / "sec05_condition_space_coords.csv", index=False)
120
+ with open(DATA / "sec05_condition_space_numbers.csv", "w", newline="") as fh:
121
+ w = csv.writer(fh)
122
+ w.writerow(["quantity", "value", "source"])
123
+ for k, v in nums.items():
124
+ w.writerow([k, v, str(METRICS)])
125
+ for k, v in bnums.items():
126
+ w.writerow([k, v, str(BATCH)])
127
+ for k, v in lnums.items():
128
+ w.writerow([k, v, f"computed here from {COORDS} (pca PC1) and pools in {FEATURES}"])
129
+
130
+ # ---- figure
131
+ fig = plt.figure(figsize=style.TALL)
132
+ gs = fig.add_gridspec(1, 2, width_ratios=[1.65, 1.0], wspace=0.32)
133
+ ax = fig.add_subplot(gs[0, 0])
134
+ c_raw, c_ps = style.ARM["zs_raw"], style.ARM["pseudo"]
135
+ edge = "#5E8FB5"
136
+ for i in range(n):
137
+ ax.plot([obs[i, 0], raw[i, 0]], [obs[i, 1], raw[i, 1]], color=style.GREY, lw=0.5, alpha=0.45, zorder=1)
138
+ lab_lo = f"sc pseudobulk, pools {block_lo[0]}–{block_lo[-1][2:]}"
139
+ lab_hi = f"sc pseudobulk, pools {block_hi[0]}–{block_hi[-1][2:]}"
140
+ ax.scatter(obs[in_lo, 0], obs[in_lo, 1], s=18, color=c_ps, lw=0, marker="o", zorder=3)
141
+ ax.scatter(obs[~in_lo, 0], obs[~in_lo, 1], s=22, facecolor="white", edgecolor=c_ps, lw=1.0, marker="o", zorder=3)
142
+ ax.scatter(raw[:, 0], raw[:, 1], s=20, color=c_raw, edgecolor=edge, lw=0.4, zorder=2)
143
+ c0 = obs.mean(0)
144
+ ax.annotate("", xy=c0 + mean_off, xytext=c0,
145
+ arrowprops=dict(arrowstyle="-|>", color=style.INK, lw=1.8, mutation_scale=16), zorder=4)
146
+ # label in the empty PC1 gap between the pseudobulk and raw clusters
147
+ ax.text(c0[0] + 0.66 * mean_off[0], c0[1] + 0.66 * mean_off[1] + 1.6, "mean shift",
148
+ ha="center", va="bottom", fontsize=style.FS - 2, color=style.INK, zorder=5,
149
+ bbox=dict(boxstyle="square,pad=0.1", fc="white", ec="none"))
150
+ ax.set_xlabel(f"PC1 ({100 * nums['pc1_evr']:.1f}%)")
151
+ ax.set_ylabel(f"PC2 ({100 * nums['pc2_evr']:.1f}%)")
152
+ ally = np.concatenate([obs[:, 1], raw[:, 1]])
153
+ ax.set_ylim(ally.min() - 3, ally.max() + 16)
154
+ handles = [Line2D([], [], marker="o", ls="", color=c_ps, markersize=6),
155
+ Line2D([], [], marker="o", ls="", markerfacecolor="white", markeredgecolor=c_ps, markersize=6),
156
+ Line2D([], [], marker="o", ls="", markerfacecolor=c_raw, markeredgecolor=edge, markersize=7)]
157
+ ax.legend(handles, [lab_lo, lab_hi, RAW_LABEL], loc="upper left", handletextpad=0.1, borderaxespad=0.1,
158
+ labelspacing=0.3)
159
+
160
+ bx = fig.add_subplot(gs[0, 1])
161
+ spaces = [("PCA-30", "top1_plain_pca30", "top1_shift_removed_pca30"),
162
+ (f"{nums['n_genes']:,}\ngenes", "top1_plain_full", "top1_shift_removed_full")]
163
+ w = 0.36
164
+ for j, (lab, k0, k1) in enumerate(spaces):
165
+ v0, v1 = 100 * nums[k0], 100 * nums[k1]
166
+ bx.bar(j - w / 2, v0, w, color="white", edgecolor=edge, lw=1.2)
167
+ bx.bar(j + w / 2, v1, w, color=c_raw, edgecolor=edge, lw=1.2)
168
+ bx.text(j - w / 2, v0 + 1.5, f"{v0:.1f}", ha="center", va="bottom", fontsize=style.FS - 3)
169
+ bx.text(j + w / 2, v1 + 1.5, f"{v1:.1f}", ha="center", va="bottom", fontsize=style.FS - 3)
170
+ ch = 100 * nums["top1_chance"]
171
+ bx.axhline(ch, color=style.GREY, lw=1.2, ls="--")
172
+ bx.set_xticks(range(len(spaces)))
173
+ bx.set_xticklabels([s[0] for s in spaces])
174
+ bx.set_xlim(-0.6, 1.6)
175
+ bx.set_ylim(0, 128)
176
+ bx.set_yticks([0, 25, 50, 75, 100])
177
+ bx.set_ylabel("Own donor = nearest pseudobulk (%)")
178
+ bh = [plt.Rectangle((0, 0), 1, 1, facecolor="white", edgecolor=edge, lw=1.2),
179
+ plt.Rectangle((0, 0), 1, 1, facecolor=c_raw, edgecolor=edge, lw=1.2),
180
+ Line2D([], [], color=style.GREY, lw=1.2, ls="--")]
181
+ bx.legend(bh, ["as measured", "shift removed", f"chance ({ch:.1f}%)"], loc="upper left", handlelength=1.2,
182
+ handletextpad=0.3, borderaxespad=0.1, labelspacing=0.3)
183
+ fig.subplots_adjust(left=0.09, right=0.99, top=0.98, bottom=0.12)
184
+ style.save(fig, "sec05_condition_space", FIG)
185
+
186
+ print("pool mean pseudobulk PC1:", {k: round(v, 2) for k, v in pool_pc1_mean.items()})
187
+ for k, v in {**nums, **bnums, **lnums}.items():
188
+ print(f"{k}\t{v}")
189
+
190
+
191
+ if __name__ == "__main__":
192
+ main()
paper-releases/pbisc-diffusion/updates/20260930T065633Z-summary-deck-scsemi-final/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, backup 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/20260930T065633Z-summary-deck-scsemi-final/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec06_finetune_method.py ADDED
@@ -0,0 +1,469 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Section 6 of the 2026-09-30 paper-summary deck: fine-tuning with paired real bulk + single cells.
3
+
4
+ Figures (CPU only; reads receipts, never loads a checkpoint):
5
+ figures/sec06_ft_method.png/.pdf method diagram (pretrained -> LoRA fine-tune -> merge -> generate),
6
+ drawn at 12.3 x 4.65 in so it places at 100 % above one keyword line
7
+ figures/sec06_eval_design.png/.pdf donor-level 5-fold vs few-pair scenario, counts for the 5 paired cohorts
8
+ Tables:
9
+ data/sec06_ft_method.csv every number printed on the method diagram / keyword line, with its source
10
+ data/sec06_eval_design.csv per-fold / per-draw train / inner-val / test counts (all 5 cohorts)
11
+ data/sec06_eval_design_sepsis_roles.csv the plotted donor x fold/draw role matrix (sepsis)
12
+
13
+ Revision r2 (after review): batches are pair-balanced, not donor-balanced (tools/ft_sdd.py draw_batch draws a
14
+ folds.csv row uniformly, then one of its cells; the ft_sdd.py docstring and README step 4 say "donor-balanced",
15
+ which is only true when every donor has one sample); cells are generated per bulk sample; the pretraining K
16
+ range is shown; LoRA counts are adapters (one per Linear), not blocks; dark-grey text; sec09 cohort names/order.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import json
21
+ import sys
22
+ from collections import OrderedDict
23
+ from pathlib import Path
24
+
25
+ import numpy as np
26
+ import pandas as pd
27
+ from matplotlib.patches import Rectangle
28
+
29
+ DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/"
30
+ "2026-09-30--paper-summary--r00")
31
+ sys.path.insert(0, str(DECK / "tools"))
32
+ import style # noqa: E402
33
+ import matplotlib.pyplot as plt # noqa: E402
34
+
35
+ FIG, DATA = DECK / "figures", DECK / "data"
36
+ M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
37
+ PLAN = M8 / "plans/paired_finetune_intradataset_20260927"
38
+ BASE_RUN = M8 / "runs/f01_6k_1x_seed20260627"
39
+
40
+ INK = style.INK
41
+ RULE = style.GREY # lines and rules only
42
+ TXT2 = "#5A5A5A" # secondary text (contrast about 6.9:1 on white)
43
+ LORA = style.ARM["lora"]
44
+ FROZEN = "#E6E6E6"
45
+ # same names and order as sec09 (tools/sec09_paired_validation.py ORDER + data/sec09_cohorts.csv study)
46
+ DATASETS = OrderedDict([
47
+ ("immicro", "ImMicro 2026"),
48
+ ("ye2026_sepsis", "Ye 2026"),
49
+ ("imperial_eskd", "Imperial ESKD"),
50
+ ("giroux2022", "Giroux 2022"),
51
+ ("ji2025_chili", "Ji 2025"),
52
+ ])
53
+ FIG_W, FIG_H = style.FULL[0], 4.65
54
+
55
+
56
+ # ------------------------------------------------------------------------------------------ read receipts
57
+ def read_method_numbers() -> tuple[dict, list[dict]]:
58
+ rows: list[dict] = []
59
+
60
+ def rec(key, value, display, src):
61
+ rows.append({"key": key, "value": value, "display": display, "source": str(src)})
62
+ return display
63
+
64
+ run_cv = PLAN / "runs/immicro/fold0/real_lora/RUN.json"
65
+ run_fs = PLAN / "runs/ye2026_sepsis/fewshot_n5/draw0/lora/RUN.json"
66
+ cv, fs = json.loads(run_cv.read_text()), json.loads(run_fs.read_text())
67
+ t = cv["trainable"]
68
+ assert t["mode"] == "lora" and fs["trainable"]["n_trainable"] == t["n_trainable"]
69
+ assert fs["trainable"]["n_total_base"] == t["n_total_base"]
70
+ assert cv["batch_size"] == fs["batch_size"]
71
+
72
+ # every LoRA receipt on this host (fixed 3,000-step few-pair runs and early-stopped / capped 5-fold runs)
73
+ all_wall = []
74
+ for p in sorted(PLAN.glob("runs/*/fewshot_n5/draw*/lora/RUN.json")) + \
75
+ sorted(PLAN.glob("runs/*/fold*/real_lora/RUN.json")):
76
+ d = json.loads(p.read_text())
77
+ assert d["trainable"]["mode"] == "lora"
78
+ all_wall.append(d["wall_seconds"])
79
+ all_wall = np.asarray(all_wall) / 60
80
+
81
+ status = json.loads((BASE_RUN / "RUN_STATUS.json").read_text())
82
+ assert status["parameters"] == t["n_total_base"], "base parameter count differs between receipts"
83
+ contract = json.loads((BASE_RUN / "ALLCELL_DATA_CONTRACT.json").read_text())["coverage_after_topup"]
84
+ kk = pd.read_csv(DATA / "sec01_recipe_k.csv") # written by sec01_overview.py from the manifest
85
+ assert int(kk["K"].max()) == int(contract["max_k"]), "pretraining K maximum disagrees with the run contract"
86
+ prep = json.loads((PLAN / "data/immicro/PREPARE.json").read_text())
87
+ gen_log = PLAN / "generated/ye2026_sepsis/fewshot_n5/draw0/lora__raw.log"
88
+ gen = json.loads(gen_log.read_text())
89
+ gen_npz = PLAN / "generated/ye2026_sepsis/fewshot_n5/draw0/lora__raw.npz"
90
+ with np.load(gen_npz, allow_pickle=False) as z: # small keys only (lazy npz access)
91
+ meta = json.loads(str(z["metadata_json"]))
92
+ cpb = np.unique(z["cells_per_bulk"])
93
+ rk = np.unique(z["recipe_k"])
94
+ assert len(cpb) == 1 and len(rk) == 1
95
+ assert gen["checkpoint_sha256"] == fs["checkpoint_sha256"], "generation log is not from this fine-tune"
96
+ for ds in DATASETS: # same condition / generation policy in all cohorts
97
+ pj = json.loads((PLAN / f"data/{ds}/PREPARE.json").read_text())
98
+ assert int(pj["recipe_k"]) == int(prep["recipe_k"]) and int(pj["cells_per_bulk"]) == int(cpb[0])
99
+
100
+ # batch sampling rule, read from the code that ran (not from the docstring)
101
+ ft_src = (PLAN / "tools/ft_sdd.py").read_text()
102
+ assert "r = rows[rng.integers(0, len(rows), size=batch)]" in ft_src, "draw_batch changed; re-check label"
103
+
104
+ # LoRA adapters per module (one B.A per nn.Linear)
105
+ names = {"condition_encoder": "condition encoder", "time_encoder": "time encoder",
106
+ "context_mixer": "context mixer", "down_blocks": "down blocks", "up_blocks": "up blocks",
107
+ "output_trunk": "output + 2 heads", "value_head": "output + 2 heads",
108
+ "active_head": "output + 2 heads"}
109
+ groups = OrderedDict((g, 0) for g in ["condition encoder", "time encoder", "context mixer", "down blocks",
110
+ "up blocks", "output + 2 heads"])
111
+ for layer in t["lora_layers"]:
112
+ groups[names[layer.split(".")[0]]] += 1
113
+ assert sum(groups.values()) == len(t["lora_layers"])
114
+
115
+ n = {}
116
+ n["n_trainable"] = rec("lora_n_trainable", t["n_trainable"], f"{t['n_trainable'] / 1e6:.2f} M", run_cv)
117
+ n["n_total"] = rec("base_n_params", t["n_total_base"], f"{t['n_total_base'] / 1e6:.1f} M", run_cv)
118
+ n["pct"] = rec("lora_trainable_pct", 100 * t["n_trainable"] / t["n_total_base"],
119
+ f"{100 * t['n_trainable'] / t['n_total_base']:.1f} %", run_cv)
120
+ n["rank"] = rec("lora_rank", t["lora_rank"], f"{t['lora_rank']}", run_cv)
121
+ n["alpha"] = rec("lora_alpha", t["lora_alpha"], f"{t['lora_alpha']:g}", run_cv)
122
+ n["n_layers"] = rec("lora_n_linear_layers", len(t["lora_layers"]), f"{len(t['lora_layers'])}", run_cv)
123
+ for g, c in groups.items():
124
+ rec(f"lora_adapters_{g.replace(' ', '_').replace('+', 'and')}", c, f"{c}", run_cv)
125
+ n["groups"] = groups
126
+ n["lr"] = rec("lr", cv["lr"], f"{cv['lr']:.0e}".replace("e-04", "e-4"), run_cv)
127
+ n["batch"] = rec("batch_size", cv["batch_size"], f"{cv['batch_size']}", run_cv)
128
+ rec("batch_sampling", "a folds.csv row (one bulk-sc sample pair) drawn uniformly, then one of its cells "
129
+ "uniformly: pair-balanced, not donor-balanced when a donor has several samples",
130
+ "pair-balanced", PLAN / "tools/ft_sdd.py (draw_batch)")
131
+ n["ema"] = rec("ema_decay", cv["ema_decay"], f"{cv['ema_decay']}", run_cv)
132
+ n["eval_every"] = rec("eval_every_steps", cv["eval_every"], f"{cv['eval_every']}", run_cv)
133
+ n["patience"] = rec("patience_evals", cv["patience"], f"{cv['patience']}", run_cv)
134
+ n["patience_steps"] = rec("patience_steps", cv["patience"] * cv["eval_every"],
135
+ f"{cv['patience'] * cv['eval_every']:,}", run_cv)
136
+ n["cap"] = rec("max_steps_cap", cv["max_steps"], f"{cv['max_steps']:,}", run_cv)
137
+ n["fixed"] = rec("fewpair_fixed_steps", fs["fixed_steps"], f"{fs['fixed_steps']:,}", run_fs)
138
+ n["fs_inner"] = rec("fewpair_inner_val_rows", len(fs["inner_val_rows"]), f"{len(fs['inner_val_rows'])}", run_fs)
139
+ assert len(fs["inner_val_rows"]) == 0
140
+ n["reload"] = rec("merge_reload_forward_max_abs_diff", cv["reload_forward_max_abs_diff"],
141
+ f"{cv['reload_forward_max_abs_diff']:g}", run_cv)
142
+ n["wall_lo"] = rec("lora_wall_minutes_min", float(all_wall.min()), f"{all_wall.min():.0f}",
143
+ PLAN / f"runs/*/fewshot_n5/draw*/lora/RUN.json + runs/*/fold*/real_lora/RUN.json "
144
+ f"(wall_seconds, n={len(all_wall)}; Imperial runs are on server_2, not included)")
145
+ n["wall_hi"] = rec("lora_wall_minutes_max", float(all_wall.max()), f"{all_wall.max():.0f}",
146
+ PLAN / f"runs/*/fewshot_n5/draw*/lora/RUN.json + runs/*/fold*/real_lora/RUN.json "
147
+ f"(wall_seconds, n={len(all_wall)})")
148
+ n["pre_steps"] = rec("pretrain_global_steps", status["global_step"], f"{status['global_step']:,}",
149
+ BASE_RUN / "RUN_STATUS.json")
150
+ n["pre_hours"] = rec("pretrain_wall_hours", status["wall_seconds"] / 3600,
151
+ f"{status['wall_seconds'] / 3600:.1f} h", BASE_RUN / "RUN_STATUS.json")
152
+ n["pre_epoch"] = rec("pretrain_epochs", status["epochs_completed"], f"E{status['epochs_completed']}",
153
+ BASE_RUN / "RUN_STATUS.json")
154
+ n["genes"] = rec("n_genes", status["n_genes"], f"{status['n_genes']:,}", BASE_RUN / "RUN_STATUS.json")
155
+ n["k_lo"] = rec("pretrain_recipe_k_min", int(kk["K"].min()), f"{int(kk['K'].min()):,}",
156
+ DATA / "sec01_recipe_k.csv")
157
+ n["k_hi"] = rec("pretrain_recipe_k_max", int(kk["K"].max()), f"{int(kk['K'].max()):,}",
158
+ f"{DATA / 'sec01_recipe_k.csv'}; = max_k in {BASE_RUN / 'ALLCELL_DATA_CONTRACT.json'}")
159
+ rec("pretrain_topup_recipes_below_grid", contract["topup_recipes"],
160
+ f"{contract['topup_recipes']:,} of {contract['total_train_recipes_with_topup']:,} train recipes are "
161
+ f"coverage top-ups ({contract['tail_policy']})", BASE_RUN / "ALLCELL_DATA_CONTRACT.json")
162
+ n["K"] = rec("condition_fixed_depth_K", prep["recipe_k"], f"{prep['recipe_k']:,}",
163
+ PLAN / "data/<cohort>/PREPARE.json (recipe_k; fixed-depth policy of "
164
+ "plans/realbulk_generation_20260922/build_realbulk_conditions.py)")
165
+ assert int(rk[0]) == prep["recipe_k"]
166
+ n["cells_per_bulk"] = rec("cells_generated_per_bulk_sample", int(cpb[0]), f"{int(cpb[0]):,}", gen_npz)
167
+ n["ddim"] = rec("ddim_steps", gen["steps"], f"{gen['steps']}", gen_log)
168
+ n["weights"] = rec("sampler_weights", gen["weights"], gen["weights"].upper(), gen_log)
169
+ n["readout"] = rec("support_readout", meta["support_readout"], meta["support_readout"].capitalize(), gen_npz)
170
+ return n, rows
171
+
172
+
173
+ # ------------------------------------------------------------------------------------------ drawing helpers
174
+ def box(ax, x, y, w, h, fc="white", ec=INK, lw=1.0, z=2):
175
+ ax.add_patch(Rectangle((x, y), w, h, facecolor=fc, edgecolor=ec, linewidth=lw, zorder=z))
176
+
177
+
178
+ def txt(ax, x, y, s, size=12, color=INK, ha="center", va="center", weight="normal", z=5):
179
+ return ax.text(x, y, s, fontsize=size, color=color, ha=ha, va=va, fontweight=weight, zorder=z)
180
+
181
+
182
+ def arrow(ax, x0, y0, x1, y1, color=INK, lw=1.1, ls="-"):
183
+ ax.annotate("", xy=(x1, y1), xytext=(x0, y0), zorder=4,
184
+ arrowprops=dict(arrowstyle="-|>", color=color, lw=lw, linestyle=ls, mutation_scale=13,
185
+ shrinkA=0, shrinkB=0))
186
+
187
+
188
+ def two_line_box(ax, x, y, w, h, l1, l2, s1=12.5, s2=11.5):
189
+ box(ax, x, y, w, h)
190
+ txt(ax, x + w / 2, y + h * 0.68, l1, size=s1)
191
+ txt(ax, x + w / 2, y + h * 0.30, l2, size=s2, color=TXT2)
192
+
193
+
194
+ def check_layout(fig, ax, W, H, name, pad=0.02) -> None:
195
+ """Fail if any text leaves the canvas; warn on text-text overlaps (inches)."""
196
+ fig.canvas.draw()
197
+ r = fig.canvas.get_renderer()
198
+ boxes = []
199
+ for t in ax.texts:
200
+ if not t.get_text():
201
+ continue
202
+ bb = t.get_window_extent(r).transformed(fig.dpi_scale_trans.inverted())
203
+ assert bb.x0 >= -pad and bb.x1 <= W + pad and bb.y0 >= -pad and bb.y1 <= H + pad, \
204
+ f"{name}: text off canvas: {t.get_text()!r} {bb}"
205
+ boxes.append((t.get_text(), bb))
206
+ for i in range(len(boxes)):
207
+ for j in range(i + 1, len(boxes)):
208
+ a, b = boxes[i][1], boxes[j][1]
209
+ if a.x0 < b.x1 and b.x0 < a.x1 and a.y0 < b.y1 and b.y0 < a.y1:
210
+ print(f"WARNING {name}: overlap {boxes[i][0]!r} / {boxes[j][0]!r}")
211
+
212
+
213
+ # ------------------------------------------------------------------------------------------ figure 1
214
+ def fig_method(n: dict) -> None:
215
+ W, H = FIG_W, FIG_H
216
+ fig = plt.figure(figsize=(W, H))
217
+ ax = fig.add_axes([0, 0, 1, 1])
218
+ ax.set_xlim(0, W)
219
+ ax.set_ylim(0, H)
220
+ ax.axis("off")
221
+
222
+ # column x positions
223
+ x1, w1 = 0.05, 2.00 # 1 pretrained
224
+ bx, bw = 2.28, 2.12 # 2 inputs
225
+ gx, gw = 4.70, 1.62 # 2 frozen layer stack
226
+ ox, ow = gx + gw + 0.05, 0.38 # 2 LoRA adapters
227
+ mx, mw = 7.42, 1.90 # 3 merge
228
+ x4, w4 = 9.72, 2.53 # 4 generate
229
+
230
+ hy = 4.47
231
+ for x, s in [(x1, "1 Pretrained"), (bx, "2 Fine-tune on bulk–sc pairs"), (mx, "3 Merge"), (x4, "4 Generate")]:
232
+ txt(ax, x, hy, s, size=14, ha="left", weight="bold")
233
+
234
+ # 6-row layer stack (stage 2)
235
+ top, rh, gap = 3.90, 0.36, 0.065
236
+ rows_y = [top - rh - i * (rh + gap) for i in range(6)]
237
+ rc = [y + rh / 2 for y in rows_y]
238
+ # small stacks (stages 1 and 3) share one vertical position
239
+ sw, sh, sg, s_top = 1.10, 0.15, 0.052, 2.98
240
+ stack_y = [s_top - sh - i * (sh + sg) for i in range(6)]
241
+ s_bot = stack_y[-1]
242
+ s_mid = (s_top + s_bot) / 2
243
+
244
+ # ---- stage 1: pretrained backbone
245
+ y_in = rc[0] - 0.335 # top-row boxes of stages 1, 2 and 4 align
246
+ two_line_box(ax, x1, y_in, w1, 0.67, "pseudobulk, one donor", f"K = {n['k_lo']}–{n['k_hi']} cells")
247
+ arrow(ax, x1 + w1 / 2, y_in, x1 + w1 / 2, s_top + 0.02)
248
+ for y in stack_y:
249
+ box(ax, x1 + (w1 - sw) / 2, y, sw, sh, fc=FROZEN, ec=INK, lw=0.8)
250
+ txt(ax, x1 + w1 / 2, s_bot - 0.24, f"W0 · {n['n_total']} weights", size=12.5)
251
+ txt(ax, x1 + w1 / 2, s_bot - 0.52, f"{n['genes']} genes · 1× · {n['pre_epoch']}", size=11.5, color=TXT2)
252
+
253
+ # ---- stage 2: one bulk-sc pair -> condition / targets -> LoRA on every Linear layer
254
+ two_line_box(ax, bx, rc[0] - 0.335, bw, 0.67, "real bulk, pair i", f"fixed depth input K = {n['K']}", s2=11)
255
+ two_line_box(ax, bx, rc[3] - 0.335, bw, 0.67, "cells, pair i", "targets x0 (+ noise)", s2=11)
256
+ two_line_box(ax, bx, rc[5] - 0.335, bw, 0.67, "pretraining loss", "value L2 + support BCE", s2=11)
257
+ arrow(ax, bx + bw / 2, rc[3] - 0.335, bx + bw / 2, rc[5] + 0.335, ls=(0, (3, 2)))
258
+
259
+ txt(ax, gx + gw / 2, top + 0.17, "frozen W0 (from 1)", size=11.5, color=TXT2)
260
+ txt(ax, ox + ow / 2, top + 0.17, "LoRA", size=11.5, color=LORA, weight="bold")
261
+ for i, (g, c) in enumerate(n["groups"].items()):
262
+ box(ax, gx, rows_y[i], gw, rh, fc=FROZEN, ec=INK, lw=0.8)
263
+ txt(ax, gx + gw / 2, rc[i], g, size=11.5)
264
+ box(ax, ox, rows_y[i], ow, rh, fc=LORA, ec=LORA, lw=0.8)
265
+ txt(ax, ox + ow / 2, rc[i], f"{c}", size=12, color="white", weight="bold")
266
+ arrow(ax, bx + bw, rc[0], gx, rc[0])
267
+ arrow(ax, bx + bw, rc[3], gx, rc[3])
268
+ arrow(ax, gx, rc[5], bx + bw, rc[5])
269
+ txt(ax, (gx + ox + ow) / 2, rows_y[5] - 0.22,
270
+ f"one B·A per Linear: {n['n_layers']} · r {n['rank']} · α {n['alpha']}", size=11.5, color=LORA)
271
+
272
+ # stage 2 -> 3
273
+ arrow(ax, ox + ow + 0.07, s_mid, mx - 0.05, s_mid)
274
+ txt(ax, (ox + ow + mx) / 2, s_mid + 0.17, "B·A", size=11.5, color=LORA)
275
+
276
+ # ---- stage 3: merge
277
+ txt(ax, mx + mw / 2, 3.56, "W = W0 + (α/r)·B·A", size=13)
278
+ for y in stack_y:
279
+ box(ax, mx + (mw - sw) / 2, y, sw, sh, fc=FROZEN, ec=LORA, lw=1.6)
280
+ txt(ax, mx + mw / 2, s_bot - 0.24, "one checkpoint, base schema", size=12.5)
281
+ txt(ax, mx + mw / 2, s_bot - 0.52, f"reload check: |Δ| = {n['reload']}", size=11.5, color=TXT2)
282
+
283
+ # stage 3 -> 4
284
+ arrow(ax, mx + mw + 0.05, s_mid, x4 - 0.05, s_mid)
285
+ txt(ax, (mx + mw + x4) / 2, s_mid + 0.17, "W", size=11.5, color=TXT2)
286
+
287
+ # ---- stage 4: generate for bulk-only donors
288
+ bh4 = 0.67
289
+ y4 = [y_in, y_in - 0.95, y_in - 1.90]
290
+ two_line_box(ax, x4, y4[0], w4, bh4, "real bulk, new donor", "same cohort + bulk protocol")
291
+ arrow(ax, x4 + w4 / 2, y4[0], x4 + w4 / 2, y4[1] + bh4)
292
+ two_line_box(ax, x4, y4[1], w4, bh4, "unchanged sampler", f"DDIM {n['ddim']} · {n['weights']} · {n['readout']}")
293
+ arrow(ax, x4 + w4 / 2, y4[1], x4 + w4 / 2, y4[2] + bh4)
294
+ two_line_box(ax, x4, y4[2], w4, bh4, f"{n['cells_per_bulk']} cells / bulk sample", "no sc needed")
295
+
296
+ # ---- parameter strip (every value read from receipts / code)
297
+ ax.plot([0.05, W - 0.05], [0.93, 0.93], color=RULE, lw=0.6)
298
+ cols = [
299
+ (0.05, 1.08, [("trainable", f"{n['n_trainable']} of {n['n_total']} ({n['pct']})"),
300
+ ("batch", f"{n['batch']} cells: random pair → 1 cell")]),
301
+ (4.52, 1.08, [("early stop", f"inner-val, patience {n['patience_steps']} steps"),
302
+ ("step cap", f"{n['cap']}")]),
303
+ (8.62, 1.08, [("optimizer", f"AdamW {n['lr']} · EMA {n['ema']}"),
304
+ ("few pairs", f"fixed {n['fixed']} steps, no inner-val")]),
305
+ ]
306
+ for x0, kw, items in cols:
307
+ for j, (k, v) in enumerate(items):
308
+ y = 0.62 - j * 0.40
309
+ txt(ax, x0, y, k, size=11.5, color=TXT2, ha="left")
310
+ txt(ax, x0 + kw, y, v, size=12.5, ha="left")
311
+ check_layout(fig, ax, W, H, "sec06_ft_method")
312
+ with plt.rc_context({"savefig.bbox": "standard"}): # exact 12.3 x 4.65 in (axes fill the canvas)
313
+ style.save(fig, "sec06_ft_method", FIG)
314
+
315
+
316
+ # ------------------------------------------------------------------------------------------ figure 2
317
+ def eval_counts() -> tuple[pd.DataFrame, dict]:
318
+ recs = []
319
+ draws_all = {}
320
+ for ds in DATASETS:
321
+ f = pd.read_csv(PLAN / f"data/{ds}/folds.csv")
322
+ u = f[f["fold"] >= 0]
323
+ per_donor = u.groupby("donor_id").size()
324
+ common = {"usable_rows": len(u), "usable_donors": int(u["donor_id"].nunique()),
325
+ "excluded_rows": int((f["fold"] < 0).sum()),
326
+ "pairs_per_donor_min": int(per_donor.min()),
327
+ "pairs_per_donor_median": float(per_donor.median()),
328
+ "pairs_per_donor_max": int(per_donor.max())}
329
+ for k in range(5):
330
+ inner = u[f"inner_val_f{k}"].astype(bool)
331
+ tr = (u["fold"] != k) & ~inner
332
+ recs.append({"dataset": ds, "name": DATASETS[ds], "setting": "5fold", "unit": k,
333
+ "train_rows": int(tr.sum()), "inner_val_rows": int(inner.sum()),
334
+ "test_rows": int((u["fold"] == k).sum()),
335
+ "train_donors": int(u.loc[tr, "donor_id"].nunique()),
336
+ "inner_val_donors": int(u.loc[inner, "donor_id"].nunique()),
337
+ "test_donors": int(u.loc[u["fold"] == k, "donor_id"].nunique()),
338
+ **common, "source": str(PLAN / f"data/{ds}/folds.csv")})
339
+ dj = json.loads((PLAN / f"data/{ds}/fewshot_n5/DRAWS.json").read_text())
340
+ draws_all[ds] = dj
341
+ assert dj["n_usable_rows"] == len(u) and dj["n_usable_donors"] == common["usable_donors"]
342
+ for k, v in dj["draw"].items():
343
+ is_tr = u["donor_id"].astype(str).isin([str(x) for x in v["train_donors"]])
344
+ assert int(is_tr.sum()) == v["n_train_rows"] and int((~is_tr).sum()) == v["n_test_rows"]
345
+ recs.append({"dataset": ds, "name": DATASETS[ds], "setting": "fewpair", "unit": int(k),
346
+ "train_rows": v["n_train_rows"], "inner_val_rows": 0, "test_rows": v["n_test_rows"],
347
+ "train_donors": len(v["train_donors"]), "inner_val_donors": 0,
348
+ "test_donors": dj["n_usable_donors"] - len(v["train_donors"]),
349
+ **common, "source": str(PLAN / f"data/{ds}/fewshot_n5/DRAWS.json")})
350
+ return pd.DataFrame(recs), draws_all
351
+
352
+
353
+ def rng_str(s: pd.Series) -> str:
354
+ lo, hi = int(s.min()), int(s.max())
355
+ return f"{lo}" if lo == hi else f"{lo}–{hi}"
356
+
357
+
358
+ def fig_eval(df: pd.DataFrame, draws_all: dict) -> list[list[str]]:
359
+ W, H = FIG_W, 4.70
360
+ fig = plt.figure(figsize=(W, H))
361
+ C_TRAIN, C_INNER, C_TEST = "#CFCFCF", "#7A7A7A", INK
362
+
363
+ # role matrix for sepsis: donors ordered by 5-fold assignment
364
+ ds = "ye2026_sepsis"
365
+ f = pd.read_csv(PLAN / f"data/{ds}/folds.csv")
366
+ u = f[f["fold"] >= 0].sort_values(["fold", "row"]).reset_index(drop=True)
367
+ assert u["donor_id"].is_unique, "sepsis role bars assume one pair per donor"
368
+ roles = pd.DataFrame({"donor_id": u["donor_id"], "group": u["group"], "fold": u["fold"]})
369
+ for k in range(5):
370
+ r = np.where(u["fold"] == k, "test", np.where(u[f"inner_val_f{k}"].astype(bool), "inner_val", "train"))
371
+ roles[f"cv_fold{k + 1}"] = r
372
+ dj = draws_all[ds]
373
+ for k, v in dj["draw"].items():
374
+ roles[f"fewpair_draw{int(k) + 1}"] = np.where(u["donor_id"].isin(v["train_donors"]), "train", "test")
375
+ roles.to_csv(DATA / "sec06_eval_design_sepsis_roles.csv", index=False)
376
+ colour = {"train": C_TRAIN, "inner_val": C_INNER, "test": C_TEST}
377
+ nd = len(u)
378
+
379
+ def fx(x): # inches -> figure fraction
380
+ return x / W
381
+
382
+ def fy(y):
383
+ return y / H
384
+
385
+ panels = [(0.78, [f"cv_fold{k}" for k in range(1, 6)], [f"fold {k}" for k in range(1, 6)],
386
+ "5-fold · train on other folds minus inner-val"),
387
+ (6.93, [f"fewpair_draw{k}" for k in range(1, 6)], [f"draw {k}" for k in range(1, 6)],
388
+ f"few pairs · train on {dj['n']} donors · {dj['draws']} draws")]
389
+ pw = 5.25
390
+ for x0, cols, labels, head in panels:
391
+ a = fig.add_axes([fx(x0), fy(3.05), fx(pw), fy(1.22)])
392
+ for i, c in enumerate(cols):
393
+ for j, role in enumerate(roles[c]):
394
+ a.add_patch(Rectangle((j, 4 - i), 1, 0.78, facecolor=colour[role], edgecolor="none"))
395
+ a.set_xlim(0, nd)
396
+ a.set_ylim(-0.1, 5)
397
+ a.set_yticks([4 - i + 0.39 for i in range(5)])
398
+ a.set_yticklabels(labels, fontsize=12)
399
+ a.set_xticks([])
400
+ for s in ("left", "bottom"):
401
+ a.spines[s].set_visible(False)
402
+ a.tick_params(axis="y", length=0)
403
+ a.set_xlabel(f"{nd} Ye 2026 sepsis donors, one pair each", fontsize=12, labelpad=4, color=TXT2)
404
+ fig.text(fx(x0 - 0.73), fy(4.52), head, fontsize=13.5, fontweight="bold", ha="left", va="center")
405
+
406
+ # legend
407
+ lx = 0.78
408
+ for lab, c in [("train (fine-tune)", C_TRAIN), ("inner-val (early stop only)", C_INNER),
409
+ ("test (generate + score)", C_TEST)]:
410
+ fig.patches.append(Rectangle((fx(lx), fy(2.44)), fx(0.15), fy(0.15), transform=fig.transFigure,
411
+ facecolor=c, edgecolor="none"))
412
+ fig.text(fx(lx + 0.22), fy(2.515), lab, fontsize=12, va="center", ha="left")
413
+ lx += 3.55
414
+
415
+ # table of counts for the five paired cohorts (sec09 names and order)
416
+ head = ["cohort", "pairs (donors)", "5-fold: train / inner-val / test pairs",
417
+ "few pairs: train / test pairs (donors)"]
418
+ xs = [0.05, 2.35, 4.25, 8.10]
419
+ ty = 2.05
420
+ for x, h in zip(xs, head):
421
+ fig.text(fx(x), fy(ty), h, fontsize=12, color=TXT2, ha="left", va="center")
422
+ fig.add_artist(plt.Line2D([fx(0.05), fx(W - 0.05)], [fy(ty - 0.17), fy(ty - 0.17)],
423
+ transform=fig.transFigure, color=RULE, lw=0.6))
424
+ table_rows = []
425
+ for i, (dsk, name) in enumerate(DATASETS.items()):
426
+ cv = df[(df.dataset == dsk) & (df.setting == "5fold")]
427
+ fp = df[(df.dataset == dsk) & (df.setting == "fewpair")]
428
+ vals = [name, f"{cv['usable_rows'].iloc[0]} ({cv['usable_donors'].iloc[0]})",
429
+ f"{rng_str(cv['train_rows'])} / {rng_str(cv['inner_val_rows'])} / {rng_str(cv['test_rows'])}",
430
+ f"{rng_str(fp['train_rows'])} ({rng_str(fp['train_donors'])}) / "
431
+ f"{rng_str(fp['test_rows'])} ({rng_str(fp['test_donors'])})"]
432
+ table_rows.append(vals)
433
+ y = ty - 0.46 - i * 0.355
434
+ for x, v in zip(xs, vals):
435
+ fig.text(fx(x), fy(y), v, fontsize=12.5, ha="left", va="center")
436
+
437
+ # off-canvas / overlap check for figure-level texts
438
+ fig.canvas.draw()
439
+ r = fig.canvas.get_renderer()
440
+ bbs = [(t.get_text(), t.get_window_extent(r).transformed(fig.dpi_scale_trans.inverted())) for t in fig.texts]
441
+ for s, bb in bbs:
442
+ assert bb.x0 >= -0.02 and bb.x1 <= W + 0.02 and bb.y0 >= -0.02 and bb.y1 <= H + 0.02, (s, bb)
443
+ for i in range(len(bbs)):
444
+ for j in range(i + 1, len(bbs)):
445
+ a, b = bbs[i][1], bbs[j][1]
446
+ if a.x0 < b.x1 and b.x0 < a.x1 and a.y0 < b.y1 and b.y0 < a.y1:
447
+ print(f"WARNING sec06_eval_design: overlap {bbs[i][0]!r} / {bbs[j][0]!r}")
448
+ style.save(fig, "sec06_eval_design", FIG)
449
+ return table_rows
450
+
451
+
452
+ def main() -> int:
453
+ n, rows = read_method_numbers()
454
+ pd.DataFrame(rows).to_csv(DATA / "sec06_ft_method.csv", index=False)
455
+ fig_method(n)
456
+ df, draws_all = eval_counts()
457
+ df.to_csv(DATA / "sec06_eval_design.csv", index=False)
458
+ table_rows = fig_eval(df, draws_all)
459
+ for r in table_rows:
460
+ print(" | ".join(r))
461
+ print(pd.DataFrame(rows)[["key", "display"]].to_string(index=False))
462
+ per = df.drop_duplicates("dataset")[["dataset", "pairs_per_donor_min", "pairs_per_donor_median",
463
+ "pairs_per_donor_max"]]
464
+ print(per.to_string(index=False))
465
+ return 0
466
+
467
+
468
+ if __name__ == "__main__":
469
+ sys.exit(main())