junidude14 commited on
Commit
0abdcfd
·
verified ·
1 Parent(s): ca12448

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/import_scsemi_legacy.py ADDED
@@ -0,0 +1,461 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Audit and adopt old exact-five-pair sepsis scSemi work without relabelling its origin.
3
+
4
+ `prepare` builds strict CPU inputs and n-only prepared assets. `verify` is read-only.
5
+ `adopt` hardlinks verified legacy evidence under the strict work's adopted_legacy/
6
+ directory and writes an explicit source-bound receipt. It does not create a
7
+ native strict run_manifest, checkpoint receipt, or scorer-ready generated arm.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import hashlib
13
+ import json
14
+ import os
15
+ import re
16
+ import subprocess
17
+ import sys
18
+ from pathlib import Path
19
+
20
+ import numpy as np
21
+
22
+ PLAN = Path(__file__).resolve().parents[1]
23
+ OLD = PLAN.parent / "paired_finetune_intradataset_20260927"
24
+ SC_PY = PLAN.parent / "immicro_scsemi_comparison_20260927/runtime_env/bin/python"
25
+ BUILDER = OLD / "scsemi/tools/prepare_draw_inputs.py"
26
+ WRAPPER = PLAN / "tools/run_scsemi_strict.py"
27
+ EXPORTER_OLD = OLD / "scsemi/tools/export_npz.py.bak_20261002"
28
+ EXCLUDE_PREPARED = {"status/init_representatives.txt", "status/init_cluster_labels.txt"}
29
+
30
+
31
+ def sha(path: Path) -> str:
32
+ h = hashlib.sha256()
33
+ with path.open("rb") as f:
34
+ for chunk in iter(lambda: f.read(1 << 22), b""):
35
+ h.update(chunk)
36
+ return h.hexdigest()
37
+
38
+
39
+ def read(path: Path) -> dict:
40
+ return json.loads(path.read_text())
41
+
42
+
43
+ def paths(support_path: Path) -> tuple[dict, Path, Path, Path]:
44
+ support_path = support_path.resolve()
45
+ support = read(support_path)
46
+ cohort, unit = support.get("cohort"), support.get("unit")
47
+ if cohort != "ye2026_sepsis" or not re.fullmatch(r"draw[0-4]_n5", str(unit)):
48
+ raise ValueError("legacy import is limited to five sepsis disease draws")
49
+ draw = unit.removesuffix("_n5")
50
+ canonical = PLAN / "protocol/splits" / cohort / "disease" / draw / "support.json"
51
+ if support_path != canonical.resolve():
52
+ raise ValueError("noncanonical strict support path")
53
+ sys.path.insert(0, str(PLAN / "tools"))
54
+ from support_manifest import load_manifest
55
+ import pandas as pd
56
+ support = load_manifest(support_path, pd.read_csv(OLD / "data" / cohort / "folds.csv"))
57
+ old = OLD / "scsemi/work" / cohort / "fewshot_n5" / draw
58
+ new = PLAN / "scsemi" / cohort / "disease" / draw
59
+ generated = OLD / "generated" / cohort / "fewshot_n5" / draw / "scsemi5__raw.npz"
60
+ return support, old, new, generated
61
+
62
+
63
+ def preflight() -> None:
64
+ active = subprocess.run(["systemctl", "--user", "is-active", "ml-memory-guard.service"],
65
+ check=True, capture_output=True, text=True)
66
+ if active.stdout.strip() != "active":
67
+ raise RuntimeError("ml-memory-guard.service inactive")
68
+ subprocess.run(["/home/sj_server_1/.local/libexec/ml-memory-guard", "--check"], check=True)
69
+ apps = subprocess.run(["nvidia-smi", "--query-compute-apps=pid,process_name,used_memory", "--format=csv,noheader"],
70
+ check=True, capture_output=True, text=True)
71
+ # CPU preparation is bounded to two threads and observed <5 GiB on draw0;
72
+ # a small active CUDA job is compatible if global headroom remains ample.
73
+ mem = next(int(x.split()[1]) for x in Path("/proc/meminfo").read_text().splitlines() if x.startswith("MemAvailable:"))
74
+ if mem < 48 * 1024 * 1024:
75
+ raise RuntimeError("less than 48 GiB MemAvailable")
76
+
77
+
78
+ def prepare(support_path: Path) -> Path:
79
+ support, _, work, _ = paths(support_path)
80
+ preflight()
81
+ env = {**os.environ, "CUDA_VISIBLE_DEVICES": "", "OMP_NUM_THREADS": "2", "OPENBLAS_NUM_THREADS": "2"}
82
+ args = [str(SC_PY), "-u", str(BUILDER), "--dataset", support["cohort"],
83
+ "--support-manifest", str(support_path), "--work", str(work)]
84
+ if not (work / "inputs/inputs_manifest.json").exists():
85
+ subprocess.run(args, check=True, env=env)
86
+ if not (work / "prepared.json").exists():
87
+ subprocess.run([str(SC_PY), "-u", str(WRAPPER), "--support-manifest", str(support_path),
88
+ "--work", str(work), "--phase", "prepare", "--device", "cpu", "--threads", "2",
89
+ "--lean-hvset"], check=True, env=env)
90
+ return work
91
+
92
+
93
+ def _assert_file(path: Path, expected: str) -> None:
94
+ if not path.is_file() or sha(path) != expected:
95
+ raise ValueError(f"file absent or hash mismatch: {path}")
96
+
97
+
98
+ def _same_rep_cells(old: Path, new: Path) -> None:
99
+ try:
100
+ import anndata as ad
101
+ except ImportError:
102
+ subprocess.run([str(SC_PY), str(Path(__file__)), "--internal-compare", str(old), str(new)], check=True)
103
+ return
104
+ a = ad.read_h5ad(old / "inputs/rep_sc.h5ad")
105
+ b = ad.read_h5ad(new / "inputs/rep_sc.h5ad")
106
+ if not a.obs_names.is_unique or not b.obs_names.is_unique or set(a.obs_names) != set(b.obs_names):
107
+ raise ValueError("representative cell identities differ")
108
+ if not a.var_names.equals(b.var_names):
109
+ raise ValueError("representative gene axis differs")
110
+ b = b[a.obs_names].copy()
111
+ if not a.obs.equals(b.obs) or not a.var.equals(b.var) or (a.X != b.X).nnz:
112
+ raise ValueError("representative observed cells differ after ID alignment")
113
+
114
+
115
+ def verify(support_path: Path) -> dict:
116
+ """Read-only full source/equivalence audit; fail before any adoption write."""
117
+ s, old, new, generated = paths(support_path)
118
+ oi, ni = read(old / "inputs/inputs_manifest.json"), read(new / "inputs/inputs_manifest.json")
119
+ op, np_ = read(old / "prepared.json"), read(new / "prepared.json")
120
+ orun, nrun = read(old / "run_manifest.json"), read(new / "run_manifest.json")
121
+ status = read(old / "status.json")
122
+ receipt = read(generated.with_suffix(".log"))
123
+ if oi.get("mode") != "fewshot" or ni.get("mode") != "strict" or oi.get("smoke") or ni.get("smoke"):
124
+ raise ValueError("source or target is not a complete full five-pair run")
125
+ if any("reuse" in key.lower() for record in (oi, op, orun) for key in record):
126
+ raise ValueError("legacy scSemi reused another run's HVG or checkpoints")
127
+ old_reps = [x["sample_id"] for x in oi["representatives"]]
128
+ new_reps = [x["sample_id"] for x in ni["representatives"]]
129
+ if set(old_reps) != set(new_reps) or new_reps != s["train_sample_ids"] or len(new_reps) != 5:
130
+ raise ValueError("five own representative IDs differ")
131
+ if oi["targets"] != ni["targets"] or ni["targets"] != s["test_sample_ids"]:
132
+ raise ValueError("target IDs/order differ")
133
+ if oi["train_donors"] != ni["train_donors"] or ni["train_donors"] != s["train_donor_ids"]:
134
+ raise ValueError("training donor identities differ")
135
+ if ni.get("support_sha256") != s["sha256"] or ni["sources"].get("support.json") != sha(support_path):
136
+ raise ValueError("strict target input has no exact support binding")
137
+ for key in ("n_representatives", "n_targets", "n_rep_cells", "modeled_genes", "depth",
138
+ "bulk_row_order", "targets", "condition_sample_order"):
139
+ if oi[key] != ni[key]:
140
+ raise ValueError(f"legacy/strict input mismatch: {key}")
141
+ if oi["condition_sha256"] != ni["condition_sha256"]:
142
+ raise ValueError("real bulk raw condition differs")
143
+ if oi["sources"]["features.npz"] != ni["sources"]["features.npz"] or \
144
+ oi["sources"]["folds.csv"] != ni["sources"]["folds.csv"] or \
145
+ oi["sources"]["cells_panel6k.npz"] != ni["sources"]["cells_panel6k.npz"]:
146
+ raise ValueError("base data sources differ")
147
+ for root, m in ((old, oi), (new, ni)):
148
+ for f, digest in m["files"].items():
149
+ _assert_file(root / "inputs" / f, digest)
150
+ if oi["files"]["bulk.h5ad"] != ni["files"]["bulk.h5ad"]:
151
+ raise ValueError("bulk input bytes differ")
152
+ _same_rep_cells(old, new)
153
+ old_protocol = {k: v for k, v in orun["protocol"].items() if k != "hvset_impl"}
154
+ new_protocol = {k: v for k, v in nrun["protocol"].items() if k != "hvset_impl"}
155
+ if old_protocol != new_protocol or orun["protocol"].get("hvset_impl") is not None or \
156
+ not str(nrun["protocol"].get("hvset_impl", "")).startswith("tools/lean_hvset."):
157
+ raise ValueError("scSemi method protocol differs")
158
+ source_provenance = {"old_initial_source": orun["source"], "strict_source": nrun["source"],
159
+ "approved_migration": None}
160
+ if orun["source"] != nrun["source"]:
161
+ migrations = orun.get("migrations", [])
162
+ allowed = read(OLD / "scsemi/compat_migrations.json")["transitions"]
163
+ allowed_ids = {x["id"] for x in allowed}
164
+ witness = next((m for m in migrations if m.get("to_binding", {}).get("source") == nrun["source"]
165
+ and "source" in m.get("changed", []) and
166
+ set(m.get("transitions", [])) <= allowed_ids and
167
+ "trailing_size1_batch_20260928" in m.get("transitions", [])), None)
168
+ if witness is None:
169
+ raise ValueError("old/new vendor source differs without an approved recorded migration")
170
+ source_provenance["approved_migration"] = witness
171
+ for k in ("environment", "lean_cellgraph_sha256", "geneset_mapped_gmt_sha256"):
172
+ if orun[k] != nrun[k]:
173
+ raise ValueError(f"scSemi source/environment differs: {k}")
174
+ if orun["protocol"]["seeds"]["base"] != 20260927:
175
+ raise ValueError("old scSemi seed rule differs")
176
+ if set(op["files"]) != set(np_["files"]):
177
+ raise ValueError("prepared asset lists differ")
178
+ missing_cleaned_source = []
179
+ cleanup_script = OLD / "scsemi/tools/run_queue_scsemi.sh"
180
+ cleanup_text = cleanup_script.read_text()
181
+ for f, digest in op["files"].items():
182
+ source_file = old / "scsemi_project" / f
183
+ if f.startswith("sample_sc/") and not source_file.exists():
184
+ if 'removed sample_sc/*.h5ad (sha256 kept in prepared.json)' not in cleanup_text:
185
+ raise ValueError("source representative cells absent without documented cleanup")
186
+ missing_cleaned_source.append(f)
187
+ else:
188
+ _assert_file(source_file, digest)
189
+ for f, digest in np_["files"].items():
190
+ _assert_file(new / "scsemi_project" / f, digest)
191
+ for f in sorted(set(op["files"]) - EXCLUDE_PREPARED):
192
+ if op["files"][f] != np_["files"][f]:
193
+ raise ValueError(f"n-only prepared/pretraining input differs: {f}")
194
+ if op["files"]["hvset.npy"] != np_["files"]["hvset.npy"]:
195
+ raise ValueError("n-only HVG differs")
196
+ if (not status["pretrain_complete"] or not status["infer_complete"] or status["n_reps"] != 5 or
197
+ status["n_targets"] != len(s["test_sample_ids"]) or status["targets_done"] != len(s["test_sample_ids"])):
198
+ raise ValueError("legacy inference incomplete")
199
+ if op["run_signature"] != orun["run_signature"] or status["run_signature"] != orun["run_signature"]:
200
+ raise ValueError("legacy work signature inconsistent")
201
+ model_hashes = {}
202
+ order = oi["bulk_row_order"]
203
+ for rep in old_reps:
204
+ for stage, stem in ((1, "fast_reconst1_"), (2, "fastreconst2_")):
205
+ file = old / "scsemi_project/models" / f"{stem}{rep}"
206
+ rec_path = file.with_name(file.name + ".receipt.json")
207
+ rec = read(rec_path)
208
+ expected_seed = 20260927 + stage * 1000 + order.index(rep)
209
+ if (not rec.get("complete") or rec["run_signature"] != orun["run_signature"] or
210
+ rec["representative"] != rep or rec["stage"] != stage or rec["seed"] != expected_seed):
211
+ raise ValueError(f"checkpoint receipt/source mismatch: {file}")
212
+ _assert_file(file, rec["sha256"])
213
+ model_hashes[file.name] = rec["sha256"]
214
+ shard_hashes = {}
215
+ for target in s["test_sample_ids"]:
216
+ file = old / "shards" / f"{target}.npz"
217
+ rec = read(old / "shards" / f"{target}.json")
218
+ if (not rec.get("complete") or rec["sample_id"] != target or
219
+ rec["run_signature"] != orun["run_signature"] or
220
+ rec["representative"] not in old_reps or
221
+ rec["target_bulk_index"] != order.index(target) or
222
+ rec["seed"] != 20260927 + order.index(target) or
223
+ not rec.get("lossless_csr_verified")):
224
+ raise ValueError(f"target shard receipt/source mismatch: {target}")
225
+ _assert_file(file, rec["shard_sha256"])
226
+ shard_hashes[target] = rec["shard_sha256"]
227
+ if receipt["run_signature"] != orun["run_signature"] or receipt["condition_sha256"] != ni["condition_sha256"]:
228
+ raise ValueError("old generated output receipt differs from exact strict raw condition")
229
+ if receipt["exporter_sha256"] != sha(EXPORTER_OLD):
230
+ raise ValueError("archived source exporter bytes differ from output receipt")
231
+ _assert_file(generated, receipt["output_sha256"])
232
+ with np.load(generated, allow_pickle=False) as z:
233
+ samples = z["sample_ids"].astype(str).tolist()
234
+ meta = json.loads(str(z["metadata_json"]))
235
+ if samples != s["test_sample_ids"] or z["cells_per_bulk"].tolist() != [1500] * len(samples):
236
+ raise ValueError("old generated sample/cell budget differs")
237
+ if meta["mode"] != "fewshot" or set(meta["representatives"]) != set(new_reps):
238
+ raise ValueError("old generated metadata does not name exact five representatives")
239
+ return {"schema": "pbisc.scsemi.legacy-adoption-proof.v1", "status": "verified_source_not_native_strict_run",
240
+ "cohort": s["cohort"], "unit": s["unit"], "support_sha256": s["sha256"],
241
+ "source_work": str(old), "strict_work": str(new), "source_generated": str(generated),
242
+ "source_generated_sha256": receipt["output_sha256"],
243
+ "source_generated_receipt_sha256": sha(generated.with_suffix(".log")),
244
+ "source_run_signature": orun["run_signature"], "strict_prepared_run_signature": nrun["run_signature"],
245
+ "source_provenance": source_provenance,
246
+ "source_manifest_sha256": {"inputs": sha(old / "inputs/inputs_manifest.json"),
247
+ "prepared": sha(old / "prepared.json"), "run": sha(old / "run_manifest.json")},
248
+ "strict_manifest_sha256": {"inputs": sha(new / "inputs/inputs_manifest.json"),
249
+ "prepared": sha(new / "prepared.json"), "run": sha(new / "run_manifest.json")},
250
+ "prepared_assets_equal": sorted(set(op["files"]) - EXCLUDE_PREPARED),
251
+ "initial_selection_status_excluded": sorted(EXCLUDE_PREPARED),
252
+ "source_sample_sc_cleaned_after_training": missing_cleaned_source,
253
+ "source_cleanup_script_sha256": sha(cleanup_script) if missing_cleaned_source else None,
254
+ "model_sha256": model_hashes, "target_shard_sha256": shard_hashes,
255
+ "scientific_equivalence": "same exact five representatives and target samples, same raw bulk condition, modeled genes, depth, cell counts after identity alignment, n-only HVG and all pretraining assets, protocol/seed and verified source model/shard/output receipts",
256
+ "provenance_limit": "legacy work was run as fewshot, not as a native strict-support run; source signature and old metadata remain unchanged"}
257
+
258
+
259
+ def adopt(support_path: Path) -> dict:
260
+ proof = verify(support_path)
261
+ source = Path(proof["source_work"])
262
+ new = Path(proof["strict_work"])
263
+ generated = Path(proof["source_generated"])
264
+ dest = new / "adopted_legacy"
265
+ dest.mkdir(parents=True, exist_ok=True)
266
+ links = [(generated, dest / generated.name),
267
+ (generated.with_suffix(".log"), dest / generated.with_suffix(".log").name)]
268
+ for name in ("inputs/inputs_manifest.json", "prepared.json", "run_manifest.json", "status.json"):
269
+ links.append((source / name, dest / name))
270
+ for name in proof["prepared_assets_equal"]:
271
+ if name not in proof["source_sample_sc_cleaned_after_training"]:
272
+ links.append((source / "scsemi_project" / name, dest / "scsemi_project" / name))
273
+ for name in proof["model_sha256"]:
274
+ file = source / "scsemi_project/models" / name
275
+ links.extend([(file, dest / "scsemi_project/models" / name),
276
+ (file.with_name(name + ".receipt.json"), dest / "scsemi_project/models" / (name + ".receipt.json"))])
277
+ for target in proof["target_shard_sha256"]:
278
+ for suffix in ("npz", "json"):
279
+ links.append((source / "shards" / f"{target}.{suffix}", dest / "shards" / f"{target}.{suffix}"))
280
+ for src, target in links:
281
+ target.parent.mkdir(parents=True, exist_ok=True)
282
+ if target.exists():
283
+ if not target.is_file() or sha(target) != sha(src):
284
+ raise ValueError(f"existing adoption evidence differs: {target}")
285
+ else:
286
+ os.link(src, target)
287
+ proof["adopted_evidence_dir"] = str(dest)
288
+ proof["linked_files"] = len(links)
289
+ path = dest / "ADOPTION.json"
290
+ if path.exists():
291
+ if read(path) != proof:
292
+ raise ValueError("existing adoption receipt differs from current verified source")
293
+ else:
294
+ path.write_text(json.dumps(proof, indent=2) + "\n")
295
+ return proof
296
+
297
+
298
+ def export_adopted(support_path: Path) -> dict:
299
+ """Publish bit-identical old cells with a truthful adoption receipt; validate all shards."""
300
+ preflight()
301
+ proof = verify(support_path)
302
+ source = Path(proof["source_generated"])
303
+ old = Path(proof["source_work"])
304
+ new = Path(proof["strict_work"])
305
+ adoption_path = new / "adopted_legacy/ADOPTION.json"
306
+ if not adoption_path.is_file():
307
+ raise ValueError("source not adopted into strict work")
308
+ adopted = read(adoption_path)
309
+ for key, value in proof.items():
310
+ if adopted.get(key) != value:
311
+ raise ValueError(f"adoption receipt/source changed: {key}")
312
+ if adopted.get("adopted_evidence_dir") != str(adoption_path.parent) or adopted.get("linked_files", 0) < 1:
313
+ raise ValueError("adoption evidence incomplete")
314
+ adopted_source = adoption_path.parent / source.name
315
+ if not adopted_source.is_file() or not os.path.samefile(source, adopted_source):
316
+ raise ValueError("adopted generated source hardlink differs")
317
+ draw = proof["unit"].removesuffix("_n5")
318
+ out = PLAN / "generated" / proof["cohort"] / "disease" / draw / "scsemi.npz"
319
+ out.parent.mkdir(parents=True, exist_ok=True)
320
+ if out.exists():
321
+ if not os.path.samefile(out, adopted_source):
322
+ raise ValueError("canonical strict arm already exists with different source")
323
+ else:
324
+ os.link(adopted_source, out)
325
+ strict_condition = PLAN / "data" / proof["cohort"] / "disease" / draw / "test_raw.npz"
326
+ old_log = read(source.with_suffix(".log"))
327
+ if sha(strict_condition) != old_log["condition_sha256"]:
328
+ raise ValueError("strict raw condition no longer equals legacy generation condition")
329
+ receipt = {"schema": "pbisc.scsemi.adopted-output.v1", "output": str(out),
330
+ "output_sha256": proof["source_generated_sha256"],
331
+ "support_sha256": proof["support_sha256"],
332
+ "condition_npz": str(strict_condition), "condition_sha256": old_log["condition_sha256"],
333
+ "source_condition_npz": old_log["condition_npz"],
334
+ "source_output": str(source), "source_output_sha256": proof["source_generated_sha256"],
335
+ "source_receipt_sha256": proof["source_generated_receipt_sha256"],
336
+ "source_work": str(old), "strict_prepared_work": str(new),
337
+ "adoption_receipt": str(adoption_path), "adoption_receipt_sha256": sha(adoption_path),
338
+ "run_signature": proof["source_run_signature"],
339
+ "provenance": "hardlink of legacy fewshot output; no native strict GPU training or inference claimed"}
340
+ log_path = out.with_suffix(".log")
341
+ if log_path.exists():
342
+ if read(log_path) != receipt:
343
+ raise ValueError("existing adopted output receipt differs")
344
+ else:
345
+ log_path.write_text(json.dumps(receipt, indent=2) + "\n")
346
+ # Legacy independent validator recomputes each exported cell from the old,
347
+ # sha-checked shard and verifies the original metadata's real bulk source.
348
+ env = {**os.environ, "CUDA_VISIBLE_DEVICES": "", "OMP_NUM_THREADS": "2", "OPENBLAS_NUM_THREADS": "2"}
349
+ subprocess.run([str(SC_PY), str(OLD / "scsemi/tools/validate_export.py"),
350
+ "--work", str(old), "--npz", str(out)], check=True, env=env)
351
+ validation = read(out.with_suffix(".validation.json"))
352
+ if validation.get("passed") is not True or validation.get("npz_sha256") != receipt["output_sha256"]:
353
+ raise ValueError("legacy independent shard-level export validation failed")
354
+ return {"schema": "pbisc.scsemi.adopted-output-status.v1", "status": "validated_legacy_adoption",
355
+ "support_sha256": proof["support_sha256"], "output": str(out),
356
+ "output_sha256": receipt["output_sha256"], "adoption_receipt": str(adoption_path),
357
+ "validation": str(out.with_suffix(".validation.json")),
358
+ "validation_sha256": sha(out.with_suffix(".validation.json"))}
359
+
360
+
361
+ def validate_adopted_generation(path: Path, support: dict) -> dict:
362
+ """Scorer binding for verified legacy sepsis output; never relabel native training."""
363
+ cohort, unit = support.get("cohort"), support.get("unit")
364
+ if cohort != "ye2026_sepsis" or not re.fullmatch(r"draw[0-4]_n5", str(unit)):
365
+ raise ValueError("adopted scSemi is limited to exact-five sepsis draws")
366
+ draw = unit.removesuffix("_n5")
367
+ canonical_support = PLAN / "protocol/splits" / cohort / "disease" / draw / "support.json"
368
+ s, old, strict_work, source = paths(canonical_support)
369
+ if s["sha256"] != support.get("sha256") or s["train_sample_ids"] != support.get("train_sample_ids") or \
370
+ s["test_sample_ids"] != support.get("test_sample_ids"):
371
+ raise ValueError("adoption support differs from canonical strict support")
372
+ expected = PLAN / "generated" / cohort / "disease" / draw / "scsemi.npz"
373
+ path = Path(path).resolve()
374
+ if path != expected.resolve() or not path.is_file() or not os.path.samefile(path, source):
375
+ raise ValueError("canonical adopted output is absent or no longer the source hardlink")
376
+ proof = verify(canonical_support)
377
+ adoption_path = strict_work / "adopted_legacy/ADOPTION.json"
378
+ adoption = read(adoption_path)
379
+ for key, value in proof.items():
380
+ if adoption.get(key) != value:
381
+ raise ValueError(f"adoption source proof differs: {key}")
382
+ if adoption.get("adopted_evidence_dir") != str(adoption_path.parent) or adoption.get("linked_files", 0) < 1:
383
+ raise ValueError("adoption receipt has no linked evidence")
384
+ receipt_path = path.with_suffix(".log")
385
+ receipt = read(receipt_path)
386
+ strict_condition = PLAN / "data" / cohort / "disease" / draw / "test_raw.npz"
387
+ source_receipt = read(source.with_suffix(".log"))
388
+ expected_fields = {"schema": "pbisc.scsemi.adopted-output.v1", "output": str(path),
389
+ "output_sha256": proof["source_generated_sha256"],
390
+ "support_sha256": s["sha256"], "condition_npz": str(strict_condition),
391
+ "condition_sha256": source_receipt["condition_sha256"],
392
+ "source_condition_npz": source_receipt["condition_npz"],
393
+ "source_output": str(source),
394
+ "source_output_sha256": proof["source_generated_sha256"],
395
+ "source_receipt_sha256": proof["source_generated_receipt_sha256"],
396
+ "source_work": str(old), "strict_prepared_work": str(strict_work),
397
+ "adoption_receipt": str(adoption_path), "adoption_receipt_sha256": sha(adoption_path),
398
+ "run_signature": proof["source_run_signature"]}
399
+ if any(receipt.get(k) != v for k, v in expected_fields.items()):
400
+ raise ValueError("adopted output receipt differs from source and strict support")
401
+ if sha(path) != receipt["output_sha256"] or sha(strict_condition) != receipt["condition_sha256"]:
402
+ raise ValueError("adopted cells or strict raw condition changed")
403
+ validation_path = path.with_suffix(".validation.json")
404
+ validation = read(validation_path)
405
+ if (validation.get("passed") is not True or validation.get("npz") != str(path) or
406
+ validation.get("npz_sha256") != receipt["output_sha256"] or
407
+ validation.get("targets") != len(s["test_sample_ids"]) or
408
+ validation.get("cells") != 1500 * len(s["test_sample_ids"]) or
409
+ validation.get("modeled_genes") != 5975):
410
+ raise ValueError("independent legacy shard-level validation absent or mismatched")
411
+ with np.load(path, allow_pickle=False) as z:
412
+ if z["sample_ids"].astype(str).tolist() != s["test_sample_ids"]:
413
+ raise ValueError("adopted output has extra or missing test samples")
414
+ metadata = json.loads(str(z["metadata_json"]))
415
+ old_inputs = read(old / "inputs/inputs_manifest.json")
416
+ if (metadata.get("work") != str(old) or metadata.get("mode") != "fewshot" or
417
+ metadata.get("arm") != "scsemi5" or metadata.get("run_signature") != proof["source_run_signature"] or
418
+ metadata.get("input_condition_path") != source_receipt["condition_npz"] or
419
+ metadata.get("input_condition_sha256") != source_receipt["condition_sha256"] or
420
+ set(metadata.get("representatives", [])) != set(s["train_sample_ids"]) or
421
+ metadata.get("seed") != 20260927 or metadata.get("unit") != "expected_counts (Poisson rates)" or
422
+ metadata.get("n_modeled_genes") != old_inputs["modeled_genes"]["n"] or
423
+ source_receipt.get("seed") != 20260927 or source_receipt.get("cells") != 115500 or
424
+ source_receipt.get("genes") != 6000 or source_receipt.get("modeled_genes") != 5975):
425
+ raise ValueError("embedded source metadata/readout differs from verified legacy run")
426
+ return {"arm": "scsemi", "npz": str(path), "npz_sha256": receipt["output_sha256"],
427
+ "receipt": str(receipt_path), "receipt_sha256": sha(receipt_path),
428
+ "source_binding": str(adoption_path), "source_binding_sha256": sha(adoption_path),
429
+ "condition_npz": str(strict_condition), "condition_sha256": receipt["condition_sha256"],
430
+ "checkpoint_sha256": None, "support_sha256": s["sha256"],
431
+ "source_kind": "verified_legacy_scsemi_adoption", "validation_sha256": sha(validation_path)}
432
+
433
+
434
+ def main(argv: list[str] | None = None) -> int:
435
+ p = argparse.ArgumentParser(description=__doc__)
436
+ p.add_argument("--support-manifest", required=True, type=Path)
437
+ p.add_argument("--action", required=True, choices=("prepare", "verify", "adopt", "export", "all"))
438
+ a = p.parse_args(argv)
439
+ if a.action in {"prepare", "all"}:
440
+ print(json.dumps({"prepared_strict_work": str(prepare(a.support_manifest))}), flush=True)
441
+ if a.action in {"verify", "all"}:
442
+ proof = verify(a.support_manifest)
443
+ print(json.dumps({"status": proof["status"], "unit": proof["unit"],
444
+ "n_model_receipts": len(proof["model_sha256"]),
445
+ "n_target_shards": len(proof["target_shard_sha256"]),
446
+ "n_equal_prepared_assets": len(proof["prepared_assets_equal"])}), flush=True)
447
+ if a.action == "adopt":
448
+ proof = adopt(a.support_manifest)
449
+ print(json.dumps({"status": proof["status"], "unit": proof["unit"],
450
+ "adopted_evidence_dir": proof["adopted_evidence_dir"],
451
+ "linked_files": proof["linked_files"]}), flush=True)
452
+ if a.action == "export":
453
+ print(json.dumps(export_adopted(a.support_manifest)), flush=True)
454
+ return 0
455
+
456
+
457
+ if __name__ == "__main__":
458
+ if len(sys.argv) == 4 and sys.argv[1] == "--internal-compare":
459
+ _same_rep_cells(Path(sys.argv[2]), Path(sys.argv[3]))
460
+ raise SystemExit(0)
461
+ 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/prepare_controls.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """External AIFI calibration using target bulk and assay metadata, never target sc expression."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ import sys
9
+
10
+ import numpy as np
11
+
12
+ ROOT = Path(__file__).resolve().parents[1]
13
+ M8 = ROOT.parents[1]
14
+ LEGACY = M8 / "plans/paired_finetune_intradataset_20260927"
15
+ REFERENCE = M8 / "plans/utility_studies_final6k_20260925/refcal/reference/aifi_donor_pseudobulk_20097.npz"
16
+ COHORTS = ("immicro", "ye2026_sepsis", "imperial_eskd", "giroux2022", "ji2025_chili")
17
+
18
+
19
+ def cpm(counts: np.ndarray) -> np.ndarray:
20
+ x = np.asarray(counts, dtype=np.float64)
21
+ if x.ndim != 2 or not np.isfinite(x).all() or (x < 0).any() or (x.sum(axis=1) <= 0).any():
22
+ raise ValueError("counts must be finite non-negative rows with positive totals")
23
+ return x / x.sum(axis=1, keepdims=True) * 1e6
24
+
25
+
26
+ def external_multiplier(bulk: np.ndarray, bulk_valid: np.ndarray,
27
+ reference_counts: np.ndarray, reference_present: np.ndarray) -> np.ndarray:
28
+ bulk = np.asarray(bulk, dtype=np.float64)
29
+ valid = np.asarray(bulk_valid, dtype=bool)
30
+ present = np.asarray(reference_present, dtype=bool)
31
+ if bulk.shape != valid.shape or present.shape != (bulk.shape[1],):
32
+ raise ValueError("assay mask or gene axis mismatch")
33
+ b = cpm(np.where(valid, bulk, 0)).mean(axis=0)
34
+ ref = cpm(reference_counts).mean(axis=0)
35
+ if ref.shape != b.shape:
36
+ raise ValueError("external reference gene axis mismatch")
37
+ keep = valid.all(axis=0) & present & (b >= 1.) & (ref >= 1.)
38
+ alpha = np.ones_like(b)
39
+ alpha[keep] = ref[keep] / b[keep]
40
+ return alpha
41
+
42
+
43
+ def prepare(cohort: str) -> dict:
44
+ import pandas as pd
45
+ from runtime import atomic_json, sha256
46
+
47
+ sys.path.insert(0, str(LEGACY / "tools"))
48
+ import prepare_dataset as PD
49
+
50
+ data = LEGACY / "data" / cohort
51
+ out = ROOT / "data/external_refcal" / cohort
52
+ sources = [data / "features.npz", data / "folds.csv", REFERENCE, ROOT / "protocol/PROTOCOL.json"]
53
+ input_hashes = {str(p): sha256(p) for p in sources}
54
+ receipt = out / "BUILD.json"
55
+ if receipt.exists():
56
+ old = json.loads(receipt.read_text())
57
+ if old["input_hashes"] != input_hashes:
58
+ raise ValueError("external-calibration inputs changed; create a new version")
59
+ if all(Path(p).is_file() and sha256(Path(p)) == h for p, h in old["outputs"].items()):
60
+ return old
61
+ raise ValueError("external-calibration output changed or missing")
62
+ if out.exists() and any(out.iterdir()):
63
+ raise ValueError(f"unreceipted conditions exist at {out}; preserve and inspect")
64
+ out.mkdir(parents=True, exist_ok=True)
65
+ folds = pd.read_csv(data / "folds.csv")
66
+ with np.load(data / "features.npz", allow_pickle=False) as z:
67
+ # Do not call PD.load: that convenience function also materialises target pseudo_raw_sum.
68
+ ids = (z["sample_ids"] if "sample_ids" in z.files else z["donor_ids"]).astype(str)
69
+ if not np.array_equal(ids, folds.sample_id.astype(str).to_numpy()):
70
+ raise ValueError("features and folds disagree")
71
+ d = {"gene_ids": z["gene_ids"].astype(str), "sample_ids": ids,
72
+ "donor_ids": folds.donor_id.astype(str).to_numpy(), "groups": folds.group.astype(str).to_numpy(),
73
+ "sc_valid": z["sc_valid"].astype(bool), "n_cells": np.full(len(ids), -1, np.int64)}
74
+ valid = z["bulk_valid"].astype(bool)
75
+ bulk = np.where(valid, z["bulk_raw"], 0).astype(np.float64)
76
+ rows = np.flatnonzero(folds.fold.to_numpy() >= 0)
77
+ with np.load(REFERENCE, allow_pickle=False) as z:
78
+ if not np.array_equal(z["gene_ids"].astype(str), d["gene_ids"]):
79
+ raise ValueError("AIFI and cohort gene axes differ")
80
+ alpha = external_multiplier(bulk[rows], valid[rows], z["sums_full"], z["present"])
81
+ n_reference_donors = len(z["donor_ids"])
82
+ adjusted = cpm(bulk) * alpha[None, :]
83
+ counts = PD.RB.to_condition_counts(adjusted, valid)
84
+ raw = PD.RB.to_condition_counts(bulk, valid)
85
+ outputs = {}
86
+ for arm, arr in (("refcal", counts), ("raw", raw)):
87
+ p = out / f"conditions_{arm}.npz"
88
+ outputs[str(p)] = PD.write_npz(p, d, rows, arr, valid, 1500, f"strict_{arm}")
89
+ np.save(out / "alpha.npy", alpha)
90
+ outputs[str(out / "alpha.npy")] = sha256(out / "alpha.npy")
91
+ rec = {"schema": "pbisc.strict.external-reference.v1", "cohort": cohort,
92
+ "input_hashes": input_hashes, "outputs": outputs,
93
+ "target_bulk_anchor_sample_ids": ids[rows].tolist(), "target_sc_expression_accessed": False,
94
+ "output_assay_mask_source": "pre-existing structural assay metadata; no expression/depth fitting",
95
+ "reference": "external AIFI donor-mean CPM", "reference_donors": n_reference_donors,
96
+ "paired_target_samples_used": 0, "transductive_target_bulk": True,
97
+ "K_cond": 1000, "rho": 3869.603120208939, "N_gen": 1500,
98
+ "alpha_genes": int((alpha != 1.).sum())}
99
+ atomic_json(receipt, rec)
100
+ return rec
101
+
102
+
103
+ def main() -> None:
104
+ p = argparse.ArgumentParser(description=__doc__)
105
+ p.add_argument("--dataset", choices=COHORTS)
106
+ p.add_argument("--all", action="store_true")
107
+ a = p.parse_args()
108
+ if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
109
+ raise SystemExit("CPU builder requires CUDA_VISIBLE_DEVICES=''")
110
+ if not a.dataset and not a.all:
111
+ p.error("choose --dataset or --all")
112
+ for cohort in COHORTS if a.all else (a.dataset,):
113
+ rec = prepare(cohort)
114
+ print(json.dumps({"cohort": cohort, "samples": len(rec["target_bulk_anchor_sample_ids"]),
115
+ "alpha_genes": rec["alpha_genes"]}), flush=True)
116
+
117
+
118
+ if __name__ == "__main__":
119
+ 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/prepare_strict_pairs.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Materialize immutable exact-support manifests; optionally prepare CPU condition arrays.
3
+
4
+ Usage: python prepare_strict_pairs.py --all [--conditions]
5
+ python prepare_strict_pairs.py --dataset immicro [--conditions]
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import importlib.util
11
+ import json
12
+ import os
13
+ import sys
14
+ from pathlib import Path
15
+
16
+ if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
17
+ raise SystemExit("CPU preparation requires CUDA_VISIBLE_DEVICES=''")
18
+
19
+ import numpy as np
20
+ import pandas as pd
21
+
22
+ HERE = Path(__file__).resolve().parents[1]
23
+ M8 = HERE.parents[1]
24
+ OLD = M8 / "plans/paired_finetune_intradataset_20260927"
25
+ sys.path.insert(0, str(HERE / "tools"))
26
+ import support_manifest as SM # noqa: E402
27
+
28
+ DISEASE = ("ye2026_sepsis", "imperial_eskd", "giroux2022", "ji2025_chili")
29
+ STRATA = {"ye2026_sepsis": "sepsis", "imperial_eskd": "positive", "giroux2022": "severe",
30
+ "ji2025_chili": "TOL|FU1"}
31
+
32
+
33
+ def _load_pd():
34
+ path = OLD / "tools/prepare_dataset.py"
35
+ spec = importlib.util.spec_from_file_location("paired_prepare_dataset", path)
36
+ mod = importlib.util.module_from_spec(spec)
37
+ sys.modules[spec.name] = mod
38
+ spec.loader.exec_module(mod)
39
+ return mod
40
+
41
+
42
+ def _unit_paths(cohort: str, m: dict) -> tuple[Path, Path]:
43
+ suffix = (Path("healthy") / m["unit"].split("_n")[0] / ("n" + str(m["n_pairs"]))
44
+ if cohort == "immicro" else Path("disease") / m["unit"].split("_n")[0])
45
+ return HERE / "protocol/splits" / cohort / suffix / "support.json", HERE / "data" / cohort / suffix
46
+
47
+
48
+ def _prepare_conditions(cohort: str, m: dict, out: Path, folds: pd.DataFrame) -> None:
49
+ if out.exists() and any(out.iterdir()):
50
+ raise FileExistsError(f"condition output already exists: {out}")
51
+ PD = _load_pd()
52
+ d = PD.load(OLD / "data" / cohort)
53
+ if d["sample_ids"].astype(str).tolist() != folds.sample_id.astype(str).tolist():
54
+ raise ValueError("features and folds order mismatch")
55
+ pos = {s: i for i, s in enumerate(d["sample_ids"].astype(str))}
56
+ train = np.asarray([pos[s] for s in m["train_sample_ids"]], dtype=np.int64)
57
+ test = np.asarray([pos[s] for s in m["test_sample_ids"]], dtype=np.int64)
58
+ valid = d["bulk_valid"][train].all(axis=0) & d["sc_valid"][train].all(axis=0)
59
+ alpha = PD.RB.gene_multiplier(d["bulk"][train], d["pseudo"][train], valid)
60
+ raw = PD.RB.to_condition_counts(d["bulk"], d["bulk_valid"])
61
+ cal = PD.RB.to_condition_counts(PD.RB.cpm(d["bulk"]) * alpha[None, :], d["bulk_valid"])
62
+ out.mkdir(parents=True, exist_ok=False)
63
+ np.save(out / "alpha.npy", alpha)
64
+ hashes = {}
65
+ for arm, arr in (("raw", raw), ("cal", cal)):
66
+ hashes[f"test_{arm}.npz"] = PD.write_npz(out / f"test_{arm}.npz", d, test, arr,
67
+ d["bulk_valid"], 1500, arm)
68
+ (out / "test_samples.txt").write_text("\n".join(m["test_sample_ids"]) + "\n")
69
+ (out / "train_samples.txt").write_text("\n".join(m["train_sample_ids"]) + "\n")
70
+ (out / "CONDITIONS.json").write_text(json.dumps({"support_sha256": m["sha256"],
71
+ "support_path": str(_unit_paths(cohort, m)[0]),
72
+ "fit_sample_ids": m["train_sample_ids"],
73
+ "alpha_genes_estimated": int((alpha != 1.0).sum()),
74
+ "files_sha256": hashes}, indent=2) + "\n")
75
+
76
+
77
+ def prepare(cohort: str, *, conditions: bool = False, unit: str | None = None) -> list[Path]:
78
+ if cohort not in ("immicro", *DISEASE):
79
+ raise ValueError(f"unknown cohort {cohort}")
80
+ ds = OLD / "data" / cohort
81
+ folds = pd.read_csv(ds / "folds.csv", dtype={"sample_id": str, "donor_id": str})
82
+ manifests = []
83
+ if cohort == "immicro":
84
+ units = (SM.build_healthy(folds, fold, n, seed=20261012 + fold)
85
+ for fold in range(5) for n in (5, 10, 20, 40))
86
+ else:
87
+ pairs = pd.read_csv(ds / "pairs.csv", dtype={"sample_id": str, "donor_id": str})
88
+ units = (SM.build_disease(folds, pairs,
89
+ (ds / f"fewshot_n5/draw{draw}/train_donors.txt").read_text().splitlines(),
90
+ cohort, draw, strata_regex=STRATA[cohort]) for draw in range(5))
91
+ for m in units:
92
+ if unit is not None and m["unit"] != unit:
93
+ continue
94
+ if cohort in DISEASE and m["n_pairs"] != 5:
95
+ raise ValueError("disease draw must contain five pairs")
96
+ path, out = _unit_paths(cohort, m)
97
+ if path.exists():
98
+ old = SM.load_manifest(path, folds)
99
+ if old != m:
100
+ raise FileExistsError(f"different support exists: {path}")
101
+ else:
102
+ SM.write_manifest(path, m)
103
+ if conditions:
104
+ _prepare_conditions(cohort, m, out, folds)
105
+ manifests.append(path)
106
+ return manifests
107
+
108
+
109
+ def main(argv: list[str] | None = None) -> int:
110
+ ap = argparse.ArgumentParser(description=__doc__)
111
+ group = ap.add_mutually_exclusive_group(required=True)
112
+ group.add_argument("--all", action="store_true")
113
+ group.add_argument("--dataset", choices=("immicro", *DISEASE))
114
+ ap.add_argument("--conditions", action="store_true", help="write test_raw/test_cal arrays using only support pairs")
115
+ ap.add_argument("--unit", help="one unit, e.g. fold0_n5 or draw0_n5; requires --dataset")
116
+ a = ap.parse_args(argv)
117
+ if a.unit and a.all:
118
+ ap.error("--unit requires --dataset")
119
+ cohorts = ("immicro", *DISEASE) if a.all else (a.dataset,)
120
+ result = {cohort: len(prepare(cohort, conditions=a.conditions, unit=a.unit)) for cohort in cohorts}
121
+ if a.unit and result[a.dataset] != 1:
122
+ ap.error(f"unit {a.unit!r} not found")
123
+ print(json.dumps({"prepared_support_units": result, "conditions": a.conditions}))
124
+ return 0
125
+
126
+
127
+ if __name__ == "__main__":
128
+ 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/rare_cache_builder.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build strict Figure 5 marker caches from generated NPZs and score_ft labels.
3
+
4
+ The 6k generated array is streamed from ZIP to temporary disk and read via mmap.
5
+ Poisson draws cover every NPZ row in original order, including unscored rows.
6
+ No CUDA, model inference, or training occurs here.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import hashlib
12
+ import json
13
+ import os
14
+ import shutil
15
+ import tempfile
16
+ import zipfile
17
+ from pathlib import Path
18
+
19
+ if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
20
+ raise SystemExit("cache builder requires CUDA_VISIBLE_DEVICES=''")
21
+
22
+ import numpy as np
23
+ import pandas as pd
24
+
25
+ from build_figure5 import FT, HERE, _observed_legacy
26
+
27
+ M8 = HERE.parents[1]
28
+ STATES = M8 / "plans/rare_states_screen_20261004/tools/states.json"
29
+ CANON = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/"
30
+ "strict_qc_v1_20260913/reference/canonical_genes.tsv")
31
+ POISSON_SEED = 20260916
32
+
33
+
34
+ def sha256(path: Path) -> str:
35
+ h = hashlib.sha256()
36
+ with path.open("rb") as f:
37
+ for block in iter(lambda: f.read(4 << 20), b""):
38
+ h.update(block)
39
+ return h.hexdigest()
40
+
41
+
42
+ def support_digest(data: dict) -> str:
43
+ body = {k: v for k, v in data.items() if k != "sha256"}
44
+ return hashlib.sha256(json.dumps(body, sort_keys=True, separators=(",", ":"),
45
+ allow_nan=False).encode()).hexdigest()
46
+
47
+
48
+ def read_support(path: Path) -> dict:
49
+ x = json.loads(path.read_text())
50
+ if x.get("schema") != "pbisc.paper.strict-support.v1" or x.get("sha256") != support_digest(x):
51
+ raise ValueError("strict support schema/hash mismatch")
52
+ if len(x["train_sample_ids"]) != 5 or len(set(x["train_donor_ids"])) != 5:
53
+ raise ValueError("support is not five unique donor pairs")
54
+ if set(x["train_donor_ids"]) & set(x["test_donor_ids"]):
55
+ raise ValueError("support train/test donor overlap")
56
+ return x
57
+
58
+
59
+ def _panel(cohort: str, states: list[dict]) -> tuple[np.ndarray, np.ndarray, list[str], np.ndarray]:
60
+ with np.load(FT / "data" / cohort / "cells_panel6k.npz", allow_pickle=False) as z:
61
+ panel = z["panel_gene_ids"].astype(str)
62
+ measured = z["panel_measured"].any(axis=0)
63
+ canon = pd.read_csv(CANON, sep="\t", dtype=str)
64
+ sym2id = dict(zip(canon.gene_symbol, canon.gene_id))
65
+ pos = {g: i for i, g in enumerate(panel)}
66
+ genes = list(dict.fromkeys(g for st in states for g in
67
+ (st.get("genes", []) + [v for group in st.get("require_any", []) for v in group]
68
+ + st.get("exclude", []))))
69
+ symbols = [g for g in genes if sym2id.get(g) in pos and measured[pos[sym2id[g]]]]
70
+ cols = np.array([pos[sym2id[g]] for g in symbols], dtype=int)
71
+ return panel, measured, symbols, cols
72
+
73
+
74
+ def _score_rows(score: Path, arm: str, support: dict) -> tuple[pd.DataFrame, pd.DataFrame]:
75
+ gc = pd.read_parquet(score / "arms" / arm / "generated_cells.parquet")
76
+ lab = pd.read_parquet(score / "arms" / arm / "labels/labels.parquet")
77
+ if len(gc) != len(lab) or not np.array_equal(
78
+ lab.sample_id.astype(str).str.removesuffix("|generated"), gc.donor.astype(str)
79
+ ):
80
+ raise ValueError(f"{arm}: scored cells and labels are not row aligned")
81
+ if set(gc.donor.astype(str)) != set(support["test_sample_ids"]):
82
+ raise ValueError(f"{arm}: score rows differ from strict test samples")
83
+ if gc.npz_row.duplicated().any() or gc.npz_row.isna().any():
84
+ raise ValueError(f"{arm}: duplicate or missing NPZ row")
85
+ return gc, lab
86
+
87
+
88
+ def validate_score_arm(score: Path, arm: str, npz_path: Path, npz_sha: str,
89
+ support: dict) -> tuple[Path, str, Path, str]:
90
+ binding_path = score.parent / "scoring_support.json"
91
+ if not binding_path.is_file():
92
+ raise ValueError(f"{arm}: scoring support binding missing")
93
+ binding = json.loads(binding_path.read_text())
94
+ expected_binding = {
95
+ "schema": "pbisc.paper.strict-score-binding.v1",
96
+ "support_sha256": support["sha256"],
97
+ "cohort": support["cohort"],
98
+ "unit": support["unit"],
99
+ "test_sample_ids": support["test_sample_ids"],
100
+ "test_donor_ids": support["test_donor_ids"],
101
+ }
102
+ if any(binding.get(k) != v for k, v in expected_binding.items()):
103
+ raise ValueError(f"{arm}: scoring support binding mismatch")
104
+ summary_path = score / "summary.json"
105
+ summary = json.loads(summary_path.read_text())
106
+ if (summary.get("schema") != "paired_ft_scores.v1" or
107
+ summary.get("dataset") != support["cohort"] or
108
+ set(summary.get("donors", [])) != set(support["test_sample_ids"]) or
109
+ arm not in summary.get("arms", [])):
110
+ raise ValueError(f"{arm}: score summary not bound to strict cohort/test support")
111
+ scored = summary.get("per_arm", {}).get(arm, {})
112
+ if (scored.get("npz_sha256") != npz_sha or
113
+ Path(scored.get("npz", "")).resolve() != npz_path.resolve() or
114
+ scored.get("receipt_verified") is not True):
115
+ raise ValueError(f"{arm}: generated NPZ differs from scorer arm provenance")
116
+ if (scored.get("poisson", {}).get("seed") != POISSON_SEED or
117
+ scored.get("poisson", {}).get("rule") != "whole NPZ, rows in NPZ order"):
118
+ raise ValueError(f"{arm}: scorer Poisson provenance differs")
119
+ return summary_path, sha256(summary_path), binding_path, sha256(binding_path)
120
+
121
+
122
+ def _stream_poisson(
123
+ rates: np.ndarray, selected: np.ndarray, measured: np.ndarray,
124
+ marker_cols: np.ndarray, score_cols: np.ndarray, *, chunk_rows: int = 512
125
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
126
+ """Small-memory exact whole-NPZ draw, then selected scored rows in their parquet order."""
127
+ n, genes = rates.shape
128
+ if selected.min(initial=0) < 0 or selected.max(initial=-1) >= n or len(set(selected)) != len(selected):
129
+ raise ValueError("scored NPZ row indices are invalid")
130
+ order = np.argsort(selected)
131
+ sorted_sel = selected[order]
132
+ markers = np.empty((len(selected), len(marker_cols)), dtype=np.int32)
133
+ libs = np.empty(len(selected), dtype=np.float32)
134
+ umis = np.empty(len(selected), dtype=np.float32)
135
+ rng = np.random.default_rng(POISSON_SEED)
136
+ for start in range(0, n, chunk_rows):
137
+ stop = min(start + chunk_rows, n)
138
+ block = np.asarray(rates[start:stop], dtype=np.float64)
139
+ if not np.isfinite(block).all() or (block < 0).any():
140
+ raise ValueError(f"invalid Poisson rates in rows {start}:{stop}")
141
+ drawn = rng.poisson(block)
142
+ lo, hi = np.searchsorted(sorted_sel, [start, stop])
143
+ if hi > lo:
144
+ dst = order[lo:hi]
145
+ chosen = drawn[sorted_sel[lo:hi] - start]
146
+ markers[dst] = chosen[:, marker_cols]
147
+ libs[dst] = chosen[:, measured].sum(axis=1)
148
+ umis[dst] = chosen[:, score_cols].sum(axis=1)
149
+ return markers, libs, umis
150
+
151
+
152
+ def build_arm(npz_path: Path, score: Path, arm: str, support: dict, output: Path,
153
+ panel: np.ndarray, measured: np.ndarray, symbols: list[str],
154
+ marker_cols: np.ndarray, score_cols: np.ndarray) -> dict:
155
+ receipt_path = npz_path.with_suffix(".log")
156
+ if not receipt_path.is_file():
157
+ raise ValueError(f"{arm}: generation receipt absent")
158
+ receipt = json.loads(receipt_path.read_text())
159
+ actual_sha = sha256(npz_path)
160
+ if receipt.get("output_sha256") != actual_sha:
161
+ raise ValueError(f"{arm}: generated NPZ differs from receipt")
162
+ summary_path, summary_sha, binding_path, binding_sha = validate_score_arm(
163
+ score, arm, npz_path, actual_sha, support)
164
+ gc, lab = _score_rows(score, arm, support)
165
+ with zipfile.ZipFile(npz_path) as z:
166
+ with z.open("gene_ids.npy") as f:
167
+ ids = np.load(f, allow_pickle=False).astype(str)
168
+ with z.open("sample_ids.npy") as f:
169
+ sample_ids = np.load(f, allow_pickle=False).astype(str)
170
+ with z.open("bulk_index.npy") as f:
171
+ bulk_index = np.load(f, allow_pickle=False).astype(int)
172
+ if not np.array_equal(ids, panel):
173
+ raise ValueError(f"{arm}: generated gene panel differs")
174
+ selected = gc.npz_row.to_numpy(dtype=np.int64)
175
+ if selected.max(initial=-1) >= len(bulk_index) or selected.min(initial=0) < 0:
176
+ raise ValueError(f"{arm}: scored row outside generated NPZ")
177
+ if not np.array_equal(sample_ids[bulk_index[selected]], gc.donor.astype(str)):
178
+ raise ValueError(f"{arm}: scored sample IDs differ from generated NPZ")
179
+ output.parent.mkdir(parents=True, exist_ok=True)
180
+ with tempfile.TemporaryDirectory(prefix="rare-npz-", dir=output.parent) as temp:
181
+ temp_npy = Path(temp) / "generated_counts.npy"
182
+ with z.open("generated_counts.npy") as source, temp_npy.open("wb") as dest:
183
+ shutil.copyfileobj(source, dest, length=4 << 20)
184
+ rates = np.load(temp_npy, mmap_mode="r", allow_pickle=False)
185
+ markers, libs, umis = _stream_poisson(rates, selected, measured, marker_cols, score_cols)
186
+ del rates
187
+ if not np.array_equal(umis, gc.umi_scoring_genes.to_numpy()):
188
+ raise ValueError(f"{arm}: benchmark UMI readout mismatch")
189
+ rec = {"schema": "pbisc.figure5.marker-cache.v1", "cohort": support["cohort"],
190
+ "unit": support["unit"], "arm": arm, "support_sha256": support["sha256"],
191
+ "generated_npz": str(npz_path.resolve()), "generated_npz_sha256": actual_sha,
192
+ "score_summary": str(summary_path.resolve()), "score_summary_sha256": summary_sha,
193
+ "scoring_support": str(binding_path.resolve()), "scoring_support_sha256": binding_sha,
194
+ "score_generated_cells": str((score / "arms" / arm / "generated_cells.parquet").resolve()),
195
+ "score_generated_cells_sha256": sha256(score / "arms" / arm / "generated_cells.parquet"),
196
+ "score_labels_sha256": sha256(score / "arms" / arm / "labels/labels.parquet"),
197
+ "poisson_seed": POISSON_SEED, "benchmark_umi_reproduced": True, "cells": len(gc)}
198
+ np.savez_compressed(output, markers=markers, marker_symbols=np.asarray(symbols),
199
+ lib_measured=libs, sample_id=gc.donor.astype(str).to_numpy(),
200
+ aifi_l1=lab.aifi_l1.astype(str).to_numpy(),
201
+ aifi_l2=lab.aifi_l2.astype(str).to_numpy(), receipt=json.dumps(rec))
202
+ return rec
203
+
204
+
205
+ def build(support_path: Path, score: Path, arms: dict[str, Path], output: Path,
206
+ *, cell_budget: int, depth_target: float) -> Path:
207
+ support = read_support(support_path)
208
+ summary = json.loads((score / "summary.json").read_text())
209
+ if summary.get("dataset") != support["cohort"] or set(summary.get("donors", [])) != set(support["test_sample_ids"]):
210
+ raise ValueError("score summary not bound to strict test samples")
211
+ if set(summary.get("arms", [])) != set(arms):
212
+ raise ValueError("score summary arm set differs")
213
+ states = json.loads(STATES.read_text())
214
+ panel, measured, symbols, cols = _panel(support["cohort"], states)
215
+ ref = np.load(FT / "scoring_cache" / support["cohort"] / "reference.npz", allow_pickle=False)
216
+ score_cols = ref["score_idx"].astype(int)
217
+ output.mkdir(parents=True, exist_ok=True)
218
+ observed = _observed_legacy(support["cohort"], states)
219
+ obs_path = output / "observed.npz"
220
+ np.savez_compressed(obs_path, **observed)
221
+ paths = {}
222
+ cache_sha = {}
223
+ for arm, source in arms.items():
224
+ path = output / f"{arm}.npz"
225
+ build_arm(source, score, arm, support, path, panel, measured, symbols, cols, score_cols)
226
+ paths[arm] = str(path.resolve())
227
+ cache_sha[arm] = sha256(path)
228
+ metadata = FT / "data" / support["cohort"] / "pairs.csv"
229
+ unit = {"cohort": support["cohort"], "unit": support["unit"].removesuffix("_n5"),
230
+ "design": "strict5pair", "train_sample_ids": support["train_sample_ids"],
231
+ "train_donor_ids": support["train_donor_ids"], "test_sample_ids": support["test_sample_ids"],
232
+ "sample_metadata": str(metadata.resolve()), "support_manifest": str(support_path.resolve()),
233
+ "observed_cache": str(obs_path.resolve()), "observed_cache_sha256": sha256(obs_path),
234
+ "generated_caches": paths, "generated_cache_sha256": cache_sha,
235
+ "cell_budget": cell_budget, "depth_target": depth_target}
236
+ manifest = output / "rare_manifest.json"
237
+ manifest.write_text(json.dumps({"schema": "pbisc.figure5.marker-caches.v1",
238
+ "units": [unit]}, indent=2) + "\n")
239
+ return manifest
240
+
241
+
242
+ def main() -> None:
243
+ ap = argparse.ArgumentParser(description=__doc__)
244
+ ap.add_argument("--support-manifest", type=Path, required=True)
245
+ ap.add_argument("--score-dir", type=Path, required=True, help="score_strict output's score/ directory")
246
+ ap.add_argument("--arm", action="append", required=True, help="NAME=generated.npz")
247
+ ap.add_argument("--output-dir", type=Path, required=True)
248
+ ap.add_argument("--cell-budget", type=int, required=True)
249
+ ap.add_argument("--depth-target", type=float, required=True)
250
+ a = ap.parse_args()
251
+ if a.cell_budget <= 0 or a.depth_target <= 0:
252
+ raise ValueError("positive common cell budget and depth target required")
253
+ arms = {}
254
+ for value in a.arm:
255
+ name, sep, raw = value.partition("=")
256
+ if sep != "=" or not name or name in arms or not raw:
257
+ raise ValueError(f"invalid arm {value!r}")
258
+ arms[name] = Path(raw)
259
+ print(build(a.support_manifest, a.score_dir, arms, a.output_dir,
260
+ cell_budget=a.cell_budget, depth_target=a.depth_target))
261
+
262
+
263
+ if __name__ == "__main__":
264
+ main()