junidude14 commited on
Commit
2ef5e54
·
verified ·
1 Parent(s): 0f2f977

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/tools/ablation_composition.py ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """CPU frozen-annotator composition on the exact Figure 2 P/C selected readout.
3
+
4
+ The existing P/C table is immutable. Every selected row and Poisson-count hash
5
+ must match its receipt before a separate composition table can be produced.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import gc
12
+ import hashlib
13
+ import json
14
+ import os
15
+ import subprocess
16
+ from datetime import datetime, timezone
17
+ from pathlib import Path
18
+
19
+ import h5py
20
+ import numpy as np
21
+ import pandas as pd
22
+ from scipy import sparse
23
+
24
+ import rescore_pretrain_ablations as pc
25
+
26
+ ROOT = pc.ROOT
27
+ WORK = ROOT / "work/ablation_composition_v1"
28
+ REBUILD = pc.MODEL / "plans/aifi_scanvi_rebuild_20260916"
29
+ MODEL = REBUILD / "runs/aifi_scanvi_f01common_v1/scanvi_model"
30
+ TRUTH_LABELS = pc.PANEL / "labels/truth_target/labels.parquet"
31
+ TRUTH_LABEL_MANIFEST = TRUTH_LABELS.with_name("labels.manifest.json")
32
+ PC_RECEIPT = ROOT / "source_data/ablation_pretrain_pc_receipt.json"
33
+ PC_CSV = ROOT / "source_data/ablation_pretrain_pc.csv"
34
+ SCANVI_PY = Path("/home/sj_server_1/miniforge3/envs/scanvi/bin/python")
35
+ DATASET = "004_A_GSE135779_SLE_PBMC"
36
+ LABELS = ["T cell", "B cell", "Monocyte", "NK cell", "DC", "Other"]
37
+
38
+
39
+ def sha_file(path: Path) -> str:
40
+ digest = hashlib.sha256()
41
+ with path.open("rb") as stream:
42
+ while chunk := stream.read(8 * 1024 * 1024):
43
+ digest.update(chunk)
44
+ return digest.hexdigest()
45
+
46
+
47
+ def file_record(path: Path) -> dict:
48
+ before = path.stat()
49
+ digest = sha_file(path)
50
+ after = path.stat()
51
+ if (before.st_size, before.st_mtime_ns) != (after.st_size, after.st_mtime_ns):
52
+ raise ValueError(f"source changed during hashing: {path}")
53
+ return {"path": str(path), "sha256": digest, "bytes": after.st_size}
54
+
55
+
56
+ def assert_array_hash(array: np.ndarray, expected: str, name: str) -> None:
57
+ if pc.sha_array(array) != expected:
58
+ raise ValueError(f"{name}: reconstructed array differs from the P/C receipt")
59
+
60
+
61
+ def decode_obs(group) -> np.ndarray:
62
+ if isinstance(group, h5py.Group):
63
+ categories = np.asarray([x.decode() if isinstance(x, bytes) else str(x) for x in group["categories"][:]])
64
+ codes = group["codes"][:]
65
+ if (codes < 0).any():
66
+ raise ValueError("missing categorical observation")
67
+ return categories[codes]
68
+ return np.asarray([x.decode() if isinstance(x, bytes) else str(x) for x in group[:]])
69
+
70
+
71
+ def align_truth_labels(frame: pd.DataFrame, truth_donors: np.ndarray) -> np.ndarray:
72
+ if frame["cell_index"].duplicated().any():
73
+ raise ValueError("truth label cell_index is not unique")
74
+ index = frame["cell_index"].to_numpy()
75
+ if len(index) != len(truth_donors) or set(index) != set(range(len(truth_donors))):
76
+ raise ValueError("truth labels must cover every original cell row exactly once")
77
+ ordered = frame.set_index("cell_index").loc[np.arange(len(truth_donors))]
78
+ if not np.array_equal(ordered["sample_id"].to_numpy(), truth_donors):
79
+ raise ValueError("truth label donor identity differs from the H5AD row")
80
+ return ordered["celltype_l1_pred"].to_numpy(dtype=str)
81
+
82
+
83
+ def composition_rows(reference: np.ndarray, candidate: np.ndarray,
84
+ reference_donors: np.ndarray, candidate_donors: np.ndarray,
85
+ donors: list[str], labels: list[str]) -> tuple[list[dict], list[dict]]:
86
+ if set(reference) - set(labels) or set(candidate) - set(labels):
87
+ raise ValueError("unrecognized composition label")
88
+ if len(reference) != len(reference_donors) or len(candidate) != len(candidate_donors):
89
+ raise ValueError("cell and donor arrays have different lengths")
90
+ summary, proportions = [], []
91
+ for donor in donors:
92
+ real = reference[reference_donors == donor]
93
+ generated = candidate[candidate_donors == donor]
94
+ if not len(real) or not len(generated):
95
+ raise ValueError(f"{donor}: no reference or candidate cells")
96
+ pr = np.asarray([np.mean(real == label) for label in labels])
97
+ pg = np.asarray([np.mean(generated == label) for label in labels])
98
+ summary.append({"donor": donor, "comp_l1": float(np.abs(pr - pg).sum()),
99
+ "n_reference": len(real), "n_candidate": len(generated)})
100
+ proportions.extend({"donor": donor, "cell_type": label, "observed_fraction": float(r),
101
+ "candidate_fraction": float(g)} for label, r, g in zip(labels, pr, pg))
102
+ return summary, proportions
103
+
104
+
105
+ def verify_records(records: dict) -> None:
106
+ for name, record in records.items():
107
+ if sha_file(Path(record["path"])) != record["sha256"]:
108
+ raise ValueError(f"changed bound input: {name}")
109
+
110
+
111
+ def prepare() -> dict:
112
+ import anndata as ad
113
+
114
+ complete = WORK / "PREPARED.json"
115
+ if complete.exists():
116
+ receipt = json.loads(complete.read_text())
117
+ verify_records(receipt["inputs"])
118
+ verify_records(receipt["outputs"])
119
+ return receipt
120
+ if WORK.exists() and any(WORK.iterdir()):
121
+ raise FileExistsError(f"partial analysis exists; preserve and inspect before retry: {WORK}")
122
+ WORK.mkdir(parents=True, exist_ok=True)
123
+ old = json.loads(PC_RECEIPT.read_text())
124
+ if old["schema"] != "pbisc.fig2.pretrain_pc.v1" or old["recipe"]["per_donor_per_set"] != 100:
125
+ raise ValueError("unexpected P/C recipe")
126
+ ids = pc.panel_gene_ids()
127
+ assert_array_hash(np.asarray(ids, dtype="S20"), old["gene_axis"]["ids_sha256"], "gene axis")
128
+ truth_manifest = json.loads(TRUTH_LABEL_MANIFEST.read_text())
129
+ if truth_manifest["target_truth_used_for_fitting"] or truth_manifest["query_train_epochs"] != 0:
130
+ raise ValueError("truth annotation was not frozen")
131
+ model_record = file_record(MODEL / "model.pt")
132
+ if model_record["sha256"] != truth_manifest["model"]["model_pt_sha256"]:
133
+ raise ValueError("frozen annotator differs from the existing truth-label model")
134
+ with h5py.File(pc.TRUTH) as f:
135
+ truth_donors = decode_obs(f["obs/donor_id"])
136
+ truth_labels = align_truth_labels(pd.read_parquet(TRUTH_LABELS), truth_donors)
137
+ inputs = {"pc_receipt": file_record(PC_RECEIPT), "pc_csv": file_record(PC_CSV),
138
+ "truth": file_record(pc.TRUTH), "truth_labels": file_record(TRUTH_LABELS),
139
+ "truth_label_manifest": file_record(TRUTH_LABEL_MANIFEST), "model": model_record,
140
+ "annotator": file_record(REBUILD / "predict_scanvi.py"),
141
+ "annotator_common": file_record(REBUILD / "scanvi_common.py"),
142
+ "gene_mapping": file_record(pc.GENES_TSV), "pc_script": file_record(Path(pc.__file__)),
143
+ "composition_script": file_record(Path(__file__))}
144
+ matrices, mapping_rows, selected = [], [], {}
145
+ families = {}
146
+ shared = None
147
+ cursor = 0
148
+ for family, specs in pc.family_specs().items():
149
+ evidence = old["families"][family]
150
+ if evidence["status"] != "complete":
151
+ raise ValueError(f"{family}: P/C family incomplete")
152
+ donors = evidence["donor_ids"]
153
+ r1, r2 = pc.balanced_real_split(truth_donors, donors, 100, pc.SEED)
154
+ assert_array_hash(r1, evidence["real_R1_rows_sha256"], "real R1 rows")
155
+ assert_array_hash(r2, evidence["real_R2_rows_sha256"], "real R2 rows")
156
+ if shared is None:
157
+ shared = (donors, r1, r2)
158
+ truth_cols = pc.gene_columns(pc.benchmark_gene_ids(), ids)
159
+ real = pc.load_real(np.concatenate([r1, r2]), truth_cols)
160
+ for method, counts, rows in zip(["real_R1", "real_R2_independent"], np.split(real, 2), [r1, r2]):
161
+ selected[method] = counts
162
+ matrices.append(sparse.csr_matrix(counts))
163
+ mapping_rows.extend({"query_row": cursor + i, "family": "shared_real", "method": method,
164
+ "donor": str(truth_donors[row]), "source_row": int(row),
165
+ "existing_truth_label": str(truth_labels[row])} for i, row in enumerate(rows))
166
+ cursor += len(rows)
167
+ del real
168
+ elif donors != shared[0] or not np.array_equal(r1, shared[1]) or not np.array_equal(r2, shared[2]):
169
+ raise ValueError("families do not share the exact real donor/cell reference")
170
+ families[family] = {"donor_ids": donors, "real_R1_rows_sha256": pc.sha_array(r1),
171
+ "real_R2_rows_sha256": pc.sha_array(r2), "methods": {}}
172
+ for method, source in specs:
173
+ print(f"hashing and reconstructing {family}/{method}", flush=True)
174
+ record = file_record(source)
175
+ generated_receipt_path = source.with_suffix(".log")
176
+ if generated_receipt_path.exists():
177
+ generated_receipt = json.loads(generated_receipt_path.read_text())
178
+ if generated_receipt.get("output_sha256") != record["sha256"]:
179
+ raise ValueError(f"generation receipt SHA does not match: {source}")
180
+ record["generation_receipt"] = file_record(generated_receipt_path)
181
+ inputs[method] = record
182
+ meta = pc.npz_metadata(source)
183
+ if meta["sample_ids"] != donors:
184
+ raise ValueError(f"{method}: changed donor order")
185
+ rows = pc.selected_generated_rows(meta["bulk_index"], len(donors), 100, pc.SEED)
186
+ assert_array_hash(rows, evidence["generated_rows_sha256"], "generated rows")
187
+ cols = pc.gene_columns(meta["gene_ids"], ids)
188
+ rates = pc.stream_selected_npz(source, rows, cols)
189
+ counts = np.random.default_rng(pc.POISSON_SEED).poisson(rates).astype(np.float32)
190
+ assert_array_hash(counts, evidence["source_files"][method]["selected_poisson_counts_sha256"], method)
191
+ selected[method] = counts
192
+ matrices.append(sparse.csr_matrix(counts))
193
+ donor_rows = np.asarray(donors)[meta["bulk_index"][rows]]
194
+ mapping_rows.extend({"query_row": cursor + i, "family": family, "method": method,
195
+ "donor": str(donor_rows[i]), "source_row": int(row),
196
+ "existing_truth_label": ""} for i, row in enumerate(rows))
197
+ cursor += len(rows)
198
+ families[family]["methods"][method] = {"selected_rows_sha256": pc.sha_array(rows),
199
+ "selected_poisson_counts_sha256": pc.sha_array(counts)}
200
+ mapping = pd.DataFrame(mapping_rows)
201
+ mapping.to_csv(WORK / "query_rows.csv", index=False)
202
+ obs = pd.DataFrame({"sample_id": mapping["donor"].to_numpy(), "source": mapping["method"].to_numpy(),
203
+ "batch_key": (DATASET + "_" + mapping["donor"]).to_numpy()},
204
+ index=[f"selected_{i}" for i in range(cursor)])
205
+ query = ad.AnnData(X=sparse.vstack(matrices, format="csr"), obs=obs,
206
+ var=pd.DataFrame(index=ids))
207
+ query.uns["query_build"] = {"kind": "exact_pc_selected_readout", "pc_receipt_sha256": inputs["pc_receipt"]["sha256"],
208
+ "poisson_seed": pc.POISSON_SEED, "real_cells_untouched": True}
209
+ query.write_h5ad(WORK / "selected_readout.h5ad", compression="gzip")
210
+ np.savez_compressed(WORK / "selected_counts.npz", **selected, gene_ids=np.asarray(ids), donor_ids=np.asarray(shared[0]))
211
+ result = {"schema": "pbisc.fig2.ablation-composition-inputs.v1", "status": "complete",
212
+ "created_at_utc": datetime.now(timezone.utc).isoformat(), "inputs": inputs,
213
+ "families": families, "n_query_rows": cursor,
214
+ "outputs": {name: file_record(WORK / name) for name in ["query_rows.csv", "selected_readout.h5ad", "selected_counts.npz"]}}
215
+ complete.write_text(json.dumps(result, indent=2) + "\n")
216
+ return result
217
+
218
+
219
+ def annotate() -> None:
220
+ prepared = json.loads((WORK / "PREPARED.json").read_text())
221
+ verify_records(prepared["outputs"])
222
+ output = WORK / "annotation"
223
+ if output.exists():
224
+ raise FileExistsError(f"annotation already exists; preserve before retry: {output}")
225
+ env = dict(os.environ, CUDA_VISIBLE_DEVICES="", OMP_NUM_THREADS="2", MKL_NUM_THREADS="2", OPENBLAS_NUM_THREADS="2", PYTHONNOUSERSITE="1")
226
+ command = [str(SCANVI_PY), str(REBUILD / "predict_scanvi.py"), "--model-dir", str(MODEL),
227
+ "--query", str(WORK / "selected_readout.h5ad"), "--out-dir", str(output),
228
+ "--method-name", "ablation_pc_selected_readout", "--dataset-id", DATASET,
229
+ "--split", "primary_kmeans", "--sample-id-col", "sample_id", "--batch-key-col", "batch_key",
230
+ "--seed", str(pc.POISSON_SEED), "--device", "cpu", "--num-threads", "2", "--eval-batch-size", "2048"]
231
+ with (WORK / "annotation.log").open("w") as log:
232
+ subprocess.run(command, env=env, check=True, stdout=log, stderr=subprocess.STDOUT)
233
+ (WORK / "ANNOTATION_RUN.json").write_text(json.dumps({"command": command, "device": "cpu",
234
+ "query_sha256": prepared["outputs"]["selected_readout.h5ad"]["sha256"],
235
+ "labels": file_record(output / "labels.parquet"), "manifest": file_record(output / "labels.manifest.json")}, indent=2) + "\n")
236
+
237
+
238
+ def summarize() -> dict:
239
+ output_receipt = ROOT / "source_data/ablation_pretrain_composition_receipt.json"
240
+ if output_receipt.exists():
241
+ raise FileExistsError("composition already complete; preserve existing version")
242
+ prepared = json.loads((WORK / "PREPARED.json").read_text())
243
+ verify_records(prepared["inputs"])
244
+ verify_records(prepared["outputs"])
245
+ annotation_run = json.loads((WORK / "ANNOTATION_RUN.json").read_text())
246
+ verify_records({key: annotation_run[key] for key in ["labels", "manifest"]})
247
+ manifest = json.loads((WORK / "annotation/labels.manifest.json").read_text())
248
+ if manifest["device"] != "cpu" or manifest["query_train_epochs"] != 0 or manifest["target_truth_used_for_fitting"]:
249
+ raise ValueError("annotator is not frozen CPU prediction")
250
+ if manifest["model"]["model_pt_sha256"] != prepared["inputs"]["model"]["sha256"]:
251
+ raise ValueError("changed annotation model")
252
+ if manifest["gene_space"]["model_genes_missing_from_query_zero_padded"] != 0:
253
+ raise ValueError("missing annotator genes")
254
+ mapping = pd.read_csv(WORK / "query_rows.csv", keep_default_na=False)
255
+ labels = pd.read_parquet(WORK / "annotation/labels.parquet")
256
+ if labels["npz_row"].duplicated().any() or set(labels["npz_row"]) != set(mapping["query_row"]):
257
+ raise ValueError("annotation does not cover query rows exactly once")
258
+ labels = labels.set_index("npz_row").loc[mapping["query_row"]].reset_index()
259
+ if not np.array_equal(labels["sample_id"].to_numpy(), mapping["donor"].to_numpy()):
260
+ raise ValueError("annotated donor identity mismatch")
261
+ if not np.array_equal(labels["source"].to_numpy(), mapping["method"].to_numpy()):
262
+ raise ValueError("annotated method identity mismatch")
263
+ mapping["label"] = labels["celltype_l1_pred"].to_numpy()
264
+ real_rows = mapping["family"] == "shared_real"
265
+ concordance = float(np.mean(mapping.loc[real_rows, "label"] == mapping.loc[real_rows, "existing_truth_label"]))
266
+ if concordance < 0.99:
267
+ raise ValueError(f"selected real annotation differs materially from original labels: {concordance}")
268
+ reference = mapping[mapping["method"] == "real_R1"]
269
+ rows, proportions = [], []
270
+ for family, evidence in prepared["families"].items():
271
+ for method in ["real_R2_independent", *evidence["methods"]]:
272
+ candidate = mapping[mapping["method"] == method]
273
+ summary, detail = composition_rows(reference["label"].to_numpy(), candidate["label"].to_numpy(),
274
+ reference["donor"].to_numpy(), candidate["donor"].to_numpy(), evidence["donor_ids"], LABELS)
275
+ rows.extend({"family": family, "method": method, **row} for row in summary)
276
+ proportions.extend({"family": family, "method": method, **row} for row in detail)
277
+ table = pd.DataFrame(rows)
278
+ table.to_csv(ROOT / "source_data/ablation_pretrain_composition.csv", index=False)
279
+ pd.DataFrame(proportions).to_csv(ROOT / "source_data/ablation_pretrain_composition_proportions.csv", index=False)
280
+ aggregate = table.groupby(["family", "method"], sort=False)["comp_l1"].agg(["mean", "std", "count"]).reset_index()
281
+ aggregate.columns = ["family", "method", "comp_l1_mean", "comp_l1_sd", "n_donors"]
282
+ aggregate.to_csv(ROOT / "source_data/ablation_pretrain_composition_summary.csv", index=False)
283
+ receipt = {"schema": "pbisc.fig2.ablation-composition.v1", "status": "complete",
284
+ "created_at_utc": datetime.now(timezone.utc).isoformat(), "prepared_inputs": file_record(WORK / "PREPARED.json"),
285
+ "inputs": prepared["inputs"], "selected_readout": prepared["outputs"],
286
+ "annotation": {"run": file_record(WORK / "ANNOTATION_RUN.json"), **annotation_run},
287
+ "recipe": {"reference": "the same 4200 real R1 cells used to fit P/C geometry",
288
+ "candidate": "100 cells per donor; exact P/C selected arrays verified by SHA256",
289
+ "real_control": "independent 4200 real R2 cells; same observed R1 reference",
290
+ "classifier": manifest["classifier"], "classifier_fitting": "external AIFI only; zero query training",
291
+ "label_space": LABELS, "classifier_gene_space": manifest["gene_space"],
292
+ "readout": "same selected 1006-gene Poisson integer counts as P/C; real counts untouched",
293
+ "summary": "unweighted mean of donor L1 errors; L1=sum over all six label fractions",
294
+ "biological_unit": "donor", "sampling_seed": pc.SEED, "poisson_seed": pc.POISSON_SEED,
295
+ "families_separate": True, "real_label_concordance_with_original_frozen_annotation": concordance},
296
+ "limitations": ["Single 100-cell draw per donor; donor sampling noise is shown by the independent real R2 control.",
297
+ "Architecture 1% and gene-panel 0.1% floors remain separate comparisons.",
298
+ "Composition describes frozen-annotator categories, not manual ground-truth identities.",
299
+ "The fixed AIFI annotator consumes 1005 of the 1006 measured P/C genes; no missing genes are fabricated."],
300
+ "outputs": {name: file_record(ROOT / "source_data" / name) for name in [
301
+ "ablation_pretrain_composition.csv", "ablation_pretrain_composition_proportions.csv", "ablation_pretrain_composition_summary.csv"]}}
302
+ output_receipt.write_text(json.dumps(receipt, indent=2) + "\n")
303
+ print(aggregate.to_string(index=False), flush=True)
304
+ return receipt
305
+
306
+
307
+ def main(argv=None) -> int:
308
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
309
+ parser.add_argument("--stage", choices=["prepare", "annotate", "summarize", "all"], default="all")
310
+ args = parser.parse_args(argv)
311
+ if args.stage in ["prepare", "all"]:
312
+ prepare()
313
+ gc.collect()
314
+ if args.stage in ["annotate", "all"]:
315
+ annotate()
316
+ if args.stage in ["summarize", "all"]:
317
+ summarize()
318
+ return 0
319
+
320
+
321
+ if __name__ == "__main__":
322
+ raise SystemExit(main())
paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/tools/archive_completed.py ADDED
@@ -0,0 +1,383 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Create an immutable, scoped task snapshot/request; never prepare or publish.
3
+
4
+ Generated arrays remain location-only. A snapshot is not a scientific-completion
5
+ claim: draft code and manuscripts retain intermediate state. This helper reads
6
+ only the named Figure 1--5 task and its three explicitly adapted legacy files.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import datetime as dt
12
+ import hashlib
13
+ import json
14
+ from pathlib import Path
15
+ import re
16
+ import shutil
17
+ import subprocess
18
+
19
+ PLAN = Path(__file__).resolve().parents[1]
20
+ MODEL8 = PLAN.parents[1]
21
+ RELEASE = Path('/home/sj_server_1/PBISC/paper-release-20260928')
22
+ ID_RE = re.compile(r'[0-9]{8}T[0-9]{6}Z-[a-z0-9-]+\Z')
23
+ SKIP_PARTS = {'.git', '__pycache__', '.pytest_cache', 'runtime_env', 'Rlib'}
24
+ PREVIEW_NOTE = ('Restructuring PREVIEW; strict experiments/derived panels remain '
25
+ 'incomplete. This is not a final manuscript or final Figure 1--5 set.')
26
+
27
+
28
+ def sha(path: Path) -> str:
29
+ h = hashlib.sha256()
30
+ with path.open('rb') as f:
31
+ for chunk in iter(lambda: f.read(1024 * 1024), b''):
32
+ h.update(chunk)
33
+ return h.hexdigest()
34
+
35
+
36
+ def fingerprint(path: Path) -> tuple[int, int, int, int]:
37
+ if path.is_symlink() or any(p.is_symlink() for p in path.parents):
38
+ raise ValueError(f'symlink refused: {path}')
39
+ s = path.stat()
40
+ if not path.is_file():
41
+ raise ValueError(f'not a regular file: {path}')
42
+ return s.st_dev, s.st_ino, s.st_size, s.st_mtime_ns
43
+
44
+
45
+ def stable_hash(path: Path) -> str:
46
+ before = fingerprint(path)
47
+ value = sha(path)
48
+ if fingerprint(path) != before:
49
+ raise RuntimeError(f'file changed during hash: {path}')
50
+ return value
51
+
52
+
53
+ def files_under(folder: Path):
54
+ return sorted(p for p in folder.rglob('*')
55
+ if p.is_file() and not any(x in SKIP_PARTS for x in p.parts))
56
+
57
+
58
+ def json_load(path: Path):
59
+ return json.loads(path.read_text())
60
+
61
+
62
+ def write_json(path: Path, value):
63
+ path.parent.mkdir(parents=True, exist_ok=True)
64
+ with path.open('x') as f:
65
+ json.dump(value, f, indent=2, ensure_ascii=False)
66
+ f.write('\n')
67
+
68
+
69
+ def observation(argv):
70
+ result = subprocess.run(argv, capture_output=True, text=True, timeout=30)
71
+ return {'argv': argv, 'returncode': result.returncode,
72
+ 'stdout': result.stdout.strip(), 'stderr': result.stderr.strip()}
73
+
74
+
75
+ def operation_state(name: str) -> str:
76
+ path = PLAN / 'receipts' / f'{name}.json'
77
+ if not path.is_file():
78
+ return 'planned'
79
+ state = json_load(path).get('state')
80
+ return state if state in {'running', 'failed'} else 'planned'
81
+
82
+
83
+ def completion_gate() -> None:
84
+ final = json_load(PLAN / 'FINALIZATION_STATUS.json')
85
+ if final.get('stage') != 'all' or final.get('state') not in {'complete', 'completed'}:
86
+ raise ValueError('complete archive requires successful all-stage finalization')
87
+ from assemble_manuscript import strict_gate
88
+ gaps, _ = strict_gate()
89
+ if gaps:
90
+ raise ValueError('complete archive strict gates failed: ' + '; '.join(gaps))
91
+ if json_load(PLAN / 'manuscript/integration_manifest.json').get('mode') != 'complete':
92
+ raise ValueError('complete archive cannot contain a preview manuscript')
93
+ for relative in ['manuscript/main.pdf', 'manuscript/supplementary.pdf',
94
+ 'deck/paper_figures_final.pptx', 'deck/paper_figures_final.pdf']:
95
+ if not (PLAN / relative).is_file():
96
+ raise ValueError(f'missing final document: {relative}')
97
+
98
+
99
+ def build(identifier: str, state: str = 'in-progress') -> Path:
100
+ if not ID_RE.fullmatch(identifier):
101
+ raise ValueError('invalid update identifier')
102
+ complete = state == 'complete'
103
+ if complete:
104
+ completion_gate()
105
+ work_state = 'completed' if complete else 'intermediate'
106
+ work_note = 'Completed source-bound Figure 1--5 campaign; Figure 6 remains reserved' if complete else PREVIEW_NOTE
107
+ destination = PLAN / 'archive' / identifier
108
+ destination.mkdir(parents=True, exist_ok=False)
109
+ payload = destination / 'snapshot'
110
+ assets, mapping = [], []
111
+ seen = set()
112
+
113
+ def register(path, kind, state, reason, copy=True, relative=None):
114
+ path = Path(path)
115
+ if path in seen:
116
+ return
117
+ seen.add(path)
118
+ if not path.is_relative_to(MODEL8) and not path.is_relative_to(RELEASE):
119
+ raise ValueError(f'outside explicit scope: {path}')
120
+ before = fingerprint(path)
121
+ digest = stable_hash(path)
122
+ archived = path
123
+ if copy:
124
+ rel = relative or (path.relative_to(PLAN) if path.is_relative_to(PLAN)
125
+ else Path('legacy_adapters') / path.relative_to(MODEL8))
126
+ # The archive intentionally forbids generated array payload paths;
127
+ # only their small metadata may be copied, into a named receipt area.
128
+ rel = Path(*('inference_metadata' if x == 'generated' else x for x in rel.parts))
129
+ archived = payload / rel
130
+ archived.parent.mkdir(parents=True, exist_ok=True)
131
+ if archived.exists():
132
+ raise ValueError(f'duplicate destination: {archived}')
133
+ shutil.copy2(path, archived)
134
+ if fingerprint(path) != before or sha(archived) != digest:
135
+ raise RuntimeError(f'file changed during snapshot: {path}')
136
+ archived.chmod(0o444)
137
+ assets.append({'host': 'server_1', 'source': str(archived),
138
+ 'kind': kind, 'state': state})
139
+ mapping.append({'source_host': 'server_1', 'source': str(path),
140
+ 'snapshot': str(archived), 'sha256': digest,
141
+ 'bytes': before[2], 'kind': kind, 'state': state,
142
+ 'reason': reason})
143
+
144
+ for sub, kind in [('tools', 'code'), ('tests', 'test')]:
145
+ for path in files_under(PLAN / sub):
146
+ if path.suffix in {'.py', '.R'}:
147
+ register(path, kind, work_state, 'Frozen implementation snapshot; ' + work_note)
148
+ register(PLAN / 'archive/test_archive_completed.py', 'test', work_state,
149
+ 'Archive-only snapshot negative controls', relative=Path('tests/test_archive_completed.py'))
150
+ for path in files_under(PLAN / 'protocol'):
151
+ register(path, 'config', 'completed', 'Exact-pair selection and fixed evaluation contract')
152
+ for path in files_under(PLAN / 'backups'):
153
+ if path.suffix in {'.json', '.py'}:
154
+ register(path, 'code' if path.suffix == '.py' else 'provenance', 'stopped',
155
+ 'Preserved earlier adapter/receipt or rejected prelaunch contract; not an active scientific input')
156
+ for path in sorted((PLAN / 'deconvolution').rglob('INPUTS.json')):
157
+ register(path, 'provenance', 'completed', 'Prepared exact-support deconvolution inputs; method runs may still be pending')
158
+ support = path.with_name('SUPPORT.json')
159
+ if support.is_file():
160
+ register(support, 'metadata', 'completed', 'Deconvolution reference/mixture support')
161
+ for path in files_under(PLAN / 'data'):
162
+ if path.suffix == '.npz':
163
+ if path.name not in {'test_raw.npz', 'test_cal.npz', 'conditions_raw.npz', 'conditions_refcal.npz'}:
164
+ raise ValueError(f'unexpected condition array: {path}')
165
+ register(path, 'condition', 'completed', 'Immutable prepared condition; no generated array', copy=False)
166
+ elif path.suffix == '.npy':
167
+ if path.name != 'alpha.npy':
168
+ raise ValueError(f'unexpected fitted data array: {path}')
169
+ register(path, 'data', 'completed', 'Exact-support or external-reference calibration coefficients', copy=False)
170
+ elif path.suffix in {'.json', '.txt', '.csv'}:
171
+ register(path, 'metadata', 'completed', 'Condition construction / sample selection provenance')
172
+ for path in files_under(PLAN / 'source_data'):
173
+ completed = complete or path.name.startswith(('ablation_pretrain', 'fig1_'))
174
+ register(path, 'table' if path.suffix == '.csv' else 'provenance',
175
+ 'completed' if completed else 'intermediate',
176
+ 'Completed native-pseudobulk rescore / corpus data' if completed else PREVIEW_NOTE)
177
+ composition_receipt = PLAN / 'source_data/ablation_pretrain_composition_receipt.json'
178
+ if composition_receipt.is_file() and json_load(composition_receipt).get('status') == 'complete':
179
+ for path in files_under(PLAN / 'work/ablation_composition_v1'):
180
+ register(path, 'data' if path.suffix in {'.npz', '.h5ad', '.parquet'} else 'provenance',
181
+ 'completed', 'Exact P/C selected cells and frozen CPU annotations for composition')
182
+ for path in files_under(PLAN / 'reports'):
183
+ completed = complete or path.name.startswith(('figure1_', 'ablation_pretrain'))
184
+ register(path, 'report', 'completed' if completed else 'intermediate',
185
+ 'Completed figure/source provenance' if completed else PREVIEW_NOTE)
186
+ for path in files_under(PLAN / 'figures'):
187
+ ready = complete or path.name.startswith('fig1_')
188
+ diagnostic = 'diagnostic' in path.name
189
+ register(path, 'figure', 'completed' if ready and not diagnostic else 'intermediate',
190
+ 'Complete inference/corpus concept figure' if path.name.startswith('fig1_') else work_note)
191
+ for sub, kind in [('deck', 'document'), ('manuscript', 'manuscript')]:
192
+ for path in files_under(PLAN / sub):
193
+ preview = sub == 'deck' and path.name.startswith('paper_figures_review')
194
+ register(path, kind, 'intermediate' if preview else work_state,
195
+ PREVIEW_NOTE if preview else work_note)
196
+ for path in files_under(PLAN / 'scores_pilot'):
197
+ register(path, 'report', 'intermediate', 'Pilot two-arm score only; not full five-arm final evaluation')
198
+ # Final strict scores and deconvolution sources are limited to completed
199
+ # per-unit evidence. The large NPZ/readout caches remain original-location data.
200
+ if complete:
201
+ for sub in ['scores', 'deconvolution']:
202
+ for path in files_under(PLAN / sub):
203
+ if path.suffix in {'.csv', '.tsv', '.json', '.txt', '.R'}:
204
+ register(path, 'provenance' if path.suffix == '.json' else 'table',
205
+ 'completed', 'Completed strict-support source data and inference provenance')
206
+ else:
207
+ for path in sorted((PLAN / 'protocol/splits').rglob('support.json')):
208
+ relative = path.parent.relative_to(PLAN / 'protocol/splits')
209
+ receipt = PLAN / 'receipts' / ('-'.join(relative.parts) + '-score.json')
210
+ if not receipt.is_file() or json_load(receipt).get('state') != 'completed':
211
+ continue
212
+ for scored in files_under(PLAN / 'scores' / relative):
213
+ if scored.suffix in {'.csv', '.tsv', '.json', '.txt'}:
214
+ register(scored, 'provenance' if scored.suffix == '.json' else 'table',
215
+ 'completed', 'Completed five-arm unit; full campaign still pending')
216
+ for path in sorted((PLAN / 'receipts').glob('*.json')):
217
+ receipt = json_load(path)
218
+ if receipt.get('state') == 'completed':
219
+ rejected = path.name == 'prepare-strict-conditions.json'
220
+ register(path, 'provenance', 'stopped' if rejected else 'completed',
221
+ 'Superseded v1 preparation receipt; not an active input' if rejected else 'Completed operation receipt')
222
+ for name in ['PLAN.md', 'PROGRESS.md', 'CAMPAIGN_STATUS.json', 'FINALIZATION_STATUS.json', 'events.jsonl']:
223
+ if (PLAN / name).exists():
224
+ register(PLAN / name, 'report', 'intermediate', 'Point-in-time task observation, not final completion')
225
+ for path in [MODEL8 / 'plans/paired_finetune_intradataset_20260927/tools/ft_sdd.py',
226
+ MODEL8 / 'plans/paired_finetune_intradataset_20260927/scsemi/tools/prepare_draw_inputs.py',
227
+ MODEL8 / 'plans/paired_finetune_intradataset_20260927/scsemi/tools/export_npz.py']:
228
+ register(path, 'code', 'intermediate', 'Explicit opt-in strict-support adapter; original mode preserved')
229
+
230
+ # Models are included only behind completed operation receipts, never from
231
+ # filename presence or incomplete controller progress alone.
232
+ for train_receipt in sorted((PLAN / 'receipts').glob('*-train.json')):
233
+ trained = json_load(train_receipt)
234
+ if trained.get('state') != 'completed':
235
+ continue
236
+ expected = {o['path']: o['sha256'] for o in trained['outputs']}
237
+ checkpoints = [Path(x) for x in expected if Path(x).suffix == '.pt']
238
+ for checkpoint in checkpoints:
239
+ if not checkpoint.is_relative_to(PLAN / 'runs'):
240
+ raise ValueError('training receipt outside strict campaign')
241
+ for path in files_under(checkpoint.parent):
242
+ if str(path) in expected and stable_hash(path) != expected[str(path)]:
243
+ raise ValueError(f'model receipt mismatch: {path}')
244
+ register(path, 'checkpoint' if path.suffix == '.pt' else 'provenance',
245
+ 'completed', 'Completed exact-support LoRA adaptation', copy=path.suffix != '.pt')
246
+ completed_sc = []
247
+ for adoption in sorted((PLAN / 'scsemi').rglob('ADOPTION.json')):
248
+ work = adoption.parent.parent
249
+ relative = work.relative_to(PLAN / 'scsemi')
250
+ exported = PLAN / 'generated' / relative / 'scsemi.log'
251
+ if not exported.is_file() or json_load(exported).get('schema') != 'pbisc.scsemi.adopted-output.v1':
252
+ continue
253
+ proof = json_load(exported)
254
+ if proof.get('adoption_receipt_sha256') != stable_hash(adoption):
255
+ raise ValueError('adopted scSemi output proof changed')
256
+ for path in files_under(work):
257
+ if path.suffix == '.json':
258
+ register(path, 'provenance', 'completed', 'Audited same-budget legacy adoption; no new native strict GPU work claimed')
259
+ for status_path in sorted((PLAN / 'scsemi').rglob('status.json')):
260
+ sc_status = json_load(status_path)
261
+ if not (sc_status.get('pretrain_complete') and sc_status.get('infer_complete')):
262
+ continue
263
+ sc = status_path.parent
264
+ completed_sc.append(sc)
265
+ for path in files_under(sc):
266
+ if path.suffix == '.json':
267
+ register(path, 'provenance', 'completed', 'Completed exact-support scSemi provenance')
268
+ elif path.parent == sc / 'scsemi_project/models' and not path.suffix:
269
+ register(path, 'data', 'completed', 'Baseline scSemi weights; private dataset payload, not PBISC model release', copy=False)
270
+
271
+ locations = []
272
+ for support in sorted((PLAN / 'protocol/splits').rglob('support.json')):
273
+ relative = support.parent.relative_to(PLAN / 'protocol/splits')
274
+ for arm in ['lora', 'pairedcal', 'scsemi']:
275
+ path = PLAN / 'generated' / relative / f'{arm}.npz'
276
+ log = path.with_suffix('.log')
277
+ row = {'host': 'server_1', 'path': str(path),
278
+ 'state': operation_state('-'.join(relative.parts) + '-' + arm),
279
+ 'cohort': relative.parts[0], 'experiment': f'strict_pairs/{relative}/{arm}',
280
+ 'support_manifest': str(support), 'support_sha256': stable_hash(support),
281
+ 'note': 'Exact support contract; no completion inferred from presence alone'}
282
+ if path.exists() and log.exists():
283
+ try:
284
+ info = json_load(log)
285
+ except json.JSONDecodeError:
286
+ row.update(state='presence_only', note='Output or log exists but completed generation receipt is unavailable')
287
+ locations.append(row)
288
+ continue
289
+ digest = info.get('output_sha256')
290
+ if not digest:
291
+ raise ValueError(f'completed output log lacks SHA: {log}')
292
+ register(log, 'provenance', 'completed', 'Immutable completed generation receipt')
293
+ receipt_copy = next(x['snapshot'] for x in mapping if x['source'] == str(log))
294
+ row.update(state='completed', receipt=receipt_copy, generation_log=str(log),
295
+ sha256=digest, output_sha256=digest,
296
+ **{k: info[k] for k in ['checkpoint_sha256', 'condition_sha256', 'checkpoint', 'condition_npz', 'bulks', 'cells', 'genes', 'seed', 'steps', 'weights'] if k in info})
297
+ row['note'] = 'Completed generated array retained in place; SHA from immutable generation receipt'
298
+ if path.with_suffix('.validation.json').exists():
299
+ register(path.with_suffix('.validation.json'), 'provenance', 'completed', 'scSemi export validation')
300
+ locations.append(row)
301
+ for cohort in ['immicro', 'ye2026_sepsis', 'imperial_eskd', 'giroux2022', 'ji2025_chili']:
302
+ for arm in ['raw', 'refcal']:
303
+ path = PLAN / 'generated/global' / cohort / f'{arm}.npz'
304
+ log = path.with_suffix('.log')
305
+ row = {'host': 'server_1', 'path': str(path),
306
+ 'state': operation_state(f'global-{cohort}-{arm}'),
307
+ 'cohort': cohort, 'experiment': f'strict_pairs/global/{arm}'}
308
+ if path.exists() and log.exists():
309
+ try:
310
+ info = json_load(log)
311
+ except json.JSONDecodeError:
312
+ row.update(state='presence_only', note='Output or log exists but completed generation receipt is unavailable')
313
+ locations.append(row)
314
+ continue
315
+ register(log, 'provenance', 'completed', 'Completed zero-target-sc generation receipt')
316
+ receipt_copy = next(x['snapshot'] for x in mapping if x['source'] == str(log))
317
+ row.update(state='completed', receipt=receipt_copy, generation_log=str(log),
318
+ sha256=info['output_sha256'], output_sha256=info['output_sha256'],
319
+ **{k: info[k] for k in ['checkpoint_sha256', 'condition_sha256', 'checkpoint', 'condition_npz', 'bulks', 'cells', 'genes', 'seed', 'steps', 'weights'] if k in info})
320
+ locations.append(row)
321
+ for sc in completed_sc:
322
+ relative = sc.relative_to(PLAN / 'scsemi')
323
+ for path in sorted((sc / 'shards').glob('*.json')):
324
+ info = json_load(path)
325
+ if info.get('complete'):
326
+ locations.append({'host': 'server_1', 'path': info['shard'], 'state': 'completed',
327
+ 'receipt': next(x['snapshot'] for x in mapping if x['source'] == str(path)),
328
+ 'sha256': info['shard_sha256'], 'cohort': relative.parts[0],
329
+ 'experiment': f'strict_pairs/{relative}/scsemi_shard',
330
+ 'note': 'Lossless CSR inference shard; generated array location only'})
331
+
332
+ observed_at = dt.datetime.now(dt.timezone.utc).isoformat()
333
+ live = {'observed_at': observed_at,
334
+ 'latest_archive': json_load(RELEASE / 'LATEST.json'),
335
+ 'server_1': [observation(['systemctl', '--user', 'is-active', 'ml-memory-guard.service']),
336
+ observation(['/home/sj_server_1/.local/libexec/ml-memory-guard', '--check']),
337
+ observation(['nvidia-smi', '--query-compute-apps=pid,process_name,used_memory', '--format=csv,noheader']),
338
+ observation(['systemctl', '--user', 'list-units', '--all', '--no-pager', 'pbisc-strict-*'])],
339
+ 'server_2': observation(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=10', 'spark-0110',
340
+ 'nvidia-smi --query-compute-apps=pid,process_name,used_memory --format=csv,noheader']),
341
+ 'figure6': 'waiting_user_data_no_execution',
342
+ 'canonical_manuscript': observation(['git', '-C', str(RELEASE / 'manuscript'), 'rev-parse', 'HEAD']),
343
+ 'archive_state': state,
344
+ 'preview_warning': work_note}
345
+ live_path = destination / 'LIVE_OBSERVATION.json'
346
+ write_json(live_path, live)
347
+ assets.append({'host': 'server_1', 'source': str(live_path), 'kind': 'report', 'state': 'intermediate'})
348
+ provenance_path = destination / 'SNAPSHOT_MANIFEST.json'
349
+ write_json(provenance_path, {'schema': 'pbisc.strict.archive-snapshot.v1', 'observed_at': observed_at,
350
+ 'project_id': 'pbisc-diffusion', 'update_id': identifier,
351
+ 'source_files': mapping, 'archive_state': state, 'preview_warning': work_note})
352
+ assets.append({'host': 'server_1', 'source': str(provenance_path), 'kind': 'provenance', 'state': 'completed'})
353
+ request = {'project_id': 'pbisc-diffusion',
354
+ 'summary': ('Figure 1--5 strict-pair implementation checkpoint. Exact-support contracts and prepared conditions; '
355
+ 'completed Figure 1 and held-out pseudobulk ablation rescoring; completed ImMicro fold0 n5 '
356
+ 'LoRA/paired-calibration/scSemi outputs and global raw/external-refcal controls. '
357
+ 'Code, review deck, staged Results/manuscript, and legacy rare-state diagnostics are explicitly '
358
+ 'INTERMEDIATE PREVIEWS, not final scientific results. The 40-unit campaign and final figure '
359
+ 'completion remain pending. Large generated arrays remain in place with recorded hashes/receipts. '
360
+ 'Figure 6 is waiting for user data and has no execution. No GitHub push or Overleaf synchronization.'),
361
+ 'assets': assets, 'inference_locations': locations}
362
+ if complete:
363
+ request['summary'] = ('Completed Figure 1--5 strict-pair campaign, quantitative source data, donor-dependent '
364
+ 'statistics, exact-support deconvolution, rare-state validation, figures, PDF/PPTX, '
365
+ 'and staged manuscript. Completion gates passed. Model/input/receipt hashes retained. '
366
+ 'Generated arrays remain original-location references. Figure 6 remains reserved '
367
+ 'pending user data. No GitHub push or Overleaf synchronization by this archive helper.')
368
+ request_path = destination / 'request.json'
369
+ write_json(request_path, request)
370
+ for path in [live_path, provenance_path, request_path]:
371
+ path.chmod(0o444)
372
+ print(json.dumps({'request': str(request_path), 'assets': len(assets), 'locations': len(locations),
373
+ 'payload_bytes': sum(Path(x['source']).stat().st_size for x in assets),
374
+ 'completed_locations': sum(x['state'] == 'completed' for x in locations)}))
375
+ return request_path
376
+
377
+
378
+ if __name__ == '__main__':
379
+ parser = argparse.ArgumentParser(description=__doc__)
380
+ parser.add_argument('--id', required=True)
381
+ parser.add_argument('--state', choices=['in-progress', 'complete'], default='in-progress')
382
+ args = parser.parse_args()
383
+ build(args.id, args.state)
paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/tools/assemble_manuscript.py ADDED
@@ -0,0 +1,565 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Stage the PBISC-Diffusion Figure 1--5 manuscript without changing its Git tree.
3
+
4
+ --preview emits an explicitly incomplete review draft. --require-complete refuses
5
+ until every strict unit and its source binding has been verified, then uses the
6
+ same staged file map. No Git, archive or network write is performed here.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import csv
12
+ import hashlib
13
+ import json
14
+ import re
15
+ import shutil
16
+ import subprocess
17
+ from collections import defaultdict
18
+ from pathlib import Path
19
+
20
+ ROOT = Path(__file__).resolve().parents[1]
21
+ CANON = Path('/home/sj_server_1/PBISC/paper-release-20260928/manuscript')
22
+ STAGE = ROOT / 'manuscript'
23
+ EDITS = STAGE / 'edits'
24
+ COHORTS = ('ye2026_sepsis', 'imperial_eskd', 'giroux2022', 'ji2025_chili')
25
+ FIGURES = {
26
+ 'fig1_overview.pdf': 'fig1_overview.pdf',
27
+ 'fig2_ablation_and_support.pdf': 'fig2_ablation_and_support.pdf',
28
+ 'fig4_historical_5fold_separate.pdf': 'fig4_historical_5fold_separate.pdf',
29
+ }
30
+ FINAL_FIGURES = {
31
+ 'fig3_healthy_strict_oof.pdf': 'fig3_healthy_strict_oof.pdf',
32
+ 'fig3_realism_metrics.pdf': 'fig3_realism_metrics.pdf',
33
+ 'fig3_canonical_marker_dotplot.pdf': 'fig3_canonical_marker_dotplot.pdf',
34
+ 'fig3_umap_by_celltype.pdf': 'fig3_umap_by_celltype.pdf',
35
+ 'fig3_composition_fractions.pdf': 'fig3_composition_fractions.pdf',
36
+ 'fig3_runtime_components.pdf': 'fig3_runtime_components.pdf',
37
+ 'fig4_disease_strict_draws.pdf': 'fig4_disease_strict_draws.pdf',
38
+ 'fig4_disease_signal_strict.pdf': 'fig4_disease_signal_strict.pdf',
39
+ 'fig4_disease_signal_scatter.pdf': 'fig4_disease_signal_scatter.pdf',
40
+ 'fig4_disease_signal_heatmap.pdf': 'fig4_disease_signal_heatmap.pdf',
41
+ 'fig4_disease_signal_cat.pdf': 'fig4_disease_signal_cat.pdf',
42
+ 'fig4_deconvolution_strict.pdf': 'fig4_deconvolution_strict.pdf',
43
+ 'fig4_deconvolution_expression_strict.pdf': 'fig4_deconvolution_expression_strict.pdf',
44
+ 'fig5_rare_states_strict.pdf': 'fig5_rare_states_strict.pdf',
45
+ 'fig5_rare_visuals_strict.pdf': 'fig5_rare_visuals_strict.pdf',
46
+ 'fig5_all_states_strict.pdf': 'fig5_all_states_strict.pdf',
47
+ 'fig5_behcet_rules_strict.pdf': 'fig5_behcet_rules_strict.pdf',
48
+ }
49
+
50
+
51
+ def digest(path: Path) -> str:
52
+ h = hashlib.sha256()
53
+ with path.open('rb') as f:
54
+ for chunk in iter(lambda: f.read(1024 * 1024), b''):
55
+ h.update(chunk)
56
+ return h.hexdigest()
57
+
58
+
59
+ def document(path: Path) -> dict:
60
+ return json.loads(path.read_text())
61
+
62
+
63
+ def rows(path: Path) -> list[dict[str, str]]:
64
+ with path.open(newline='') as f:
65
+ return list(csv.DictReader(f))
66
+
67
+
68
+ def tracked_sources() -> list[Path]:
69
+ raw = subprocess.check_output(['git', '-C', str(CANON), 'ls-files', '-z'])
70
+ paths = [Path(p.decode()) for p in raw.split(b'\0') if p]
71
+ wanted = {'.tex', '.bib', '.cls', '.bst'}
72
+ return [p for p in paths if p.suffix in wanted or
73
+ (p.parts[0] == 'figures' and p.suffix.lower() in {'.pdf', '.png'})]
74
+
75
+
76
+ def checked_provenance(path: Path, label: str) -> dict:
77
+ if not path.is_file():
78
+ raise ValueError(f'{label}: missing {path}')
79
+ item = document(path)
80
+ for entry in item.get('sources', []) + item.get('outputs', []):
81
+ source = Path(entry['path'])
82
+ if not source.is_file() or digest(source) != entry['sha256']:
83
+ raise ValueError(f'{label}: source/output hash mismatch: {source}')
84
+ return item
85
+
86
+
87
+ def strict_gate() -> tuple[list[str], dict]:
88
+ gaps = []
89
+ readiness_path = ROOT / 'reports/figures234_readiness.json'
90
+ readiness = document(readiness_path) if readiness_path.is_file() else {}
91
+ if readiness.get('schema') != 'pbisc.paper.figures234.v1' or readiness.get('status') != 'complete':
92
+ gaps.append('Figures 2--4 readiness is not complete')
93
+ f2, f3, f4 = (readiness.get(k, {}) for k in ('figure2', 'figure3', 'figure4'))
94
+ if f2.get('strict_complete_units') != 20 or f2.get('strict_missing') or not f2.get('pretrain_composition_ready'):
95
+ gaps.append('Figure 2 needs 20/20 strict healthy support units')
96
+ if (f3.get('strict_complete_folds') != 5 or not f3.get('visual_export_ready') or
97
+ not f3.get('extras_complete') or not f3.get('runtime_ready')):
98
+ gaps.append('Figure 3 needs 5/5 folds, visual, extras and time receipts')
99
+ if (set(f4.get('strict_complete_draws', {})) != set(COHORTS) or
100
+ any(f4['strict_complete_draws'].get(c) != 5 for c in COHORTS) or
101
+ any(f4.get(k) for k in ('contrast_missing', 'deconvolution_missing',
102
+ 'deconvolution_signal_missing'))):
103
+ gaps.append('Figure 4 needs 5/5 strict draws per cohort and contrast/deconvolution evidence')
104
+ expected_healthy = {(f'fold{fold}', n) for fold in range(5) for n in (5, 10, 20, 40)}
105
+ expected_disease = {(c, f'draw{draw}') for c in COHORTS for draw in range(5)}
106
+ curve = rows(ROOT / 'source_data/fig2_strict_curve.csv')
107
+ if {(r['fold'], int(r['n_pairs'])) for r in curve} != expected_healthy:
108
+ gaps.append('Figure 2 strict CSV has incomplete fold/size units')
109
+ healthy = rows(ROOT / 'source_data/fig3_per_sample.csv')
110
+ if {r['fold'] for r in healthy} != {f'fold{n}' for n in range(5)}:
111
+ gaps.append('Figure 3 strict per-sample CSV has incomplete folds')
112
+ disease = rows(ROOT / 'source_data/fig4_strict_per_sample.csv')
113
+ if {(r['cohort'], r['draw']) for r in disease} != expected_disease or any(
114
+ r.get('design') != 'strict_exact5_donor_draw' for r in disease):
115
+ gaps.append('Figure 4 strict CSV has incomplete or mixed-design draws')
116
+ for filename, table in [('fig2_strict_curve.csv', curve), ('fig3_per_sample.csv', healthy),
117
+ ('fig4_strict_per_sample.csv', disease)]:
118
+ if not table or any(not r.get('support_sha256') for r in table):
119
+ gaps.append(f'{filename} lacks source-bound support hashes')
120
+ for record in curve + healthy + disease:
121
+ source = record.get('summary')
122
+ source_hash = record.get('summary_sha256')
123
+ if source and source_hash and (not Path(source).is_file() or digest(Path(source)) != source_hash):
124
+ gaps.append(f'score summary hash mismatch: {source}')
125
+ break
126
+ for table, kind in ((curve, 'healthy'), (healthy, 'healthy'), (disease, 'disease')):
127
+ for record in table:
128
+ cohort = record.get('cohort', 'immicro')
129
+ unit = record.get('fold') if kind == 'healthy' else record.get('draw')
130
+ suffix = f'{unit}/n{record["n_pairs"]}' if table is curve else (
131
+ f'{unit}/n5' if kind == 'healthy' else unit)
132
+ support = ROOT / 'protocol/splits' / cohort / kind / suffix / 'support.json'
133
+ if not support.is_file() or document(support).get('sha256') != record.get('support_sha256'):
134
+ gaps.append(f'{cohort}/{kind}/{suffix}: source support mismatch')
135
+ break
136
+ summary = ROOT / 'scores' / cohort / kind / suffix / 'score/summary.json'
137
+ score_sha = record.get('score_sha256') or record.get('summary_sha256')
138
+ if not summary.is_file() or digest(summary) != score_sha:
139
+ gaps.append(f'{cohort}/{kind}/{suffix}: score summary hash mismatch')
140
+ break
141
+ rare_path = ROOT / 'reports/rare_provenance.json'
142
+ rare = document(rare_path) if rare_path.is_file() else {}
143
+ units = rare.get('units', [])
144
+ if (rare.get('schema') != 'pbisc.figure5.analysis.v1' or len(units) != 20 or
145
+ {(u.get('cohort'), u.get('unit')) for u in units} != expected_disease or
146
+ any(u.get('design') != 'strict5pair' or u.get('evidence_tier') != 'strict'
147
+ or not u.get('support_sha256') for u in units)):
148
+ gaps.append('Figure 5 needs all 20 strict rare-state receipts')
149
+ rare_table = rows(ROOT / 'source_data/rare_summary.csv')
150
+ if (not rare_table or {r.get('evidence_tier') for r in rare_table} != {'strict'} or
151
+ {(r['cohort'], r['unit']) for r in rare_table} != expected_disease):
152
+ gaps.append('Figure 5 rare-state CSV is absent, diagnostic or incomplete')
153
+ for cohort, unit in expected_disease:
154
+ subset = [r for r in rare_table if r.get('cohort') == cohort and r.get('unit') == unit]
155
+ if {r.get('arm') for r in subset} != {'raw', 'refcal', 'pairedcal', 'scsemi', 'lora'}:
156
+ gaps.append(f'Figure 5 strict arms incomplete: {cohort}/{unit}')
157
+ break
158
+ for unit in units:
159
+ support = ROOT / 'protocol/splits' / str(unit.get('cohort')) / 'disease' / str(unit.get('unit')) / 'support.json'
160
+ if not support.is_file() or document(support).get('sha256') != unit.get('support_sha256'):
161
+ gaps.append(f'Figure 5 strict support hash mismatch: {unit.get("cohort")}/{unit.get("unit")}')
162
+ break
163
+ if readiness.get('status') == 'complete':
164
+ runtime = ROOT / 'source_data/fig3_runtime.csv'
165
+ runtime_meta = ROOT / 'source_data/fig3_runtime.json'
166
+ visual = ROOT / 'source_data/fig3_visual_data.npz'
167
+ visual_meta = ROOT / 'source_data/fig3_visual_data.json'
168
+ if (not runtime.is_file() or not runtime_meta.is_file() or
169
+ document(runtime_meta).get('csv_sha256') != digest(runtime)):
170
+ gaps.append('Figure 3 runtime source/receipt hash mismatch')
171
+ if (not visual.is_file() or not visual_meta.is_file() or
172
+ document(visual_meta).get('npz_sha256') != digest(visual)):
173
+ gaps.append('Figure 3 visual source/receipt hash mismatch')
174
+ extras = ROOT / 'source_data/fig3_extras.csv'
175
+ if not extras.is_file() or not rows(extras):
176
+ gaps.append('Figure 3 realism extras CSV is missing')
177
+ for name in ('fig4_strict_contrast.csv', 'fig4_deconvolution.csv',
178
+ 'fig4_deconvolution_signal.csv', 'fig4_corrected_statistics.csv',
179
+ 'fig4_cross_draw_donor_ci.csv', 'fig4_donor_aware_signal.csv',
180
+ 'fig4_donor_aware_summary.csv', 'fig4_donor_aware_genes.csv',
181
+ 'fig4_donor_aware_cat.csv'):
182
+ path = ROOT / 'source_data' / name
183
+ if not path.is_file() or not rows(path):
184
+ gaps.append(f'Figure 4 required source table missing: {name}')
185
+ cross = ROOT / 'source_data/fig4_cross_draw_donor_ci.csv'
186
+ cross_receipt = ROOT / 'source_data/fig4_cross_draw_donor_ci.json'
187
+ if (not cross_receipt.is_file() or not cross.is_file() or
188
+ document(cross_receipt).get('csv_sha256') != digest(cross) or
189
+ {r.get('cohort') for r in rows(cross)} != set(COHORTS)):
190
+ gaps.append('Figure 4 five-draw donor-cluster CI source or receipt mismatch')
191
+ corrected = ROOT / 'source_data/fig4_donor_aware_signal.csv'
192
+ corrected_provenance = ROOT / 'source_data/fig4_donor_aware_provenance.json'
193
+ corrected_rows = rows(corrected) if corrected.is_file() else []
194
+ if (not corrected_provenance.is_file() or not corrected_rows or
195
+ {(r.get('cohort'), r.get('draw')) for r in corrected_rows} != expected_disease or
196
+ any(r.get('status') not in ('ok', 'not_estimable') for r in corrected_rows)):
197
+ gaps.append('Figure 4 corrected donor-aware disease signal is absent or incomplete')
198
+ for filename in FINAL_FIGURES:
199
+ if not (ROOT / 'figures' / filename).is_file():
200
+ gaps.append(f'missing strict figure: {filename}')
201
+ return gaps, readiness
202
+
203
+
204
+ def numeric_summary(table: list[dict], keys: tuple[str, ...], metrics: tuple[str, ...]) -> str:
205
+ """Render observed means only; no unsupported ordering or P value."""
206
+ data: dict[tuple[str, ...], dict[str, list[float]]] = defaultdict(lambda: defaultdict(list))
207
+ for row in table:
208
+ group = tuple(row[k] for k in keys)
209
+ for metric in metrics:
210
+ try:
211
+ value = float(row[metric])
212
+ except (KeyError, ValueError, TypeError):
213
+ continue
214
+ if value == value and value not in (float('inf'), float('-inf')):
215
+ data[group][metric].append(value)
216
+ lines = []
217
+ for group, values in sorted(data.items()):
218
+ parts = [f'{key}={value}' for key, value in zip(keys, group)]
219
+ parts += [f'{metric}={sum(items)/len(items):.3f} (n={len(items)})'
220
+ for metric, items in values.items() if items]
221
+ lines.append('; '.join(parts).replace('_', r'\_') + r'\par')
222
+ return '\n'.join(lines)
223
+
224
+
225
+ def complete_results() -> None:
226
+ """Fill only numbers present in verified strict CSVs; leave no preview placeholders."""
227
+ additions = {
228
+ 2: ('source_data/fig2_strict_curve.csv', ('n_pairs', 'arm'), ('precision', 'coverage')),
229
+ 3: ('source_data/fig3_per_sample.csv', ('arm',), ('precision', 'coverage', 'comp_l1')),
230
+ 4: ('source_data/fig4_strict_per_sample.csv', ('cohort', 'arm'), ('pb_r', 'comp_l1')),
231
+ 5: ('source_data/rare_summary.csv', ('cohort', 'arm'), ('mae_donor_pp', 'generated_zero_donors')),
232
+ }
233
+ openers = {
234
+ 2: (r'\subsection*{Pretraining design and strict paired-support curve}' '\n'
235
+ 'The held-out native-pseudobulk precision and coverage ablations use the '
236
+ 'common 1,006-gene rescore described in Methods. Architecture and gene-panel '
237
+ 'families have different training detection floors. The nested ImMicro curve '
238
+ 'uses five outer folds and $n=5,10,20,40$ distinct training donors per fold. '
239
+ 'Historical rank and full-parameter five-fold results are reported separately.\n'),
240
+ 3: (r'\subsection*{Healthy generation with exact five-pair support}' '\n'
241
+ 'Each ImMicro outer fold uses one matched sample from each of five training '
242
+ 'donors for LoRA, paired calibration and scSemiProfiler. The remaining donors '
243
+ 'are evaluated on common observed cells, measured genes and frozen labels. '
244
+ 'Figure~\\ref{fig:fig3} displays the strict quality measures and operational '
245
+ 'time, which excludes population pretraining.\n'),
246
+ 4: (r'\subsection*{Disease comparisons with exact five-pair support}' '\n'
247
+ 'Each of four disease cohorts contributes five frozen draws. One earliest '
248
+ 'identity-passed matched-stratum visit per selected donor trains all arms; '
249
+ 'other visits of that donor are excluded. Donor-aware disease contrasts and '
250
+ 'deconvolution are scored on the common held-out support. The old five-fold '
251
+ 'analysis remains a separate historical sensitivity analysis.\n'),
252
+ 5: (r'\subsection*{Rare states with paired support}' '\n'
253
+ 'All four disease cohorts and five draws use the exact same five-pair supports '
254
+ 'as Figure~\\ref{fig:fig4}. Zero-generated-state draws remain in every '
255
+ 'aggregate, required-marker failures make a state ineligible, and repeated '
256
+ 'visits are clustered by donor. The unmatched Beh\\c{c}et analysis is '
257
+ 'descriptive and separate.\n'),
258
+ }
259
+ for number, (source, keys, metrics) in additions.items():
260
+ path = STAGE / 'sections' / f'results_fig{number}.tex'
261
+ text = openers[number]
262
+ text += ('\n\\textbf{Measured strict-support summary.} Values below are arithmetic means '
263
+ 'of the named source-data rows; $n$ counts rows, not independent donors. '
264
+ 'Donor-cluster uncertainty and formal comparisons require the separate '
265
+ 'statistics receipts.\\par\n')
266
+ text += numeric_summary(rows(ROOT / source), keys, metrics) + '\n'
267
+ if number == 3:
268
+ extras = []
269
+ for record in rows(ROOT / 'source_data/fig3_extras.csv'):
270
+ if record.get('table') == 'metrics.csv' and record.get('mode') == 'raw':
271
+ extras.append({'arm': record.get('set', ''), **record})
272
+ elif (record.get('table') == 'en.csv' and record.get('cellset') == 'pc'
273
+ and record.get('distance') == 'sq'):
274
+ extras.append({'arm': record.get('set', ''), **record})
275
+ text += ('\n\\textbf{Realism and operational time.} C2ST AUC, MMD$^2$ '
276
+ 'and $E_N$ are computed from the strict extras; time is fine-tuning '
277
+ 'plus inference seconds, with pretraining excluded.\\par\n')
278
+ text += numeric_summary(extras, ('arm',), ('c2st_rf_auc', 'mmd2_sum', 'en')) + '\n'
279
+ text += numeric_summary(rows(ROOT / 'source_data/fig3_runtime.csv'),
280
+ ('arm',), ('operational_seconds',)) + '\n'
281
+ if number == 4:
282
+ donor_aware = [r for r in rows(ROOT / 'source_data/fig4_donor_aware_signal.csv')
283
+ if r.get('status') == 'ok']
284
+ text += ('\n\\textbf{Primary donor-aware disease signal.} Equal-patient '
285
+ 'condition contrasts, with repeated visits collapsed by donor and '
286
+ 'condition, are reported by cohort, arm, cell type and draw. '
287
+ 'A missing population is marked not estimable and contributes no '
288
+ 'fabricated zero. The values below summarize estimable rows; '
289
+ 'patient-cluster intervals are in the accompanying source tables.\\par\n')
290
+ text += numeric_summary(donor_aware, ('cohort', 'arm'),
291
+ ('pearson_r', 'partial_r', 'cat50', 'limma_top50')) + '\n'
292
+ contrast = [r for r in rows(ROOT / 'source_data/fig4_strict_contrast.csv')
293
+ if r.get('table') == 'headline.csv']
294
+ text += ('\n\\textbf{Historical contrast sensitivity.} The legacy per-sample '
295
+ 'logFC, CAT and limma headline values below retain their original '
296
+ 'independent-sample definition. They are separate from corrected '
297
+ 'donor-aware disease signal.\\par\n')
298
+ text += numeric_summary(contrast, ('cohort', 'arm'),
299
+ ('partial_r', 'cat50', 'limma_top50')) + '\n'
300
+ text += ('\n\\textbf{Cross-draw uncertainty.} Donor-cluster confidence intervals '
301
+ 'over all five verified draws, with repeated visits and draw membership '
302
+ 'kept together, are supplied in '
303
+ '\\texttt{fig4\\_cross\\_draw\\_donor\\_ci.csv}.\\par\n')
304
+ text += ('\n\\textbf{Same-support deconvolution.} Deconvolution '
305
+ 'provides fractions and supported cell-type expression, not '
306
+ 'generated-cell realism scores.\\par\n')
307
+ text += numeric_summary(rows(ROOT / 'source_data/fig4_deconvolution.csv'),
308
+ ('cohort', 'arm'), ('composition_l1',)) + '\n'
309
+ path.write_text(text)
310
+ path = STAGE / 'sections/discussion.tex'
311
+ path.write_text('\\section*{Discussion}\n'
312
+ 'The strict-support numerical summaries in Figs~2--5 report the completed '
313
+ 'five-pair design. They should be interpreted with their donor-cluster '
314
+ 'uncertainty and source tables; row counts are not biological replicates. '
315
+ 'Historical five-fold and unmatched Beh\\c{c}et analyses remain separate. '
316
+ 'Figure~\\ref{fig:fig6} awaits the user-prepared bulk-only reproduction data.\n')
317
+
318
+
319
+ def copy_source_files() -> dict[str, str]:
320
+ before = {}
321
+ for rel in tracked_sources():
322
+ src, dst = CANON / rel, STAGE / rel
323
+ if not src.is_file():
324
+ raise ValueError(f'tracked source missing: {src}')
325
+ before[str(rel)] = digest(src)
326
+ dst.parent.mkdir(parents=True, exist_ok=True)
327
+ shutil.copy2(src, dst)
328
+ return before
329
+
330
+
331
+ def edit_method_model() -> None:
332
+ path = STAGE / 'sections/methods_model.tex'
333
+ body = path.read_text().split('\\subsection*{SLE benchmark and frozen cell-type annotator}')[0]
334
+ body = body.replace('Fig.~\\ref{fig:fig1}b', 'Fig.~\\ref{fig:fig1}')
335
+ body = body.replace('Fig.~\\ref{fig:fig1}a', 'Fig.~\\ref{fig:fig1}')
336
+ body = body.replace('Fig.~\\ref{fig:fig1}c', 'Fig.~\\ref{fig:fig1}')
337
+ body = body.replace('Fig.~\\ref{fig:fig1}d', 'Fig.~\\ref{fig:fig1}')
338
+ body = body.replace('Fig.~\\ref{fig:fig1}f', 'Fig.~\\ref{fig:fig2}')
339
+ body = re.sub(r'It produced every generated cell set in this study except the threshold-read-out sets.*?Unless stated otherwise',
340
+ 'The pretraining design rescoring in Fig.~\\\\ref{fig:fig2} uses saved epoch-16 Bernoulli outputs. Unless stated otherwise',
341
+ body, flags=re.S)
342
+ body += '\n\\subsection*{Held-out pretraining design rescore}\n'
343
+ body += ('Saved architecture and gene-panel outputs for the 42 held-out SLE donors were rescored '
344
+ 'separately. On the common 1,006-gene axis, each donor contributed 100 real reference cells, '
345
+ '100 disjoint real query cells and 100 generated cells per arm. One fixed Poisson read-out, '
346
+ 'a real-reference 50-component PCA and $k=10$ local neighbourhoods defined precision and '
347
+ 'coverage. The architecture and panel families had different training detection floors and '
348
+ 'are not a factorial comparison. One saved generation seed per arm makes these descriptive scores.\n')
349
+ path.write_text(body)
350
+
351
+
352
+ def overlay(final: bool) -> list[str]:
353
+ changed = []
354
+ for src in sorted((EDITS / 'sections').glob('*.tex')):
355
+ dst = STAGE / 'sections' / src.name
356
+ shutil.copy2(src, dst)
357
+ changed.append(str(dst.relative_to(STAGE)))
358
+ edit_method_model()
359
+ changed.append('sections/methods_model.tex')
360
+ main = STAGE / 'main.tex'
361
+ content = main.read_text()
362
+ content = content.replace('% Overleaf main document.', '% RESTRUCTURING DRAFT: strict Figures 3--5 remain pending.\n% Overleaf main document.', 1)
363
+ content = content.replace('% Figures with their legends, each on its own page(s). Panels are the deck\'s vector graphics, placed as-is;\n% the 180 mm journal layout is still to be drawn.',
364
+ '% Figure 1--5 restructuring draft; strict missing panels are explicitly labelled.')
365
+ if final:
366
+ content = content.replace('% RESTRUCTURING DRAFT: strict Figures 3--5 remain pending.\n', '')
367
+ else:
368
+ content = content.replace('\\maketitle',
369
+ '\\maketitle\n\\noindent\\fcolorbox{red}{white}{\\parbox{0.92\\textwidth}{'
370
+ '\\textbf{RESTRUCTURING DRAFT.} Strict five-pair results for Figs 2--5 '
371
+ 'are incomplete. The approved title, abstract and Introduction retain their '
372
+ 'original wording and must be rereviewed against final strict results.}}\\par\\medskip', 1)
373
+ main.write_text(content)
374
+ changed.append('main.tex')
375
+ supp = STAGE / 'supplementary.tex'
376
+ supp_text = supp.read_text()
377
+ supp_text = supp_text.replace('\\begin{document}',
378
+ '\\begin{document}\n\\noindent\\textcolor{red}{[HISTORICAL SUPPLEMENTARY DRAFT: '
379
+ 'legacy analyses have not been reconciled with exact-five-pair support.]}\\par\\medskip', 1)
380
+ supp.write_text(supp_text)
381
+ changed.append('supplementary.tex')
382
+ figures = dict(FIGURES)
383
+ if final:
384
+ complete_results()
385
+ figures.update(FINAL_FIGURES)
386
+ strict_figures = {
387
+ 'fig3': ('Healthy exact five-pair OOF', 'fig3_healthy_strict_oof.pdf'),
388
+ 'fig4': ('Disease exact five-pair draws', 'fig4_disease_strict_draws.pdf'),
389
+ 'fig5': ('Paired rare states under exact five-pair support', 'fig5_rare_states_strict.pdf'),
390
+ }
391
+ for name, (title, filename) in strict_figures.items():
392
+ p = STAGE / 'sections' / f'{name}.tex'
393
+ panels = f'\\figpanelh{{}}{{figures/strict_20261012/{filename}}}{{0.77}}\n'
394
+ if name == 'fig3':
395
+ panels += ('\\figpanelh{}{figures/strict_20261012/fig3_realism_metrics.pdf}{0.38}\n')
396
+ panels += ('\\figpanelh{}{figures/strict_20261012/fig3_canonical_marker_dotplot.pdf}{0.42}\n')
397
+ for extra in ('umap_by_celltype','composition_fractions','runtime_components'):
398
+ panels += f'\\figpanelh{{}}{{figures/strict_20261012/fig3_{extra}.pdf}}{{0.62}}\n'
399
+ if name == 'fig4':
400
+ panels += ('\\figpanelh{}{figures/strict_20261012/fig4_disease_signal_strict.pdf}{0.48}\n'
401
+ '\\figpanelh{}{figures/strict_20261012/fig4_deconvolution_strict.pdf}{0.42}\n'
402
+ '\\figpanelh{}{figures/strict_20261012/fig4_deconvolution_expression_strict.pdf}{0.48}\n')
403
+ panels += ('\\figpanelh{}{figures/strict_20261012/fig4_historical_5fold_separate.pdf}{0.38}\n')
404
+ for extra in ('scatter','heatmap','cat'):
405
+ panels += f'\\figpanelh{{}}{{figures/strict_20261012/fig4_disease_signal_{extra}.pdf}}{{0.60}}\n'
406
+ if name == 'fig5':
407
+ for extra in ('rare_visuals','all_states','behcet_rules'):
408
+ panels += f'\\figpanelh{{}}{{figures/strict_20261012/fig5_{extra}_strict.pdf}}{{0.72}}\n'
409
+ p.write_text(f'\\mainfigure{{fig:{name}}}{{{title}}}\n' + panels +
410
+ '\\figlegend{Strict-support results and source-data tables are '
411
+ 'reported in the corresponding Results section. Figure 4 historical '
412
+ 'five-fold values appear in a separate labelled panel.}\n')
413
+ for source, target in figures.items():
414
+ src = ROOT / 'figures' / source
415
+ if not src.is_file():
416
+ raise ValueError(f'missing figure: {src}')
417
+ dst = STAGE / 'figures/strict_20261012' / target
418
+ dst.parent.mkdir(parents=True, exist_ok=True)
419
+ shutil.copy2(src, dst)
420
+ changed.append(str(dst.relative_to(STAGE)))
421
+ evidence = ('source_data/fig1_corpus_aggregates.json',
422
+ 'source_data/ablation_pretrain_pc.csv',
423
+ 'source_data/ablation_pretrain_pc_receipt.json',
424
+ 'source_data/fig2_historical_rank_full.csv',
425
+ 'source_data/fig4_historical_5fold.csv',
426
+ 'reports/figure1_provenance.json',
427
+ 'reports/figures234_readiness.json',
428
+ 'reports/rare_provenance.json')
429
+ if final:
430
+ evidence += ('source_data/fig2_strict_curve.csv',
431
+ 'source_data/fig3_per_sample.csv',
432
+ 'source_data/fig3_extras.csv',
433
+ 'source_data/fig3_runtime.csv',
434
+ 'source_data/fig3_runtime.json',
435
+ 'source_data/fig3_visual_data.json',
436
+ 'source_data/fig4_strict_per_sample.csv',
437
+ 'source_data/fig4_corrected_statistics.csv',
438
+ 'source_data/fig4_cross_draw_donor_ci.csv',
439
+ 'source_data/fig4_cross_draw_donor_ci.json',
440
+ 'source_data/fig4_donor_aware_signal.csv',
441
+ 'source_data/fig4_donor_aware_summary.csv',
442
+ 'source_data/fig4_donor_aware_genes.csv',
443
+ 'source_data/fig4_donor_aware_cat.csv',
444
+ 'source_data/fig4_donor_aware_provenance.json',
445
+ 'source_data/fig4_strict_contrast.csv',
446
+ 'source_data/fig4_deconvolution.csv',
447
+ 'source_data/fig4_deconvolution_signal.csv',
448
+ 'source_data/rare_summary.csv',
449
+ 'source_data/rare_ineligible_states.csv',
450
+ 'source_data/rare_behcet_descriptive.csv')
451
+ for rel in evidence:
452
+ src = ROOT / rel
453
+ if not src.is_file():
454
+ raise ValueError(f'missing source data: {src}')
455
+ dst = STAGE / 'strict_20261012' / rel
456
+ dst.parent.mkdir(parents=True, exist_ok=True)
457
+ shutil.copy2(src, dst)
458
+ changed.append(str(dst.relative_to(STAGE)))
459
+ changed.extend(['sections/fig1.tex', 'sections/fig2.tex', 'sections/fig3.tex',
460
+ 'sections/fig4.tex', 'sections/fig5.tex'])
461
+ return sorted(set(changed))
462
+
463
+
464
+ def verify_unchanged_frontmatter(original: dict[str, str]) -> None:
465
+ for name in ('sections/abstract.tex', 'sections/introduction.tex', 'authors.tex'):
466
+ if digest(STAGE / name) != original[name]:
467
+ raise ValueError(f'user-approved frontmatter changed: {name}')
468
+ canonical_main = (CANON / 'main.tex').read_text()
469
+ staged_main = (STAGE / 'main.tex').read_text()
470
+ for pattern in (r'\\title\{[^\n]+', r'\\abstract\{[^\n]+'):
471
+ if re.search(pattern, canonical_main).group() != re.search(pattern, staged_main).group():
472
+ raise ValueError(f'user-approved title or abstract command changed: {pattern}')
473
+
474
+
475
+ def allowed_frontmatter_refresh(previous: dict[str, str], current: dict[str, str],
476
+ *, old_main: str | None = None, new_main: str | None = None) -> dict:
477
+ """Permit only new approved Title, Abstract and Introduction source text."""
478
+ changed = {name: {'previous_sha256': old, 'current_sha256': current.get(name)}
479
+ for name, old in previous.items() if current.get(name) != old}
480
+ allowed = {'main.tex', 'sections/abstract.tex', 'sections/introduction.tex'}
481
+ extra = set(changed) - allowed
482
+ if extra:
483
+ raise ValueError(f'canonical source changed outside approved frontmatter: {sorted(extra)}')
484
+ if 'main.tex' in changed:
485
+ if old_main is None or new_main is None:
486
+ raise ValueError('main.tex changed beyond approved title/abstract commands')
487
+ pattern = r'\\(?:title|abstract)\{[^\n]*\}'
488
+ if re.sub(pattern, r'\\frontmatter{APPROVED}', old_main) != re.sub(
489
+ pattern, r'\\frontmatter{APPROVED}', new_main):
490
+ raise ValueError('main.tex changed beyond approved title/abstract commands')
491
+ return changed
492
+
493
+
494
+ def main() -> None:
495
+ p = argparse.ArgumentParser(description=__doc__)
496
+ mode = p.add_mutually_exclusive_group(required=True)
497
+ mode.add_argument('--preview', action='store_true')
498
+ mode.add_argument('--require-complete', action='store_true')
499
+ args = p.parse_args()
500
+ if subprocess.check_output(['git', '-C', str(CANON), 'status', '--porcelain']).strip():
501
+ raise SystemExit('canonical manuscript is not clean; refusing to assemble')
502
+ checked_provenance(ROOT / 'reports/figure1_provenance.json', 'Figure 1')
503
+ pretrain = checked_provenance(ROOT / 'source_data/ablation_pretrain_pc_receipt.json', 'Figure 2 P/C')
504
+ recipe = pretrain.get('recipe', {})
505
+ if (pretrain.get('schema') != 'pbisc.fig2.pretrain_pc.v1' or
506
+ recipe.get('n_pcs') != 50 or recipe.get('local_k') != 10 or
507
+ pretrain.get('gene_axis', {}).get('n') != 1006 or
508
+ {r['family'] for r in rows(ROOT / 'source_data/ablation_pretrain_pc.csv')} !=
509
+ {'architecture_floor1pct', 'panel_floor0.1pct'}):
510
+ raise SystemExit('Figure 2 measured P/C receipt or source table differs from the frozen rescore')
511
+ gaps, readiness = strict_gate()
512
+ if args.require_complete and gaps:
513
+ raise SystemExit('final assembly refused:\n- ' + '\n- '.join(sorted(set(gaps))))
514
+ previous = STAGE / 'integration_manifest.json'
515
+ refreshed = {}
516
+ if previous.is_file() and args.require_complete:
517
+ prior = document(previous)
518
+ old = prior.get('canonical_source_sha256', {})
519
+ current = {rel: digest(CANON / rel) if (CANON / rel).is_file() else None for rel in old}
520
+ old_main = None
521
+ if current.get('main.tex') != old.get('main.tex'):
522
+ old_head = prior.get('canonical_head')
523
+ if not old_head:
524
+ raise SystemExit('review preview has no canonical head for frontmatter comparison')
525
+ old_main = subprocess.check_output(['git', '-C', str(CANON), 'show',
526
+ f'{old_head}:main.tex'], text=True)
527
+ try:
528
+ refreshed = allowed_frontmatter_refresh(old, current, old_main=old_main,
529
+ new_main=(CANON / 'main.tex').read_text())
530
+ except ValueError as exc:
531
+ raise SystemExit(str(exc)) from exc
532
+ originals = copy_source_files()
533
+ changed = overlay(args.require_complete)
534
+ verify_unchanged_frontmatter(originals)
535
+ # Keep the original claims available for review without placing them in Results.
536
+ legacy = STAGE / 'editorial/legacy_results'
537
+ legacy.mkdir(parents=True, exist_ok=True)
538
+ for name in ('results_fig1', 'results_fig2', 'results_fig3', 'results_fig4',
539
+ 'results_fig5', 'results_fig6', 'methods_paired', 'methods_eval', 'discussion'):
540
+ src = CANON / 'sections' / f'{name}.tex'
541
+ shutil.copy2(src, legacy / src.name)
542
+ changed.append(str((legacy / src.name).relative_to(STAGE)))
543
+ manifest = {
544
+ 'schema': 'pbisc.paper.manuscript-integration.v1',
545
+ 'mode': 'complete' if args.require_complete else 'restructuring_preview',
546
+ 'canonical_root': str(CANON), 'stage_root': str(STAGE),
547
+ 'canonical_head': subprocess.check_output(['git', '-C', str(CANON), 'rev-parse', 'HEAD'], text=True).strip(),
548
+ 'canonical_source_sha256': originals,
549
+ 'approved_frontmatter_refresh': refreshed,
550
+ 'staged_changes': {rel: {'sha256': digest(STAGE / rel),
551
+ 'canonical_sha256': originals.get(rel)} for rel in changed},
552
+ 'figure_source_sha256': {name: digest(ROOT / 'figures' / name) for name in
553
+ (FIGURES | (FINAL_FIGURES if args.require_complete else {}))},
554
+ 'readiness': readiness,
555
+ 'gaps': gaps,
556
+ 'figure6': 'waiting_user_prepared_data; unchanged placeholder',
557
+ 'git_push': False, 'overleaf_sync': False,
558
+ }
559
+ previous.write_text(json.dumps(manifest, indent=2) + '\n')
560
+ print(json.dumps({'mode': manifest['mode'], 'staged_changed_files': len(changed),
561
+ 'gaps': gaps, 'manifest': str(previous)}, indent=2))
562
+
563
+
564
+ if __name__ == '__main__':
565
+ main()
paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/tools/build_figure1.py ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Deterministically draw the 180 mm PBISC-Diffusion overview from frozen tables."""
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ import hashlib
7
+ import json
8
+ from pathlib import Path
9
+
10
+ import matplotlib
11
+
12
+ matplotlib.use("Agg")
13
+ import matplotlib.pyplot as plt
14
+ from matplotlib.patches import FancyArrowPatch, FancyBboxPatch, Rectangle
15
+
16
+
17
+ ROOT = Path(__file__).resolve().parents[1]
18
+ MANUSCRIPT = Path("/home/sj_server_1/PBISC/paper-release-20260928/manuscript")
19
+ CORPUS = MANUSCRIPT / "source_data/corpus"
20
+ SOURCES = [
21
+ CORPUS / "corpus_summary.json",
22
+ CORPUS / "corpus_assay_condition.csv",
23
+ CORPUS / "corpus_celltypes.csv",
24
+ CORPUS / "corpus_datasets.csv",
25
+ CORPUS / "README.md",
26
+ MANUSCRIPT / "sections/methods_model.tex",
27
+ MANUSCRIPT / "sections/methods_paired.tex",
28
+ ROOT / "protocol/PROTOCOL.json",
29
+ ]
30
+ INK = "#26384a"
31
+ MUTED = "#526478"
32
+ FAINT = "#d9e1e8"
33
+ BG = "#ffffff"
34
+ BLUE = "#0072B2"
35
+ TEAL = "#009E73"
36
+ ORANGE = "#E69F00"
37
+ VERMILION = "#D55E00"
38
+ PURPLE = "#765A9A"
39
+ GREY = "#8995a3"
40
+ LIGHT_BLUE = "#eaf4fa"
41
+ LIGHT_TEAL = "#eaf6f2"
42
+ LIGHT_ORANGE = "#fbf3e0"
43
+ LIGHT_PURPLE = "#f2eef8"
44
+
45
+
46
+ def sha(path: Path) -> str:
47
+ h = hashlib.sha256()
48
+ with path.open("rb") as f:
49
+ for block in iter(lambda: f.read(1024 * 1024), b""):
50
+ h.update(block)
51
+ return h.hexdigest()
52
+
53
+
54
+ def read_data() -> dict:
55
+ s = json.loads((CORPUS / "corpus_summary.json").read_text())
56
+ datasets = list(csv.DictReader((CORPUS / "corpus_datasets.csv").open()))
57
+ assay_condition = list(csv.DictReader((CORPUS / "corpus_assay_condition.csv").open()))
58
+ celltypes = list(csv.DictReader((CORPUS / "corpus_celltypes.csv").open()))
59
+ assert len(datasets) == s["datasets"] == 22
60
+ assert sum(int(r["n_cells"]) for r in datasets) == s["cells"] == 41_395_184
61
+ assert sum(int(r["n_cells"]) for r in assay_condition) == s["cells"]
62
+ assert sum(int(r["n_cells"]) for r in celltypes) == s["cells"]
63
+ assert sum(s["split_cells"].values()) == s["cells"]
64
+ assert s["split_cells"]["train"] == 33_141_380
65
+ assert s["donors"] == 3199 and s["samples"] == 6507
66
+ assert abs(s["family_cells"]["Healthy"] / s["cells"] - 0.8851) < .001
67
+ assert abs(s["handling_cells"]["in vitro"] / s["cells"] - 0.2361) < .001
68
+ # Healthy and in-vitro are overlapping attributes; preserve their separate denominators.
69
+ by_assay = {
70
+ "10x": s["platform_cells"]["10x"],
71
+ "Parse": s["platform_cells"]["Parse"],
72
+ "ScaleBio + Seq-Well": s["platform_cells"]["ScaleBio"] + s["platform_cells"]["Seq-Well"],
73
+ }
74
+ by_condition = {
75
+ "Healthy": s["family_cells"]["Healthy"],
76
+ "Autoimmune": s["family_cells"]["Autoimmune"],
77
+ "Infection": s["family_cells"]["Infection"],
78
+ "Other": s["family_cells"]["Hematologic"] + s["family_cells"]["Drug reaction"],
79
+ }
80
+ by_celltype = {
81
+ "T cell": s["celltype_l1_cells"]["T cell"],
82
+ "Monocyte": s["celltype_l1_cells"]["Monocyte"],
83
+ "B cell": s["celltype_l1_cells"]["B cell"],
84
+ "NK cell": s["celltype_l1_cells"]["NK cell"],
85
+ "Other / unlabeled": s["cells"] - sum(s["celltype_l1_cells"][x] for x in ("T cell", "Monocyte", "B cell", "NK cell")),
86
+ }
87
+ for group in (by_assay, by_condition, by_celltype):
88
+ assert sum(group.values()) == s["cells"]
89
+ return {"summary": s, "assay": by_assay, "condition": by_condition, "cell_type": by_celltype}
90
+
91
+
92
+ def box(ax, x, y, w, h, face, edge=FAINT, radius=.011, lw=.7):
93
+ p = FancyBboxPatch((x, y), w, h, boxstyle=f"round,pad=0,rounding_size={radius}",
94
+ facecolor=face, edgecolor=edge, linewidth=lw)
95
+ ax.add_patch(p)
96
+ return p
97
+
98
+
99
+ def tx(ax, x, y, value, size=7.4, color=INK, weight="normal", ha="left", va="center", **kw):
100
+ return ax.text(x, y, value, fontsize=size, color=color, weight=weight,
101
+ ha=ha, va=va, family="DejaVu Sans", **kw)
102
+
103
+
104
+ def arrow(ax, x0, y0, x1, y1, color=MUTED, lw=1.25, ls="solid", scale=9):
105
+ ax.add_patch(FancyArrowPatch((x0, y0), (x1, y1), arrowstyle="-|>",
106
+ mutation_scale=scale, linewidth=lw, linestyle=ls, color=color))
107
+
108
+
109
+ def panel(ax, letter, title, y):
110
+ tx(ax, .025, y, letter, 12.2, INK, "bold", va="top")
111
+ tx(ax, .073, y-.002, title, 9.6, INK, "bold", va="top")
112
+
113
+
114
+ def stacked(ax, y, label, items, colors, total):
115
+ x0, w = .205, .739
116
+ tx(ax, .077, y+.012, label, 7.6, INK, "bold")
117
+ x = x0
118
+ for (name, value), color in zip(items.items(), colors):
119
+ dx = w * value / total
120
+ ax.add_patch(Rectangle((x, y), dx, .022, facecolor=color, edgecolor="white", linewidth=.6))
121
+ if dx >= .057:
122
+ tx(ax, x + dx/2, y+.011, f"{100*value/total:.1f}%", 6.6,
123
+ "white" if color not in (ORANGE, GREY) else INK, "bold", ha="center")
124
+ x += dx
125
+ # Every category is in an editable legend below each bar.
126
+ legend = " · ".join(f"{k} {100*v/total:.1f}%" for k,v in items.items())
127
+ tx(ax, x0, y-.012, legend, 6.55, MUTED, va="top")
128
+
129
+
130
+ def draw(data):
131
+ plt.rcParams.update({"svg.fonttype": "none", "pdf.fonttype": 42,
132
+ "font.family": "DejaVu Sans", "savefig.facecolor": "white"})
133
+ fig = plt.figure(figsize=(7.087, 8.55), facecolor=BG)
134
+ ax = fig.add_axes([0,0,1,1]); ax.set_xlim(0,1); ax.set_ylim(0,1); ax.axis("off")
135
+ ax.add_patch(Rectangle((0,0),1,1,facecolor=BG,edgecolor="none"))
136
+ tx(ax, .025, .988, "PBISC-Diffusion", 14, INK, "bold", va="top")
137
+ tx(ax, .975, .987, "from population pretraining to one measured bulk", 8.2, MUTED, ha="right", va="top")
138
+ ax.plot([.025,.975],[.962,.962],color=FAINT,lw=.9)
139
+
140
+ # a. One main adaptation path; the external-reference route is explicitly separate.
141
+ panel(ax, "a", "Pretrain once → adapt on five independent donors → infer a new sample", .946)
142
+ y,h=.852,.063
143
+ box(ax,.075,y,.249,h,LIGHT_BLUE,BLUE)
144
+ tx(ax,.092,y+.041,"PBMC pseudobulk pretraining",8.1,BLUE,"bold")
145
+ tx(ax,.092,y+.018,"33.1 M train cells · 6,000 genes",7.15,INK)
146
+ arrow(ax,.328,y+.031,.380,y+.031,BLUE)
147
+ box(ax,.383,y,.251,h,LIGHT_ORANGE,ORANGE)
148
+ tx(ax,.400,y+.041,"LoRA r = 16 · 3,000 steps",8.1,VERMILION,"bold")
149
+ tx(ax,.400,y+.018,"exactly 5 donors × 1 pair each",7.15,INK)
150
+ arrow(ax,.638,y+.031,.691,y+.031,VERMILION)
151
+ box(ax,.695,y,.258,h,LIGHT_TEAL,TEAL)
152
+ tx(ax,.712,y+.041,"New measured real bulk",8.1,TEAL,"bold")
153
+ tx(ax,.712,y+.018,"one condition → synthetic cells",7.15,INK)
154
+ ax.plot([.160,.160,.280],[.846,.826,.826],color=GREY,lw=1,ls=(0,(2.2,2.2)))
155
+ ax.plot([.665,.744],[.826,.826],color=GREY,lw=1,ls=(0,(2.2,2.2)))
156
+ arrow(ax,.744,.826,.744,.850,GREY,.95,"dotted",7)
157
+ tx(ax,.455,.825,"Alternative: external AIFI reference calibration",7.0,MUTED,ha="center")
158
+ tx(ax,.086,.805,"Reference branch uses external cells; no calibration is part of the main LoRA path.",7.0,MUTED)
159
+ ax.plot([.025,.975],[.787,.787],color=FAINT,lw=.7)
160
+
161
+ # b. State and conditioner, with measurable/unmeasured semantics.
162
+ panel(ax,"b","Gene-space joint diffusion with a measured-gene mask",.775)
163
+ box(ax,.075,.686,.238,.060,LIGHT_BLUE,BLUE)
164
+ tx(ax,.092,.726,"Noisy cell state [2 × 6,000]",7.7,BLUE,"bold")
165
+ tx(ax,.092,.704,"value + detection support",7.3,INK)
166
+ arrow(ax,.316,.716,.371,.716,BLUE)
167
+ box(ax,.374,.680,.251,.073,"#f2f5f8",MUTED)
168
+ tx(ax,.499,.729,"7-block denoiser",8.15,INK,"bold",ha="center")
169
+ tx(ax,.499,.707,"time + self-conditioning",7.2,MUTED,ha="center")
170
+ tx(ax,.499,.691,"measured genes enter loss",6.9,MUTED,ha="center")
171
+ arrow(ax,.629,.716,.687,.716,TEAL)
172
+ box(ax,.690,.686,.265,.060,LIGHT_TEAL,TEAL)
173
+ tx(ax,.707,.726,"Predicted clean cell",7.8,TEAL,"bold")
174
+ tx(ax,.707,.704,"value + support logits",7.3,INK)
175
+ box(ax,.077,.624,.876,.052,LIGHT_PURPLE,PURPLE)
176
+ tx(ax,.092,.651,"Bulk condition",7.6,PURPLE,"bold")
177
+ tx(ax,.226,.651,"6,000 expression + 6 scalars + 6,000 input measurement + 6,000 output availability",6.95,INK)
178
+ tx(ax,.226,.638,"18,006 inputs → 512-dimensional context; assay-missing genes are excluded, not treated as zeros",6.9,MUTED)
179
+ arrow(ax,.498,.676,.498,.679,PURPLE,1.0,scale=7)
180
+ ax.plot([.025,.975],[.610,.610],color=FAINT,lw=.7)
181
+
182
+ # c. Parameter meanings have two distinct routes.
183
+ panel(ax,"c","Constructing the condition: pseudobulk and real bulk",.598)
184
+ box(ax,.075,.524,.425,.049,LIGHT_BLUE,BLUE)
185
+ tx(ax,.090,.552,"Pretraining pseudobulk",7.8,BLUE,"bold")
186
+ tx(ax,.090,.535,"K_cond = member cells · L = Σ raw UMIs · ρ = L/K_cond",6.95,INK)
187
+ box(ax,.515,.524,.440,.049,LIGHT_ORANGE,ORANGE)
188
+ tx(ax,.530,.552,"Real-bulk adaptation and inference",7.8,VERMILION,"bold")
189
+ tx(ax,.530,.535,"K_cond = 1,000 supplied · ρ = 3,869.603 train anchor",6.95,INK)
190
+ tx(ax,.085,.504,"ρ is the per-cell depth used to scale the bulk; it is derived in pretraining and fixed for real bulk.",7.05,MUTED)
191
+ ax.plot([.025,.975],[.490,.490],color=FAINT,lw=.7)
192
+
193
+ # d. Shared conditioning, independent stochastic cells; no hidden compositional constraint.
194
+ panel(ax,"d","Independent cell draws from the same measured bulk",.478)
195
+ box(ax,.075,.401,.183,.047,LIGHT_TEAL,TEAL)
196
+ tx(ax,.166,.432,"One condition",7.7,TEAL,"bold",ha="center")
197
+ tx(ax,.166,.413,"K_cond = 1,000",7.1,INK,ha="center")
198
+ arrow(ax,.261,.424,.309,.424,TEAL)
199
+ box(ax,.312,.398,.318,.053,"#f2f5f8",MUTED)
200
+ tx(ax,.471,.433,"50 DDIM steps · shared denoiser",7.75,INK,"bold",ha="center")
201
+ tx(ax,.471,.412,"independent initial noise for each cell",7.05,MUTED,ha="center")
202
+ arrow(ax,.635,.424,.679,.424,TEAL)
203
+ box(ax,.683,.401,.271,.047,LIGHT_TEAL,TEAL)
204
+ tx(ax,.819,.432,"N_gen = 1,500 cells",7.75,TEAL,"bold",ha="center")
205
+ tx(ax,.819,.413,"batchable · no autoregression",7.0,INK,ha="center")
206
+ tx(ax,.085,.379,"Each cell receives its own noise and support draw; cell sums are evaluated against bulk, never constrained to equal it.",7.05,MUTED)
207
+ ax.plot([.025,.975],[.360,.360],color=FAINT,lw=.7)
208
+
209
+ # e. Corpus is a genuine data panel, values generated from manuscript source tables.
210
+ panel(ax,"e","Pretraining corpus: assay, condition and cell-type coverage",.347)
211
+ cards=[("41,395,184","all cells"),("33,141,380","train cells"),("22","datasets"),("3,199","donors"),("6,507","samples")]
212
+ for i,(number,label) in enumerate(cards):
213
+ x=.076+i*.177
214
+ box(ax,x,.283,.167,.043,"#f4f7f9",FAINT,radius=.006)
215
+ tx(ax,x+.0835,.308,number,8.2,INK,"bold",ha="center")
216
+ tx(ax,x+.0835,.291,label,6.7,MUTED,ha="center")
217
+ total=data["summary"]["cells"]
218
+ stacked(ax,.244,"Assay",data["assay"],[BLUE,TEAL,GREY],total)
219
+ stacked(ax,.183,"Condition",data["condition"],[TEAL,VERMILION,ORANGE,GREY],total)
220
+ stacked(ax,.122,"Cell type",data["cell_type"],[BLUE,VERMILION,PURPLE,TEAL,GREY],total)
221
+ healthy=100*data["summary"]["family_cells"]["Healthy"]/total
222
+ vitro=100*data["summary"]["handling_cells"]["in vitro"]/total
223
+ tx(ax,.077,.057,f"{healthy:.1f}% healthy · {vitro:.1f}% in vitro",7.7,INK,"bold")
224
+ tx(ax,.077,.038,"Shares are of all cells; healthy and in vitro overlap. Labels describe the corpus, not model inputs.",6.9,MUTED)
225
+ ax.plot([.025,.975],[.026,.026],color=FAINT,lw=.8)
226
+ tx(ax,.025,.015,"PBISC-Diffusion | 180 mm figure width | source data: manuscript corpus tables",6.1,MUTED,va="center")
227
+ return fig
228
+
229
+
230
+ def main():
231
+ data=read_data()
232
+ (ROOT/"figures").mkdir(exist_ok=True)
233
+ (ROOT/"source_data").mkdir(exist_ok=True)
234
+ (ROOT/"reports").mkdir(exist_ok=True)
235
+ src=ROOT/"source_data/fig1_corpus_aggregates.json"
236
+ src.write_text(json.dumps({
237
+ "schema":"pbisc.figure1.corpus.v1",
238
+ "denominator":"all 41,395,184 corpus cells; proportions are cell shares, not donor shares",
239
+ "condition_handling_overlap":"healthy and in vitro are overlapping attributes",
240
+ "aggregates":{k:v for k,v in data.items() if k != "summary"},
241
+ "totals":{k:data["summary"][k] for k in ("cells","datasets","samples","donors","split_cells","family_cells","handling_cells")},
242
+ "sources":[{"path":str(p),"sha256":sha(p)} for p in SOURCES],
243
+ },indent=2)+"\n")
244
+ fig=draw(data)
245
+ base=ROOT/"figures/fig1_overview"
246
+ for ext, kw in [("svg",{}),("pdf",{}),("png",{"dpi":300})]:
247
+ fig.savefig(base.with_suffix("."+ext), facecolor="white", **kw)
248
+ plt.close(fig)
249
+ provenance={
250
+ "schema":"pbisc.figure1.provenance.v1",
251
+ "figure_width_mm":180,
252
+ "scope":"Figure 1 overview; schematic method panels and manuscript-derived corpus aggregates",
253
+ "design":"deterministic Matplotlib vector authoring; SVG retains editable text",
254
+ "sources":[{"path":str(p),"sha256":sha(p)} for p in SOURCES],
255
+ "outputs":[{"path":str(p),"sha256":sha(p),"bytes":p.stat().st_size} for p in
256
+ [base.with_suffix(".svg"),base.with_suffix(".pdf"),base.with_suffix(".png"),src]],
257
+ "semantics":{
258
+ "pseudobulk_K_cond":"number of source recipe cells; L=sum of raw UMIs; rho=L/K_cond",
259
+ "real_bulk_K_cond":1000,
260
+ "real_bulk_rho_counts_per_cell":3869.603120208939,
261
+ "N_gen":1500,
262
+ "independence":"N_gen independent noise and support draws; no autoregression or sum constraint",
263
+ "main_adaptation":"LoRA rank 16, 3000 steps, exactly one pair from each of five independent donors; no calibration",
264
+ "alternative":"external AIFI reference calibration, shown schematically without performance claim",
265
+ "condition_dimensions": {"expression":6000,"scalars":6,"input_measurement":6000,"output_availability":6000,"total":18006,"context":512},
266
+ },
267
+ }
268
+ (ROOT/"reports/figure1_provenance.json").write_text(json.dumps(provenance,indent=2)+"\n")
269
+ print(json.dumps({"figure":str(base.with_suffix('.png')),"source_data":str(src),"outputs":provenance["outputs"]},indent=2))
270
+
271
+
272
+ if __name__=="__main__":
273
+ main()