junidude14 commited on
Commit
d634b02
·
verified ·
1 Parent(s): 392efd6

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/sample_one.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run the frozen sampler inside the caller's ml-run unit, preserving separate receipt and error logs."""
2
+ from __future__ import annotations
3
+ import argparse
4
+ import json
5
+ from pathlib import Path
6
+ import subprocess
7
+ import sys
8
+ from runtime import sha256
9
+
10
+
11
+ def main() -> int:
12
+ p = argparse.ArgumentParser()
13
+ p.add_argument("--checkpoint", type=Path, required=True)
14
+ p.add_argument("--checkpoint-sha", required=True)
15
+ p.add_argument("--condition", type=Path, required=True)
16
+ p.add_argument("--output", type=Path, required=True)
17
+ p.add_argument("--seed", type=int, default=20260928)
18
+ a = p.parse_args()
19
+ if "ml.slice" not in Path("/proc/self/cgroup").read_text():
20
+ raise SystemExit("sampler wrapper must be started through ml-run")
21
+ if sha256(a.checkpoint) != a.checkpoint_sha:
22
+ raise SystemExit("checkpoint hash mismatch")
23
+ if any(a.output.with_suffix(s).exists() for s in (".npz", ".log", ".err")):
24
+ raise SystemExit("existing sampling output or log: preserve and inspect")
25
+ a.output.parent.mkdir(parents=True, exist_ok=True)
26
+ script = Path(__file__).resolve().parents[3] / "scripts/sample_sdd_standalone.py"
27
+ argv = [sys.executable, "-u", str(script), "--checkpoint", str(a.checkpoint),
28
+ "--condition-npz", str(a.condition), "--output", str(a.output), "--weights", "ema",
29
+ "--batch-size", "256", "--steps", "50", "--seed", str(a.seed), "--device", "cuda",
30
+ "--conditioner-source", "embedded", "--active-logit-threshold", "0.0",
31
+ "--support-readout", "bernoulli"]
32
+ with a.output.with_suffix(".log").open("x") as out, a.output.with_suffix(".err").open("x") as err:
33
+ result = subprocess.run(argv, stdout=out, stderr=err)
34
+ if result.returncode:
35
+ return result.returncode
36
+ receipt = json.loads(a.output.with_suffix(".log").read_text())
37
+ if receipt["output_sha256"] != sha256(a.output):
38
+ raise SystemExit("sampler output differs from its receipt")
39
+ print(json.dumps({"output": str(a.output), "output_sha256": receipt["output_sha256"]}), flush=True)
40
+ return 0
41
+
42
+
43
+ if __name__ == "__main__":
44
+ 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/score_strict.py ADDED
@@ -0,0 +1,717 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Strict-support CPU scorer; imports legacy metric mains with isolated output roots.
3
+
4
+ Example: python tools/score_strict.py --support-manifest protocol/splits/.../support.json
5
+ --out scores/COHORT/UNIT --arm lora=generated.npz --action all
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import hashlib
11
+ import importlib.util
12
+ import json
13
+ import os
14
+ import re
15
+ import sys
16
+ from pathlib import Path
17
+
18
+ for _key in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "NUMBA_NUM_THREADS"):
19
+ os.environ.setdefault(_key, "4")
20
+ os.environ["CUDA_VISIBLE_DEVICES"] = ""
21
+
22
+ import pandas as pd # noqa: E402
23
+ import numpy as np # noqa: E402
24
+
25
+ PLAN = Path(__file__).resolve().parents[1]
26
+ LEGACY = PLAN.parent / "paired_finetune_intradataset_20260927"
27
+ TOOLS = LEGACY / "tools"
28
+ sys.path.insert(0, str(TOOLS))
29
+ sys.path.insert(0, str(PLAN / "tools"))
30
+ from campaign import BASE, BASE_SHA # noqa: E402 canonical pretraining checkpoint pinned by campaign
31
+
32
+
33
+ def manifest_digest(data: dict) -> str:
34
+ body = {k: v for k, v in data.items() if k != "sha256"}
35
+ return hashlib.sha256(json.dumps(body, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()).hexdigest()
36
+
37
+
38
+ def read_support(path: Path) -> dict:
39
+ data = json.loads(Path(path).read_text())
40
+ if data.get("schema") != "pbisc.paper.strict-support.v1" or data.get("sha256") != manifest_digest(data):
41
+ raise ValueError("strict support schema or hash mismatch")
42
+ train, test = data.get("train_sample_ids", []), data.get("test_sample_ids", [])
43
+ td, vd = data.get("train_donor_ids", []), data.get("test_donor_ids", [])
44
+ if not test or not train or len(train) != len(td) or len(test) != len(vd):
45
+ raise ValueError("support requires aligned train/test identities")
46
+ if data.get("n_pairs") != len(train):
47
+ raise ValueError("support n_pairs differs from exact training rows")
48
+ if len(set(train)) != len(train) or len(set(td)) != len(td) or len(set(test)) != len(test):
49
+ raise ValueError("duplicate support identity")
50
+ if set(td) & set(vd):
51
+ raise ValueError("train/test donor overlap")
52
+ if set(train) & set(test + data.get("excluded_sample_ids", [])):
53
+ raise ValueError("support sample overlap")
54
+ return data
55
+
56
+
57
+ def patient_mapping(support: dict) -> pd.DataFrame:
58
+ return pd.DataFrame({"sample_id": support["test_sample_ids"], "donor_id": support["test_donor_ids"]})
59
+
60
+
61
+ def validate_lora_run(run: dict, support: dict) -> None:
62
+ """Reject an old larger-support run even if its held-out IDs coincide."""
63
+ expected = support["train_sample_ids"]
64
+ actual = run.get("train_rows", [])
65
+ if len(actual) != len(expected) or set(actual) != set(expected):
66
+ raise ValueError("LoRA train_rows differ from exact strict support")
67
+ if len(expected) != support["n_pairs"] or len(set(support["train_donor_ids"])) != len(expected):
68
+ raise ValueError("strict support pair count differs from unique donors")
69
+ checks = {
70
+ "support_sha256": support["sha256"], "train_donor_ids": support["train_donor_ids"],
71
+ "test_rows_never_loaded_for_training": support["test_sample_ids"],
72
+ "excluded_selected_donor_visits": support.get("excluded_sample_ids", []),
73
+ "inner_val_rows": [], "fixed_steps": 3000, "steps_run": 3000,
74
+ "selected_step": 3000, "mode": "lora", "source_checkpoint_sha256": BASE_SHA,
75
+ }
76
+ for field, want in checks.items():
77
+ got = run.get(field)
78
+ if field in {"test_rows_never_loaded_for_training", "excluded_selected_donor_visits"}:
79
+ if not isinstance(got, list) or len(got) != len(want) or set(got) != set(want):
80
+ raise ValueError(f"LoRA {field} differs from strict support")
81
+ elif got != want:
82
+ raise ValueError(f"LoRA {field} differs from strict support")
83
+ if run.get("trainable", {}).get("lora_rank") != 16:
84
+ raise ValueError("LoRA rank differs from strict protocol")
85
+ if not re.fullmatch(r"[0-9a-f]{64}", str(run.get("checkpoint_sha256", ""))):
86
+ raise ValueError("LoRA checkpoint hash absent or invalid")
87
+
88
+
89
+ def _sha(path: Path) -> str:
90
+ h = hashlib.sha256()
91
+ with Path(path).open("rb") as f:
92
+ for block in iter(lambda: f.read(8 * 1024 * 1024), b""):
93
+ h.update(block)
94
+ return h.hexdigest()
95
+
96
+
97
+ def _unit_relative(support: dict) -> Path:
98
+ unit = support["unit"]
99
+ cohort = support["cohort"]
100
+ if support.get("design") == "healthy_outerfold":
101
+ match = re.fullmatch(r"fold(\d+)_n(\d+)", unit)
102
+ if match and int(match[2]) == support["n_pairs"]:
103
+ return Path(cohort) / "healthy" / f"fold{match[1]}" / f"n{match[2]}"
104
+ elif support.get("design") == "disease_existing_draw":
105
+ match = re.fullmatch(r"draw(\d+)_n(\d+)", unit)
106
+ if match and int(match[2]) == support["n_pairs"]:
107
+ return Path(cohort) / "disease" / f"draw{match[1]}"
108
+ raise ValueError("support unit/design is not a canonical strict campaign unit")
109
+
110
+
111
+ def _strict_conditions(support: dict, rel: Path) -> dict:
112
+ folder = PLAN / "data" / rel
113
+ path = folder / "CONDITIONS.json"
114
+ support_path = PLAN / "protocol/splits" / rel / "support.json"
115
+ if not path.is_file() or not support_path.is_file():
116
+ raise ValueError("strict condition or support receipt missing")
117
+ if read_support(support_path)["sha256"] != support["sha256"]:
118
+ raise ValueError("canonical support hash differs")
119
+ rec = json.loads(path.read_text())
120
+ if (rec.get("support_sha256") != support["sha256"] or
121
+ rec.get("support_path") != str(support_path) or
122
+ rec.get("fit_sample_ids") != support["train_sample_ids"]):
123
+ raise ValueError("strict condition fit/support binding differs")
124
+ for name in ("test_raw.npz", "test_cal.npz"):
125
+ file = folder / name
126
+ if not file.is_file() or rec.get("files_sha256", {}).get(name) != _sha(file):
127
+ raise ValueError(f"strict condition file missing or hash differs: {name}")
128
+ with np.load(file, allow_pickle=False) as z:
129
+ if set(z["sample_ids"].astype(str)) != set(support["test_sample_ids"]):
130
+ raise ValueError(f"strict condition sample IDs differ: {name}")
131
+ return rec
132
+
133
+
134
+ def validate_global_build_inputs(build: dict) -> None:
135
+ inputs = build.get("input_hashes", {})
136
+ if not inputs:
137
+ raise ValueError("global BUILD input hashes missing")
138
+ for raw, expected in inputs.items():
139
+ source = Path(raw)
140
+ if not source.is_file() or _sha(source) != expected:
141
+ raise ValueError(f"global BUILD input changed or missing: {source}")
142
+
143
+
144
+ def validate_generation_arm(name: str, path: Path, support: dict) -> dict:
145
+ """Bind an NPZ to its actual strict training/calibration/export sources."""
146
+ rel = _unit_relative(support)
147
+ canonical_support = PLAN / "protocol/splits" / rel / "support.json"
148
+ if not canonical_support.is_file() or read_support(canonical_support)["sha256"] != support["sha256"]:
149
+ raise ValueError("arm support hash differs from canonical strict campaign support")
150
+ if name not in ("lora", "pairedcal", "scsemi", "raw", "refcal"):
151
+ raise ValueError(f"unsupported campaign arm {name}")
152
+ expected = (PLAN / "generated/global" / support["cohort"] / f"{name}.npz" if name in ("raw", "refcal")
153
+ else PLAN / "generated" / rel / f"{name}.npz")
154
+ path = Path(path).resolve()
155
+ if path != expected.resolve():
156
+ raise ValueError(f"canonical strict arm path required: {expected}")
157
+ if not path.is_file() or not path.with_suffix(".log").is_file():
158
+ raise ValueError(f"generation NPZ or receipt missing: {path}")
159
+ receipt = json.loads(path.with_suffix(".log").read_text())
160
+ if name == "scsemi" and receipt.get("schema") == "pbisc.scsemi.adopted-output.v1":
161
+ from import_scsemi_legacy import validate_adopted_generation
162
+ return validate_adopted_generation(path, support)
163
+ npz_sha = _sha(path)
164
+ if receipt.get("output") != str(path) or receipt.get("output_sha256") != npz_sha:
165
+ raise ValueError("generation output path/hash differs from receipt")
166
+ with np.load(path, allow_pickle=False) as z:
167
+ samples = z["sample_ids"].astype(str).tolist()
168
+ meta = json.loads(str(z["metadata_json"]))
169
+ if len(samples) != len(set(samples)) or not set(support["test_sample_ids"]) <= set(samples):
170
+ raise ValueError("generation sample IDs omit strict held-out samples")
171
+ if name not in ("raw", "refcal") and set(samples) != set(support["test_sample_ids"]):
172
+ raise ValueError("unit generation includes samples beyond strict test support")
173
+ if name in ("raw", "refcal"):
174
+ build_path = PLAN / "data/external_refcal" / support["cohort"] / "BUILD.json"
175
+ if not build_path.is_file():
176
+ raise ValueError("global external reference BUILD.json missing")
177
+ build = json.loads(build_path.read_text())
178
+ validate_global_build_inputs(build)
179
+ cond = PLAN / "data/external_refcal" / support["cohort"] / f"conditions_{name}.npz"
180
+ cond_sha = _sha(cond) if cond.is_file() else None
181
+ if (build.get("schema") != "pbisc.strict.external-reference.v1" or
182
+ build.get("cohort") != support["cohort"] or
183
+ build.get("target_sc_expression_accessed") is not False or
184
+ build.get("paired_target_samples_used") != 0 or
185
+ build.get("outputs", {}).get(str(cond)) != cond_sha or
186
+ not set(support["test_sample_ids"]) <= set(build.get("target_bulk_anchor_sample_ids", []))):
187
+ raise ValueError("global BUILD/condition metadata differs from external-reference protocol")
188
+ checkpoint_sha, checkpoint = BASE_SHA, BASE
189
+ source = str(build_path)
190
+ else:
191
+ conditions = _strict_conditions(support, rel)
192
+ cond_name = "test_cal.npz" if name == "pairedcal" else "test_raw.npz"
193
+ cond = PLAN / "data" / rel / cond_name
194
+ cond_sha = conditions["files_sha256"][cond_name]
195
+ checkpoint_sha, checkpoint = BASE_SHA, BASE
196
+ source = str(PLAN / "data" / rel / "CONDITIONS.json")
197
+ if name == "lora":
198
+ run_path = PLAN / "runs" / rel / "lora/RUN.json"
199
+ if not run_path.is_file():
200
+ raise ValueError("strict LoRA RUN.json missing")
201
+ run = json.loads(run_path.read_text())
202
+ validate_lora_run(run, support)
203
+ checkpoint = PLAN / "runs" / rel / "lora/checkpoint_ft.pt"
204
+ checkpoint_sha = run["checkpoint_sha256"]
205
+ if not checkpoint.is_file() or _sha(checkpoint) != checkpoint_sha:
206
+ raise ValueError("strict LoRA checkpoint differs from RUN.json")
207
+ source = str(run_path)
208
+ elif name == "scsemi":
209
+ work = PLAN / "scsemi" / rel
210
+ inputs_path = work / "inputs/inputs_manifest.json"
211
+ validation_path = path.with_suffix(".validation.json")
212
+ if not inputs_path.is_file() or not validation_path.is_file():
213
+ raise ValueError("strict scSemi inputs or export validation missing")
214
+ inputs, validation = json.loads(inputs_path.read_text()), json.loads(validation_path.read_text())
215
+ reps = [x["sample_id"] for x in inputs.get("representatives", [])]
216
+ if (inputs.get("mode") != "strict" or inputs.get("smoke") or
217
+ inputs.get("support_sha256") != support["sha256"] or
218
+ reps != support["train_sample_ids"] or
219
+ inputs.get("targets") != support["test_sample_ids"] or
220
+ inputs.get("train_donors") != support["train_donor_ids"] or
221
+ inputs.get("n_representatives") != support["n_pairs"] or
222
+ inputs.get("sources", {}).get("support.json") != _sha(PLAN / "protocol/splits" / rel / "support.json") or
223
+ inputs.get("condition_sha256") != cond_sha or
224
+ validation.get("passed") is not True or validation.get("npz_sha256") != npz_sha or
225
+ receipt.get("run_signature") != meta.get("run_signature") or
226
+ meta.get("work") != str(work)):
227
+ raise ValueError("scSemi export/work inputs differ from strict support")
228
+ source = str(inputs_path)
229
+ checkpoint_sha, checkpoint = None, None
230
+ if (receipt.get("condition_npz") != str(cond) or receipt.get("condition_sha256") != cond_sha or
231
+ meta.get("input_condition_path") != str(cond) or meta.get("input_condition_sha256") != cond_sha):
232
+ raise ValueError("generation condition differs from strict source")
233
+ if name != "scsemi" and (receipt.get("checkpoint") != str(checkpoint) or
234
+ receipt.get("checkpoint_sha256") != checkpoint_sha or
235
+ meta.get("checkpoint") != str(checkpoint) or
236
+ meta.get("checkpoint_sha256") != checkpoint_sha):
237
+ raise ValueError("generation checkpoint differs from strict source")
238
+ if name == "scsemi" and (meta.get("representatives") != support["train_sample_ids"] or
239
+ meta.get("train_donors") != support["train_donor_ids"] or meta.get("smoke")):
240
+ raise ValueError("scSemi metadata differs from strict representatives")
241
+ return {"arm": name, "npz": str(path), "npz_sha256": npz_sha,
242
+ "receipt": str(path.with_suffix(".log")), "receipt_sha256": _sha(path.with_suffix(".log")),
243
+ "source_binding": source, "source_binding_sha256": _sha(Path(source)),
244
+ "condition_npz": str(cond), "condition_sha256": cond_sha,
245
+ "checkpoint_sha256": checkpoint_sha, "support_sha256": support["sha256"]}
246
+
247
+
248
+ def safe_out(path: Path) -> Path:
249
+ out = Path(path).resolve()
250
+ if not out.is_relative_to(PLAN.resolve()):
251
+ raise ValueError("--out must be within the strict-pairs plan directory")
252
+ protected = ("protocol", "tools", "tests", "data", "figures", "manuscript", "deck", "backups", "source_data")
253
+ if out == PLAN.resolve() or any(out.is_relative_to((PLAN / part).resolve()) for part in protected):
254
+ raise ValueError("--out must be a dedicated result directory within the strict-pairs plan")
255
+ return out
256
+
257
+
258
+ def extra_root(out: Path) -> Path:
259
+ return Path(out) / "extras"
260
+
261
+
262
+ def contrast_root(out: Path) -> Path:
263
+ return Path(out) / "contrast"
264
+
265
+
266
+ def _legacy_module(name: str):
267
+ if name in sys.modules:
268
+ return sys.modules[name]
269
+ spec = importlib.util.spec_from_file_location(name, TOOLS / f"{name}.py")
270
+ module = importlib.util.module_from_spec(spec)
271
+ sys.modules[name] = module
272
+ spec.loader.exec_module(module)
273
+ return module
274
+
275
+
276
+ def _arms(values: list[str]) -> list[str]:
277
+ names = set()
278
+ out = []
279
+ for value in values:
280
+ name, sep, raw = value.partition("=")
281
+ if name == "observed":
282
+ raise ValueError("arm name 'observed' is reserved for the real reference")
283
+ if sep != "=" or not name or not raw or not name.replace("_", "").replace("-", "").isalnum() or name in names:
284
+ raise ValueError(f"bad or duplicate --arm {value!r}")
285
+ names.add(name)
286
+ out.append(f"{name}={Path(raw).resolve()}")
287
+ return out
288
+
289
+
290
+ def _existing_score(score: Path, support: dict, names: list[str]) -> dict:
291
+ binding = score.parent / "scoring_support.json"
292
+ rec = json.loads(binding.read_text()) if binding.is_file() else {}
293
+ if rec.get("support_sha256") != support["sha256"]:
294
+ raise ValueError("score support hash absent or different")
295
+ p = score / "summary.json"
296
+ if not p.is_file():
297
+ raise ValueError(f"score output missing: {p}; run --action score first")
298
+ summary = json.loads(p.read_text())
299
+ if summary.get("dataset") != support["cohort"] or set(summary.get("donors", [])) != set(support["test_sample_ids"]):
300
+ raise ValueError("score summary does not match strict support test samples")
301
+ if names and set(summary.get("arms", [])) != set(names):
302
+ raise ValueError("score summary arm names differ from requested arms")
303
+ bindings = rec.get("arm_bindings", {})
304
+ if set(bindings) != set(summary.get("arms", [])):
305
+ raise ValueError("score generation binding missing or has different arms")
306
+ for name in summary["arms"]:
307
+ scored = summary.get("per_arm", {}).get(name, {})
308
+ source = bindings[name]
309
+ if scored.get("npz_sha256") != source.get("npz_sha256") or scored.get("npz") != source.get("npz"):
310
+ raise ValueError(f"score generation binding differs for {name}")
311
+ return summary
312
+
313
+
314
+ def _call_score(support: dict, out: Path, arms: list[str], a: argparse.Namespace) -> None:
315
+ if not arms:
316
+ raise ValueError("--action score requires --arm NAME=NPZ")
317
+ arm_bindings = {name: validate_generation_arm(name, Path(path), support)
318
+ for name, path in (arm.split("=", 1) for arm in arms)}
319
+ score = out / "score"
320
+ score.mkdir(parents=True, exist_ok=True)
321
+ binding = out / "scoring_support.json"
322
+ if binding.is_file() and json.loads(binding.read_text()).get("support_sha256") != support["sha256"]:
323
+ raise ValueError("existing output belongs to a different support hash")
324
+ if (score / "summary.json").is_file():
325
+ existing = json.loads((score / "summary.json").read_text())
326
+ if (existing.get("dataset") != support["cohort"] or
327
+ set(existing.get("donors", [])) != set(support["test_sample_ids"]) or
328
+ set(existing.get("arms", [])) != set(arm_bindings)):
329
+ raise ValueError("existing score differs from requested strict support or arms")
330
+ for name, source in arm_bindings.items():
331
+ scored = existing.get("per_arm", {}).get(name, {})
332
+ if scored.get("npz_sha256") != source["npz_sha256"] or scored.get("npz") != source["npz"]:
333
+ raise ValueError(f"existing score differs from validated generation for {name}")
334
+ binding.write_text(json.dumps({"schema": "pbisc.paper.strict-score-binding.v1",
335
+ "support_sha256": support["sha256"],
336
+ "cohort": support["cohort"], "unit": support["unit"],
337
+ "test_sample_ids": support["test_sample_ids"],
338
+ "test_donor_ids": support["test_donor_ids"],
339
+ "arm_bindings": arm_bindings}, indent=2) + "\n")
340
+ if (score / "summary.json").is_file():
341
+ _existing_score(score, support, list(arm_bindings))
342
+ return
343
+ mapping = patient_mapping(support)
344
+ mapping.to_csv(out / "patient_mapping.csv", index=False)
345
+ donor_file = out / "test_sample_ids.txt"
346
+ donor_file.write_text("\n".join(support["test_sample_ids"]) + "\n")
347
+ argv = ["--dataset", support["cohort"], "--out", str(score), "--donors", str(donor_file),
348
+ "--threads", str(a.threads)]
349
+ for arm in arms:
350
+ argv += ["--arm", arm]
351
+ if a.reference:
352
+ argv += ["--reference", str(a.reference)]
353
+ if a.annot:
354
+ argv += ["--annot", str(a.annot)]
355
+ for condition in a.condition:
356
+ argv += ["--condition", condition]
357
+ if a.allow_no_receipt:
358
+ argv.append("--allow-no-receipt")
359
+ if support["cohort"] == "giroux2022":
360
+ exclude = LEGACY / "data/sex_linked_genes/sex_linked_genes_exclude.csv"
361
+ if not exclude.is_file():
362
+ raise ValueError(f"required Giroux sex-gene exclusion missing: {exclude}")
363
+ argv += ["--exclude-genes", str(exclude)]
364
+ groups = {
365
+ "ye2026_sepsis": ("adult_sepsis,ped_sepsis", "adult_HC,adult_ICU_ctrl,ped_HC,ped_ICU_ctrl"),
366
+ "ji2025_chili": ("TOL,FU1", "BC,AC"),
367
+ "imperial_eskd": ("covid_positive", "covid_negative"),
368
+ "giroux2022": ("severe", "mild"),
369
+ }
370
+ if support["cohort"] in groups:
371
+ case, ctrl = groups[support["cohort"]]
372
+ argv += ["--case-groups", case, "--control-groups", ctrl]
373
+ else:
374
+ argv += ["--no-contrast", "--no-deg"]
375
+ if a.reuse_labels:
376
+ argv += ["--reuse-labels", str(a.reuse_labels)]
377
+ previous_argv = sys.argv
378
+ try:
379
+ sys.argv = [str(TOOLS / "score_ft.py"), *argv]
380
+ _legacy_module("score_ft").main(argv)
381
+ finally:
382
+ sys.argv = previous_argv
383
+ _existing_score(score, support, [x.split("=", 1)[0] for x in arms])
384
+
385
+
386
+ def _call_extra(kind: str, support: dict, out: Path, arms: list[str], threads: int) -> None:
387
+ score = out / "score"
388
+ names = [x.split("=", 1)[0] for x in arms]
389
+ summary = _existing_score(score, support, names)
390
+ names = summary["arms"]
391
+ mod = _legacy_module("extra_metrics" if kind == "extras" else "contrast_extra")
392
+ root = extra_root(out) if kind == "extras" else contrast_root(out)
393
+ mod.OUT_ROOT = root
394
+ mod.SCORED.clear()
395
+ # Scored-mode paths are all rooted at OUT_ROOT; no legacy output tree is touched.
396
+ argv = ["--design", "scored", "--dataset", support["cohort"], "--score-dir", str(score),
397
+ "--arms", ",".join(names), "--unit", "strict", "--threads", str(threads),
398
+ "--fetch-dir", str(root / "_fetch_tmp")]
399
+ mod.main(argv)
400
+
401
+
402
+ def _automatic_deg(support: dict, out: Path, summary: dict, threads: int) -> dict:
403
+ """Rebuild scored per-sample×type counts from the same legacy sources/readout.
404
+
405
+ This is bounded one arm and one cell type at a time. The legacy scorer's
406
+ DEG outputs remain available for comparison; these fits are independent
407
+ corrected outputs and use the explicit support patient map.
408
+ """
409
+ import donor_statistics as DS
410
+
411
+ F = _legacy_module("ft_common")
412
+ S = _legacy_module("score_ft")
413
+ cache = Path(summary["reference"]["cache"])
414
+ ref, man = F.load_reference(cache)
415
+ if man["reference_sha256"] != summary["reference"]["reference_sha256"]:
416
+ raise ValueError("reference cache differs from scored reference")
417
+ deg = F.load_deg_reference(cache, man, ref)
418
+ sample_ids = np.asarray(summary["donors"], dtype=str)
419
+ pos = {x: i for i, x in enumerate(ref["donors"].astype(str))}
420
+ if any(x not in pos for x in sample_ids):
421
+ raise ValueError("scored sample absent from DEG reference")
422
+ sel_ref = np.asarray([pos[x] for x in sample_ids], dtype=int)
423
+ patient_of = dict(zip(support["test_sample_ids"], support["test_donor_ids"]))
424
+ donors = np.asarray([patient_of[x] for x in sample_ids], dtype=str)
425
+ conditions = np.asarray(summary["contrast_definition"]["groups"], dtype=str)
426
+ if conditions.shape != sample_ids.shape:
427
+ raise ValueError("contrast groups do not align with scored samples")
428
+ gene_ids = ref["score_ids"].astype(str)
429
+ keep = np.ones(len(gene_ids), bool)
430
+ exclusion = summary.get("gene_exclusion")
431
+ if support["cohort"] == "giroux2022" and not exclusion:
432
+ raise ValueError("Giroux DEG requires the recorded sex-gene exclusion")
433
+ if exclusion:
434
+ path = Path(exclusion["file"])
435
+ if not path.is_file() or F.sha(path) != exclusion["sha256"]:
436
+ raise ValueError("recorded gene exclusion file changed")
437
+ keep, _ = S.gene_exclusion(path, gene_ids.tolist())
438
+ genes = gene_ids[keep]
439
+ dest = out / "statistics" / "donor_deg"
440
+ dest.mkdir(parents=True, exist_ok=True)
441
+ pd.DataFrame({"gene_id": genes}).to_csv(dest / "genes_kept.csv", index=False)
442
+ all_rows = []
443
+ for arm_name in summary["arms"]:
444
+ pa = summary["per_arm"][arm_name]
445
+ path = Path(pa["npz"])
446
+ if not path.is_file():
447
+ all_rows.append({"arm": arm_name, "status": "pending", "reason": f"generated NPZ missing: {path}"})
448
+ continue
449
+ arm = S.open_arm(arm_name, path, ref["panel_ids"].astype(str), allow_no_receipt=True)
450
+ if arm["sha256"] != pa["npz_sha256"]:
451
+ arm["d"].close()
452
+ raise ValueError(f"{arm_name}: generated NPZ differs from scored input")
453
+ try:
454
+ npos = {x: i for i, x in enumerate(arm["sample_ids"])}
455
+ if any(x not in npos for x in sample_ids):
456
+ raise ValueError(f"{arm_name}: scored sample absent from generated NPZ")
457
+ row_lists = [np.flatnonzero(arm["bulk_index"] == npos[x]) for x in sample_ids]
458
+ selected = np.concatenate(row_lists)
459
+ gen_d = np.repeat(np.arange(len(sample_ids)), [len(x) for x in row_lists])
460
+ cells = pd.read_parquet(out / "score" / "arms" / arm_name / "generated_cells.parquet",
461
+ columns=["npz_row", "donor", "label"])
462
+ if not np.array_equal(cells.npz_row.to_numpy(), selected) or not np.array_equal(
463
+ cells.donor.astype(str).to_numpy(), sample_ids[gen_d]):
464
+ raise ValueError(f"{arm_name}: generated cell labels do not match scored NPZ rows")
465
+ # Exact legacy rule: integerise the whole NPZ first, then select
466
+ # scored rows. The seed and chunk size are inherited, not retyped.
467
+ rates = np.ascontiguousarray(arm["d"]["generated_counts"], dtype=np.float32)
468
+ full = F.PR.poisson_integerise(rates, seed=F.POISSON_SEED, chunk_rows=4096)
469
+ del rates
470
+ Xg = full[selected][:, ref["score_idx"]].tocsr()[:, keep].tocsr()
471
+ del full
472
+ ag = F.type_aggregates(Xg, gen_d, cells.label.astype(str).to_numpy(), len(sample_ids),
473
+ types=tuple(deg["types"]))
474
+ del Xg
475
+ arm_dir = dest / arm_name
476
+ arm_dir.mkdir(parents=True, exist_ok=True)
477
+ for ti, celltype in enumerate(deg["types"]):
478
+ slug = re.sub(r"[^a-z0-9]+", "_", str(celltype).lower()).strip("_")
479
+ type_dir = arm_dir / slug
480
+ obs = DS.pseudobulk_rows_from_arrays(
481
+ sample_ids=sample_ids, donors=donors, conditions=conditions, gene_ids=genes,
482
+ celltype=str(celltype), side="observed", n_cells=deg["n"][sel_ref, ti],
483
+ sums=deg["sum"][sel_ref, ti][:, keep])
484
+ generated = DS.pseudobulk_rows_from_arrays(
485
+ sample_ids=sample_ids, donors=donors, conditions=conditions, gene_ids=genes,
486
+ celltype=str(celltype), side=arm_name, n_cells=ag["n"][:, ti],
487
+ sums=ag["sum"][:, ti])
488
+ table = DS.donor_condition_pseudobulk(pd.concat([obs, generated], ignore_index=True))
489
+ result = DS.run_donor_limma(table, type_dir,
490
+ case=",".join(summary["contrast_definition"]["case_groups"]),
491
+ control=",".join(summary["contrast_definition"]["control_groups"]),
492
+ threads=threads)
493
+ jobs = {j["side"]: j for j in result.get("jobs", [])}
494
+ o, g = jobs.get("observed", {}), jobs.get(arm_name, {})
495
+ okay = o.get("status") == "ok" and g.get("status") == "ok"
496
+ missing_population = obs.empty or generated.empty
497
+ if result.get("status") in ("pending", "partial_or_pending"):
498
+ type_status = "pending"
499
+ elif okay:
500
+ type_status = "ok"
501
+ elif missing_population or all(x.get("status", "not_estimable") in ("ok", "not_estimable")
502
+ for x in (o, g)):
503
+ type_status = "not_estimable"
504
+ else:
505
+ type_status = "pending"
506
+ row = {"arm": arm_name, "celltype": celltype,
507
+ "status": type_status,
508
+ "observed_status": o.get("status", "no_population" if obs.empty else "missing"),
509
+ "generated_status": g.get("status", "no_population" if generated.empty else "missing"),
510
+ "n_case_donors_observed": o.get("n_case_donors"),
511
+ "n_control_donors_observed": o.get("n_control_donors"),
512
+ "n_case_donors_generated": g.get("n_case_donors"),
513
+ "n_control_donors_generated": g.get("n_control_donors"),
514
+ "method_observed": o.get("method"), "method_generated": g.get("method"),
515
+ "reason_observed": o.get("reason"), "reason_generated": g.get("reason"),
516
+ "reason_fit": result.get("reason"),
517
+ "reason_population": ("observed cell type absent" if obs.empty else
518
+ "generated cell type absent" if generated.empty else None)}
519
+ if okay:
520
+ top_o, top_g = set(o.get("top50_gene_ids", [])), set(g.get("top50_gene_ids", []))
521
+ row.update(top50_overlap_count=len(top_o & top_g),
522
+ observed_top50_size=len(top_o), generated_top50_size=len(top_g))
523
+ all_rows.append(row)
524
+ finally:
525
+ arm["d"].close()
526
+ pd.DataFrame(all_rows).to_csv(dest / "donor_deg_summary.csv", index=False)
527
+ n_pending = sum(x["status"] == "pending" for x in all_rows)
528
+ n_not_estimable = sum(x["status"] == "not_estimable" for x in all_rows)
529
+ overall = ("partial_or_pending" if n_pending or not all_rows else
530
+ "complete_with_not_estimable" if n_not_estimable else "ok")
531
+ return {"status": overall,
532
+ "method": "donor_condition_pseudobulk_limma_duplicateCorrelation_if_repeated_condition",
533
+ "n_genes_kept": int(len(genes)), "rows": len(all_rows),
534
+ "n_pending": n_pending, "n_not_estimable": n_not_estimable,
535
+ "summary_csv": str(dest / "donor_deg_summary.csv")}
536
+
537
+
538
+ def require_corrected_deg(result: dict) -> None:
539
+ if result.get("status") not in ("ok", "complete_with_not_estimable", "not_applicable"):
540
+ raise ValueError("donor-aware DEG pending; inspect statistics/status.json and donor_deg summary")
541
+
542
+
543
+ def validate_draw_long(path: Path, current_support: dict, expected_arms: list[str] | tuple[str, ...]) -> pd.DataFrame:
544
+ """Read one other disease draw only after its support, score and generation binding agree."""
545
+ if (current_support.get("design") != "disease_existing_draw" or current_support.get("n_pairs") != 5 or
546
+ not re.fullmatch(r"draw\d+_n5", current_support.get("unit", ""))):
547
+ raise ValueError("--draw-long requires a current strict disease n=5 draw")
548
+ path = Path(path).resolve()
549
+ try:
550
+ parts = path.relative_to((PLAN / "scores").resolve()).parts
551
+ except ValueError as exc:
552
+ raise ValueError("--draw-long must be a canonical score statistics path") from exc
553
+ if len(parts) != 5 or parts[1] != "disease" or parts[3:] != ("statistics", "per_donor_long.csv") or not re.fullmatch(r"draw\d+", parts[2]):
554
+ raise ValueError("--draw-long must be a canonical disease score statistics path")
555
+ cohort, draw = parts[0], parts[2]
556
+ if cohort != current_support["cohort"]:
557
+ raise ValueError("--draw-long cohort differs from current cohort")
558
+ unit = f"{draw}_n5"
559
+ if unit == current_support["unit"]:
560
+ raise ValueError("--draw-long must be a distinct draw")
561
+ support_path = PLAN / "protocol/splits" / cohort / "disease" / draw / "support.json"
562
+ if not support_path.is_file():
563
+ raise ValueError("--draw-long canonical support missing")
564
+ other = read_support(support_path)
565
+ if (other.get("cohort") != cohort or other.get("design") != "disease_existing_draw" or
566
+ other.get("unit") != unit or other.get("n_pairs") != 5):
567
+ raise ValueError("--draw-long strict support cohort/unit/n=5 mismatch")
568
+ base = path.parents[1]
569
+ binding_path = base / "scoring_support.json"
570
+ if not binding_path.is_file():
571
+ raise ValueError("--draw-long generation binding missing")
572
+ binding = json.loads(binding_path.read_text())
573
+ if (binding.get("schema") != "pbisc.paper.strict-score-binding.v1" or
574
+ binding.get("support_sha256") != other["sha256"] or
575
+ binding.get("cohort") != cohort or binding.get("unit") != unit or
576
+ binding.get("test_sample_ids") != other["test_sample_ids"] or
577
+ binding.get("test_donor_ids") != other["test_donor_ids"]):
578
+ raise ValueError("--draw-long generation binding differs from support")
579
+ names = set(expected_arms)
580
+ if not names or set(binding.get("arm_bindings", {})) != names:
581
+ raise ValueError("--draw-long arms differ from current score")
582
+ score = _existing_score(base / "score", other, list(names))
583
+ if set(score["arms"]) != names:
584
+ raise ValueError("--draw-long arms differ from current score")
585
+ for name, source in binding["arm_bindings"].items():
586
+ if validate_generation_arm(name, Path(source["npz"]), other) != source:
587
+ raise ValueError(f"--draw-long generation provenance differs for {name}")
588
+ rows = pd.read_csv(path, dtype={"draw": str, "sample_id": str, "donor_id": str, "arm": str, "metric": str})
589
+ required = {"draw", "sample_id", "donor_id", "arm", "metric", "value"}
590
+ if not required <= set(rows):
591
+ raise ValueError(f"--draw-long missing {sorted(required - set(rows))}")
592
+ if (rows.empty or set(rows.draw) != {unit} or set(rows.arm) != names or
593
+ set(rows.sample_id) != set(other["test_sample_ids"]) or
594
+ rows.duplicated(["draw", "sample_id", "donor_id", "arm", "metric"]).any()):
595
+ raise ValueError("--draw-long rows differ from strict draw/sample/arm contract")
596
+ if any(set(group.sample_id) != set(other["test_sample_ids"]) for _, group in rows.groupby("arm")):
597
+ raise ValueError("--draw-long arm lacks strict test samples")
598
+ patient_of = dict(zip(other["test_sample_ids"], other["test_donor_ids"]))
599
+ if (rows.donor_id != rows.sample_id.map(patient_of)).any():
600
+ raise ValueError("--draw-long patient mapping differs from strict support")
601
+ import donor_statistics as DS
602
+ expected = DS.score_table_with_patients(pd.read_csv(base / "score/per_donor.csv"), patient_mapping(other), draw=unit)
603
+ keys = ["draw", "sample_id", "donor_id", "arm", "metric"]
604
+ got = rows.sort_values(keys).reset_index(drop=True)
605
+ want = expected.sort_values(keys).reset_index(drop=True)
606
+ if (len(got) != len(want) or not got[keys].equals(want[keys]) or
607
+ not np.isclose(pd.to_numeric(got.value, errors="coerce"),
608
+ pd.to_numeric(want.value, errors="coerce"), rtol=1e-12, atol=0,
609
+ equal_nan=True).all()):
610
+ raise ValueError("--draw-long differs from scored metrics")
611
+ rows.attrs["support_sha256"] = other["sha256"]
612
+ rows.attrs["unit"] = unit
613
+ return rows
614
+
615
+
616
+ def validate_draw_longs(paths: list[Path], current_support: dict,
617
+ expected_arms: list[str] | tuple[str, ...]) -> list[pd.DataFrame]:
618
+ seen = {current_support["unit"]}
619
+ tables = []
620
+ for path in paths:
621
+ rows = validate_draw_long(path, current_support, expected_arms)
622
+ unit = rows.attrs["unit"]
623
+ if unit in seen:
624
+ raise ValueError(f"duplicate draw in --draw-long: {unit}")
625
+ seen.add(unit)
626
+ tables.append(rows)
627
+ return tables
628
+
629
+
630
+ def _call_stats(support: dict, out: Path, arms: list[str], a: argparse.Namespace) -> None:
631
+ import donor_statistics as DS
632
+ score = out / "score"
633
+ summary = _existing_score(score, support, [x.split("=", 1)[0] for x in arms])
634
+ dest = out / "statistics"
635
+ dest.mkdir(parents=True, exist_ok=True)
636
+ mapping = patient_mapping(support)
637
+ mapping.to_csv(dest / "patient_mapping.csv", index=False)
638
+ rows = DS.score_table_with_patients(pd.read_csv(score / "per_donor.csv"), mapping, draw=support["unit"])
639
+ rows.to_csv(dest / "per_donor_long.csv", index=False)
640
+ combined = [rows]
641
+ for other in validate_draw_longs(a.draw_long, support, summary["arms"]):
642
+ combined.append(other)
643
+ all_rows = pd.concat(combined, ignore_index=True)
644
+ if all_rows.duplicated(["draw", "sample_id", "donor_id", "arm", "metric"]).any():
645
+ raise ValueError("duplicate draw/sample/arm/metric across --draw-long inputs")
646
+ all_rows.to_csv(dest / "per_donor_long_all.csv", index=False)
647
+ baseline = a.baseline or summary["arms"][0]
648
+ if baseline not in summary["arms"]:
649
+ raise ValueError(f"baseline {baseline} absent from score arms")
650
+ corrected = DS.summarize_metrics(all_rows, baseline=baseline)
651
+ corrected.to_csv(dest / "donor_bootstrap_2000.csv", index=False)
652
+ status = {"schema": "pbisc.paper.strict-statistics.v1", "support_sha256": support["sha256"],
653
+ "bootstrap_unit": "unique_donor_all_visits_and_draws", "bootstrap_replicates": 2000,
654
+ "draws": sorted(all_rows.draw.astype(str).unique().tolist()),
655
+ "disease_deg": {"status": "pending", "reason": "no donor x cell-type per-sample count table supplied"}}
656
+ if a.pseudobulk_table:
657
+ raw = pd.read_csv(a.pseudobulk_table)
658
+ if not set(raw.sample_id.astype(str)) <= set(support["test_sample_ids"]):
659
+ raise ValueError("pseudobulk table contains samples outside strict test support")
660
+ raw = raw.merge(mapping, on="sample_id", how="left", suffixes=("", "_support"), validate="many_to_one")
661
+ if "donor_id_support" in raw:
662
+ if (raw.donor_id.astype(str) != raw.donor_id_support.astype(str)).any():
663
+ raise ValueError("pseudobulk donor mapping differs from support")
664
+ raw = raw.drop(columns="donor_id_support")
665
+ raw["donor_id"] = raw["donor_id"].astype(str)
666
+ agg = DS.donor_condition_pseudobulk(raw)
667
+ cd = summary["contrast_definition"]
668
+ if cd.get("enabled"):
669
+ status["disease_deg"] = DS.run_donor_limma(agg, dest / "donor_deg",
670
+ case=",".join(cd["case_groups"]),
671
+ control=",".join(cd["control_groups"]),
672
+ threads=a.threads)
673
+ else:
674
+ status["disease_deg"] = {"status": "not_applicable", "reason": "no case/control contrast"}
675
+ elif summary["contrast_definition"].get("enabled"):
676
+ status["disease_deg"] = _automatic_deg(support, out, summary, a.threads)
677
+ else:
678
+ status["disease_deg"] = {"status": "not_applicable", "reason": "no case/control contrast"}
679
+ (dest / "status.json").write_text(json.dumps(status, indent=2) + "\n")
680
+ require_corrected_deg(status["disease_deg"])
681
+
682
+
683
+ def main(argv: list[str] | None = None) -> int:
684
+ p = argparse.ArgumentParser(description=__doc__)
685
+ p.add_argument("--support-manifest", type=Path, required=True)
686
+ p.add_argument("--out", type=Path, required=True)
687
+ p.add_argument("--arm", action="append", default=[])
688
+ p.add_argument("--action", choices=("score", "extras", "contrast", "stats", "all"), required=True)
689
+ p.add_argument("--reference", type=Path)
690
+ p.add_argument("--annot", type=Path)
691
+ p.add_argument("--condition", action="append", default=[])
692
+ p.add_argument("--reuse-labels", type=Path)
693
+ p.add_argument("--pseudobulk-table", type=Path)
694
+ p.add_argument("--draw-long", type=Path, action="append", default=[],
695
+ help="other strict draw statistics/per_donor_long.csv files to cluster jointly")
696
+ p.add_argument("--baseline")
697
+ p.add_argument("--allow-no-receipt", action="store_true")
698
+ p.add_argument("--threads", type=int, default=4)
699
+ a = p.parse_args(argv)
700
+ if not 1 <= a.threads <= 8:
701
+ p.error("--threads must be 1..8")
702
+ support = read_support(a.support_manifest)
703
+ out = safe_out(a.out)
704
+ arms = _arms(a.arm)
705
+ out.mkdir(parents=True, exist_ok=True)
706
+ for action in (("score", "extras", "contrast", "stats") if a.action == "all" else (a.action,)):
707
+ if action == "score":
708
+ _call_score(support, out, arms, a)
709
+ elif action in ("extras", "contrast"):
710
+ _call_extra(action, support, out, arms, a.threads)
711
+ else:
712
+ _call_stats(support, out, arms, a)
713
+ return 0
714
+
715
+
716
+ if __name__ == "__main__":
717
+ 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/support_manifest.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CPU-only, exact one-sample-per-donor support contract for strict paired runs."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ import json
6
+ import re
7
+ from datetime import datetime
8
+ from pathlib import Path
9
+
10
+ import numpy as np
11
+ import pandas as pd
12
+
13
+ SCHEMA = "pbisc.paper.strict-support.v1"
14
+
15
+
16
+ def _digest(value: dict) -> str:
17
+ body = {k: v for k, v in value.items() if k != "sha256"}
18
+ return hashlib.sha256(json.dumps(body, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()).hexdigest()
19
+
20
+
21
+ def _rows(folds: pd.DataFrame) -> pd.DataFrame:
22
+ need = {"sample_id", "donor_id", "group", "fold"}
23
+ if not need <= set(folds):
24
+ raise ValueError(f"folds missing {sorted(need - set(folds))}")
25
+ f = folds.copy()
26
+ for col in ("sample_id", "donor_id", "group"):
27
+ if f[col].isna().any() or f[col].astype(str).str.strip().eq("").any():
28
+ raise ValueError(f"missing or empty {col}")
29
+ f[col] = f[col].astype(str)
30
+ if f.sample_id.duplicated().any():
31
+ raise ValueError("duplicate or missing sample IDs")
32
+ return f
33
+
34
+
35
+ def _finish(cohort: str, design: str, unit: str, f: pd.DataFrame, train: list[str], test: list[str],
36
+ *, seed: int | None = None, selection_audit: list[dict] | None = None) -> dict:
37
+ by_sample = f.set_index("sample_id")
38
+ donors = [str(by_sample.loc[s, "donor_id"]) for s in train]
39
+ selected = set(donors)
40
+ excluded = sorted(set(f.loc[f.donor_id.isin(selected), "sample_id"]) - set(train))
41
+ m = {"schema": SCHEMA, "cohort": cohort, "design": design, "unit": unit,
42
+ "n_pairs": len(train), "train_sample_ids": train, "train_donor_ids": donors,
43
+ "test_sample_ids": test, "test_donor_ids": f.set_index("sample_id").loc[test, "donor_id"].astype(str).tolist(),
44
+ "excluded_sample_ids": excluded, "seed": seed, "selection_audit": selection_audit or []}
45
+ m["sha256"] = _digest(m)
46
+ validate_manifest(m, f)
47
+ return m
48
+
49
+
50
+ def validate_manifest(m: dict, folds: pd.DataFrame) -> None:
51
+ f = _rows(folds)
52
+ if m.get("schema") != SCHEMA or m.get("sha256") != _digest(m):
53
+ raise ValueError("support schema or hash mismatch")
54
+ index = f.set_index("sample_id")
55
+ train = m.get("train_sample_ids", [])
56
+ donors = m.get("train_donor_ids", [])
57
+ test = m.get("test_sample_ids", [])
58
+ td = m.get("test_donor_ids", [])
59
+ exc = m.get("excluded_sample_ids", [])
60
+ if not train or len(train) != len(donors) or len(train) != m.get("n_pairs") or len(set(donors)) != len(donors):
61
+ raise ValueError("n_pairs requires one unique sample per unique donor")
62
+ if any(len(set(x)) != len(x) for x in (train, test, exc)):
63
+ raise ValueError("duplicate sample ID")
64
+ if not set(train + test + exc) <= set(index.index):
65
+ raise ValueError("unknown sample ID")
66
+ if set(train) & (set(test) | set(exc)) or set(test) & set(exc):
67
+ raise ValueError("training/test/excluded overlap")
68
+ if index.loc[train, "donor_id"].astype(str).tolist() != donors:
69
+ raise ValueError("train sample/donor mismatch")
70
+ if index.loc[test, "donor_id"].astype(str).tolist() != td:
71
+ raise ValueError("test sample/donor mismatch")
72
+ if set(donors) & set(td):
73
+ raise ValueError("test donor overlaps training")
74
+ if (index.loc[train + test, "fold"] < 0).any():
75
+ raise ValueError("identity-excluded row used")
76
+ all_selected = set(f.loc[f.donor_id.isin(donors), "sample_id"])
77
+ if set(exc) != all_selected - set(train):
78
+ raise ValueError("other selected-donor visits must be excluded")
79
+ if m.get("design") == "healthy_outerfold":
80
+ fold = int(m["unit"].split("fold")[1].split("_")[0])
81
+ expected = set(f.loc[f.fold == fold, "sample_id"])
82
+ if set(test) != expected or set(f.loc[f.sample_id.isin(train), "fold"]) & {fold}:
83
+ raise ValueError("healthy outer fold mismatch")
84
+ elif m.get("design") == "disease_existing_draw":
85
+ expected = set(f.loc[(f.fold >= 0) & ~f.donor_id.isin(donors), "sample_id"])
86
+ if set(test) != expected:
87
+ raise ValueError("disease test set mismatch")
88
+ else:
89
+ raise ValueError("unknown design")
90
+
91
+
92
+ def build_healthy(folds: pd.DataFrame, fold: int, n: int, *, seed: int) -> dict:
93
+ f = _rows(folds)
94
+ if fold not in range(5) or n < 1:
95
+ raise ValueError("invalid fold or n")
96
+ pool = f[(f.fold >= 0) & (f.fold != fold)]
97
+ # One permutation per fold, reused for every n: prefixes are nested.
98
+ donor_ids = sorted(pool.donor_id.unique())
99
+ if n > len(donor_ids):
100
+ raise ValueError("n exceeds training donors")
101
+ order = np.random.default_rng(seed).permutation(donor_ids).tolist()
102
+ train = []
103
+ for donor in order[:n]:
104
+ visits = sorted(pool.loc[pool.donor_id == donor, "sample_id"])
105
+ if len(visits) != 1:
106
+ raise ValueError("healthy donor has multiple visits; explicit visit policy required")
107
+ train.append(visits[0])
108
+ test = f.loc[f.fold == fold, "sample_id"].tolist()
109
+ return _finish("immicro", "healthy_outerfold", f"fold{fold}_n{n}", f, train, test, seed=seed)
110
+
111
+
112
+ def _time_key(value: object, cohort: str) -> tuple[float, str]:
113
+ s = str(value).strip()
114
+ try:
115
+ v = float(s)
116
+ if np.isfinite(v):
117
+ return v, s
118
+ except ValueError:
119
+ pass
120
+ match = re.fullmatch(r"(?:day|d|fu)[ _-]?(\d+(?:\.\d+)?)", s, re.I)
121
+ if match:
122
+ return float(match.group(1)), s
123
+ if cohort == "ji2025_chili" and s.upper() in ("BC", "AC", "TOL"):
124
+ return (1.0 if s.upper() == "AC" else 0.0), s
125
+ if s.lower() in ("none (single sample per donor)", "baseline"):
126
+ return 0.0, s
127
+ try:
128
+ return float(datetime.strptime(s, "%d/%m/%Y").date().toordinal()), s
129
+ except ValueError as exc:
130
+ raise ValueError(f"unparseable clinical time {s!r}") from exc
131
+
132
+
133
+ def build_disease(folds: pd.DataFrame, pairs: pd.DataFrame, draw_donors: list[str], cohort: str, draw: int,
134
+ *, strata_regex: str = "") -> dict:
135
+ f = _rows(folds)
136
+ if len(draw_donors) != 5 or len(set(draw_donors)) != 5:
137
+ raise ValueError("disease draw requires exactly five unique donors")
138
+ need = {"sample_id", "timepoint", "identity_pass"}
139
+ if not need <= set(pairs):
140
+ raise ValueError(f"pairs metadata missing {sorted(need - set(pairs))}")
141
+ p = pairs.copy()
142
+ p.sample_id = p.sample_id.astype(str)
143
+ if p.sample_id.duplicated().any():
144
+ raise ValueError("duplicate pairs metadata sample ID")
145
+ p = p.set_index("sample_id")
146
+ chosen, audit = [], []
147
+ for donor in draw_donors:
148
+ rows = f[(f.donor_id == str(donor)) & (f.fold >= 0)]
149
+ if rows.empty or not set(rows.sample_id) <= set(p.index):
150
+ raise ValueError(f"donor {donor}: missing usable pair metadata")
151
+ matches = rows.group.str.contains(strata_regex, regex=True) if strata_regex else pd.Series(True, index=rows.index)
152
+ stratum = bool(matches.any())
153
+ candidates = []
154
+ for _, row in rows.iterrows():
155
+ sid = row.sample_id
156
+ if "donor_id" in p and str(p.loc[sid, "donor_id"]) != str(donor):
157
+ raise ValueError(f"{sid}: pairs metadata donor mismatch")
158
+ if "group" in p and str(p.loc[sid, "group"]) != str(row.group):
159
+ raise ValueError(f"{sid}: pairs metadata group mismatch")
160
+ identity = p.loc[sid, "identity_pass"]
161
+ if not (isinstance(identity, (bool, np.bool_)) and bool(identity)) or bool(matches.loc[row.name]) != stratum:
162
+ continue
163
+ time_field = "sample_date" if cohort == "imperial_eskd" and "sample_date" in p else "timepoint"
164
+ value = p.loc[sid, time_field]
165
+ if pd.isna(value):
166
+ raise ValueError(f"{sid}: missing {time_field}; cannot rank visits on one clinical time axis")
167
+ key, raw = _time_key(value, cohort)
168
+ candidates.append({"sample_id": sid, "time_value": key, "time_raw": raw,
169
+ "time_field": time_field, "group": row.group})
170
+ candidates.sort(key=lambda x: (x["time_value"], x["sample_id"]))
171
+ if not candidates:
172
+ raise ValueError(f"donor {donor}: no identity-passed visit in assigned stratum")
173
+ chosen.append(candidates[0]["sample_id"])
174
+ audit.append({"donor_id": str(donor), "assigned_stratum": stratum,
175
+ "selected_sample_id": candidates[0]["sample_id"], "candidates": candidates})
176
+ test = f.loc[(f.fold >= 0) & ~f.donor_id.isin(draw_donors), "sample_id"].tolist()
177
+ return _finish(cohort, "disease_existing_draw", f"draw{draw}_n{len(chosen)}", f, chosen, test,
178
+ selection_audit=audit)
179
+
180
+
181
+ def write_manifest(path: Path, manifest: dict) -> None:
182
+ path = Path(path)
183
+ path.parent.mkdir(parents=True, exist_ok=True)
184
+ with path.open("x") as stream:
185
+ json.dump(manifest, stream, indent=2, allow_nan=False)
186
+ stream.write("\n")
187
+
188
+
189
+ def load_manifest(path: Path, folds: pd.DataFrame) -> dict:
190
+ m = json.loads(Path(path).read_text())
191
+ validate_manifest(m, folds)
192
+ return m
193
+
194
+
195
+ def select_rows(manifest: dict, folds: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]:
196
+ """Return exact training and test row indices in manifest order; no validation subset."""
197
+ validate_manifest(manifest, folds)
198
+ pos = {str(s): int(i) for i, s in enumerate(folds.sample_id)}
199
+ return (np.asarray([pos[s] for s in manifest["train_sample_ids"]], dtype=np.int64),
200
+ np.asarray([pos[s] for s in manifest["test_sample_ids"]], dtype=np.int64))
201
+
202
+
203
+ def validate_existing_run(manifest: dict, run: dict, *, fixed_steps: int, lora_rank: int,
204
+ source_checkpoint_sha256: str, condition_npz_sha256: str,
205
+ lr: float, lora_alpha: float, warmup: int, batch_size: int,
206
+ ema_decay: float, seed: int) -> None:
207
+ """Refuse a skip unless the existing checkpoint receipt matches the requested strict run."""
208
+ fields = (("support_sha256", manifest["sha256"]),
209
+ ("train_donor_ids", manifest["train_donor_ids"]),
210
+ ("inner_val_rows", []), ("fixed_steps", fixed_steps),
211
+ ("steps_run", fixed_steps), ("selected_step", fixed_steps),
212
+ ("mode", "lora"), ("source_checkpoint_sha256", source_checkpoint_sha256),
213
+ ("condition_npz_sha256", condition_npz_sha256), ("lr", lr),
214
+ ("warmup", warmup), ("batch_size", batch_size),
215
+ ("ema_decay", ema_decay), ("seed", seed))
216
+ for key, expected in fields:
217
+ if run.get(key) != expected:
218
+ raise ValueError(f"existing strict run mismatch: {key}")
219
+ if (run.get("trainable", {}).get("lora_rank") != lora_rank or
220
+ run.get("trainable", {}).get("lora_alpha") != lora_alpha):
221
+ raise ValueError("existing strict run mismatch: LoRA rank/alpha")
222
+ for key, expected in (("train_rows", manifest["train_sample_ids"]),
223
+ ("test_rows_never_loaded_for_training", manifest["test_sample_ids"])):
224
+ actual = run.get(key, [])
225
+ if len(actual) != len(expected) or set(actual) != set(expected):
226
+ raise ValueError(f"existing strict run mismatch: {key}")
paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/tools/verify_scsemi_adoption.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Validate explicit, same-budget legacy reuse without claiming new GPU work."""
2
+ import argparse
3
+ import json
4
+ from pathlib import Path
5
+ from import_scsemi_legacy import validate_adopted_generation
6
+ from score_strict import read_support
7
+ from runtime import atomic_json
8
+
9
+
10
+ def main():
11
+ p = argparse.ArgumentParser()
12
+ p.add_argument('--support-manifest', type=Path, required=True)
13
+ p.add_argument('--npz', type=Path, required=True)
14
+ p.add_argument('--out', type=Path, required=True)
15
+ a = p.parse_args()
16
+ binding = validate_adopted_generation(a.npz, read_support(a.support_manifest))
17
+ record = {'schema': 'pbisc.scsemi.verified-reuse.v1', 'state': 'completed',
18
+ 'new_gpu_training_or_inference': False, 'binding': binding}
19
+ if a.out.exists() and json.loads(a.out.read_text()) != record:
20
+ raise ValueError('existing adoption verification differs')
21
+ if not a.out.exists():
22
+ atomic_json(a.out, record)
23
+
24
+
25
+ if __name__ == '__main__':
26
+ main()