junidude14 commited on
Commit
2444cdf
·
verified ·
1 Parent(s): 93a1580

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20260930T090852Z-summary-deck-final-path-story/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec03_width_bench.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Section 3b: SLE benchmark of the width / context / proportion-hint arms.
3
+
4
+ One scANVI scoring call (summary_tidy_latest.csv, comparison 'all_diffusion', six-type common gate,
5
+ 2,980-gene panel, held-out SLE donors), so every row here is comparable with every other row.
6
+ Bars: mean over schedule parts 14-16 with the default cut (support probability > 0.5), which is the
7
+ only read-out scored for every arm. Diamonds: the same checkpoints with the drawn (Bernoulli) read-out
8
+ used by the final model; scored for the four width arms only. The 16x arm failed in part 3 (memory floor,
9
+ not resumed) and is not shown here (it is on the loss slide). The quoted run-to-run resolution is the SD of
10
+ the per-part prop - 1x difference, so the hint is judged on oracle vs predicted, not on that resolution.
11
+
12
+ Writes figures/sec03_width_bench.{png,pdf}, data/sec03_width_bench.csv (per part),
13
+ data/sec03_width_bench_summary.csv (means).
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import sys
18
+
19
+ sys.path.insert(0, "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/"
20
+ "2026-09-30--paper-summary--r00/tools")
21
+ import matplotlib.pyplot as plt
22
+ import numpy as np
23
+ import pandas as pd
24
+ from matplotlib.lines import Line2D
25
+ from matplotlib.patches import Patch
26
+
27
+ import style
28
+ from sec03_common import (DATA, FIG, WIDTH_RUNS, WIDTH_SCORES, WIDTH_SCORES_MD, n_donors, param_count,
29
+ read_run, run_to_run_resolution)
30
+
31
+ PARTS = (14, 15, 16)
32
+ # arm key, tick label, colour key, cut-read-out tag pattern, Bernoulli tag pattern
33
+ ARMS = [
34
+ ("1x", "1x", "1x", "diffusion_6k_e{e}", "diffusion_bern6k_e{e}"),
35
+ ("ctx4x", "ctx\nx4", "ctx4x", "diffusion_ctx2048_e{e}", "diffusion_bernctx2048_e{e}"),
36
+ ("trunk4x", "trunk\nx4", "trunk4x", "diffusion_4xctx512_e{e}", "diffusion_bern4xctx512_e{e}"),
37
+ ("4x", "both\nx4", "4x", "diffusion_4x_e{e}", "diffusion_bern4x_e{e}"),
38
+ ("prop_pred", "hint\npred", "prop", "diffusion_prop_e{e}_pred", None),
39
+ ("prop_oracle", "hint\noracle", "prop", "diffusion_prop_e{e}_oracle", None),
40
+ ]
41
+ XPOS = [0, 1, 2, 3, 4.6, 5.75]
42
+ REFS = ("scSemiProfiler",) # external reference drawn as a line on every panel
43
+ METRICS = [("logfc_r", "mean_logFC_pearson", "logFC r (higher better)"),
44
+ ("top50", "total_top50_overlap", "Top-50 DEG overlap (higher better)"),
45
+ ("comp_l1", "composition_l1", "Composition L1 (lower better)")]
46
+
47
+
48
+ def main() -> int:
49
+ t = pd.read_csv(WIDTH_SCORES)
50
+ t = t[(t["comparison"] == "all_diffusion") & (t["celltype_gate"] == "common_celltype_gate")]
51
+ t = t.drop_duplicates("method").set_index("method")
52
+ assert t["panel_genes"].nunique() == 1
53
+ panel_genes = int(t["panel_genes"].iloc[0])
54
+ donors = n_donors(WIDTH_SCORES_MD)
55
+ res_r, res_deg = run_to_run_resolution()
56
+
57
+ rows = []
58
+ for key, _, _, cut, bern in ARMS:
59
+ for readout, pat in (("cut_p>0.5", cut), ("bernoulli", bern)):
60
+ if pat is None:
61
+ continue
62
+ for e in PARTS:
63
+ m = pat.format(e=e)
64
+ r = t.loc[m]
65
+ rows.append({"arm": key, "readout": readout, "part": e, "method": m,
66
+ **{k: float(r[c]) for k, c, _ in METRICS}})
67
+ per = pd.DataFrame(rows)
68
+ per["panel_genes"], per["n_donors"], per["source"] = panel_genes, donors, str(WIDTH_SCORES)
69
+ per.to_csv(DATA / "sec03_width_bench.csv", index=False)
70
+ summ = per.groupby(["arm", "readout"])[[k for k, _, _ in METRICS]].mean().reset_index()
71
+ base = [{"arm": b, "readout": "reference", **{k: float(t.loc[b, c]) for k, c, _ in METRICS}}
72
+ for b in REFS]
73
+ summ = pd.concat([summ, pd.DataFrame(base)], ignore_index=True)
74
+ summ["panel_genes"], summ["n_donors"], summ["source"] = panel_genes, donors, str(WIDTH_SCORES)
75
+ summ["run_to_run_resolution_r"], summ["run_to_run_resolution_deg"] = res_r, res_deg
76
+ summ.to_csv(DATA / "sec03_width_bench_summary.csv", index=False)
77
+ S = summ.set_index(["arm", "readout"])
78
+
79
+ fig, axes = plt.subplots(1, 3, figsize=style.FULL)
80
+ rng = np.random.default_rng(0)
81
+ for ax, (k, _, ylab) in zip(axes, METRICS):
82
+ for x, (key, _, ck, _, bern) in zip(XPOS, ARMS):
83
+ col = style.VARIANT[ck]
84
+ v = S.loc[(key, "cut_p>0.5"), k]
85
+ if key == "prop_oracle":
86
+ ax.bar(x, v, width=0.72, facecolor="white", edgecolor=col, hatch="///", lw=1.4, zorder=2)
87
+ else:
88
+ ax.bar(x, v, width=0.72, color=col, zorder=2)
89
+ pts = per[(per["arm"] == key) & (per["readout"] == "cut_p>0.5")][k].to_numpy()
90
+ ax.scatter(x + rng.uniform(-0.15, 0.15, len(pts)), pts, s=20, color=style.INK, zorder=3,
91
+ edgecolors="white", linewidths=0.6)
92
+ if bern is not None:
93
+ ax.plot([x], [S.loc[(key, "bernoulli"), k]], marker="D", ms=9, mfc="white", mec=style.INK,
94
+ mew=1.5, zorder=4, ls="none")
95
+ ax.axhline(S.loc[("scSemiProfiler", "reference"), k], color=style.ARM["scsemi"], lw=1.8, ls="--", zorder=1)
96
+ ax.set_xticks(XPOS)
97
+ ax.set_xticklabels([a[1] for a in ARMS])
98
+ ax.get_xticklabels()[0].set_fontweight("bold")
99
+ ax.set_ylabel(ylab)
100
+ ax.set_xlim(-0.6, 6.35)
101
+ lo = min(per[k].min(), S[k].min())
102
+ hi = max(per[k].max(), S[k].max())
103
+ ax.set_ylim(0 if k != "logfc_r" else 0, hi * 1.12)
104
+ handles = [Patch(facecolor=style.GREY, label="mean of parts 14-16, cut p>0.5"),
105
+ Line2D([], [], marker="o", ls="none", color=style.INK, ms=4, label="single part"),
106
+ Line2D([], [], marker="D", ls="none", mfc="white", mec=style.INK, mew=1.5, ms=8,
107
+ label="Bernoulli read-out (mean 14-16)"),
108
+ Line2D([], [], color=style.ARM["scsemi"], lw=1.8, ls="--", label="scSemiProfiler")]
109
+ fig.legend(handles=handles, loc="upper center", ncol=len(handles), bbox_to_anchor=(0.5, 1.07),
110
+ handlelength=1.8, columnspacing=2.0, handletextpad=0.5)
111
+ fig.tight_layout(w_pad=2.5)
112
+ style.save(fig, "sec03_width_bench", FIG)
113
+ # headline numbers for the keyword lines
114
+ runs = {k: read_run(name, host) for k, _, name, host in WIDTH_RUNS if k in ("1x", "ctx4x")}
115
+ params = {k: param_count(r, None) for k, r in runs.items()}
116
+ po = per[per["arm"].isin(["prop_pred", "prop_oracle"])].pivot(index="part", columns="arm")
117
+ d_or = {k: (po[(k, "prop_oracle")] - po[(k, "prop_pred")]).abs().max() for k, _, _ in METRICS}
118
+ B, C = "bernoulli", "cut_p>0.5"
119
+ head = pd.DataFrame([
120
+ {"quantity": "trunk4x_minus_1x_top50_cut", "value": S.loc[("trunk4x", C), "top50"] - S.loc[("1x", C), "top50"]},
121
+ {"quantity": "trunk4x_minus_1x_top50_bern", "value": S.loc[("trunk4x", B), "top50"] - S.loc[("1x", B), "top50"]},
122
+ {"quantity": "trunk4x_minus_1x_r_cut", "value": S.loc[("trunk4x", C), "logfc_r"] - S.loc[("1x", C), "logfc_r"]},
123
+ {"quantity": "trunk4x_minus_1x_r_bern", "value": S.loc[("trunk4x", B), "logfc_r"] - S.loc[("1x", B), "logfc_r"]},
124
+ {"quantity": "prop_oracle_vs_pred_max_abs_diff_per_part_r", "value": d_or["logfc_r"]},
125
+ {"quantity": "prop_oracle_vs_pred_max_abs_diff_per_part_top50", "value": d_or["top50"]},
126
+ {"quantity": "prop_pred_comp_l1_cut", "value": S.loc[("prop_pred", C), "comp_l1"]},
127
+ {"quantity": "1x_comp_l1_cut", "value": S.loc[("1x", C), "comp_l1"]},
128
+ {"quantity": "1x_bern_r_top50_l1", "value": "/".join(f"{S.loc[('1x', B), k]:.3f}" for k, _, _ in METRICS)},
129
+ {"quantity": "ctx4x_bern_r_top50_l1", "value": "/".join(f"{S.loc[('ctx4x', B), k]:.3f}" for k, _, _ in METRICS)},
130
+ {"quantity": "params_1x", "value": params["1x"][0]},
131
+ {"quantity": "params_ctx4x", "value": params["ctx4x"][0]},
132
+ {"quantity": "run_to_run_resolution_r_top50",
133
+ "value": f"{res_r}/{res_deg} (SD over 16 parts of the per-part prop - 1x difference; THRESHOLD_RESCORE.md)"},
134
+ ])
135
+ head["source"] = f"{WIDTH_SCORES} via data/sec03_width_bench*.csv; params from RUN_STATUS.json"
136
+ head.to_csv(DATA / "sec03_width_bench_headline.csv", index=False)
137
+ print(head[["quantity", "value"]].to_string())
138
+ print(f"panel genes {panel_genes}, donors {donors}, resolution r {res_r} DEG {res_deg}")
139
+ print(summ[["arm", "readout", "logfc_r", "top50", "comp_l1"]].round(3).to_string())
140
+ return 0
141
+
142
+
143
+ if __name__ == "__main__":
144
+ raise SystemExit(main())
paper-releases/pbisc-diffusion/updates/20260930T090852Z-summary-deck-final-path-story/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/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, see backup).
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 backup: 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 (backup)"))
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/20260930T090852Z-summary-deck-final-path-story/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec05_behcet_direction.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Section 5, slide (c): Behcet disease direction, zero-shot from real bulk (raw) vs from sc pseudobulk vs observed
2
+ cells (final model), with the depth control.
3
+
4
+ Real bulk (raw): 19 bulk samples (GSE198533, BD 9 / HC 10) x 5,000 cells, 5 seeds.
5
+ Observed: sc GSE198616, BD 4 / HC 4 (different people). sc pseudobulk row = those 8 sc donors' own pseudobulks, 5 seeds.
6
+ Left: CD16 share of monocytes, BD mean - HC mean, pp. Right: C1Q-high monocyte share (rule A), BD - HC, pp.
7
+ Circles = native depth: per-seed values (hollow) and mean +- SD (filled), from
8
+ input_path_compare/immicro_behcet/tables/behcet_per_seed.csv (arms raw, pseudo_ceiling, observed), checked against
9
+ behcet_table.csv. Only these three rows are read, plotted and written to data/sec05_behcet_direction.csv.
10
+ Diamonds = every sample thinned to one common monocyte depth (scored in the analysis folder RS below; no common-depth
11
+ value exists for the sc pseudobulk row):
12
+ C1Q-high: E-share at common depth, 5-seed mean +- SD (out/summary/seeds_stats.csv, family raw); observed = rule A at
13
+ the same depth (out/summary/comparison_table.csv, obs_f01_common).
14
+ CD16: relabelled at common depth, seed 0 (comparison_table.csv, gen_f016k_common_rl); observed labels kept.
15
+ Observed descriptive Mann-Whitney p (4 vs 4) from behcet_probe/analysis/out/rules_groups/c1q_by_monocyte_subtype_tests.csv.
16
+ CPU only.
17
+ """
18
+ import json
19
+ import sys
20
+ from pathlib import Path
21
+
22
+ import numpy as np
23
+ import pandas as pd
24
+
25
+ DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/2026-09-30--paper-summary--r00")
26
+ sys.path.insert(0, str(DECK / "tools"))
27
+ import style # noqa: E402
28
+ import matplotlib.pyplot as plt # noqa: E402
29
+ from matplotlib.lines import Line2D # noqa: E402
30
+
31
+ UT = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/utility_studies_final6k_20260925")
32
+ T = UT / "input_path_compare/immicro_behcet/tables"
33
+ PER_SEED = T / "behcet_per_seed.csv"
34
+ TABLE = T / "behcet_table.csv"
35
+ DEPTH = T / "behcet_monocyte_depth_by_group.csv"
36
+ RS = UT / "refcal_scoring/behcet/out/summary"
37
+ SEEDS_STATS = RS / "seeds_stats.csv"
38
+ COMPARE = RS / "comparison_table.csv"
39
+ SUMMARY = RS / "SUMMARY.json"
40
+ OBS_TESTS = UT / "behcet_probe/analysis/out/rules_groups/c1q_by_monocyte_subtype_tests.csv"
41
+ FIG = DECK / "figures"
42
+ DATA = DECK / "data"
43
+
44
+ RAW_EDGE = "#5E8FB5"
45
+ ARMS = [ # (arm key in behcet_per_seed.csv, y label (donor counts are added from the CSV), fill, edge)
46
+ ("raw", "real bulk (raw)", style.ARM["zs_raw"], RAW_EDGE),
47
+ ("pseudo_ceiling", "sc pseudobulk", style.ARM["pseudo"], style.ARM["pseudo"]),
48
+ ("observed", "observed", style.GREY, style.GREY),
49
+ ]
50
+ D_OFF, S_OFF = 0.27, 0.25 # row offsets (y units) of the common-depth diamond (above) and the seed dots (below)
51
+ # (per-seed column, x label, observed-test metric name)
52
+ METRICS = [("share_CD16_gap", "CD16 monocytes,\nBD − HC (pp)", "share_CD16_monocyte"),
53
+ ("A_share_gap", "C1Q-high monocytes,\nBD − HC (pp)", "c1q_pos_share_of_monocytes")]
54
+
55
+
56
+ def main():
57
+ ps = pd.read_csv(PER_SEED)
58
+ ps = ps[ps["arm"].isin([a[0] for a in ARMS])].copy()
59
+ tab = pd.read_csv(TABLE).set_index("arm")
60
+ obs = ps[ps["arm"] == "observed"].iloc[0]
61
+ n_bd_obs, n_hc_obs = int(obs["n_BD"]), int(obs["n_HC"])
62
+ n_donors = {}
63
+ for arm, *_ in ARMS:
64
+ sub = ps[ps["arm"] == arm]
65
+ assert sub["n_BD"].nunique() == 1 and sub["n_HC"].nunique() == 1, arm
66
+ n_donors[arm] = (int(sub["n_BD"].iloc[0]), int(sub["n_HC"].iloc[0]))
67
+
68
+ # ---- native depth, per seed
69
+ rows, summ = [], {}
70
+ for arm, *_ in ARMS:
71
+ if arm == "observed":
72
+ continue
73
+ sub = ps[ps["arm"] == arm]
74
+ for mk, *_ in METRICS:
75
+ v = 100 * sub[mk].to_numpy(float)
76
+ mean = float(v.mean())
77
+ sd = float(v.std(ddof=1)) if len(v) > 1 else float("nan")
78
+ summ[(arm, mk)] = (mean, sd, len(v), int((v > 0).sum()))
79
+ tm = tab.loc[arm, f"{mk}_mean"]
80
+ if len(v) > 1:
81
+ assert abs(100 * tm - mean) < 1e-9, (arm, mk, tm, mean)
82
+ assert abs(100 * tab.loc[arm, f"{mk}_sd"] - sd) < 1e-9, (arm, mk)
83
+ else:
84
+ assert abs(100 * tab.loc[arm, f"{mk}_s0"] - mean) < 1e-9, (arm, mk)
85
+ for s, x in zip(sub["seed_tag"], v):
86
+ rows.append({"arm": arm, "metric": mk, "depth": "native", "seed": s, "value_pp": x, "source": str(PER_SEED)})
87
+ rows.append({"arm": arm, "metric": mk, "depth": "native", "seed": "mean", "value_pp": mean, "source": str(PER_SEED)})
88
+ rows.append({"arm": arm, "metric": mk, "depth": "native", "seed": "sd", "value_pp": sd, "source": str(PER_SEED)})
89
+ rows.append({"arm": arm, "metric": mk, "depth": "native", "seed": "n_positive", "value_pp": summ[(arm, mk)][3],
90
+ "source": str(PER_SEED)})
91
+ obs_native = {mk: 100 * float(obs[mk]) for mk, *_ in METRICS}
92
+ for mk, v in obs_native.items():
93
+ rows.append({"arm": "observed", "metric": mk, "depth": "native", "seed": "-", "value_pp": v, "source": str(PER_SEED)})
94
+
95
+ # ---- common monocyte depth (scored in RS; rows used: family raw, arms gen_f016k_common_rl and obs_f01_common)
96
+ st = pd.read_csv(SEEDS_STATS).set_index(["family", "metric"])
97
+ cmp_ = pd.read_csv(COMPARE).set_index("arm_id")
98
+ # the RS family "raw" holds the same 5 seeds as the input_path_compare arm "raw": cross-check native mean and SD;
99
+ # its ceiling columns are the sc pseudobulk seeds and its observed column is the observed gap
100
+ for met, mk in (("A", "A_share_gap"), ("share_CD16", "share_CD16_gap")):
101
+ assert abs(100 * st.loc[("raw", met), "gap_mean"] - summ[("raw", mk)][0]) < 1e-9, met
102
+ assert abs(100 * st.loc[("raw", met), "gap_sd"] - summ[("raw", mk)][1]) < 1e-9, met
103
+ assert abs(100 * st.loc[("raw", met), "ceiling_gap_mean"] - summ[("pseudo_ceiling", mk)][0]) < 1e-9, met
104
+ assert abs(100 * st.loc[("raw", met), "ceiling_gap_sd"] - summ[("pseudo_ceiling", mk)][1]) < 1e-9, met
105
+ assert abs(100 * st.loc[("raw", met), "observed_gap"] - obs_native[mk]) < 1e-9, met
106
+ common = { # (arm, metric) -> (mean, sd or nan, n seeds, n positive or None, source)
107
+ ("raw", "A_share_gap"): (100 * st.loc[("raw", "E_share_common"), "gap_mean"],
108
+ 100 * st.loc[("raw", "E_share_common"), "gap_sd"],
109
+ int(st.loc[("raw", "E_share_common"), "n_seeds"]),
110
+ int(st.loc[("raw", "E_share_common"), "n_seeds_gap_positive"]),
111
+ f"{SEEDS_STATS} (family raw, metric E_share_common)"),
112
+ ("observed", "A_share_gap"): (100 * cmp_.loc["obs_f01_common", "A_gap"], float("nan"), 0, None,
113
+ f"{COMPARE} (arm_id obs_f01_common, A_gap)"),
114
+ ("raw", "share_CD16_gap"): (100 * cmp_.loc["gen_f016k_common_rl", "share_CD16_gap"], float("nan"), 1, None,
115
+ f"{COMPARE} (arm_id gen_f016k_common_rl)"),
116
+ ("observed", "share_CD16_gap"): (100 * cmp_.loc["obs_f01_common", "share_CD16_gap"], float("nan"), 0, None,
117
+ f"{COMPARE} (arm_id obs_f01_common)"),
118
+ }
119
+ summary = json.load(open(SUMMARY))
120
+ p_raw_common = float(summary["seeds"]["seed_pooled"]["raw"]["E_share_common"]["exact_perm_p_two_sided"])
121
+ for (arm, mk), (m, s, n, npos, src) in common.items():
122
+ rows.append({"arm": arm, "metric": mk, "depth": "common", "seed": "mean" if n > 1 else ("s0" if n == 1 else "-"),
123
+ "value_pp": m, "source": src})
124
+ if n > 1:
125
+ rows.append({"arm": arm, "metric": mk, "depth": "common", "seed": "sd", "value_pp": s, "source": src})
126
+ rows.append({"arm": arm, "metric": mk, "depth": "common", "seed": "n_positive", "value_pp": npos, "source": src})
127
+ rows.append({"arm": "raw", "metric": "A_share_gap", "depth": "common", "seed": "seed_pooled_perm_p",
128
+ "value_pp": p_raw_common, "source": f"{SUMMARY} seeds.seed_pooled.raw.E_share_common"})
129
+
130
+ # ---- observed descriptive p-values (4 vs 4)
131
+ ot = pd.read_csv(OBS_TESTS)
132
+ ot = ot[ot["arm"] == "obs_f01"].set_index("metric")
133
+ p_obs = {}
134
+ for mk, _, tmet in METRICS:
135
+ r = ot.loc[tmet]
136
+ assert int(r["n_BD"]) == n_bd_obs and int(r["n_HC"]) == n_hc_obs
137
+ assert abs(100 * (r["BD_mean"] - r["HC_mean"]) - obs_native[mk]) < 1e-9, (mk, r["BD_mean"] - r["HC_mean"])
138
+ p_obs[mk] = float(r["mw_p_descriptive"])
139
+ rows.append({"arm": "observed", "metric": mk, "depth": "native", "seed": "mw_p_descriptive",
140
+ "value_pp": p_obs[mk], "source": str(OBS_TESTS)})
141
+ dep = pd.read_csv(DEPTH).set_index("arm")
142
+ for arm, *_ in ARMS:
143
+ rows.append({"arm": arm, "metric": "mono_library_BD_over_HC", "depth": "native", "seed": "s0",
144
+ "value_pp": float(dep.loc[arm, "BD_over_HC"]), "source": str(DEPTH)})
145
+ for arm, *_ in ARMS:
146
+ for grp, n in zip(("BD", "HC"), n_donors[arm]):
147
+ rows.append({"arm": arm, "metric": f"n_{grp}_donors", "depth": "-", "seed": "-", "value_pp": n,
148
+ "source": f"{PER_SEED} (column n_{grp})"})
149
+ pd.DataFrame(rows).to_csv(DATA / "sec05_behcet_direction.csv", index=False)
150
+
151
+ # ---- figure
152
+ n_seeds = {summ[(arm, mk)][2] for arm, *_ in ARMS if arm != "observed" for mk, *_ in METRICS}
153
+ assert len(n_seeds) == 1 and n_seeds.pop() == 5, "legend says 5 seeds"
154
+ labels = [f"{lab}\n({n_donors[arm][0]} BD vs {n_donors[arm][1]} HC)" for arm, lab, *_ in ARMS]
155
+ fig, axes = plt.subplots(1, 2, figsize=style.TALL, sharey=True)
156
+ ys = np.arange(len(ARMS))
157
+ for ax, (mk, xlab, _) in zip(axes, METRICS):
158
+ o = obs_native[mk]
159
+ ax.axvline(0, color=style.INK, lw=0.8, zorder=0)
160
+ ax.axvline(o, color=style.GREY, lw=1.2, ls="--", zorder=0)
161
+ for y, (arm, lab, col, edge) in zip(ys, ARMS):
162
+ if arm == "observed":
163
+ ax.scatter([o], [y], s=70, color=col, edgecolor=edge, lw=0.8, zorder=4)
164
+ ax.annotate(f"p {p_obs[mk]:.2g}", (o, y), xytext=(10, 0), textcoords="offset points",
165
+ ha="left", va="center", fontsize=style.FS - 3, color=style.SUBINK)
166
+ else:
167
+ sub = 100 * ps[ps["arm"] == arm][mk].to_numpy(float)
168
+ mean, sd, n, _ = summ[(arm, mk)]
169
+ ax.scatter(sub, np.full(n, y + S_OFF), s=16, facecolor="white", edgecolor=edge, lw=0.9, zorder=3)
170
+ ax.errorbar(mean, y, xerr=sd, fmt="none", ecolor=edge, elinewidth=1.6, capsize=4, zorder=2)
171
+ ax.scatter([mean], [y], s=70, color=col, edgecolor=edge, lw=0.8, zorder=4)
172
+ if (arm, mk) in common:
173
+ cm, cs, cn, _, _ = common[(arm, mk)]
174
+ yd = y - D_OFF
175
+ if cn > 1:
176
+ ax.errorbar(cm, yd, xerr=cs, fmt="none", ecolor=style.INK, elinewidth=1.2, capsize=3, zorder=5)
177
+ ax.scatter([cm], [yd], s=62, marker="D", color=col, edgecolor=style.INK, lw=0.9, zorder=6)
178
+ ax.set_xlabel(xlab)
179
+ ax.tick_params(axis="y", length=0)
180
+ axes[0].set_yticks(ys)
181
+ axes[0].set_yticklabels(labels)
182
+ axes[0].set_ylim(len(ARMS) - 0.6, -0.52)
183
+ for ax, (mk, *_) in zip(axes, METRICS):
184
+ allv = [100 * ps[mk].min(), 100 * ps[mk].max()]
185
+ allv += [v[0] for (a, m), v in common.items() if m == mk]
186
+ span = max(allv) - min(allv)
187
+ ax.set_xlim(min(allv) - 0.08 * span, max(allv) + 0.08 * span)
188
+ hk = dict(ls="", markersize=8)
189
+ handles = [Line2D([], [], marker="o", markerfacecolor="white", markeredgecolor=style.SUBINK, markersize=5, ls=""),
190
+ Line2D([], [], marker="o", color=style.SUBINK, **hk),
191
+ Line2D([], [], marker="D", markerfacecolor="white", markeredgecolor=style.INK, markersize=7, ls="")]
192
+ fig.legend(handles, ["seed", "mean ± SD (5 seeds)", "common monocyte depth"], loc="upper center", ncol=3,
193
+ bbox_to_anchor=(0.6, 1.0), handletextpad=0.2, columnspacing=1.2, borderaxespad=0.0)
194
+ fig.subplots_adjust(left=0.24, right=0.98, top=0.93, bottom=0.14, wspace=0.12)
195
+ style.save(fig, "sec05_behcet_direction", FIG)
196
+
197
+ print("observed n BD / HC:", n_bd_obs, n_hc_obs, {k: round(v, 3) for k, v in obs_native.items()},
198
+ "descriptive p:", {k: round(v, 3) for k, v in p_obs.items()})
199
+ for (arm, mk), (m, s, n, npos) in summ.items():
200
+ print(f"native\t{arm}\t{mk}\tmean {m:+.3f}\tsd {s:.3f}\tn {n}\tpositive {npos}")
201
+ for (arm, mk), (m, s, n, npos, _) in common.items():
202
+ print(f"common\t{arm}\t{mk}\tmean {m:+.3f}\tsd {s:.3f}\tn {n}\tpositive {npos}")
203
+ print("raw C1Q at common depth, seed-pooled perm p", round(p_raw_common, 3))
204
+ print(dep.loc[[a[0] for a in ARMS]])
205
+
206
+
207
+ if __name__ == "__main__":
208
+ main()
paper-releases/pbisc-diffusion/updates/20260930T090852Z-summary-deck-final-path-story/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec05_cells_offmanifold.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Section 5, slide (b): cells generated zero-shot from real bulk (raw) vs from sc pseudobulk vs real cells
2
+ (ImMicro, final model).
3
+
4
+ Figure 1 (HALF): cell UMAP (fitted on real R1 cells; other sets placed with umap.transform), 3,000 held-out real
5
+ R2 cells and the same 3,000 matched generated cells from real bulk (raw) and from the donor's own sc pseudobulk,
6
+ coloured by the frozen f01common six-type label. Source: umap/cell_immicro_5arm/interactive/cells_5arm.json.
7
+ Figure 2 (HALF): monocyte %, precision and coverage for the three sets (PCA-50, k = 10, 150 cells x 107 donors per
8
+ set, one scoring call) from input_path_compare/immicro_behcet/tables/immicro_table.csv, rows raw, pseudo, real_R2.
9
+ Only these three rows are read, plotted and written to data/sec05_cells_metrics.csv.
10
+ CPU only.
11
+ """
12
+ import json
13
+ import sys
14
+ from pathlib import Path
15
+
16
+ import numpy as np
17
+ import pandas as pd
18
+
19
+ DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/2026-09-30--paper-summary--r00")
20
+ sys.path.insert(0, str(DECK / "tools"))
21
+ import style # noqa: E402
22
+ import matplotlib.pyplot as plt # noqa: E402
23
+ from matplotlib.lines import Line2D # noqa: E402
24
+
25
+ U = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/utility_studies_final6k_20260925")
26
+ CELLS = U / "umap/cell_immicro_5arm/interactive/cells_5arm.json"
27
+ TABLE = U / "input_path_compare/immicro_behcet/tables/immicro_table.csv"
28
+ TRANS = U / "umap/cell_immicro_5arm/tables/c_label_transition_pseudo_to_raw_counts.csv"
29
+ FIG = DECK / "figures"
30
+ DATA = DECK / "data"
31
+
32
+ RAW_EDGE = "#5E8FB5"
33
+ # (arm key in immicro_table.csv, legend label, fill colour, edge colour)
34
+ ARMS = [
35
+ ("raw", "real bulk (raw)", style.ARM["zs_raw"], RAW_EDGE),
36
+ ("pseudo", "sc pseudobulk", style.ARM["pseudo"], style.ARM["pseudo"]),
37
+ ("real_R2", "real cells", style.GREY, style.GREY),
38
+ ]
39
+
40
+
41
+ def umap_figure():
42
+ d = json.load(open(CELLS))
43
+ sets, labels = d["sets"], d["labels_l1"]
44
+ lab_col = d["meta"]["colours"]["labels_l1"]
45
+ c = pd.DataFrame({k: d["cells"][k] for k in ("set", "pair_id", "donor_index", "l1", "x", "y")})
46
+ c["set_name"] = [sets[i] for i in c["set"]]
47
+ c["label"] = [labels[i] for i in c["l1"]]
48
+ keep = c[c["set_name"].isin(["R2", "raw", "pseudo"])].copy()
49
+ keep[["set_name", "pair_id", "donor_index", "label", "x", "y"]].to_csv(DATA / "sec05_cells_umap_coords.csv", index=False)
50
+ real = keep[keep["set_name"] == "R2"]
51
+ n_per = keep.groupby("set_name").size().to_dict()
52
+ assert n_per["R2"] == n_per["raw"] == n_per["pseudo"], n_per
53
+
54
+ fig, axes = plt.subplots(2, 2, figsize=style.HALF)
55
+ panels = [("R2", "Real cells"), ("raw", "From real bulk (raw)"), ("pseudo", "From sc pseudobulk")]
56
+ rng = np.random.default_rng(0)
57
+ for ax, (key, title) in zip(axes.flat[:3], panels):
58
+ s = keep[keep["set_name"] == key]
59
+ if key != "R2":
60
+ ax.scatter(real["x"], real["y"], s=1.2, color="#D9D9D9", lw=0, rasterized=True)
61
+ order = rng.permutation(len(s))
62
+ s = s.iloc[order]
63
+ ax.scatter(s["x"], s["y"], s=1.6, c=[lab_col[l] for l in s["label"]], lw=0, rasterized=True)
64
+ ax.text(0.02, 0.99, title, transform=ax.transAxes, ha="left", va="top", fontsize=style.FS - 2)
65
+ ax.set_xticks([])
66
+ ax.set_yticks([])
67
+ for sp in ax.spines.values():
68
+ sp.set_visible(False)
69
+ xs = np.r_[keep["x"]]
70
+ ys = np.r_[keep["y"]]
71
+ for ax in axes.flat[:3]:
72
+ ax.set_xlim(xs.min() - 0.5, xs.max() + 0.5)
73
+ ax.set_ylim(ys.min() - 0.5, ys.max() + 2.5)
74
+ lg = axes.flat[3]
75
+ lg.axis("off")
76
+ handles = [Line2D([], [], marker="o", ls="", color=lab_col[l], markersize=8) for l in labels]
77
+ handles.append(Line2D([], [], marker="o", ls="", color="#D9D9D9", markersize=8))
78
+ names = list(labels) + ["real cells"]
79
+ lg.legend(handles, names, loc="center left", handletextpad=0.2, labelspacing=0.45, borderaxespad=0.0,
80
+ fontsize=style.FS - 2)
81
+ fig.subplots_adjust(left=0.01, right=0.99, top=0.99, bottom=0.01, wspace=0.04, hspace=0.04)
82
+ style.save(fig, "sec05_cells_umap", FIG)
83
+
84
+ mono = {k: 100 * float((keep[keep["set_name"] == k]["label"] == "Monocyte").mean()) for k in ("R2", "raw", "pseudo")}
85
+ # provenance of data/sec05_cells_umap_coords.csv (that file has no source column)
86
+ src_rows = [{"arm": {"R2": "real_R2"}.get(k, k), "metric": "umap_cells_plotted", "value": int(n),
87
+ "source": f"{CELLS} (cells with set == {k}); coordinates in data/sec05_cells_umap_coords.csv"}
88
+ for k, n in sorted(n_per.items(), key=lambda kv: ["raw", "pseudo", "R2"].index(kv[0]))]
89
+ return n_per, mono, src_rows
90
+
91
+
92
+ def metrics_figure(src_rows):
93
+ t = pd.read_csv(TABLE).set_index("arm")
94
+ vals = {}
95
+ for arm, *_ in ARMS:
96
+ vals[arm] = {"monocyte_pct": float(t.loc[arm, "monocyte_pct_150"]),
97
+ "precision": float(t.loc[arm, "precision"]),
98
+ "coverage": float(t.loc[arm, "coverage"])}
99
+ if arm != "real_R2":
100
+ vals[arm]["comp_L1"] = float(t.loc[arm, "comp_L1"])
101
+ # the real_R2 row's comp_L1 is the cohort-mean leave-one-out null, not a property of the R2 cells
102
+ null = float(t.loc["raw", "comp_L1_obs_LOO_null"])
103
+ assert abs(null - float(t.loc["real_R2", "comp_L1"])) < 1e-12, "null differs between rows"
104
+ out = []
105
+ for arm, *_ in ARMS:
106
+ for k, v in vals[arm].items():
107
+ out.append({"arm": arm, "metric": k, "value": v, "source": str(TABLE)})
108
+ out.append({"arm": "null", "metric": "comp_L1_LOO_null", "value": null,
109
+ "source": f"{TABLE} (column comp_L1_obs_LOO_null)"})
110
+ tr = pd.read_csv(TRANS, index_col=0)
111
+ t_row = tr.loc["T cell"]
112
+ t_to_mono = float(t_row["Monocyte"] / t_row.sum())
113
+ n_t, n_t_mono, n_all = int(t_row.sum()), int(t_row["Monocyte"]), int(tr.to_numpy().sum())
114
+ out.append({"arm": "raw", "metric": "pseudo_T_cells_labelled_monocyte_under_raw", "value": t_to_mono,
115
+ "source": str(TRANS)})
116
+ out.append({"arm": "raw", "metric": "n_pseudo_T_cells", "value": n_t, "source": str(TRANS)})
117
+ out.append({"arm": "raw", "metric": "n_pseudo_T_to_monocyte", "value": n_t_mono, "source": str(TRANS)})
118
+ out.append({"arm": "raw", "metric": "n_cells_in_transition_table", "value": n_all, "source": str(TRANS)})
119
+ out.extend(src_rows)
120
+ pd.DataFrame(out).to_csv(DATA / "sec05_cells_metrics.csv", index=False)
121
+
122
+ # one panel per metric, one bar per set; drawn at the UMAP figure's height so both sit side by side at one scale
123
+ fig, axes = plt.subplots(1, 3, figsize=style.HALF)
124
+ specs = [("monocyte_pct", "Monocytes (%)", 40, "{:.1f}", [0, 20, 40]),
125
+ ("precision", "Precision", 1.12, "{:.2f}", [0, 0.5, 1.0]),
126
+ ("coverage", "Coverage", 1.12, "{:.2f}", [0, 0.5, 1.0])]
127
+ xs = np.arange(len(ARMS))
128
+ for i, (ax, (k, xlab, ymax, fmt, ticks)) in enumerate(zip(axes, specs)):
129
+ for x, (arm, lab, col, edge) in zip(xs, ARMS):
130
+ v = vals[arm][k]
131
+ ax.bar(x, v, 0.74, color=col, edgecolor=edge, lw=0.9)
132
+ ax.text(x, v + ymax * 0.015, fmt.format(v), ha="center", va="bottom", fontsize=style.FS - 2)
133
+ ax.set_ylim(0, ymax)
134
+ ax.set_yticks(ticks)
135
+ ax.set_yticklabels([f"{y:g}" for y in ticks] if i < 2 else [])
136
+ ax.set_xlim(-0.6, len(ARMS) - 0.4)
137
+ ax.set_xticks([])
138
+ ax.set_xlabel(xlab, labelpad=6)
139
+ handles = [plt.Rectangle((0, 0), 1, 1, facecolor=col, edgecolor=edge, lw=0.9) for _, _, col, edge in ARMS]
140
+ fig.legend(handles, [a[1] for a in ARMS], loc="upper center", ncol=3, bbox_to_anchor=(0.5, 1.0),
141
+ handlelength=1.1, handletextpad=0.4, columnspacing=1.1, borderaxespad=0.0)
142
+ fig.subplots_adjust(left=0.08, right=0.99, top=0.90, bottom=0.08, wspace=0.28)
143
+ style.save(fig, "sec05_cells_metrics", FIG)
144
+ return vals, null, (t_to_mono, n_t_mono, n_t, n_all)
145
+
146
+
147
+ def main():
148
+ n_per, mono_json, src_rows = umap_figure()
149
+ vals, null, tm = metrics_figure(src_rows)
150
+ print("cells per UMAP panel", n_per)
151
+ print("monocyte % in the 3,000-cell UMAP subsample", {k: round(v, 1) for k, v in mono_json.items()})
152
+ for arm, d in vals.items():
153
+ print(arm, {k: round(v, 4) for k, v in d.items()})
154
+ print("composition L1 LOO null", round(null, 4))
155
+ print("pseudo T cells that become monocytes under raw: %.4f (%d / %d; %d cells in table)" % tm)
156
+
157
+
158
+ if __name__ == "__main__":
159
+ main()