junidude14 commited on
Commit
cad138b
·
verified ·
1 Parent(s): 516cdbe

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/sec02_backbone.py ADDED
@@ -0,0 +1,609 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Section 2 of the 2026-09-30 paper-summary deck: backbone comparison and bulk conditioning.
2
+
3
+ Two line diagrams, CPU only, no torch import:
4
+ figures/sec02_backbone_compare.{png,pdf} scDiffusion | SDD | PBISC-Diffusion, same rows each
5
+ figures/sec02_bulk_conditioning.{png,pdf} bulk profile -> condition vector -> 512 context -> every block
6
+
7
+ Every cell of the comparison is checked against a source before it is drawn: each claim carries an
8
+ evidence string that must occur (whitespace-normalised) in the named source file, else the script
9
+ fails. External papers are read from their arXiv text copies in data/refs (pdftotext of
10
+ arXiv 2502.02448v3 and arXiv 2401.03968v2); the SDD code is read from the upstream file at the
11
+ reference commit named in THIRD_PARTY_NOTICES.md (PhilSid/sparse-data-diffusion 1d5423c,
12
+ sparsity_bit_diffusion.py, saved in data/refs). The 'changed from SDD' flag of every PBISC cell is
13
+ checked against the SDD side (paper and upstream code), not only against PBISC sources.
14
+ Every number is read from a run/config/source file.
15
+ Source tables: data/sec02_backbone_compare.csv, data/sec02_bulk_conditioning.csv,
16
+ data/sec02_slide_text.csv (keyword lines and their evidence).
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import ast
21
+ import csv
22
+ import hashlib
23
+ import io
24
+ import json
25
+ import pickle
26
+ import re
27
+ import sys
28
+ import zipfile
29
+ from pathlib import Path
30
+
31
+ DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/"
32
+ "2026-09-30--paper-summary--r00")
33
+ sys.path.insert(0, str(DECK / "tools"))
34
+ import style # noqa: E402
35
+ import matplotlib.pyplot as plt # noqa: E402
36
+ from matplotlib.patches import Rectangle, Circle, FancyArrowPatch # noqa: E402
37
+
38
+ FIG = DECK / "figures"
39
+ DATA = DECK / "data"
40
+ M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
41
+ RUN = M8 / "runs/f01_6k_1x_seed20260627"
42
+ MS = Path("/home/sj_server_1/PBISC/paper-release-20260928/manuscript")
43
+
44
+ SRC = {
45
+ "run_status": RUN / "RUN_STATUS.json",
46
+ "eff_config": RUN / "effective_config.json",
47
+ "data_audit": RUN / "data_audit.json",
48
+ "panel_manifest": M8 / "artifacts/panel_ladder_floor01_1m_20260923/manifest.json",
49
+ "model_py": M8 / "src/pbisc_sdd/model.py",
50
+ "diffusion_py": M8 / "src/pbisc_sdd/diffusion.py",
51
+ "data_py": M8 / "src/pbisc_sdd/data.py",
52
+ "experiment_py": M8 / "src/pbisc_sdd/experiment.py",
53
+ "sampler_py": M8 / "scripts/sample_sdd_standalone.py",
54
+ "notices": M8 / "THIRD_PARTY_NOTICES.md",
55
+ "final_readme": M8 / "plans/utility_studies_final6k_20260925/README.md",
56
+ "methods": MS / "sections/methods.tex",
57
+ "intro": MS / "sections/introduction.tex",
58
+ "sdd_paper": DATA / "refs/sec02_ref_sdd_arxiv2502.02448v3.txt",
59
+ "scdiff_paper": DATA / "refs/sec02_ref_scdiffusion_arxiv2401.03968v2.txt",
60
+ "sdd_upstream": DATA / "refs/sec02_ref_sdd_upstream_1d5423c_sparsity_bit_diffusion.py",
61
+ }
62
+ SDD_COMMIT = "1d5423c13477f2a52269a6f79113b45c6af5510f"
63
+ URL = {
64
+ "sdd_paper": "https://arxiv.org/abs/2502.02448v3",
65
+ "scdiff_paper": "https://arxiv.org/abs/2401.03968v2 (Bioinformatics 40(9):btae518, 2024)",
66
+ "sdd_upstream": ("https://raw.githubusercontent.com/PhilSid/sparse-data-diffusion/"
67
+ f"{SDD_COMMIT}/sparsity_bit_diffusion.py"),
68
+ }
69
+
70
+
71
+ def read(key: str) -> str:
72
+ return SRC[key].read_text(encoding="utf-8", errors="replace")
73
+
74
+
75
+ def norm(text: str) -> str:
76
+ return re.sub(r"\s+", " ", text)
77
+
78
+
79
+ def require(key: str, quote: str) -> str:
80
+ if norm(quote) not in norm(read(key)):
81
+ raise AssertionError(f"evidence not found in {SRC[key]}: {quote!r}")
82
+ return quote
83
+
84
+
85
+ def sha(path: Path) -> str:
86
+ return hashlib.sha256(path.read_bytes()).hexdigest()[:16]
87
+
88
+
89
+ # --------------------------------------------------------------------------------------------
90
+ # 1. Numbers from run, config and conditioner state
91
+ # --------------------------------------------------------------------------------------------
92
+ status = json.loads(read("run_status"))
93
+ cfg = json.loads(read("eff_config"))
94
+ audit = json.loads(read("data_audit"))
95
+ panel = json.loads(read("panel_manifest"))
96
+
97
+ G = int(status["n_genes"])
98
+ COND_DIM = int(status["condition_dim"])
99
+ N_PARAMS = int(status["parameters"])
100
+ CTX = int(cfg["model"]["context_dim"])
101
+ TEMB = int(cfg["model"]["time_embedding_dim"])
102
+ HID = [int(w) for w in cfg["model"]["hidden_dims"]]
103
+ N_FULL = int(panel["n_full_genes"])
104
+ assert len(audit["gene_ids"]) == G == int(cfg["data"]["n_genes"])
105
+ assert cfg["data"]["include_bulk_measurement_in_condition"] is True
106
+ assert cfg["data"]["include_availability_in_condition"] is True
107
+ STEPS = int(cfg["sampling"]["steps"])
108
+ ETA = float(cfg["sampling"]["eta"])
109
+
110
+ # Conditioner state (full-axis normalisation). Read from the torch zip without importing torch;
111
+ # the state holds plain numpy arrays and scalars.
112
+ cond_cache = Path(cfg["paths"]["conditioner_cache"])
113
+ SRC["conditioner_cache"] = cond_cache
114
+
115
+
116
+ class _Stub:
117
+ def __init__(self, *a, **k):
118
+ self.a = a
119
+
120
+ def __call__(self, *a, **k):
121
+ return _Stub(*a)
122
+
123
+ def __setstate__(self, s):
124
+ self.s = s
125
+
126
+
127
+ class _NoTorch(pickle.Unpickler):
128
+ def find_class(self, mod, name):
129
+ if mod.startswith("torch"):
130
+ return _Stub
131
+ return super().find_class(mod, name)
132
+
133
+ def persistent_load(self, pid):
134
+ return None
135
+
136
+
137
+ with zipfile.ZipFile(cond_cache) as zf:
138
+ pkl = [n for n in zf.namelist() if n.endswith("data.pkl")][0]
139
+ cache = _NoTorch(io.BytesIO(zf.read(pkl))).load()
140
+ cstate = cache["conditioner_state"]
141
+ assert cache["corpus_fingerprint"] == status["corpus_fingerprint"], "conditioner / run corpus mismatch"
142
+ N_FULL_COND = int(cstate["n_genes"])
143
+ CLIP_Z = float(cstate["clip_z"])
144
+ SCALARS = list(cstate["feature_names"][N_FULL_COND:])
145
+ N_SCALARS = len(SCALARS)
146
+ assert N_FULL_COND == N_FULL, (N_FULL_COND, N_FULL)
147
+ assert N_SCALARS == 6 and len(cstate["scalar_mean"]) == N_SCALARS
148
+ # Scalar names must match the sampler's replica of the conditioner.
149
+ tree = ast.parse(read("sampler_py"))
150
+ sampler_scalars = None
151
+ for node in ast.walk(tree):
152
+ if isinstance(node, ast.Assign) and any(getattr(t, "id", "") == "SCALAR_FEATURE_NAMES"
153
+ for t in node.targets):
154
+ sampler_scalars = list(ast.literal_eval(node.value))
155
+ assert sampler_scalars == SCALARS, (sampler_scalars, SCALARS)
156
+
157
+ # Condition width = G panel genes + 6 scalars + G bulk measured fraction + G output mask.
158
+ assert COND_DIM == G + N_SCALARS + 2 * G, (COND_DIM, G)
159
+ require("experiment_py", "condition_dim = int(base_condition_dim) + 2 * int(n_genes)")
160
+ require("data_py", "return torch.cat([condition, bulk_analog, output_analog], dim=-1)")
161
+ require("data_py", "return np.concatenate(\n [full[self.panel_positions], full[n_full:]], axis=0")
162
+ require("sampler_py", "normalized_bulk = np.log1p(raw / max(size_factor, self.eps))")
163
+ require("sampler_py", "size_factor = total / float(k)")
164
+ require("sampler_py", "np.clip(gene_z, -self.clip_z, self.clip_z)")
165
+ require("model_py", "context = self.context_mixer(time_context + condition_context)")
166
+ require("model_py", "hidden = self.input_projection(inputs) + self.context_projection(context)")
167
+ require("model_py", "hidden = torch.cat((noisy_state, self_condition), dim=-1)")
168
+
169
+ # Architecture check: recompute the parameter count from the drawn structure (model.py).
170
+ def _lin(i, o):
171
+ return i * o + o
172
+
173
+
174
+ def _block(i, o):
175
+ return _lin(i, o) + _lin(CTX, o) + 2 * o
176
+
177
+
178
+ S = 2 * G
179
+ p = _lin(TEMB, CTX) + _lin(CTX, CTX) # time encoder
180
+ p += _lin(COND_DIM, CTX) + 2 * CTX + _lin(CTX, CTX) # condition encoder
181
+ p += 2 * CTX + _lin(CTX, CTX) # context mixer
182
+ p += _block(2 * S, HID[0]) + sum(_block(HID[i], HID[i + 1]) for i in range(len(HID) - 1))
183
+ p += sum(_block(HID[i + 1], HID[i]) for i in reversed(range(len(HID) - 1)))
184
+ p += _lin(HID[0], HID[0]) + 2 * HID[0] + 2 * _lin(HID[0], G) # trunk + two heads
185
+ assert p == N_PARAMS, (p, N_PARAMS)
186
+ BLOCK_WIDTHS = HID + HID[-2::-1] # 7 conditioned blocks
187
+ N_BLOCKS = len(BLOCK_WIDTHS)
188
+
189
+ # Final model settings recorded for the final checkpoint.
190
+ require("final_readme", "runs/f01_6k_1x_seed20260627/checkpoint_epoch_016.pt")
191
+ require("final_readme", "Bernoulli read-out")
192
+
193
+ # External numbers
194
+ m = re.search(r"output is a (\d+)-dimension latent space embedding", norm(read("scdiff_paper")))
195
+ assert m, "scDiffusion latent width not found"
196
+ SCDIFF_LATENT = int(m.group(1))
197
+
198
+ # SDD has no condition input: every 'condition' before its references is 'self-condition'.
199
+ sdd_text = read("sdd_paper")
200
+ sdd_body = sdd_text[: sdd_text.index("References")]
201
+ hits = [mm.start() for mm in re.finditer(r"condition", sdd_body, flags=re.I)]
202
+ assert hits and all(sdd_body[h - 5:h].lower() == "self-" for h in hits), "SDD mentions conditioning"
203
+ SDD_COND_HITS = len(hits)
204
+
205
+ # SDD upstream code at the reference commit (the commit PBISC names as its source).
206
+ require("notices", f"Reference commit: `{SDD_COMMIT}`")
207
+ up = read("sdd_upstream")
208
+ # scRNA denoiser: the forward takes only (x, t, x_self_cond) -> no condition input.
209
+ require("sdd_upstream", "class Cell_Unet(nn.Module):")
210
+ require("sdd_upstream", "def forward(self, x, t, x_self_cond=None):")
211
+ # Block = Linear(x) + SiLU->Linear(emb), LayerNorm, SiLU; time embedding enters every block.
212
+ UP_BLOCK = "h = self.fc(x)\n h = h + self.emb_layer(emb)\n h = self.norm(h)\n h = self.act(h)"
213
+ UP_EVERY = "for layer in self.layers:\n x = layer(x, emb)"
214
+ UP_SKIP = "x = layer(x, emb)\n x = x + history.pop() # Skip connection"
215
+ UP_CUT = "(img[:, self.data_channels:] > 0).float()"
216
+ for q in (UP_BLOCK, UP_EVERY, UP_SKIP, UP_CUT):
217
+ require("sdd_upstream", q)
218
+ # PBISC block: the same four operations in the same order, with the shared context in place of emb.
219
+ PB_BLOCK = ("hidden = self.input_projection(inputs) + self.context_projection(context)\n"
220
+ " hidden = self.normalization(hidden)\n hidden = self.activation(hidden)")
221
+ PB_EVERY = "for block in self.down_blocks:\n hidden = block(hidden, context)"
222
+ PB_SKIP = "hidden = block(hidden, context)\n hidden = hidden + history.pop()"
223
+ for q in (PB_BLOCK, PB_EVERY, PB_SKIP):
224
+ require("model_py", q)
225
+ # Note (reported, not drawn): the paper trains the bit with CE (Eq. 6), while the public code at
226
+ # this commit returns F.mse_loss over values and bits together. The slide avoids the loss name.
227
+ require("sdd_paper", "a cross entropy loss (CE on labels in")
228
+ require("sdd_upstream", "return F.mse_loss(pred, img), get_classification_error(")
229
+
230
+ # Recipe size K used for real bulk (condition-level experiments), and K vs cells generated.
231
+ mk = re.search(r"\$K=(\d+)\$ cells and a fixed per-cell depth", read("methods"))
232
+ assert mk, "real-bulk K not found in methods"
233
+ K_REAL = int(mk.group(1))
234
+ require("sampler_py", "recipe_k=external.recipe_k[:keep],")
235
+ require("sampler_py", "cells_per_bulk=external.cells_per_bulk[:keep],")
236
+ # Read-out definitions.
237
+ require("methods", r"$p_{ig}=\mathrm{sigmoid}(\ell_{ig})$")
238
+ require("methods", r"(a) The inherited default keeps gene $g$ when $\ell_{ig}>0$")
239
+ require("methods", "(c) The drawn read-out keeps gene $g$ when $u_{ig}<p_{ig}$")
240
+ require("sampler_py", "probability = torch.sigmoid(sample.active_logits.to(dtype=torch.float32))")
241
+
242
+ # --------------------------------------------------------------------------------------------
243
+ # 2. Comparison table (cells 2-5 words). Each cell: text, evidence [(source key, quote), ...].
244
+ # PBISC cells also carry vs_sdd = same | partial | changed, checked against SDD evidence.
245
+ # --------------------------------------------------------------------------------------------
246
+ ROWS = ["Diffusion space", "Denoiser", "Zeros in training", "Zeros at the end",
247
+ "Conditioned on", "Generates"]
248
+ COLS = [("scDiffusion", "Luo et al. 2024"), ("SDD", "Ostheimer et al. 2025"),
249
+ ("PBISC-Diffusion", "ours, adapted from SDD")]
250
+ fmt = "{:,}".format
251
+ NOTICE_ADDS = ("adds conditional bulk/depth inputs, a three-state\nmeasurement contract, "
252
+ "measured-only BCE/L2 losses")
253
+ cells = {
254
+ # ---- scDiffusion
255
+ ("Diffusion space", "scDiffusion"): (f"{SCDIFF_LATENT}-d latent (SCimilarity AE)", [
256
+ ("scdiff_paper", "we used the pre-trained foundation model SCimilarity [29] as the autoencoder"),
257
+ ("scdiff_paper", f"the output is a {SCDIFF_LATENT}-dimension latent space embedding")]),
258
+ ("Denoiser", "scDiffusion"): ("Skip-MLP, predicts noise", [
259
+ ("scdiff_paper", "fully connected layers and a skip-connected structure"),
260
+ ("scdiff_paper", "as inputs to predict the noise")]),
261
+ ("Zeros in training", "scDiffusion"): ("No explicit zero model", [
262
+ ("sdd_paper", "lacks explicit sparsity enforcement")]),
263
+ ("Zeros at the end", "scDiffusion"): ("No zero step (decoder)", [
264
+ ("scdiff_paper", "put it into the decoder to get the final gene expression data"),
265
+ ("sdd_paper", "lacks explicit sparsity enforcement")]),
266
+ ("Conditioned on", "scDiffusion"): ("Cell-type classifier guidance", [
267
+ ("scdiff_paper", "We use the classifier guidance method to perform conditional generation")]),
268
+ ("Generates", "scDiffusion"): ("Decoded gene expression", [
269
+ ("scdiff_paper", "The generated embeddings are finally fed into the decoder to obtain full gene "
270
+ "expression")]),
271
+ # ---- SDD (paper + upstream code at the reference commit)
272
+ ("Diffusion space", "SDD"): ("Gene space: value + bit", [
273
+ ("sdd_paper", "our forward–backward process diffuses continuous and discrete variables jointly")]),
274
+ ("Denoiser", "SDD"): ("Skip-MLP, predicts $x_0$", [
275
+ ("sdd_paper", "we adopt a skip-connected MLP following scDiffusion"),
276
+ ("sdd_paper", "denoising neural network fθ to predict x"),
277
+ ("sdd_upstream", UP_BLOCK), ("sdd_upstream", UP_EVERY)]),
278
+ ("Zeros in training", "SDD"): ("Sparsity bit (±1)", [
279
+ ("sdd_paper", "a cross entropy loss (CE on labels in"),
280
+ ("sdd_upstream", "return F.mse_loss(pred, img), get_classification_error(")]),
281
+ ("Zeros at the end", "SDD"): ("Hard cut: bit > 0", [
282
+ ("sdd_paper", "using the heaviside step function H applied element-wise"),
283
+ ("sdd_upstream", UP_CUT)]),
284
+ ("Conditioned on", "SDD"): ("Nothing (unconditional)", [
285
+ ("sdd_upstream", "def forward(self, x, t, x_self_cond=None):"),
286
+ ("sdd_paper", "We use self-conditioning [2]")]),
287
+ ("Generates", "SDD"): ("Values with exact zeros", [
288
+ ("sdd_paper", "we apply an element-wise product to get the sparsified output")]),
289
+ # ---- PBISC-Diffusion
290
+ ("Diffusion space", "PBISC-Diffusion"): (f"Value + bit, {fmt(G)} genes", [
291
+ ("diffusion_py", "Values and active/support variables are diffused jointly in the original gene\n"
292
+ "space."),
293
+ ("model_py", "self.state_dim = 2 * config.n_genes")]),
294
+ ("Denoiser", "PBISC-Diffusion"): ("Same skip-MLP, predicts $x_0$", [
295
+ ("model_py", "Skip-connected conditional MLP predicting value x0 and active logits."),
296
+ ("model_py", PB_BLOCK), ("model_py", PB_EVERY), ("model_py", PB_SKIP)]),
297
+ ("Zeros in training", "PBISC-Diffusion"): (("Same bit;", "unmeasured masked out"), [
298
+ ("diffusion_py", "A measured active target is represented by ``+support_scale`` and a\n"
299
+ "measured inactive target by ``-support_scale``."),
300
+ ("diffusion_py", "Unmeasured coordinates are\nneutralized to zero and excluded from both loss terms"),
301
+ ("notices", NOTICE_ADDS)]),
302
+ ("Zeros at the end", "PBISC-Diffusion"): ("Bernoulli, p = σ(logit)", [
303
+ ("sampler_py", "``bernoulli`` instead draws each gene from its own probability"),
304
+ ("sampler_py", "probability = torch.sigmoid(sample.active_logits.to(dtype=torch.float32))"),
305
+ ("methods", r"$p_{ig}=\mathrm{sigmoid}(\ell_{ig})$"),
306
+ ("final_readme", "Bernoulli read-out")]),
307
+ ("Conditioned on", "PBISC-Diffusion"): ("Bulk + depth + assay masks", [
308
+ ("intro", "It receives a bulk vector, depth features, the fraction of cells whose assay measured "
309
+ "each gene and the output assay mask"),
310
+ ("notices", NOTICE_ADDS)]),
311
+ ("Generates", "PBISC-Diffusion"): ("Many cells from one bulk", [
312
+ ("methods", "Cells generated from the same bulk shared its features and output-assay mask."),
313
+ ("sampler_py", "cells_per_bulk=external.cells_per_bulk[:keep],")]),
314
+ }
315
+ # How each PBISC cell compares with SDD, and the SDD-side evidence that decides it.
316
+ VS_SDD = {
317
+ "Diffusion space": ("same", "SDD paper: continuous + discrete diffused jointly in data space"),
318
+ "Denoiser": ("same", "upstream ResidualBlock h=fc(x)+emb_layer(emb), LayerNorm, SiLU; emb fed to every "
319
+ "block; skip adds; PBISC _ConditionedBlock is the same op sequence; heads "
320
+ f"2 x Linear({HID[0]},G) = one Linear to 2G"),
321
+ "Zeros in training": ("partial", "bit kept (+-1 targets, cut at 0 as in SDD); new = unmeasured genes "
322
+ "excluded from loss (THIRD_PARTY_NOTICES: measured-only BCE/L2). SDD bit loss: CE in "
323
+ "the paper (Eq. 6) but F.mse_loss in the public code at 1d5423c, "
324
+ "so the loss name is left off the slide"),
325
+ "Zeros at the end": ("changed", "SDD: Heaviside cut on the bit (paper) and (bit > 0) in upstream code; "
326
+ "PBISC final read-out draws Bernoulli(sigmoid(logit)); the logit > 0 "
327
+ "cut is kept as the inherited default and also reported (methods)"),
328
+ "Conditioned on": ("changed", "upstream Cell_Unet.forward(x, t, x_self_cond) has no condition input; "
329
+ f"SDD paper body: every 'condition' match (n={SDD_COND_HITS}) is 'self-conditioning'; "
330
+ "THIRD_PARTY_NOTICES: PBISC adds conditional bulk/depth inputs"),
331
+ "Generates": ("changed", "SDD samples unconditionally; PBISC draws cells_per_bulk cells per bulk "
332
+ "condition (separate from recipe size K)"),
333
+ }
334
+ assert set(VS_SDD) == set(ROWS)
335
+ for (row, col), (txt, ev) in cells.items():
336
+ for key, q in ev:
337
+ require(key, q)
338
+ flat = " ".join(txt) if isinstance(txt, tuple) else txt
339
+ nwords = len(re.sub(r"\$[^$]*\$", "x", flat).replace("+", " ").split())
340
+ assert 2 <= nwords <= 5, (flat, nwords)
341
+ if col == "PBISC-Diffusion":
342
+ # a partial change is drawn two-tone (black kept part, orange changed part)
343
+ assert isinstance(txt, tuple) == (VS_SDD[row][0] == "partial"), row
344
+
345
+ with open(DATA / "sec02_backbone_compare.csv", "w", newline="") as fh:
346
+ w = csv.writer(fh)
347
+ w.writerow(["row", "model", "cell_text", "vs_sdd", "vs_sdd_basis", "source_paths", "source_urls",
348
+ "evidence_quotes"])
349
+ for row in ROWS:
350
+ for col, _ in COLS:
351
+ txt, ev = cells[(row, col)]
352
+ flat = " | ".join(txt) if isinstance(txt, tuple) else txt
353
+ vs, basis = VS_SDD[row] if col == "PBISC-Diffusion" else ("", "")
354
+ keys = list(dict.fromkeys(k for k, _ in ev))
355
+ w.writerow([row, col, flat, vs, basis, " ; ".join(str(SRC[k]) for k in keys),
356
+ " ; ".join(URL.get(k, "") for k in keys if URL.get(k)),
357
+ " || ".join(f"[{k}] {norm(q)}" for k, q in ev)])
358
+
359
+ # --------------------------------------------------------------------------------------------
360
+ # 3. Figure (a): comparison drawn as a plain ruled table. 12.3 x 4.5 in leaves a keyword strip.
361
+ # --------------------------------------------------------------------------------------------
362
+ W, H = style.FULL[0], 4.5
363
+ PB = style.ARM["pbisc"]
364
+ fig = plt.figure(figsize=(W, H))
365
+ ax = fig.add_axes([0, 0, 1, 1])
366
+ ax.set_xlim(0, W)
367
+ ax.set_ylim(0, H)
368
+ ax.axis("off")
369
+ LW = 2.35
370
+ CW = (W - LW - 0.05) / 3
371
+ HEAD = 0.80
372
+ LEG = 0.34
373
+ RH = (H - 0.02 - HEAD - LEG) / len(ROWS)
374
+ top = H - 0.02
375
+ x0s = [LW + i * CW for i in range(3)]
376
+ FS_CELL = 14
377
+ renderer = fig.canvas.get_renderer()
378
+
379
+
380
+ def two_tone(xc, y, parts, fs):
381
+ """Centre several differently coloured text pieces on one line (data units = inches)."""
382
+ gap = 0.07
383
+ objs = [ax.text(0, y, s, ha="left", va="center", fontsize=fs, color=c) for s, c in parts]
384
+ widths = [o.get_window_extent(renderer).width / fig.dpi for o in objs]
385
+ x = xc - (sum(widths) + gap * (len(objs) - 1)) / 2
386
+ for o, wd in zip(objs, widths):
387
+ o.set_x(x)
388
+ x += wd + gap
389
+
390
+
391
+ for i, (name, cite) in enumerate(COLS):
392
+ cx = x0s[i] + CW / 2
393
+ col = PB if name == "PBISC-Diffusion" else style.INK
394
+ ax.text(cx, top - 0.26, name, ha="center", va="center", fontsize=16, weight="bold", color=col)
395
+ ax.text(cx, top - 0.58, cite, ha="center", va="center", fontsize=12, color=style.GREY)
396
+ y_head = top - HEAD
397
+ ax.plot([0.05, W - 0.05], [y_head, y_head], color=style.INK, lw=1.2)
398
+ for r, row in enumerate(ROWS):
399
+ yc = y_head - (r + 0.5) * RH
400
+ ax.text(0.12, yc, row, ha="left", va="center", fontsize=FS_CELL, color=style.INK)
401
+ for i, (name, _) in enumerate(COLS):
402
+ txt = cells[(row, name)][0]
403
+ cx = x0s[i] + CW / 2
404
+ if name != "PBISC-Diffusion":
405
+ ax.text(cx, yc, txt, ha="center", va="center", fontsize=FS_CELL, color=style.INK)
406
+ elif VS_SDD[row][0] == "partial":
407
+ two_tone(cx, yc, [(txt[0], style.INK), (txt[1], PB)], FS_CELL)
408
+ else:
409
+ col = PB if VS_SDD[row][0] == "changed" else style.INK
410
+ ax.text(cx, yc, txt, ha="center", va="center", fontsize=FS_CELL, color=col)
411
+ yb = y_head - (r + 1) * RH
412
+ last = r == len(ROWS) - 1
413
+ ax.plot([0.05, W - 0.05], [yb, yb], color=style.INK if last else "#C8C8C8", lw=1.2 if last else 0.8)
414
+ y_bot = y_head - len(ROWS) * RH
415
+ for x in x0s:
416
+ ax.plot([x, x], [y_bot, top - 0.06], color="#C8C8C8", lw=0.8)
417
+ ax.text(W - 0.08, y_bot - LEG / 2, "orange = changed from SDD", ha="right", va="center",
418
+ fontsize=12, color=PB)
419
+ style.save(fig, "sec02_backbone_compare", FIG)
420
+
421
+ # --------------------------------------------------------------------------------------------
422
+ # 4. Figure (b): bulk conditioning path, 12.3 x 4.5 in
423
+ # --------------------------------------------------------------------------------------------
424
+ fig = plt.figure(figsize=(W, H))
425
+ ax = fig.add_axes([0, 0, 1, 1])
426
+ ax.set_xlim(0, W)
427
+ ax.set_ylim(0, H)
428
+ ax.axis("off")
429
+ EDGE = style.INK
430
+ FS_MAIN, FS_SUB = 14, 12.5
431
+
432
+
433
+ def box(x, y, w, h, main, sub=None, ec=EDGE, color=style.INK, lw=1.0):
434
+ """Plain box; `sub` may hold several grey lines separated by newlines."""
435
+ ax.add_patch(Rectangle((x, y), w, h, fill=False, ec=ec, lw=lw))
436
+ subs = [] if sub is None else sub.split("\n")
437
+ n = 1 + len(subs)
438
+ step = 0.26
439
+ y_top = y + h / 2 + step * (n - 1) / 2
440
+ ax.text(x + w / 2, y_top, main, ha="center", va="center", fontsize=FS_MAIN, color=color)
441
+ for j, s in enumerate(subs, start=1):
442
+ ax.text(x + w / 2, y_top - j * step, s, ha="center", va="center", fontsize=FS_SUB,
443
+ color=style.GREY)
444
+
445
+
446
+ def arrow(x1, y1, x2, y2, color=EDGE, ls="-", lw=1.1):
447
+ ax.add_patch(FancyArrowPatch((x1, y1), (x2, y2), arrowstyle="-|>", mutation_scale=13,
448
+ color=color, lw=lw, linestyle=ls, shrinkA=0, shrinkB=0))
449
+
450
+
451
+ # four input rows: (y bottom, height)
452
+ R_B, R_K, R_F, R_M = (3.15, 1.0), (1.95, 1.0), (1.0, 0.75), (0.05, 0.75)
453
+ mid = lambda r: r[0] + r[1] / 2 # noqa: E731
454
+
455
+ # inputs (left)
456
+ IX, IW = 0.06, 2.4
457
+ box(IX, R_B[0], IW, R_B[1], "Bulk counts b", f"{fmt(N_FULL)}-gene axis")
458
+ box(IX, R_K[0], IW, R_K[1], "Recipe size K", f"cells in the bulk\nreal bulk: K = {fmt(K_REAL)}")
459
+ box(IX, R_F[0], IW, R_F[1], "Measured fraction f", "per gene, input bulk")
460
+ box(IX, R_M[0], IW, R_M[1], "Output assay mask m", "per gene, output cell")
461
+
462
+ # transforms (middle); b and K feed both the gene features and the scalars (shared bus)
463
+ TX, TW = 2.86, 2.95
464
+ box(TX, R_B[0], TW, R_B[1], "log1p(b·K / Σb)",
465
+ f"on {fmt(N_FULL)}, keep {fmt(G)} genes\nz-score, clip ±{CLIP_Z:g}")
466
+ box(TX, R_K[0], TW, R_K[1], f"{N_SCALARS} depth / shape scalars", f"z-score, clip ±{CLIP_Z:g}")
467
+ box(TX, R_F[0], TW, R_F[1], "2f − 1", f"{fmt(G)} genes")
468
+ box(TX, R_M[0], TW, R_M[1], "2m − 1", f"{fmt(G)} genes")
469
+ BUS = IX + IW + 0.2
470
+ ax.plot([IX + IW, BUS], [mid(R_B)] * 2, color=EDGE, lw=1.1)
471
+ ax.plot([IX + IW, BUS], [mid(R_K)] * 2, color=EDGE, lw=1.1)
472
+ ax.plot([BUS, BUS], [mid(R_K), mid(R_B)], color=EDGE, lw=1.1)
473
+ arrow(BUS, mid(R_B), TX, mid(R_B))
474
+ arrow(BUS, mid(R_K), TX, mid(R_K))
475
+ arrow(IX + IW, mid(R_F), TX, mid(R_F))
476
+ arrow(IX + IW, mid(R_M), TX, mid(R_M))
477
+
478
+ # condition vector: four concatenated parts (schematic heights), bracket = one vector
479
+ BX, BWID = 6.12, 0.42
480
+ for r, lab in zip((R_B, R_K, R_F, R_M), (fmt(G), f"{N_SCALARS}", fmt(G), fmt(G))):
481
+ ax.add_patch(Rectangle((BX, r[0]), BWID, r[1], fill=False, ec=EDGE, lw=1.0))
482
+ ax.text(BX + BWID / 2, mid(r), lab, ha="center", va="center", fontsize=12, rotation=90,
483
+ color=style.INK)
484
+ arrow(TX + TW, mid(r), BX, mid(r))
485
+ BRK = BX + BWID + 0.12
486
+ y_lo, y_hi = R_M[0], R_B[0] + R_B[1]
487
+ ax.plot([BRK, BRK], [y_lo, y_hi], color=EDGE, lw=1.0)
488
+ for yy in (y_lo, y_hi):
489
+ ax.plot([BRK - 0.05, BRK], [yy, yy], color=EDGE, lw=1.0)
490
+ ax.text(BX + BWID / 2, y_hi + 0.17, f"condition c · {fmt(COND_DIM)}", ha="center", va="center",
491
+ fontsize=FS_MAIN, color=style.INK, weight="bold")
492
+
493
+ # encoders (right)
494
+ EX, EW = 7.05, 2.55
495
+ YC = 2.80 # height of the condition -> context line
496
+ box(EX, YC - 0.36, EW, 0.72, "Condition MLP", f"{fmt(COND_DIM)} → {CTX} → {CTX}")
497
+ arrow(BRK, YC, EX, YC)
498
+ T_Y0, T_H = 3.45, 0.70
499
+ box(EX, T_Y0, EW, T_H, "Time t", f"sinusoid {TEMB} → MLP → {CTX}")
500
+ PX, PR = 9.97, 0.17
501
+ ax.add_patch(Circle((PX, YC), PR, fill=False, ec=EDGE, lw=1.0))
502
+ ax.text(PX, YC, "+", ha="center", va="center", fontsize=15)
503
+ arrow(EX + EW, YC, PX - PR, YC)
504
+ T_MID = T_Y0 + T_H / 2
505
+ ax.plot([EX + EW, PX], [T_MID, T_MID], color=EDGE, lw=1.1)
506
+ arrow(PX, T_MID, PX, YC + PR)
507
+ CX0 = 10.42
508
+ CWD = W - 0.06 - CX0
509
+ box(CX0, YC - 0.36, CWD, 0.72, f"context e · {CTX}", "LN, SiLU, Linear", ec=PB, color=PB, lw=1.3)
510
+ arrow(PX + PR, YC, CX0, YC)
511
+
512
+ # denoiser: 7 conditioned blocks, each receiving e; data in/out written inside the box
513
+ DX, DY = EX, 0.05
514
+ DW, DH = W - 0.06 - DX, 1.95
515
+ ax.add_patch(Rectangle((DX, DY), DW, DH, fill=False, ec=EDGE, lw=1.0))
516
+ bw, gap = 0.40, 0.14
517
+ total = N_BLOCKS * bw + (N_BLOCKS - 1) * gap
518
+ bx0 = DX + DW - 0.18 - total
519
+ centers = [bx0 + k * (bw + gap) + bw / 2 for k in range(N_BLOCKS)]
520
+ BAR_Y = DY + 0.86
521
+ ax.text(DX + 0.14, BAR_Y + 0.52, "Denoiser", ha="left", va="center", fontsize=FS_MAIN, color=style.INK)
522
+ ax.text(DX + 0.14, BAR_Y + 0.22, f"{N_BLOCKS} blocks", ha="left", va="center", fontsize=FS_SUB,
523
+ color=style.GREY)
524
+ IN_DIM, OUT_DIM = 2 * S, G # [x_t, self-cond] each 2G wide; value head and logit head each G
525
+ ax.text(DX + 0.14, DY + 0.44, f"in: $x_t$ + self-cond, {fmt(IN_DIM)}", ha="left", va="center",
526
+ fontsize=12, color=style.GREY)
527
+ ax.text(DX + 0.14, DY + 0.18, f"out: value + logit, 2 × {fmt(OUT_DIM)}", ha="left", va="center",
528
+ fontsize=12, color=style.GREY)
529
+ drop_x = CX0 + CWD / 2
530
+ bus_y = DY + DH + 0.20
531
+ ax.plot([min(centers + [drop_x]), max(centers + [drop_x])], [bus_y, bus_y], color=PB, lw=1.2,
532
+ ls=(0, (4, 2)))
533
+ ax.plot([drop_x, drop_x], [bus_y, YC - 0.36], color=PB, lw=1.2, ls=(0, (4, 2)))
534
+ max_w = max(BLOCK_WIDTHS)
535
+ for cx, wdt in zip(centers, BLOCK_WIDTHS):
536
+ hh = 0.28 + 0.45 * wdt / max_w
537
+ ax.add_patch(Rectangle((cx - bw / 2, BAR_Y), bw, hh, fill=False, ec=EDGE, lw=1.0))
538
+ ax.text(cx, BAR_Y - 0.16, f"{wdt:,}", ha="center", va="center", fontsize=11, color=style.GREY)
539
+ arrow(cx, bus_y, cx, BAR_Y + hh + 0.02, color=PB, ls=(0, (4, 2)), lw=1.1)
540
+ style.save(fig, "sec02_bulk_conditioning", FIG)
541
+
542
+ # --------------------------------------------------------------------------------------------
543
+ # 5. Source table for (b) and the numbers quoted on the slides
544
+ # --------------------------------------------------------------------------------------------
545
+ rows_b = [
546
+ ("canonical_gene_axis", N_FULL, SRC["panel_manifest"], "n_full_genes"),
547
+ ("canonical_gene_axis_conditioner", N_FULL_COND, cond_cache, "conditioner_state.n_genes"),
548
+ ("panel_genes_G", G, SRC["run_status"], "n_genes"),
549
+ ("condition_dim", COND_DIM, SRC["run_status"], "condition_dim"),
550
+ ("n_scalars", N_SCALARS, cond_cache, "conditioner_state.feature_names[n_genes:]"),
551
+ ("scalar_names", ";".join(SCALARS), cond_cache, "conditioner_state.feature_names[n_genes:]"),
552
+ ("clip_z", CLIP_Z, cond_cache, "conditioner_state.clip_z"),
553
+ ("recipe_k_real_bulk", K_REAL, SRC["methods"], "'$K=1000$ cells and a fixed per-cell depth' (regex)"),
554
+ ("context_dim", CTX, SRC["eff_config"], "model.context_dim"),
555
+ ("time_embedding_dim", TEMB, SRC["eff_config"], "model.time_embedding_dim"),
556
+ ("hidden_dims", ";".join(map(str, HID)), SRC["eff_config"], "model.hidden_dims"),
557
+ ("conditioned_blocks", N_BLOCKS, SRC["model_py"], "len(down_blocks)+len(up_blocks)"),
558
+ ("block_widths", ";".join(map(str, BLOCK_WIDTHS)), SRC["model_py"], "down then up widths"),
559
+ ("parameters", N_PARAMS, SRC["run_status"], "parameters (recomputed from structure: equal)"),
560
+ ("state_dim_2G", 2 * G, SRC["model_py"], "state_dim = 2 * n_genes"),
561
+ ("denoiser_input_dim", IN_DIM, SRC["model_py"], "first block input 2 * state_dim = [x_t, self-cond]"),
562
+ ("value_head_out", OUT_DIM, SRC["model_py"], "value_head = Linear(widths[0], n_genes)"),
563
+ ("logit_head_out", OUT_DIM, SRC["model_py"], "active_head = Linear(widths[0], n_genes)"),
564
+ ("ddim_steps", STEPS, SRC["eff_config"], "sampling.steps"),
565
+ ("ddim_eta", ETA, SRC["eff_config"], "sampling.eta"),
566
+ ("scdiffusion_latent_dim", SCDIFF_LATENT, SRC["scdiff_paper"], "Sec 2.1 text"),
567
+ ("sdd_condition_hits_all_self", SDD_COND_HITS, SRC["sdd_paper"], "regex 'condition' before References"),
568
+ ]
569
+ with open(DATA / "sec02_bulk_conditioning.csv", "w", newline="") as fh:
570
+ w = csv.writer(fh)
571
+ w.writerow(["quantity", "value", "source_path", "source_key", "source_sha256_16"])
572
+ for q, v, pth, k in rows_b:
573
+ w.writerow([q, v, str(pth), k, sha(Path(pth))])
574
+
575
+ # --------------------------------------------------------------------------------------------
576
+ # 6. Slide keyword lines and their evidence (checked like the table cells)
577
+ # --------------------------------------------------------------------------------------------
578
+ slide_text = [
579
+ ("backbone", "Kept from SDD: value + bit, skip-MLP", [
580
+ ("sdd_paper", "our forward–backward process diffuses continuous and discrete variables jointly"),
581
+ ("sdd_upstream", UP_BLOCK), ("model_py", PB_BLOCK)]),
582
+ ("backbone", "Changed: bulk condition, masked loss, Bernoulli read-out", [
583
+ ("notices", NOTICE_ADDS),
584
+ ("sampler_py", "``bernoulli`` instead draws each gene from its own probability")]),
585
+ ("conditioning", "Same bulk condition for every generated cell", [
586
+ ("methods", "Cells generated from the same bulk shared its features and output-assay mask.")]),
587
+ ("conditioning", "Final: no cell types, proportions, sum constraint", [
588
+ ("intro", "it receives no cell-type labels, no target proportions and no term that forces "
589
+ "generated counts to sum to the bulk")]),
590
+ ("conditioning", f"{fmt(COND_DIM)} → {CTX} context into every block", [
591
+ ("model_py", "context = self.context_mixer(time_context + condition_context)"),
592
+ ("model_py", PB_EVERY)]),
593
+ ]
594
+ with open(DATA / "sec02_slide_text.csv", "w", newline="") as fh:
595
+ w = csv.writer(fh)
596
+ w.writerow(["slide", "keyword_line", "n_words", "source_paths", "evidence_quotes"])
597
+ for slide, line, ev in slide_text:
598
+ for key, q in ev:
599
+ require(key, q)
600
+ n = len(line.split())
601
+ assert n <= 7, (line, n)
602
+ keys = list(dict.fromkeys(k for k, _ in ev))
603
+ w.writerow([slide, line, n, " ; ".join(str(SRC[k]) for k in keys),
604
+ " || ".join(f"[{k}] {norm(q)}" for k, q in ev)])
605
+
606
+ print(f"G={G} full={N_FULL} cond_dim={COND_DIM} ctx={CTX} temb={TEMB} blocks={BLOCK_WIDTHS} "
607
+ f"params={N_PARAMS} clip={CLIP_Z} scalars={SCALARS} scdiff_latent={SCDIFF_LATENT} "
608
+ f"K_real={K_REAL} in={IN_DIM} out=2x{OUT_DIM} sdd_cond_hits={SDD_COND_HITS} "
609
+ f"upstream_sha16={sha(SRC['sdd_upstream'])}")
paper-releases/pbisc-diffusion/updates/20260930T065633Z-summary-deck-scsemi-final/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec03_common.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared loaders for section 3 (model-structure ablation and gene-panel ablation).
2
+
3
+ Every number used by the section-3 figures is read here from the run's own files or from the
4
+ scANVI score tables; nothing is typed in. Runs whose files live only on sj_server_2 (spark-0110) are
5
+ read from a snapshot in data/sec03_server2_snapshots/<run>/, fetched read-only with
6
+ `ssh -n spark-0110 cat <same path>` when the snapshot is missing.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import re
12
+ import subprocess
13
+ from pathlib import Path
14
+
15
+ import pandas as pd
16
+
17
+ M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
18
+ DECK = M8 / "presentations/2026-09-30--paper-summary--r00"
19
+ FIG = DECK / "figures"
20
+ DATA = DECK / "data"
21
+ SNAP = DATA / "sec03_server2_snapshots"
22
+ OLD_DECK_DATA = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/presentations/"
23
+ "2026-09-16--model8-diffusion-vs-vae--r00--labmeeting/data")
24
+
25
+ # width / context / proportion-hint arms (6k panel at the published 1% detection floor)
26
+ WIDTH_RUNS = [
27
+ # key, label, run dir name, host holding the complete run files
28
+ ("1x", "1x", "s0_6k_allK_topup16_seed20260627_bundle_v2", "server_1"),
29
+ ("ctx4x", "context x4", "s0_6k_allK_topup16_seed20260627_archctx2048_v1", "server_2"),
30
+ ("trunk4x", "trunk x4", "s0_6k_allK_topup16_seed20260627_arch4x_ctx512_v1", "server_1"),
31
+ ("4x", "trunk x4 + context x4", "s0_6k_allK_topup16_seed20260627_arch4x_v1", "server_2"),
32
+ ("16x", "16x", "s0_6k_allK_topup16_seed20260627_arch16x_v1", "server_2"),
33
+ ("prop", "1x + proportion hint", "s0_6k_allK_topup16_seed20260627_prop_v1", "server_1"),
34
+ ]
35
+ # gene panels at the 0.1% detection floor, 1x architecture
36
+ PANEL_RUNS = [
37
+ ("2k", "f01_2k_1x_seed20260627", "server_1"),
38
+ ("3k", "f01_3k_1x_seed20260627", "server_2"),
39
+ ("6k", "f01_6k_1x_seed20260627", "server_1"),
40
+ ("15k", "f01_p15k_1x_seed20260627", "server_2"),
41
+ ]
42
+ FILES = ("effective_config.json", "RUN_STATUS.json", "history.json")
43
+
44
+ # scANVI score tables
45
+ WIDTH_SCORES = M8 / ("analysis/scsemi_benchmark_diffusion_20260913/metrics_arch_epochs/"
46
+ "scanvi_server2/summary_tidy_latest.csv")
47
+ WIDTH_SCORES_MD = M8 / "plans/threshold_rescore_20260922/THRESHOLD_RESCORE.md"
48
+ PANEL_SCORES = M8 / "analysis/floor01_benchmark_20260923/metrics/summary_tidy.csv"
49
+ PANEL_SCORES_MD = M8 / "plans/floor01_campaign_20260923/RESULTS.md"
50
+ # same 1,006-gene scoring pipeline re-run with 4 extra sampling seeds of the final 6k checkpoint;
51
+ # it reproduces every floor01 row exactly (checked in sec03_panel.py)
52
+ PANEL_SEED_SCORES = M8 / "plans/utility_studies_final6k_20260925/sle/metrics_1006/summary_tidy.csv"
53
+ PANEL_SEED_MANIFEST = M8 / "plans/utility_studies_final6k_20260925/sle/MANIFEST.json"
54
+ PARAM_COUNTS = OLD_DECK_DATA / "param_counts.json"
55
+
56
+ SAT_TOL = 0.01 # saturation: first part after which validation loss stays within 1% of its part-16 value
57
+ SAT_TOL_SENS = (0.005, 0.02) # the rule is tolerance-sensitive; these are written next to it
58
+
59
+
60
+ def run_dir(name: str, host: str) -> tuple[Path, str]:
61
+ """Local directory holding the run's JSON files, and the original source path to cite."""
62
+ original = M8 / "runs" / name
63
+ if host == "server_1":
64
+ return original, f"server_1:{original}"
65
+ local = SNAP / name
66
+ local.mkdir(parents=True, exist_ok=True)
67
+ for f in FILES:
68
+ if not (local / f).is_file() or (local / f).stat().st_size == 0:
69
+ out = subprocess.run(["ssh", "-n", "-o", "BatchMode=yes", "spark-0110", f"cat {original / f}"],
70
+ capture_output=True, text=True, timeout=60)
71
+ if out.returncode != 0 or not out.stdout.strip():
72
+ raise SystemExit(f"cannot read {original / f} on spark-0110")
73
+ (local / f).write_text(out.stdout)
74
+ return local, f"server_2:{original}"
75
+
76
+
77
+ def read_run(name: str, host: str) -> dict:
78
+ d, src = run_dir(name, host)
79
+ cfg = json.loads((d / "effective_config.json").read_text())
80
+ st = json.loads((d / "RUN_STATUS.json").read_text())
81
+ hist = json.loads((d / "history.json").read_text())["epochs"]
82
+ rows = []
83
+ for e in sorted(hist, key=lambda r: r["epoch"]):
84
+ rows.append({
85
+ "epoch": int(e["epoch"]),
86
+ "train_loss": float(e["train"]["loss"]),
87
+ "val_loss": float(e["validation"]["loss"]),
88
+ "val_batches": int(e["validation"]["batches"]),
89
+ "val_support_elements": int(e["validation"]["support_elements"]),
90
+ "train_hours": float(e["train_seconds"]) / 3600.0,
91
+ })
92
+ return {"cfg": cfg, "status": st, "hist": pd.DataFrame(rows), "source": src, "local": str(d)}
93
+
94
+
95
+ def param_count(run: dict, key_in_param_file: str | None) -> tuple[int, str]:
96
+ """Parameter count from RUN_STATUS; the 16x run never completed, so its count comes from the
97
+ parameter-count file of the 2026-09-16 lab meeting (same hidden_dims/context_dim, checked)."""
98
+ p = run["status"].get("parameters")
99
+ if p:
100
+ return int(p), run["source"] + "/RUN_STATUS.json"
101
+ pc = json.loads(PARAM_COUNTS.read_text())["diffusion"][key_in_param_file]
102
+ m = run["cfg"]["model"]
103
+ assert pc["hidden_dims"] == m["hidden_dims"] and pc["context_dim"] == m["context_dim"], "param file mismatch"
104
+ assert pc["n_genes"] == run["cfg"]["data"]["n_genes"]
105
+ return int(pc["total"]), f"{PARAM_COUNTS} [diffusion.{key_in_param_file}.total]"
106
+
107
+
108
+ def saturation_epoch(val: list[float], tol: float = SAT_TOL) -> int:
109
+ last = val[-1]
110
+ for i in range(len(val)):
111
+ if all(v <= last * (1.0 + tol) for v in val[i:]):
112
+ return i + 1
113
+ return len(val)
114
+
115
+
116
+ def fmt_params(n: int) -> str:
117
+ return f"{n / 1e9:.2f}B" if n >= 1e9 else f"{n / 1e6:.0f}M"
118
+
119
+
120
+ def n_donors(md_path: Path) -> int:
121
+ m = re.search(r"(\d+)\s+donors", md_path.read_text())
122
+ if not m:
123
+ raise SystemExit(f"no donor count in {md_path}")
124
+ return int(m.group(1))
125
+
126
+
127
+ def run_to_run_resolution() -> tuple[float, float]:
128
+ """Run-to-run resolution quoted in the threshold rescore report: SD over 16 parts of the per-part
129
+ difference between the proportion-hint run and 1x (t20_table.py: 'two runs that differ only by an
130
+ unused input'). It is derived from the prop-vs-1x pair itself, so it cannot judge the hint."""
131
+ m = re.search(r"Run-to-run resolution[^:]*:\s*([0-9.]+) in logFC r,\s*([0-9.]+) in top-50", WIDTH_SCORES_MD.read_text())
132
+ if not m:
133
+ raise SystemExit("no run-to-run resolution line")
134
+ return float(m.group(1)), float(m.group(2))
paper-releases/pbisc-diffusion/updates/20260930T065633Z-summary-deck-scsemi-final/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec03_panel.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Section 3c: gene-context (panel) ablation on the 0.1% detection-floor panels, 1x architecture.
3
+
4
+ Benchmark: part 16 of each panel, Bernoulli (drawn) read-out, scANVI metrics on the 1,006 benchmark genes
5
+ present in every panel (the 2,980-gene benchmark panel intersected with the 2k tier;
6
+ evaluation_manifest_common.json), with scSemiProfiler and PBISC-VAE on the same axis.
7
+ Scores come from the utility-study re-run of the same 1,006-gene pipeline (metrics_1006/summary_tidy.csv),
8
+ which adds 4 extra sampling seeds of the final 6k checkpoint and reproduces every floor01 row exactly
9
+ (asserted here against analysis/floor01_benchmark_20260923/metrics/summary_tidy.csv).
10
+ 6k is drawn as the 5-seed mean +- SD with the seeds as dots; the base seed used by the floor01 ranking is
11
+ the best of the five. 2k, 3k and 15k have one seed each.
12
+ Loss: validation loss divided by the panel's own part-16 value. Absolute losses are not compared
13
+ across panels because each panel predicts a different gene set.
14
+
15
+ Writes figures/sec03_panel.{png,pdf}, data/sec03_panel_bench.csv, data/sec03_panel_seeds.csv,
16
+ data/sec03_panel_loss.csv, data/sec03_panel_headline.csv.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import json
21
+ import re
22
+ import sys
23
+
24
+ sys.path.insert(0, "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/"
25
+ "2026-09-30--paper-summary--r00/tools")
26
+ import matplotlib.pyplot as plt
27
+ import numpy as np
28
+ import pandas as pd
29
+ from matplotlib.lines import Line2D
30
+ from matplotlib.patches import Patch
31
+
32
+ import style
33
+ from sec03_common import (DATA, FIG, M8, PANEL_RUNS, PANEL_SCORES, PANEL_SCORES_MD, PANEL_SEED_MANIFEST,
34
+ PANEL_SEED_SCORES, SAT_TOL, fmt_params, n_donors, read_run, saturation_epoch)
35
+
36
+ COMMON = M8 / "plans/floor01_campaign_20260923/evaluation_manifest_common.json"
37
+ FINAL_CKPT = M8 / "runs/f01_6k_1x_seed20260627/checkpoint_epoch_016.pt"
38
+ METHOD = {"2k": "diffusion_f012k_e16", "3k": "diffusion_f013k_e16", "6k": "diffusion_f016k_e16",
39
+ "15k": "diffusion_f01p15k_e16"}
40
+ SEED_METHODS = ["diffusion_f016k_e16"] + [f"diffusion_f016ks{i}_e16" for i in range(1, 5)] # base seed first
41
+ METRICS = [("logfc_r", "mean_logFC_pearson", "logFC r (higher better)"),
42
+ ("top50", "total_top50_overlap", "Top-50 DEG overlap (higher better)"),
43
+ ("comp_l1", "composition_l1", "Composition L1 (lower better)")]
44
+ REFS = ("scSemiProfiler", "PBISC-VAE")
45
+
46
+
47
+ def load_scores(path) -> pd.DataFrame:
48
+ t = pd.read_csv(path)
49
+ t = t[t["celltype_gate"] == "common_celltype_gate"]
50
+ # each comparison block carries the reference rows once; they are identical across blocks
51
+ for b in REFS:
52
+ rb = t[t["method"] == b]
53
+ assert rb[[c for _, c, _ in METRICS]].nunique().max() == 1, b
54
+ return t.drop_duplicates("method").set_index("method")
55
+
56
+
57
+ def main() -> int:
58
+ n_common = len(json.loads(COMMON.read_text())["evaluation_gene_ids"])
59
+ donors = n_donors(PANEL_SCORES_MD)
60
+ t = load_scores(PANEL_SEED_SCORES)
61
+ assert set(t["panel_genes"]) == {n_common}, (set(t["panel_genes"]), n_common)
62
+ # the seed re-run must reproduce the floor01 scoring call row for row
63
+ f01 = load_scores(PANEL_SCORES)
64
+ for m in list(METHOD.values()) + list(REFS):
65
+ for _, c, _ in METRICS:
66
+ assert abs(float(t.loc[m, c]) - float(f01.loc[m, c])) < 1e-9, (m, c)
67
+ # all five 6k seeds come from the one final checkpoint
68
+ ck = json.loads(PANEL_SEED_MANIFEST.read_text())["files"]["checkpoint"]
69
+ assert len(ck) == 1 and ck[0]["path"] == str(FINAL_CKPT), ck
70
+ ckpt_sha = ck[0]["sha256"]
71
+
72
+ seeds = pd.DataFrame([{"method": m, "seed_rank_in_list": i, "is_base_seed": i == 0,
73
+ **{k: float(t.loc[m, c]) for k, c, _ in METRICS}} for i, m in enumerate(SEED_METHODS)])
74
+ seeds["checkpoint"], seeds["checkpoint_sha256"] = str(FINAL_CKPT), ckpt_sha
75
+ seeds["source"] = str(PANEL_SEED_SCORES)
76
+ seeds.to_csv(DATA / "sec03_panel_seeds.csv", index=False)
77
+ s_mean = {k: seeds[k].mean() for k, _, _ in METRICS}
78
+ s_sd = {k: seeds[k].std(ddof=1) for k, _, _ in METRICS}
79
+
80
+ runs, loss_rows, bench_rows = {}, [], []
81
+ for key, name, host in PANEL_RUNS:
82
+ r = read_run(name, host)
83
+ runs[key] = r
84
+ h = r["hist"]
85
+ assert int(h["epoch"].max()) == 16
86
+ v16 = float(h["val_loss"].iloc[-1])
87
+ sat = saturation_epoch(h["val_loss"].tolist())
88
+ r["sat"], r["v16"] = sat, v16
89
+ for _, e in h.iterrows():
90
+ loss_rows.append({"panel": key, "run": name, "source": r["source"] + "/history.json",
91
+ "n_genes": r["cfg"]["data"]["n_genes"], "params": r["status"]["parameters"],
92
+ "epoch": int(e["epoch"]), "train_loss": e["train_loss"], "val_loss": e["val_loss"],
93
+ "val_rel_e16": e["val_loss"] / v16, "sat_epoch": sat,
94
+ "sat_rule": f"val within {SAT_TOL:.0%} of part-16 value"})
95
+ row = {"arm": key, "method": METHOD[key], "n_genes": r["cfg"]["data"]["n_genes"],
96
+ "params": r["status"]["parameters"], "val_loss_e16": v16}
97
+ if key == "6k":
98
+ row.update({"n_seeds": len(seeds), **{k: s_mean[k] for k in s_mean},
99
+ **{f"{k}_sd": s_sd[k] for k in s_sd},
100
+ **{f"{k}_base_seed": float(t.loc[METHOD[key], c]) for k, c, _ in METRICS}})
101
+ else:
102
+ row.update({"n_seeds": 1, **{k: float(t.loc[METHOD[key], c]) for k, c, _ in METRICS}})
103
+ bench_rows.append(row)
104
+ for b in REFS:
105
+ bench_rows.append({"arm": b, "method": b, **{k: float(t.loc[b, c]) for k, c, _ in METRICS}})
106
+ bench = pd.DataFrame(bench_rows)
107
+ bench["eval_genes"], bench["n_donors"], bench["part"] = n_common, donors, 16
108
+ bench["readout"] = "Bernoulli (drawn)"
109
+ bench["source"] = str(PANEL_SEED_SCORES)
110
+ bench.to_csv(DATA / "sec03_panel_bench.csv", index=False)
111
+ loss = pd.DataFrame(loss_rows)
112
+ assert loss["params"].notna().all()
113
+ loss.to_csv(DATA / "sec03_panel_loss.csv", index=False)
114
+ B = bench.set_index("arm")
115
+
116
+ # headline checks for the keyword lines
117
+ lo = {k: seeds[k].min() for k, _, _ in METRICS}
118
+ hi = {k: seeds[k].max() for k, _, _ in METRICS}
119
+ in_range_3k = {k: bool(lo[k] - 1e-12 <= B.loc["3k", k] <= hi[k] + 1e-12) for k, _, _ in METRICS}
120
+ base_rank = {k: int((seeds[k] > seeds.loc[0, k]).sum()) + 1 if k != "comp_l1"
121
+ else int((seeds[k] < seeds.loc[0, k]).sum()) + 1 for k, _, _ in METRICS}
122
+ m = re.search(r"\|\s*CLEC9A\s*\|\s*([^|]+?)\s*\|\s*([\d,]+)\s*\|\s*(\w+)\s*\|", PANEL_SCORES_MD.read_text())
123
+ assert m, "CLEC9A row missing"
124
+ head = pd.DataFrame([
125
+ {"quantity": "6k_seed_mean_r_top50_l1", "value": "/".join(f"{s_mean[k]:.3f}" for k in s_mean)},
126
+ {"quantity": "6k_seed_sd_r_top50_l1", "value": "/".join(f"{s_sd[k]:.3f}" for k in s_sd)},
127
+ {"quantity": "6k_seed_min_max_r", "value": f"{lo['logfc_r']:.3f}-{hi['logfc_r']:.3f}"},
128
+ {"quantity": "6k_seed_min_max_top50", "value": f"{lo['top50']:.0f}-{hi['top50']:.0f}"},
129
+ {"quantity": "6k_base_seed_rank_of_5_r_top50_l1", "value": "/".join(str(v) for v in base_rank.values())},
130
+ {"quantity": "3k_inside_6k_seed_range_r_top50_l1", "value": "/".join(str(v) for v in in_range_3k.values())},
131
+ {"quantity": "6k_mean_minus_3k_r", "value": s_mean["logfc_r"] - B.loc["3k", "logfc_r"]},
132
+ {"quantity": "6k_mean_minus_3k_top50", "value": s_mean["top50"] - B.loc["3k", "top50"]},
133
+ {"quantity": "best_comp_l1_panel", "value": B.loc[["2k", "3k", "6k", "15k"], "comp_l1"].idxmin()},
134
+ {"quantity": "worst_comp_l1_panel", "value": B.loc[["2k", "3k", "6k", "15k"], "comp_l1"].idxmax()},
135
+ {"quantity": "CLEC9A_population_rank_smallest_panel", "value": f"{m.group(1)}/{m.group(2)}/{m.group(3)}"},
136
+ {"quantity": "final_checkpoint_sha256", "value": ckpt_sha},
137
+ ])
138
+ head["source"] = [str(PANEL_SEED_SCORES)] * 10 + [str(PANEL_SCORES_MD), str(PANEL_SEED_MANIFEST)]
139
+ head.to_csv(DATA / "sec03_panel_headline.csv", index=False)
140
+
141
+ # --- one full-width figure: three benchmark panels + relative validation loss ----------------
142
+ keys = [k for k, _, _ in PANEL_RUNS]
143
+ i6 = keys.index("6k")
144
+ fig, axes = plt.subplots(1, 4, figsize=style.FULL, gridspec_kw={"width_ratios": [1, 1, 1, 1.55]})
145
+ rng = np.random.default_rng(0)
146
+ for ax, (k, _, ylab) in zip(axes[:3], METRICS):
147
+ for i, key in enumerate(keys):
148
+ ax.bar(i, B.loc[key, k], width=0.72, color=style.PANEL[key], zorder=2)
149
+ # SD whisker left of centre, the five seeds right of centre, so neither hides the other
150
+ ax.errorbar(i6 - 0.14, s_mean[k], yerr=s_sd[k], color=style.INK, lw=1.4, capsize=4, capthick=1.4, zorder=4)
151
+ ax.scatter(i6 + 0.16 + rng.uniform(-0.06, 0.06, len(seeds)), seeds[k], s=22, color=style.INK, zorder=5,
152
+ edgecolors="white", linewidths=0.6)
153
+ ax.axhline(B.loc["PBISC-VAE", k], color=style.ARM["vae"], lw=1.8, zorder=3)
154
+ ax.axhline(B.loc["scSemiProfiler", k], color=style.ARM["scsemi"], lw=1.8, ls="--", zorder=3)
155
+ ax.set_xticks(range(len(keys)))
156
+ ax.set_xticklabels(keys)
157
+ ax.get_xticklabels()[i6].set_fontweight("bold")
158
+ ax.set_xlim(-0.6, len(keys) - 0.4)
159
+ ax.set_xlabel("Gene panel")
160
+ ax.set_ylabel(ylab)
161
+ ax.set_ylim(0, max(B[k].max(), seeds[k].max()) * 1.12)
162
+
163
+ ax = axes[3]
164
+ for key in keys:
165
+ r = runs[key]
166
+ h = r["hist"]
167
+ rel = h["val_loss"] / r["v16"]
168
+ ax.plot(h["epoch"], rel, "-o", color=style.PANEL[key], ms=3.5, lw=1.8,
169
+ label=f"{key}, {fmt_params(int(r['status']['parameters']))}, sat. E{r['sat']}")
170
+ ax.plot([r["sat"]], [rel.iloc[r["sat"] - 1]], marker="o", ms=11, mfc="none", mec=style.INK, mew=1.3)
171
+ ax.axhline(1.0 + SAT_TOL, color=style.GREY, lw=0.9, ls=":")
172
+ ax.text(16.3, 1.0 + SAT_TOL + 0.002, f"+{SAT_TOL:.0%}", va="bottom", ha="right", fontsize=12,
173
+ color=style.GREY)
174
+ ax.set_xlabel("Schedule part (epoch)")
175
+ ax.set_ylabel("Val. loss / own part-16 value")
176
+ ax.set_xticks([1, 4, 8, 12, 16])
177
+ ax.set_xlim(0.5, 16.5)
178
+ ax.legend(loc="upper right", handlelength=1.4, borderaxespad=0.1)
179
+
180
+ handles = [Patch(facecolor=style.GREY, label="bars 2k, 3k, 15k: 1 seed"),
181
+ Line2D([], [], color=style.INK, lw=1.4, marker="o", ms=4, mec="white",
182
+ label=f"6k: {len(seeds)} seeds, mean ± SD"),
183
+ Line2D([], [], color=style.ARM["vae"], lw=1.8, label="PBISC-VAE"),
184
+ Line2D([], [], color=style.ARM["scsemi"], lw=1.8, ls="--", label="scSemiProfiler")]
185
+ fig.legend(handles=handles, loc="upper left", ncol=4, bbox_to_anchor=(0.06, 1.07), handlelength=2.0,
186
+ columnspacing=1.6)
187
+ fig.tight_layout(w_pad=1.6)
188
+ style.save(fig, "sec03_panel", FIG)
189
+
190
+ print(f"common genes {n_common}, donors {donors}, checkpoint sha {ckpt_sha[:8]}")
191
+ print(bench.drop(columns=["source"]).round(4).to_string())
192
+ print(seeds[["method", "logfc_r", "top50", "comp_l1"]].round(4).to_string())
193
+ print(head[["quantity", "value"]].to_string())
194
+ print({k: runs[k]["sat"] for k in runs})
195
+ return 0
196
+
197
+
198
+ if __name__ == "__main__":
199
+ raise SystemExit(main())
paper-releases/pbisc-diffusion/updates/20260930T065633Z-summary-deck-scsemi-final/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec03_width_bench.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ METRICS = [("logfc_r", "mean_logFC_pearson", "logFC r (higher better)"),
43
+ ("top50", "total_top50_overlap", "Top-50 DEG overlap (higher better)"),
44
+ ("comp_l1", "composition_l1", "Composition L1 (lower better)")]
45
+
46
+
47
+ def main() -> int:
48
+ t = pd.read_csv(WIDTH_SCORES)
49
+ t = t[(t["comparison"] == "all_diffusion") & (t["celltype_gate"] == "common_celltype_gate")]
50
+ t = t.drop_duplicates("method").set_index("method")
51
+ assert t["panel_genes"].nunique() == 1
52
+ panel_genes = int(t["panel_genes"].iloc[0])
53
+ donors = n_donors(WIDTH_SCORES_MD)
54
+ res_r, res_deg = run_to_run_resolution()
55
+
56
+ rows = []
57
+ for key, _, _, cut, bern in ARMS:
58
+ for readout, pat in (("cut_p>0.5", cut), ("bernoulli", bern)):
59
+ if pat is None:
60
+ continue
61
+ for e in PARTS:
62
+ m = pat.format(e=e)
63
+ r = t.loc[m]
64
+ rows.append({"arm": key, "readout": readout, "part": e, "method": m,
65
+ **{k: float(r[c]) for k, c, _ in METRICS}})
66
+ per = pd.DataFrame(rows)
67
+ per["panel_genes"], per["n_donors"], per["source"] = panel_genes, donors, str(WIDTH_SCORES)
68
+ per.to_csv(DATA / "sec03_width_bench.csv", index=False)
69
+ summ = per.groupby(["arm", "readout"])[[k for k, _, _ in METRICS]].mean().reset_index()
70
+ base = [{"arm": b, "readout": "reference", **{k: float(t.loc[b, c]) for k, c, _ in METRICS}}
71
+ for b in ("scSemiProfiler", "PBISC-VAE")]
72
+ summ = pd.concat([summ, pd.DataFrame(base)], ignore_index=True)
73
+ summ["panel_genes"], summ["n_donors"], summ["source"] = panel_genes, donors, str(WIDTH_SCORES)
74
+ summ["run_to_run_resolution_r"], summ["run_to_run_resolution_deg"] = res_r, res_deg
75
+ summ.to_csv(DATA / "sec03_width_bench_summary.csv", index=False)
76
+ S = summ.set_index(["arm", "readout"])
77
+
78
+ fig, axes = plt.subplots(1, 3, figsize=style.FULL)
79
+ rng = np.random.default_rng(0)
80
+ for ax, (k, _, ylab) in zip(axes, METRICS):
81
+ for x, (key, _, ck, _, bern) in zip(XPOS, ARMS):
82
+ col = style.VARIANT[ck]
83
+ v = S.loc[(key, "cut_p>0.5"), k]
84
+ if key == "prop_oracle":
85
+ ax.bar(x, v, width=0.72, facecolor="white", edgecolor=col, hatch="///", lw=1.4, zorder=2)
86
+ else:
87
+ ax.bar(x, v, width=0.72, color=col, zorder=2)
88
+ pts = per[(per["arm"] == key) & (per["readout"] == "cut_p>0.5")][k].to_numpy()
89
+ ax.scatter(x + rng.uniform(-0.15, 0.15, len(pts)), pts, s=20, color=style.INK, zorder=3,
90
+ edgecolors="white", linewidths=0.6)
91
+ if bern is not None:
92
+ ax.plot([x], [S.loc[(key, "bernoulli"), k]], marker="D", ms=9, mfc="white", mec=style.INK,
93
+ mew=1.5, zorder=4, ls="none")
94
+ ax.axhline(S.loc[("PBISC-VAE", "reference"), k], color=style.ARM["vae"], lw=1.8, zorder=1)
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["vae"], lw=1.8, label="PBISC-VAE"),
109
+ Line2D([], [], color=style.ARM["scsemi"], lw=1.8, ls="--", label="scSemiProfiler")]
110
+ fig.legend(handles=handles, loc="upper center", ncol=5, bbox_to_anchor=(0.5, 1.07), handlelength=1.8,
111
+ columnspacing=1.2, handletextpad=0.5)
112
+ fig.tight_layout(w_pad=2.5)
113
+ style.save(fig, "sec03_width_bench", FIG)
114
+ # headline numbers for the keyword lines
115
+ runs = {k: read_run(name, host) for k, _, name, host in WIDTH_RUNS if k in ("1x", "ctx4x")}
116
+ params = {k: param_count(r, None) for k, r in runs.items()}
117
+ po = per[per["arm"].isin(["prop_pred", "prop_oracle"])].pivot(index="part", columns="arm")
118
+ d_or = {k: (po[(k, "prop_oracle")] - po[(k, "prop_pred")]).abs().max() for k, _, _ in METRICS}
119
+ B, C = "bernoulli", "cut_p>0.5"
120
+ head = pd.DataFrame([
121
+ {"quantity": "trunk4x_minus_1x_top50_cut", "value": S.loc[("trunk4x", C), "top50"] - S.loc[("1x", C), "top50"]},
122
+ {"quantity": "trunk4x_minus_1x_top50_bern", "value": S.loc[("trunk4x", B), "top50"] - S.loc[("1x", B), "top50"]},
123
+ {"quantity": "trunk4x_minus_1x_r_cut", "value": S.loc[("trunk4x", C), "logfc_r"] - S.loc[("1x", C), "logfc_r"]},
124
+ {"quantity": "trunk4x_minus_1x_r_bern", "value": S.loc[("trunk4x", B), "logfc_r"] - S.loc[("1x", B), "logfc_r"]},
125
+ {"quantity": "prop_oracle_vs_pred_max_abs_diff_per_part_r", "value": d_or["logfc_r"]},
126
+ {"quantity": "prop_oracle_vs_pred_max_abs_diff_per_part_top50", "value": d_or["top50"]},
127
+ {"quantity": "prop_pred_comp_l1_cut", "value": S.loc[("prop_pred", C), "comp_l1"]},
128
+ {"quantity": "1x_comp_l1_cut", "value": S.loc[("1x", C), "comp_l1"]},
129
+ {"quantity": "1x_bern_r_top50_l1", "value": "/".join(f"{S.loc[('1x', B), k]:.3f}" for k, _, _ in METRICS)},
130
+ {"quantity": "ctx4x_bern_r_top50_l1", "value": "/".join(f"{S.loc[('ctx4x', B), k]:.3f}" for k, _, _ in METRICS)},
131
+ {"quantity": "params_1x", "value": params["1x"][0]},
132
+ {"quantity": "params_ctx4x", "value": params["ctx4x"][0]},
133
+ {"quantity": "run_to_run_resolution_r_top50",
134
+ "value": f"{res_r}/{res_deg} (SD over 16 parts of the per-part prop - 1x difference; THRESHOLD_RESCORE.md)"},
135
+ ])
136
+ head["source"] = f"{WIDTH_SCORES} via data/sec03_width_bench*.csv; params from RUN_STATUS.json"
137
+ head.to_csv(DATA / "sec03_width_bench_headline.csv", index=False)
138
+ print(head[["quantity", "value"]].to_string())
139
+ print(f"panel genes {panel_genes}, donors {donors}, resolution r {res_r} DEG {res_deg}")
140
+ print(summ[["arm", "readout", "logfc_r", "top50", "comp_l1"]].round(3).to_string())
141
+ return 0
142
+
143
+
144
+ if __name__ == "__main__":
145
+ raise SystemExit(main())