junidude14 commited on
Commit
bc66894
·
verified ·
1 Parent(s): 13f54cc

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261013T005008Z-reuse-audit-results-deck/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/reports/deconv_strict.md ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Strict five-pair deconvolution adapter
2
+
3
+ **2026-10-13 reuse correction:** all five Sepsis draws already have completed
4
+ BayesPrism and CIBERSORTx outputs on exactly the same five reference samples
5
+ and 77 mixture samples. Their `ADOPTION.json` records in
6
+ `deconvolution/ye2026_sepsis/disease/draw{0..4}/` verify source/input/output hashes,
7
+ axes and original draw-specific sampling. Sepsis runs **adopt → fresh corrected
8
+ CPU scoring**. Missing or changed proof fails closed; the adapter never reruns
9
+ either method as a fallback. Historical score-file versions are recorded
10
+ truthfully and are not relabelled as corrected results.
11
+
12
+ The native instructions below apply to the 15 Imperial/Giroux/Ji units whose
13
+ exact-five supports differ from the historical multi-visit supports. Existing
14
+ Sepsis source outputs must remain available for their hardlink/symlink views.
15
+
16
+ `tools/deconv_strict.py` runs one disease unit at a time. The support manifest is authoritative: exactly its five `train_sample_ids` form the reference, exactly its `test_sample_ids` form the real-bulk mixture, and `excluded_sample_ids` never enter either side. The old five-donor/all-visits split is not used. The original `aggregates_full.npz` is linked read-only inside the new unit output; it is a per-sample raw-count aggregate, not a fitted model or test-derived reference. The legacy builders and scorer are imported into one isolated Python invocation and redirected in memory. No legacy file is edited.
17
+
18
+ For a unit such as `protocol/splits/ji2025_chili/disease/draw0/support.json`, run from this plan directory:
19
+
20
+ ```bash
21
+ CUDA_VISIBLE_DEVICES='' python tools/deconv_strict.py --support-manifest protocol/splits/ji2025_chili/disease/draw0/support.json --action prepare --threads 4
22
+ CUDA_VISIBLE_DEVICES='' python tools/deconv_strict.py --support-manifest protocol/splits/ji2025_chili/disease/draw0/support.json --action bayesprism --threads 4
23
+ CUDA_VISIBLE_DEVICES='' python tools/deconv_strict.py --support-manifest protocol/splits/ji2025_chili/disease/draw0/support.json --action cibersortx --threads 4
24
+ CUDA_VISIBLE_DEVICES='' python tools/deconv_strict.py --support-manifest protocol/splits/ji2025_chili/disease/draw0/support.json --action score --threads 4
25
+ ```
26
+
27
+ `--action all` performs the native stages in order for non-Sepsis cohorts and adoption plus scoring for Sepsis. `--out` is accepted only when it equals the unit's canonical `deconvolution/<cohort>/disease/drawN` directory. Native method runs apply only to the 15 non-Sepsis disease support manifests, one unit at a time. The CIBERSORTx action checks the two existing local images. It reads `cibersortx.key` only at runtime, writes a temporary mode-600 env file, expands credentials inside the container, redacts any echoed values before saving a log, and removes the temp file. It does not install images. Its two containers are each capped at 16 GiB and the requested CPU count. BayesPrism reuses the existing pinned R script and R library.
28
+
29
+ Memory-heavy native methods and scoring run the host guard checks first, defer when CUDA compute is present, and require at least 48 GiB `MemAvailable`. Lightweight Sepsis adoption verifies existing files without launching a method. The adapter never starts a CUDA process.
30
+
31
+ Each unit writes `INPUTS.json`, BayesPrism and CIBERSORTx method outputs, and `score/{figure4_methods.csv,expression_signal.csv,SUMMARY.json}`. The shared `deconvolution/deconvolution_manifest.json` is an atomic Figure 4 input with exact support hash, reference and mixture IDs, source hashes, methods, metric summaries, and CSV hashes. Pass it to `tools/build_results_figures.py --deconvolution-manifest deconvolution/deconvolution_manifest.json`. The old five-fold results remain a separately labelled historical panel.
32
+
33
+ Preparation is immutable once `INPUTS.json` exists: rerunning `prepare` verifies every input hash and the raw-count aggregate link, then returns without rewriting. A method's existing `DONE` is reusable only with a receipt bound to the support hash, prepared input hash, and method output hashes. HiRes also binds its copied Fractions signature, source GEP, and filtered fractions results. Changed inputs, an unreceipted existing `DONE`, or partial method files fail closed; the adapter does not delete or automatically relaunch those outputs.
34
+
35
+ The composition CSV contains observed and predicted cell fractions by test sample and six-type gate. The signal CSV has a donor-aware primary sensitivity: visits are averaged within donor and case/control condition after per-sample log2-CPM normalization, so each donor-condition contributes once. On the same covered scoring genes, observed and method profiles receive separate unweighted limma `lmFit`/`eBayes` fits, with `duplicateCorrelation` and donor blocking when donors appear in both conditions. It exports donor-equal logFC correlation, partial correlation given real bulk, and FDR-significant top-50 DEG overlap where estimable. BayesPrism Z and CIBERSORTx HiRes are continuous posterior or imputed expression, so this is labelled continuous-expression sensitivity, separate from the raw-integer-count edgeR/limma-voom primary in `donor_statistics.py`. The historical sample-level Welch family is retained with distinct metric names and `gene_variant` values. HiRes with at most eight mixture samples, missing output, or zero imputed genes is `not_estimable`, never zero. Missing limma infrastructure is `pending`; scientifically underpowered groups or genes are `not_estimable`. Method-only scores are not relabelled as a LoRA comparison.
36
+
37
+ `score/SUMMARY.json` has top-level `status`, `required_methods`, `methods`, `metrics`, and `pending_reasons`. A completed method has `methods.<name>.status=complete`; a missing required method or required HiRes output is `pending`. `metrics.<name>.corrected_deg.status` is `complete`, `not_estimable` for a scientific data limit, or `pending` for missing fit infrastructure. Any pending method or type fit makes the top-level status `pending`; the `score`/`all` CLI action returns nonzero and does not publish a Figure 4 manifest entry. If a previous completed entry exists, it moves to `inactive_units` with its evidence preserved so Figure 4 cannot mistake a pending rerun for completion. HiRes at most eight mixtures or a verified zero-imputed result is scientifically `not_estimable`.
38
+
39
+ Verification so far: thirteen focused CPU tests pass, covering all 20 strict support manifests, exact five-reference selection, exclusion of visits, rejection of extra or missing method mixtures and HiRes types, output isolation and hostile unit paths, receipt/input immutability and partial-output preservation, pending readiness precedence and stale Figure 4 invalidation, credential-free host argv and saved logs, equal donor-condition weighting with repeated visits, and tiny unpaired/paired limma fixtures. No BayesPrism or CIBERSORTx method was executed as part of this implementation.
paper-releases/pbisc-diffusion/updates/20261013T005008Z-reuse-audit-results-deck/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/tests/test_deconv_adoption.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reject scientific/provenance drift and avoid repeating completed Sepsis methods."""
2
+ from __future__ import annotations
3
+
4
+ import gzip
5
+ import errno
6
+ import hashlib
7
+ import importlib
8
+ import json
9
+ import sys
10
+ from pathlib import Path
11
+
12
+ import pytest
13
+
14
+ ROOT = Path(__file__).resolve().parents[1]
15
+ sys.path.insert(0, str(ROOT / "tools"))
16
+ import deconv_strict as D
17
+
18
+
19
+ def digest(p: Path) -> str:
20
+ return hashlib.sha256(p.read_bytes()).hexdigest()
21
+
22
+
23
+ def write(p: Path, value: str) -> Path:
24
+ p.parent.mkdir(parents=True, exist_ok=True)
25
+ if p.suffix == ".gz":
26
+ with gzip.open(p, "wt") as f:
27
+ f.write(value)
28
+ else:
29
+ p.write_text(value)
30
+ return p
31
+
32
+
33
+ def fixture(tmp: Path, draw: int = 3) -> tuple[dict, Path, Path, Path]:
34
+ old, ft, out = tmp / "old", tmp / "ft", tmp / "unit"
35
+ train, test = [f"S{i}" for i in range(5)], [f"T{i}" for i in range(9)]
36
+ s = dict(schema="pbisc.paper.strict-support.v1", cohort="ye2026_sepsis",
37
+ design="disease_existing_draw", unit=f"draw{draw}_n5", n_pairs=5,
38
+ train_sample_ids=train, train_donor_ids=train, test_sample_ids=test,
39
+ test_donor_ids=test, excluded_sample_ids=[])
40
+ s["sha256"] = hashlib.sha256(json.dumps(s, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
41
+ for name in ("build_split.py", "build_cibersortx_inputs.py", "common.py", "score_bp.py",
42
+ "run_bp.R", "run_cibersortx.sh"):
43
+ write(old / "tools" / name, f"source {name}\n")
44
+ write(ft / "tools/score_ft.py", "score source\n")
45
+ aggregate = write(old / "data/ye2026_sepsis/aggregates_full.npz", "aggregate fixture\n")
46
+ bp = old / f"inputs/ye2026_sepsis/fewshot{draw}_full"
47
+ cx = old / f"cibersortx/ye2026_sepsis/fewshot{draw}"
48
+ types = ["B cell", "DC", "Monocyte", "NK cell", "Other", "T cell"]
49
+ for name, val in (("reference.tsv.gz", "state\tG1\nT|a\t2\n"),
50
+ ("mixture.tsv.gz", "sample\tG1\n" + "".join(f"{x}\t2\n" for x in test)),
51
+ ("state_types.tsv", "state\ttype\tn_cells\nT|a\tT cell\t10\n")):
52
+ write(bp / name, val)
53
+ b = dict(dataset=s["cohort"], kind="fewshot", idx=draw, reference=train[::-1], mixture=test,
54
+ train_donors=train[::-1], run_json_check=True, n_reference_samples=5,
55
+ n_mixture_samples=9, gene_mode="full", aggregates_sha256=digest(aggregate),
56
+ tool_sha256=digest(old / "tools/build_split.py"),
57
+ common_sha256=digest(old / "tools/common.py"),
58
+ files={n: digest(bp / n) for n in ("reference.tsv.gz", "mixture.tsv.gz", "state_types.tsv")})
59
+ write(bp / "SPLIT.json", json.dumps(b))
60
+ for name in ("refsample.txt", "mixture.txt", "hires_genes.txt"):
61
+ write(cx / name, f"{name} draw {draw}\n")
62
+ c = dict(dataset=s["cohort"], kind="fewshot", idx=draw, reference_samples=train,
63
+ mixture_samples=test, seed=20261006, cells_per_type_cap=400,
64
+ tool_sha256=digest(old / "tools/build_cibersortx_inputs.py"),
65
+ common_sha256=digest(old / "tools/common.py"),
66
+ files={n: digest(cx / n) for n in ("refsample.txt", "mixture.txt", "hires_genes.txt")})
67
+ write(cx / "INPUT.json", json.dumps(c))
68
+ theta = "," + ",".join(types) + "\n" + "".join(f"{x},0.1,0.1,0.2,0.2,0.2,0.2\n" for x in test)
69
+ write(bp / "bp/theta_final.csv", theta)
70
+ write(bp / "bp/theta_first.csv", theta)
71
+ write(bp / "bp/genes_used.txt", "G1\n")
72
+ write(bp / "bp/DONE", "1.2\n")
73
+ for typ in types:
74
+ write(bp / f"bp/Z_type_{typ.replace(' ', '_')}.tsv.gz", "sample\tG1\n" + "".join(f"{x}\t2\n" for x in test))
75
+ write(cx / f"out_hires/CIBERSORTxHiRes_NA_{typ.replace(' ', '')}_Window24.txt",
76
+ "GeneSymbol\t" + "\t".join(test) + "\nG1\t" + "\t".join(["2"] * 9) + "\n")
77
+ write(cx / "out_fractions/CIBERSORTx_Adjusted.txt", theta.replace(",", "\t"))
78
+ write(cx / "out_fractions/DONE", "10\n")
79
+ write(cx / "out_hires/DONE", "20\n")
80
+ for a, bname, content in [("sigmatrix.txt", "fixture_inferred_refsample.bm.K999.txt", "signature\n"),
81
+ ("source_geps.txt", "CIBERSORTx_cell_type_sourceGEP.txt", "gep\n")]:
82
+ write(cx / a, content); write(cx / "out_fractions" / bname, content)
83
+ write(cx / "out_hires/fractions_results.txt", theta.replace(",", "\t"))
84
+ for mode, method in (("full", "bayesprism"), ("cibersortx", "cibersortx")):
85
+ summary = dict(dataset=s["cohort"], comparison="fewshot", draw=draw, gene_mode=mode,
86
+ n_donors=9, method=method, has_cell_type_expression=True,
87
+ tool_sha256=digest(old / "tools/score_bp.py"),
88
+ score_ft_sha256=digest(ft / "tools/score_ft.py"),
89
+ gates={"observed_composition_equal": True, "broadcast_r_equal": True, "broadcast_deg_equal": True})
90
+ write(old / f"results/ye2026_sepsis/fewshot_draw{draw}_{mode}/summary.json", json.dumps(summary))
91
+ return s, old, ft, out
92
+
93
+
94
+ def helper():
95
+ assert (ROOT / "tools/adopt_deconv_legacy.py").is_file(), "Missing explicit historical adoption path"
96
+ return importlib.import_module("adopt_deconv_legacy")
97
+
98
+
99
+ def test_adopts_completed_methods_without_claiming_native_execution(tmp_path: Path):
100
+ a = helper()
101
+ s, old, ft, out = fixture(tmp_path)
102
+ proof = a.adopt(s, out, old=old, ft=ft)
103
+ assert proof["schema"] == "pbisc.deconvolution.adopted-legacy.v1"
104
+ assert proof["legacy_draw_index"] == 3
105
+ assert proof["method_execution"] == "historical_outputs_reused_no_method_execution"
106
+ assert (out / "adopted_legacy/cibersortx/ye2026_sepsis/fewshot3/INPUT.json").is_file()
107
+ assert not (out / "adopted_legacy/cibersortx/ye2026_sepsis/fewshot0").exists()
108
+ assert a.verify(s, out)["support_sha256"] == s["sha256"]
109
+ before = (out / "ADOPTION.json").read_bytes()
110
+ a.adopt(s, out, old=old, ft=ft)
111
+ assert (out / "ADOPTION.json").read_bytes() == before
112
+
113
+
114
+ @pytest.mark.parametrize("change", ["support", "input", "source", "missing_done", "wrong_output_samples"])
115
+ def test_invalid_scientific_or_provenance_inputs_fail_before_adoption(tmp_path: Path, change: str):
116
+ a = helper()
117
+ s, old, ft, out = fixture(tmp_path)
118
+ if change == "support":
119
+ s["train_sample_ids"][0] = "EXTRA"
120
+ elif change == "input":
121
+ write(old / "cibersortx/ye2026_sepsis/fewshot3/refsample.txt", "altered")
122
+ elif change == "source":
123
+ write(old / "tools/build_split.py", "changed source")
124
+ elif change == "missing_done":
125
+ (old / "inputs/ye2026_sepsis/fewshot3_full/bp/DONE").unlink()
126
+ else:
127
+ f = old / "inputs/ye2026_sepsis/fewshot3_full/bp/theta_final.csv"
128
+ f.write_text(f.read_text().replace("T0,", "TRAIN,"))
129
+ with pytest.raises((ValueError, FileNotFoundError)):
130
+ a.adopt(s, out, old=old, ft=ft)
131
+ assert not (out / "ADOPTION.json").exists()
132
+
133
+
134
+ def test_adopted_output_mutation_is_rejected(tmp_path: Path):
135
+ a = helper()
136
+ s, old, ft, out = fixture(tmp_path)
137
+ a.adopt(s, out, old=old, ft=ft)
138
+ write(old / "cibersortx/ye2026_sepsis/fewshot3/out_hires/CIBERSORTxHiRes_NA_Tcell_Window24.txt", "altered")
139
+ with pytest.raises(ValueError, match="changed"):
140
+ a.verify(s, out)
141
+
142
+
143
+ def test_fraction_serialization_roundoff_is_preserved_but_actual_changes_rejected(tmp_path: Path):
144
+ a = helper()
145
+ s, old, ft, out = fixture(tmp_path)
146
+ p = old / "cibersortx/ye2026_sepsis/fewshot3/out_hires/fractions_results.txt"
147
+ p.write_text(p.read_text().replace("0.2", "0.2000000000000001"))
148
+ assert a.verify_legacy(s, old=old, ft=ft)["fraction_serialization_max_abs_error"] < 2e-16
149
+ p.write_text(p.read_text().replace("0.2000000000000001", "0.21"))
150
+ with pytest.raises(ValueError, match="fractions differ"):
151
+ a.verify_legacy(s, old=old, ft=ft)
152
+
153
+
154
+ def test_altered_adoption_manifest_cannot_drop_hash_checks(tmp_path: Path):
155
+ a = helper()
156
+ s, old, ft, out = fixture(tmp_path)
157
+ a.adopt(s, out, old=old, ft=ft)
158
+ p = out / "ADOPTION.json"
159
+ proof = json.loads(p.read_text())
160
+ proof["files"].pop()
161
+ p.write_text(json.dumps(proof))
162
+ with pytest.raises(ValueError, match="receipt hash"):
163
+ a.verify(s, out)
164
+
165
+
166
+ def test_older_scoring_receipt_is_kept_as_historical_not_claimed_replayed(tmp_path: Path):
167
+ a = helper()
168
+ s, old, ft, out = fixture(tmp_path)
169
+ p = old / "results/ye2026_sepsis/fewshot_draw3_full/summary.json"
170
+ summary = json.loads(p.read_text())
171
+ summary.pop("has_cell_type_expression")
172
+ summary.pop("method")
173
+ summary["bayesprism"] = {"per_type_logfc_r": {k: 0.5 for k in ("T cell", "B cell", "Monocyte", "NK cell")}}
174
+ summary["tool_sha256"] = "a" * 64
175
+ p.write_text(json.dumps(summary))
176
+ proof = a.verify_legacy(s, old=old, ft=ft)
177
+ assert proof["legacy_endpoints"]["full"]["old_scores_reused"] is False
178
+ assert proof["legacy_endpoints"]["full"]["scorer_source_matches_current"] is False
179
+
180
+
181
+ def test_readable_root_owned_outputs_reuse_symlinks_without_copying(tmp_path: Path, monkeypatch):
182
+ a = helper()
183
+ s, old, ft, out = fixture(tmp_path)
184
+ link = a.os.link
185
+ def protected(source, target):
186
+ if Path(source).name == "CIBERSORTx_Adjusted.txt":
187
+ raise PermissionError(errno.EPERM, "protected hardlink")
188
+ return link(source, target)
189
+ monkeypatch.setattr(a.os, "link", protected)
190
+ a.adopt(s, out, old=old, ft=ft)
191
+ target = out / "adopted_legacy/cibersortx/ye2026_sepsis/fewshot3/out_fractions/CIBERSORTx_Adjusted.txt"
192
+ assert target.is_symlink()
193
+ assert target.resolve() == old / "cibersortx/ye2026_sepsis/fewshot3/out_fractions/CIBERSORTx_Adjusted.txt"
194
+ assert a.verify(s, out)["legacy_draw_index"] == 3
195
+
196
+
197
+ def test_sepsis_method_calls_reuse_and_never_spawn_method_process(tmp_path: Path, monkeypatch):
198
+ a = helper()
199
+ s, old, ft, out = fixture(tmp_path)
200
+ a.adopt(s, out, old=old, ft=ft)
201
+ monkeypatch.setattr(D.subprocess, "run", lambda *_a, **_k: pytest.fail("method subprocess launched"))
202
+ D.bayesprism(s, out, 2)
203
+ assert D.cibersortx(s, out, 2)["hires"] == "complete"
204
+ assert D.verify_stage_receipt(s, out, "hires")["method_execution"] == "historical_outputs_reused_no_method_execution"
205
+
206
+
207
+ def test_unproved_sepsis_fails_without_launch_or_heavy_prepare(tmp_path: Path, monkeypatch):
208
+ helper()
209
+ s, old, ft, out = fixture(tmp_path)
210
+ monkeypatch.setattr(D, "OLD", tmp_path / "absent")
211
+ monkeypatch.setattr(D.subprocess, "run", lambda *_a, **_k: pytest.fail("unproved method relaunched"))
212
+ with pytest.raises((ValueError, FileNotFoundError)):
213
+ D.bayesprism(s, out, 2)
214
+
215
+
216
+ def test_strict_split_dispatch_preserves_draw_specific_subsampling(tmp_path: Path):
217
+ s, old, ft, out = fixture(tmp_path)
218
+ c = D.patched_modules(s, out)
219
+ assert c.split_rows("ye2026_sepsis", "fewshot", 3)["reference"] == s["train_sample_ids"]
220
+ with pytest.raises(ValueError):
221
+ c.split_rows("ye2026_sepsis", "fewshot", 0)
222
+
223
+
224
+ def test_finalizer_uses_adopt_then_score_and_preserves_existing_adoption(tmp_path: Path, monkeypatch):
225
+ import finalize_campaign as f
226
+ s, old, ft, out = fixture(tmp_path)
227
+ monkeypatch.setattr(f, "ROOT", tmp_path)
228
+ monkeypatch.setattr(f.C, "ROOT", tmp_path)
229
+ monkeypatch.setattr(f, "wait_cuda_idle", lambda: None)
230
+ path = write(tmp_path / "protocol/splits/ye2026_sepsis/disease/draw3/support.json", json.dumps(s))
231
+ target = tmp_path / "deconvolution/ye2026_sepsis/disease/draw3"
232
+ helper().adopt(s, target, old=old, ft=ft)
233
+ calls = []
234
+ class RuntimeBoundary:
235
+ def receipt_path(self, name):
236
+ return tmp_path / "receipts" / f"{name}.json"
237
+ def execute(self, name, argv, **kwargs):
238
+ action = argv[argv.index("--action") + 1]
239
+ calls.append((action, kwargs))
240
+ if action == "score":
241
+ write(target / "score/SUMMARY.json", '{"status":"complete"}')
242
+ f.deconvolution(RuntimeBoundary(), [path])
243
+ assert [x[0] for x in calls] == ["adopt", "score"]
244
+ assert calls[0][1]["previous_outputs"][str(target / "ADOPTION.json")]["sha256"] == digest(target / "ADOPTION.json")
245
+
246
+
247
+ def test_finalizer_checks_live_sources_before_runtime_can_skip(tmp_path: Path, monkeypatch):
248
+ import finalize_campaign as f
249
+ s, old, ft, out = fixture(tmp_path)
250
+ monkeypatch.setattr(f, "ROOT", tmp_path)
251
+ monkeypatch.setattr(f.C, "ROOT", tmp_path)
252
+ path = write(tmp_path / "protocol/splits/ye2026_sepsis/disease/draw3/support.json", json.dumps(s))
253
+ target = tmp_path / "deconvolution/ye2026_sepsis/disease/draw3"
254
+ helper().adopt(s, target, old=old, ft=ft)
255
+ write(old / "cibersortx/ye2026_sepsis/fewshot3/refsample.txt", "altered")
256
+ class RuntimeBoundary:
257
+ def receipt_path(self, name):
258
+ return tmp_path / "receipts" / f"{name}.json"
259
+ def execute(self, *_args, **_kwargs):
260
+ pytest.fail("unchecked adoption reached runtime skip/execute")
261
+ with pytest.raises(ValueError, match="changed"):
262
+ f.deconvolution(RuntimeBoundary(), [path])
paper-releases/pbisc-diffusion/updates/20261013T005008Z-reuse-audit-results-deck/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/tools/adopt_deconv_legacy.py ADDED
@@ -0,0 +1,312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bounded-memory, fail-closed adoption of completed exact-five Sepsis deconvolution.
2
+
3
+ This does not execute either method or prepare new reference cells. Historical
4
+ input manifests, completion markers, scored summaries and current source bytes
5
+ are verified before a separate provenance receipt and linked view are created.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import csv
11
+ import errno
12
+ import gzip
13
+ import hashlib
14
+ import json
15
+ import math
16
+ import os
17
+ import re
18
+ import tempfile
19
+ from pathlib import Path
20
+
21
+ PLAN = Path(__file__).resolve().parents[1]
22
+ OLD = PLAN.parent / "bayesprism_paired_20261006"
23
+ FT = PLAN.parent / "paired_finetune_intradataset_20260927"
24
+ SCHEMA = "pbisc.deconvolution.adopted-legacy.v1"
25
+ TYPES = ("B cell", "DC", "Monocyte", "NK cell", "Other", "T cell")
26
+
27
+
28
+ def sha(path: Path, *, unpack: bool = False) -> str:
29
+ h = hashlib.sha256()
30
+ with (gzip.open(path, "rb") if unpack else path.open("rb")) as f:
31
+ for chunk in iter(lambda: f.read(1 << 20), b""):
32
+ h.update(chunk)
33
+ return h.hexdigest()
34
+
35
+
36
+ def read(path: Path) -> dict:
37
+ return json.loads(path.read_text())
38
+
39
+
40
+ def receipt_hash(proof: dict) -> str:
41
+ body = {k: v for k, v in proof.items() if k != "receipt_sha256"}
42
+ return hashlib.sha256(json.dumps(body, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()).hexdigest()
43
+
44
+
45
+ def _support(s: dict) -> int:
46
+ body = {k: v for k, v in s.items() if k != "sha256"}
47
+ expected = hashlib.sha256(json.dumps(body, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()).hexdigest()
48
+ if s.get("sha256") != expected or s.get("schema") != "pbisc.paper.strict-support.v1":
49
+ raise ValueError("strict support hash/schema mismatch")
50
+ match = re.fullmatch(r"draw([0-4])_n5", s.get("unit", ""))
51
+ if s.get("cohort") != "ye2026_sepsis" or not match or s.get("design") != "disease_existing_draw":
52
+ raise ValueError("legacy adoption is limited to exact-five Sepsis draws")
53
+ train, test = s["train_sample_ids"], s["test_sample_ids"]
54
+ if (s.get("n_pairs") != 5 or len(train) != 5 or len(set(train)) != 5
55
+ or len(s["train_donor_ids"]) != 5 or len(set(s["train_donor_ids"])) != 5
56
+ or not test or len(test) != len(set(test)) or len(test) != len(s["test_donor_ids"])
57
+ or set(train) & set(test) or set(s["train_donor_ids"]) & set(s["test_donor_ids"])
58
+ or set(s["excluded_sample_ids"]) & set(train + test)):
59
+ raise ValueError("invalid exact-five support")
60
+ return int(match.group(1))
61
+
62
+
63
+ def _axis(path: Path, samples: list[str], *, columns: bool = False, sep: str = "\t") -> None:
64
+ """Read only labels/axes, never materialize an expression matrix."""
65
+ with (gzip.open(path, "rt") if path.suffix == ".gz" else path.open()) as f:
66
+ rows = csv.reader(f, delimiter=sep)
67
+ header = next(rows)
68
+ ids = header[1:] if columns else [r[0] for r in rows if r]
69
+ if len(ids) != len(samples) or set(ids) != set(samples):
70
+ raise ValueError(f"output mixtures differ from exact support: {path}")
71
+
72
+
73
+ def _files(manifest: dict, directory: Path, names: tuple[str, ...]) -> list[Path]:
74
+ if set(manifest.get("files", {})) != set(names):
75
+ raise ValueError(f"unexpected input file contract: {directory}")
76
+ paths = []
77
+ for name in names:
78
+ path = directory / name
79
+ if sha(path) != manifest["files"][name]:
80
+ raise ValueError(f"legacy input changed: {path}")
81
+ paths.append(path)
82
+ return paths
83
+
84
+
85
+ def verify_legacy(s: dict, *, old: Path = OLD, ft: Path = FT) -> dict:
86
+ draw = _support(s)
87
+ ds, split = s["cohort"], f"fewshot{draw}"
88
+ bp, cx = old / "inputs" / ds / f"{split}_full", old / "cibersortx" / ds / split
89
+ b, c = read(bp / "SPLIT.json"), read(cx / "INPUT.json")
90
+ artifacts = [bp / "SPLIT.json", cx / "INPUT.json"]
91
+ for manifest, rk, mk in ((b, "reference", "mixture"), (c, "reference_samples", "mixture_samples")):
92
+ if (manifest.get("dataset") != ds or manifest.get("kind") != "fewshot" or manifest.get("idx") != draw
93
+ or len(manifest[rk]) != 5 or set(manifest[rk]) != set(s["train_sample_ids"])
94
+ or manifest[mk] != s["test_sample_ids"]):
95
+ raise ValueError("legacy reference/mixture differs from exact support or draw")
96
+ if (b.get("gene_mode") != "full" or b.get("run_json_check") is not True
97
+ or set(b["train_donors"]) != set(s["train_donor_ids"])
98
+ or b.get("n_reference_samples") != 5 or b.get("n_mixture_samples") != len(s["test_sample_ids"])
99
+ or c.get("seed") != 20261006 or c.get("cells_per_type_cap") != 400):
100
+ raise ValueError("legacy scientific recipe differs")
101
+ for manifest, name in ((b, "build_split.py"), (c, "build_cibersortx_inputs.py")):
102
+ for field, src in (("tool_sha256", old / "tools" / name),
103
+ ("common_sha256", old / "tools/common.py")):
104
+ if sha(src) != manifest[field]:
105
+ raise ValueError(f"legacy source changed: {src}")
106
+ artifacts.append(src)
107
+ aggregate = old / "data" / ds / "aggregates_full.npz"
108
+ if sha(aggregate) != b["aggregates_sha256"]:
109
+ raise ValueError("legacy raw-count aggregate changed")
110
+ artifacts.append(aggregate)
111
+ artifacts += _files(b, bp, ("reference.tsv.gz", "mixture.tsv.gz", "state_types.tsv"))
112
+ artifacts += _files(c, cx, ("refsample.txt", "mixture.txt", "hires_genes.txt"))
113
+ for method in (bp / "bp", cx / "out_fractions", cx / "out_hires"):
114
+ done = method / "DONE"
115
+ if not done.is_file() or not done.read_text().strip():
116
+ raise FileNotFoundError(f"legacy DONE missing: {done}")
117
+ artifacts.append(done)
118
+ for name in ("theta_final.csv", "theta_first.csv"):
119
+ p = bp / "bp" / name
120
+ _axis(p, s["test_sample_ids"], sep=",")
121
+ artifacts.append(p)
122
+ artifacts.append(bp / "bp/genes_used.txt")
123
+ for typ in TYPES:
124
+ p = bp / "bp" / f"Z_type_{typ.replace(' ', '_')}.tsv.gz"
125
+ _axis(p, s["test_sample_ids"])
126
+ artifacts.append(p)
127
+ candidates = sorted((cx / "out_hires").glob(f"CIBERSORTxHiRes_*_{typ.replace(' ', '')}_Window*.txt"))
128
+ if len(candidates) != 1:
129
+ raise ValueError(f"missing or ambiguous historical HiRes type: {typ}")
130
+ _axis(candidates[0], s["test_sample_ids"], columns=True)
131
+ artifacts.append(candidates[0])
132
+ fractions = cx / "out_fractions/CIBERSORTx_Adjusted.txt"
133
+ _axis(fractions, s["test_sample_ids"])
134
+ artifacts.append(fractions)
135
+ signatures = sorted((cx / "out_fractions").glob("*inferred_refsample.bm.K999.txt"))
136
+ if len(signatures) != 1 or sha(signatures[0]) != sha(cx / "sigmatrix.txt"):
137
+ raise ValueError("historical HiRes signature differs from Fractions output")
138
+ gep = cx / "out_fractions/CIBERSORTx_cell_type_sourceGEP.txt"
139
+ if sha(gep) != sha(cx / "source_geps.txt"):
140
+ raise ValueError("historical HiRes source GEP differs from Fractions output")
141
+ selected_fractions = cx / "out_hires/fractions_results.txt"
142
+ _axis(selected_fractions, s["test_sample_ids"])
143
+ fraction_error = 0.0
144
+ with fractions.open() as f, selected_fractions.open() as g:
145
+ source_rows, used_rows = csv.DictReader(f, delimiter="\t"), csv.DictReader(g, delimiter="\t")
146
+ fields = [x for x in source_rows.fieldnames if x not in ("P-value", "Correlation", "RMSE")]
147
+ if fields != used_rows.fieldnames:
148
+ raise ValueError("historical HiRes fraction columns differ")
149
+ for left, right in zip(source_rows, used_rows, strict=True):
150
+ errors = [abs(float(left[k]) - float(right[k])) for k in fields[1:]]
151
+ if left[fields[0]] != right[fields[0]] or any(not math.isfinite(v) or v > 1e-15 for v in errors):
152
+ raise ValueError("historical HiRes fractions differ from Fractions output")
153
+ fraction_error = max(fraction_error, max(errors, default=0.0))
154
+ artifacts += [signatures[0], cx / "sigmatrix.txt", gep, cx / "source_geps.txt", selected_fractions]
155
+ endpoints = {}
156
+ for mode in ("full", "cibersortx"):
157
+ p = old / "results" / ds / f"fewshot_draw{draw}_{mode}/summary.json"
158
+ summary = read(p)
159
+ expression_present = summary.get("has_cell_type_expression") is True or (
160
+ mode == "full" and set(summary.get("bayesprism", {}).get("per_type_logfc_r", {}))
161
+ >= {"T cell", "B cell", "Monocyte", "NK cell"})
162
+ if (summary.get("dataset") != ds or summary.get("comparison") != "fewshot"
163
+ or summary.get("draw") != draw or summary.get("gene_mode") != mode
164
+ or summary.get("n_donors") != len(s["test_sample_ids"])
165
+ or not expression_present
166
+ or not all(summary.get("gates", {}).get(k) is True for k in
167
+ ("observed_composition_equal", "broadcast_r_equal", "broadcast_deg_equal"))):
168
+ raise ValueError("legacy scoring receipt does not cover exact mixtures/expression")
169
+ for field, src in (("tool_sha256", old / "tools/score_bp.py"),
170
+ ("score_ft_sha256", ft / "tools/score_ft.py")):
171
+ # Old summary estimators are not adopted as new statistics. Their
172
+ # source digest is retained even when the scorer has since evolved.
173
+ if not re.fullmatch(r"[0-9a-f]{64}", summary.get(field, "")):
174
+ raise ValueError(f"historical scorer digest missing: {p}")
175
+ if field == "score_ft_sha256" and sha(src) != summary[field]:
176
+ raise ValueError(f"legacy scoring source changed: {src}")
177
+ artifacts.append(src)
178
+ artifacts.append(p)
179
+ endpoints[mode] = {"n_samples": summary["n_donors"], "has_cell_type_expression": True,
180
+ "hires_imputed_genes": summary.get("hires_imputed_genes"),
181
+ "old_scores_reused": False, "fresh_corrected_scoring_required": True,
182
+ "recorded_scorer_sha256": summary["tool_sha256"],
183
+ "current_scorer_sha256": sha(old / "tools/score_bp.py"),
184
+ "scorer_source_matches_current": sha(old / "tools/score_bp.py") == summary["tool_sha256"]}
185
+ artifacts += [old / "tools/run_bp.R", old / "tools/run_cibersortx.sh"]
186
+ files = []
187
+ for p in sorted(set(artifacts)):
188
+ if not p.is_file() or p.stat().st_size == 0:
189
+ raise FileNotFoundError(f"historical evidence missing or empty: {p}")
190
+ files.append({"source": str(p.resolve()), "sha256": sha(p), "bytes": p.stat().st_size,
191
+ "view": str(p.relative_to(old)) if p.is_relative_to(old) else None})
192
+ return {"schema": SCHEMA, "support_sha256": s["sha256"], "cohort": ds, "unit": s["unit"],
193
+ "reference_sample_ids": s["train_sample_ids"], "mixture_sample_ids": s["test_sample_ids"],
194
+ "legacy_draw_index": draw, "legacy_split": split,
195
+ "method_execution": "historical_outputs_reused_no_method_execution",
196
+ "input_equivalence": "exact support and ordered mixtures; original recorded draw-specific reference-cell subsampling retained",
197
+ "output_hash_basis": "current historical completed and scored files, verified now; not a retroactive native execution receipt",
198
+ "aggregate_source": str(aggregate.resolve()), "aggregate_sha256": b["aggregates_sha256"],
199
+ "fraction_serialization_max_abs_error": fraction_error,
200
+ "legacy_endpoints": endpoints, "files": files}
201
+
202
+
203
+ def _native_inputs(s: dict, out: Path, old: Path) -> list[dict]:
204
+ """Keep prepared draw0 bytes in place and prove their equality before adoption."""
205
+ receipt = out / "INPUTS.json"
206
+ if not receipt.exists():
207
+ return []
208
+ r = read(receipt)
209
+ if r.get("support_sha256") != s["sha256"]:
210
+ raise ValueError("existing native prepared input support differs")
211
+ draw = _support(s)
212
+ bp, cx = out / "inputs" / s["cohort"] / "fewshot0_full", out / "cibersortx" / s["cohort"] / "fewshot0"
213
+ if draw != 0:
214
+ raise ValueError("preserve and explicitly migrate pre-existing reset-index inputs before adopting this draw")
215
+ evidence = [receipt]
216
+ for directory, manifest, root, names in (
217
+ (bp, "SPLIT.json", old / "inputs" / s["cohort"] / "fewshot0_full", ("reference.tsv.gz", "mixture.tsv.gz", "state_types.tsv")),
218
+ (cx, "INPUT.json", old / "cibersortx" / s["cohort"] / "fewshot0", ("refsample.txt", "mixture.txt", "hires_genes.txt"))):
219
+ m = read(directory / manifest)
220
+ _files(m, directory, names)
221
+ evidence.append(directory / manifest)
222
+ for name in names:
223
+ p = directory / name
224
+ if sha(p, unpack=name.endswith(".gz")) != sha(root / name, unpack=name.endswith(".gz")):
225
+ raise ValueError(f"existing native input differs from legacy: {p}")
226
+ evidence.append(p)
227
+ for method in (bp / "bp", cx / "out_fractions", cx / "out_hires"):
228
+ if method.exists() and any(method.iterdir()):
229
+ raise ValueError("native method evidence already exists; refusing implicit replacement")
230
+ return [{"source": str(p.resolve()), "sha256": sha(p), "bytes": p.stat().st_size, "view": None} for p in evidence]
231
+
232
+
233
+ def verify(s: dict, out: Path) -> dict:
234
+ draw = _support(s)
235
+ proof = read(out / "ADOPTION.json")
236
+ if proof.get("receipt_sha256") != receipt_hash(proof):
237
+ raise ValueError("adoption receipt hash changed")
238
+ if (proof.get("schema") != SCHEMA or proof.get("support_sha256") != s["sha256"]
239
+ or proof.get("legacy_draw_index") != draw or proof.get("legacy_split") != f"fewshot{draw}"
240
+ or proof.get("reference_sample_ids") != s["train_sample_ids"]
241
+ or proof.get("mixture_sample_ids") != s["test_sample_ids"]
242
+ or proof.get("method_execution") != "historical_outputs_reused_no_method_execution"):
243
+ raise ValueError("adoption receipt does not match exact support and historical draw")
244
+ if not proof.get("files"):
245
+ raise ValueError("adoption proof contains no evidence files")
246
+ for entry in proof["files"]:
247
+ src = Path(entry["source"])
248
+ if src.stat().st_size != entry["bytes"] or sha(src) != entry["sha256"]:
249
+ raise ValueError(f"adopted source changed: {src}")
250
+ if entry["view"] is not None:
251
+ rel = Path(entry["view"])
252
+ if rel.is_absolute() or ".." in rel.parts:
253
+ raise ValueError("adopted view escapes unit output")
254
+ target = out / "adopted_legacy" / rel
255
+ if target.is_symlink() and target.resolve() != src.resolve():
256
+ raise ValueError("adopted view symlink changed")
257
+ if target.stat().st_size != entry["bytes"] or sha(target) != entry["sha256"]:
258
+ raise ValueError(f"adopted view changed: {target}")
259
+ return proof
260
+
261
+
262
+ def adopt(s: dict, out: Path, *, old: Path = OLD, ft: Path = FT) -> dict:
263
+ if (out / "ADOPTION.json").exists():
264
+ return verify(s, out)
265
+ proof = verify_legacy(s, old=old, ft=ft)
266
+ proof["files"] += _native_inputs(s, out, old)
267
+ proof["receipt_sha256"] = receipt_hash(proof)
268
+ for entry in proof["files"]:
269
+ if entry["view"] is None:
270
+ continue
271
+ dest = out / "adopted_legacy" / entry["view"]
272
+ if dest.exists() and sha(dest) != entry["sha256"]:
273
+ raise ValueError(f"existing adoption view differs: {dest}")
274
+ for entry in proof["files"]:
275
+ if entry["view"] is not None:
276
+ dest = out / "adopted_legacy" / entry["view"]
277
+ dest.parent.mkdir(parents=True, exist_ok=True)
278
+ if not dest.exists():
279
+ try:
280
+ os.link(entry["source"], dest)
281
+ except OSError as e:
282
+ if e.errno not in (errno.EPERM, errno.EACCES, errno.EXDEV):
283
+ raise
284
+ # Official Docker outputs may be root-owned and protected
285
+ # from hardlink creation. Preserve their bytes and owner.
286
+ dest.symlink_to(entry["source"])
287
+ out.mkdir(parents=True, exist_ok=True)
288
+ with tempfile.NamedTemporaryFile("w", dir=out, prefix=".adoption-", delete=False) as f:
289
+ json.dump(proof, f, indent=2)
290
+ f.write("\n")
291
+ tmp = Path(f.name)
292
+ # Do not replace a concurrent or earlier receipt.
293
+ os.link(tmp, out / "ADOPTION.json")
294
+ tmp.unlink()
295
+ return verify(s, out)
296
+
297
+
298
+ def main() -> int:
299
+ parser = argparse.ArgumentParser(description=__doc__)
300
+ parser.add_argument("--support-manifest", type=Path, required=True)
301
+ parser.add_argument("--verify-only", action="store_true")
302
+ args = parser.parse_args()
303
+ import deconv_strict as d
304
+ s = d.support(args.support_manifest)
305
+ out = d.unit_out(s, None)
306
+ result = verify(s, out) if args.verify_only else adopt(s, out)
307
+ print(json.dumps({k: result[k] for k in ("schema", "cohort", "unit", "legacy_draw_index", "method_execution")}))
308
+ return 0
309
+
310
+
311
+ if __name__ == "__main__":
312
+ raise SystemExit(main())
paper-releases/pbisc-diffusion/updates/20261013T005008Z-reuse-audit-results-deck/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/tools/deconv_strict.py ADDED
@@ -0,0 +1,881 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Exact-support BayesPrism/CIBERSORTx adapter for one strict disease unit.
3
+
4
+ CPU only. Each invocation is an isolated process; legacy modules are imported
5
+ unchanged and their output root and split function are patched in memory.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import csv
11
+ import hashlib
12
+ import importlib
13
+ import json
14
+ import os
15
+ import re
16
+ import subprocess
17
+ import sys
18
+ import tempfile
19
+ from pathlib import Path
20
+
21
+ os.environ["CUDA_VISIBLE_DEVICES"] = ""
22
+ for key in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS"):
23
+ os.environ.setdefault(key, "4")
24
+
25
+ import numpy as np # noqa: E402
26
+ import pandas as pd # noqa: E402
27
+
28
+ PLAN = Path(__file__).resolve().parents[1]
29
+ OLD = PLAN.parent / "bayesprism_paired_20261006"
30
+ OLD_TOOLS = OLD / "tools"
31
+ KEY = Path("/home/sj_server_1/cibersortx.key")
32
+ GUARD = Path("/home/sj_server_1/.local/libexec/ml-memory-guard")
33
+ sys.path.insert(0, str(OLD_TOOLS))
34
+
35
+
36
+ def sha(path: Path) -> str:
37
+ h = hashlib.sha256()
38
+ with path.open("rb") as f:
39
+ for chunk in iter(lambda: f.read(1 << 20), b""):
40
+ h.update(chunk)
41
+ return h.hexdigest()
42
+
43
+
44
+ def host_preflight() -> None:
45
+ """Host-wide GB10 guard checks before memory-heavy CPU preparation or methods."""
46
+ active = subprocess.run(["systemctl", "--user", "is-active", "ml-memory-guard.service"],
47
+ capture_output=True, text=True)
48
+ if active.returncode or active.stdout.strip() != "active":
49
+ subprocess.run(["systemctl", "--user", "restart", "ml-memory-guard.service"], check=True)
50
+ active = subprocess.run(["systemctl", "--user", "is-active", "ml-memory-guard.service"],
51
+ capture_output=True, text=True)
52
+ if active.returncode or active.stdout.strip() != "active":
53
+ raise RuntimeError("ml-memory-guard.service is inactive after restart")
54
+ subprocess.run([str(GUARD), "--check"], check=True)
55
+ apps = subprocess.run(["nvidia-smi", "--query-compute-apps=pid,process_name,used_memory", "--format=csv,noheader"],
56
+ check=True, capture_output=True, text=True)
57
+ if apps.stdout.strip():
58
+ raise RuntimeError("a CUDA compute job is active; queue this memory-heavy CPU unit until it completes")
59
+ available_kib = next(int(line.split()[1]) for line in Path("/proc/meminfo").read_text().splitlines()
60
+ if line.startswith("MemAvailable:"))
61
+ if available_kib < 48 * 1024 * 1024:
62
+ raise RuntimeError("less than 48 GiB MemAvailable; defer the memory-heavy deconvolution unit")
63
+
64
+
65
+ def validate_support_data(s: dict) -> dict:
66
+ body = {k: v for k, v in s.items() if k != "sha256"}
67
+ digest = hashlib.sha256(json.dumps(body, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()).hexdigest()
68
+ if s.get("schema") != "pbisc.paper.strict-support.v1" or s.get("sha256") != digest:
69
+ raise ValueError("strict support schema or hash mismatch")
70
+ train, test = s.get("train_sample_ids", []), s.get("test_sample_ids", [])
71
+ td, vd = s.get("train_donor_ids", []), s.get("test_donor_ids", [])
72
+ if not train or not test or len(train) != len(td) or len(test) != len(vd):
73
+ raise ValueError("strict support requires aligned sample and donor IDs")
74
+ if len(set(train)) != len(train) or len(set(test)) != len(test) or len(set(td)) != len(td):
75
+ raise ValueError("duplicate strict reference or mixture identity")
76
+ if set(td) & set(vd) or set(train) & set(test):
77
+ raise ValueError("reference and mixture donors/samples overlap")
78
+ if s["cohort"] not in {"ye2026_sepsis", "ji2025_chili", "imperial_eskd", "giroux2022"}:
79
+ raise ValueError("deconvolution supports disease cohorts only")
80
+ if s.get("design") != "disease_existing_draw" or not re.fullmatch(r"draw[0-4]_n5", str(s.get("unit", ""))):
81
+ raise ValueError("deconvolution requires a canonical disease draw unit")
82
+ if s["n_pairs"] != 5 or len(s["train_sample_ids"]) != 5:
83
+ raise ValueError("deconvolution requires exact five-pair support")
84
+ if set(s["excluded_sample_ids"]) & (set(s["train_sample_ids"]) | set(s["test_sample_ids"])):
85
+ raise ValueError("excluded visits entered the reference or mixture")
86
+ return s
87
+
88
+
89
+ def support(path: Path) -> dict:
90
+ s = validate_support_data(json.loads(path.read_text()))
91
+ draw = s["unit"].replace("_n5", "")
92
+ canonical = PLAN / "protocol" / "splits" / s["cohort"] / "disease" / draw / "support.json"
93
+ if path.resolve() != canonical.resolve() or not canonical.is_file():
94
+ raise ValueError("support manifest must be the canonical protocol file")
95
+ return s
96
+
97
+
98
+ def unit_out(s: dict, out: Path | None) -> Path:
99
+ validate_support_data(s)
100
+ expected = (PLAN / "deconvolution" / s["cohort"] / "disease" /
101
+ s["unit"].replace("_n5", "")).resolve()
102
+ if not expected.is_relative_to((PLAN / "deconvolution").resolve()):
103
+ raise ValueError("unit output escapes deconvolution directory")
104
+ chosen = (out or expected).resolve()
105
+ if chosen != expected:
106
+ raise ValueError(f"--out must be the strict unit output: {expected}")
107
+ return chosen
108
+
109
+
110
+ def strict_split(s: dict) -> dict:
111
+ return {"reference": list(s["train_sample_ids"]), "mixture": list(s["test_sample_ids"]),
112
+ "train_donors": list(s["train_donor_ids"]), "excluded_samples": list(s["excluded_sample_ids"]),
113
+ "support_sha256": s["sha256"], "run_json_check": "strict_manifest"}
114
+
115
+
116
+ def bind(s: dict, out: Path) -> None:
117
+ out.mkdir(parents=True, exist_ok=True)
118
+ p = out / "SUPPORT.json"
119
+ if p.exists() and json.loads(p.read_text()) != {
120
+ "support_sha256": s["sha256"], "reference": s["train_sample_ids"],
121
+ "mixture": s["test_sample_ids"], "excluded": s["excluded_sample_ids"]}:
122
+ raise ValueError("output directory is bound to another strict support")
123
+ p.write_text(json.dumps({"support_sha256": s["sha256"], "reference": s["train_sample_ids"],
124
+ "mixture": s["test_sample_ids"], "excluded": s["excluded_sample_ids"]}, indent=2) + "\n")
125
+
126
+
127
+ def split_name(s: dict) -> str:
128
+ return "fewshot" + s["unit"].split("_", 1)[0].removeprefix("draw")
129
+
130
+
131
+ def method_root(s: dict, out: Path) -> Path:
132
+ return out / "adopted_legacy" if s["cohort"] == "ye2026_sepsis" else out
133
+
134
+
135
+ def adopt_completed(s: dict, out: Path) -> dict:
136
+ """Sepsis must reuse proven historical methods; missing proof never triggers a rerun."""
137
+ import adopt_deconv_legacy as adoption
138
+ return adoption.adopt(s, out, old=OLD, ft=PLAN.parent / "paired_finetune_intradataset_20260927")
139
+
140
+
141
+ def patched_modules(s: dict, out: Path):
142
+ C = importlib.import_module("common")
143
+ C.PLAN = method_root(s, out)
144
+ C.split_rows = lambda ds, kind, idx: strict_split(s) if (ds, kind, idx) == (s["cohort"], "fewshot", int(split_name(s).removeprefix("fewshot"))) else (_ for _ in ()).throw(ValueError("unexpected split"))
145
+ return C
146
+
147
+
148
+ def prepare(s: dict, out: Path) -> dict:
149
+ if s["cohort"] == "ye2026_sepsis":
150
+ return adopt_completed(s, out)
151
+ bind(s, out)
152
+ previous = out / "INPUTS.json"
153
+ if previous.exists():
154
+ return require_inputs(s, out)
155
+ method_dirs = [out / "inputs" / s["cohort"] / f"{split_name(s)}_full" / "bp",
156
+ out / "cibersortx" / s["cohort"] / split_name(s) / "out_fractions",
157
+ out / "cibersortx" / s["cohort"] / split_name(s) / "out_hires"]
158
+ if any(d.is_dir() and any(d.iterdir()) for d in method_dirs):
159
+ raise ValueError("existing method output has no prepared-input receipt; refusing to rewrite inputs")
160
+ C = patched_modules(s, out)
161
+ ds = s["cohort"]
162
+ aggregate = OLD / "data" / ds / "aggregates_full.npz"
163
+ if not aggregate.is_file():
164
+ raise FileNotFoundError(f"read-only raw-count aggregate missing: {aggregate}")
165
+ link = out / "data" / ds / "aggregates_full.npz"
166
+ link.parent.mkdir(parents=True, exist_ok=True)
167
+ if link.is_symlink() and link.resolve() != aggregate.resolve():
168
+ raise ValueError("aggregate link points to a different source")
169
+ if link.exists() and (not link.is_symlink() or link.resolve() != aggregate.resolve()):
170
+ raise ValueError("aggregate destination is not the read-only legacy link")
171
+ if not link.exists():
172
+ link.symlink_to(aggregate)
173
+ bp = importlib.import_module("build_split")
174
+ bp.main([ds, "fewshot", split_name(s).removeprefix("fewshot"), "full"])
175
+ cx = importlib.import_module("build_cibersortx_inputs")
176
+ cx.SPLITS = [("fewshot", int(split_name(s).removeprefix("fewshot")))]
177
+ cx.main([ds])
178
+ bdir = out / "inputs" / ds / f"{split_name(s)}_full"
179
+ cdir = out / "cibersortx" / ds / split_name(s)
180
+ b = json.loads((bdir / "SPLIT.json").read_text())
181
+ c = json.loads((cdir / "INPUT.json").read_text())
182
+ if b["reference"] != s["train_sample_ids"] or b["mixture"] != s["test_sample_ids"]:
183
+ raise ValueError("BayesPrism input rows differ from strict support")
184
+ if c["reference_samples"] != s["train_sample_ids"] or c["mixture_samples"] != s["test_sample_ids"]:
185
+ raise ValueError("CIBERSORTx input rows differ from strict support")
186
+ rec = {"schema": "pbisc.deconvolution.strict-inputs.v1", "support_sha256": s["sha256"],
187
+ "reference_sample_ids": s["train_sample_ids"], "mixture_sample_ids": s["test_sample_ids"],
188
+ "excluded_sample_ids": s["excluded_sample_ids"], "aggregate_source": str(aggregate),
189
+ "aggregate_sha256": sha(aggregate), "bayesprism_split_sha256": sha(bdir / "SPLIT.json"),
190
+ "cibersortx_input_sha256": sha(cdir / "INPUT.json"), "adapter_sha256": sha(Path(__file__))}
191
+ (out / "INPUTS.json").write_text(json.dumps(rec, indent=2) + "\n")
192
+ return rec
193
+
194
+
195
+ def require_inputs(s: dict, out: Path) -> dict:
196
+ if s["cohort"] == "ye2026_sepsis":
197
+ import adopt_deconv_legacy as adoption
198
+ return adoption.verify(s, out)
199
+ rec = json.loads((out / "INPUTS.json").read_text())
200
+ if (rec["support_sha256"] != s["sha256"] or rec["reference_sample_ids"] != s["train_sample_ids"]
201
+ or rec["mixture_sample_ids"] != s["test_sample_ids"]
202
+ or rec["excluded_sample_ids"] != s["excluded_sample_ids"]):
203
+ raise ValueError("prepared inputs differ from strict support")
204
+ aggregate = Path(rec["aggregate_source"])
205
+ link = out / "data" / s["cohort"] / "aggregates_full.npz"
206
+ if not link.is_symlink() or link.resolve() != aggregate.resolve():
207
+ raise ValueError("read-only raw-count aggregate link changed after preparation")
208
+ if sha(aggregate) != rec["aggregate_sha256"]:
209
+ raise ValueError("read-only raw-count aggregate changed after preparation")
210
+ if sha(out / "inputs" / s["cohort"] / f"{split_name(s)}_full" / "SPLIT.json") != rec["bayesprism_split_sha256"]:
211
+ raise ValueError("BayesPrism split manifest changed after preparation")
212
+ if sha(out / "cibersortx" / s["cohort"] / split_name(s) / "INPUT.json") != rec["cibersortx_input_sha256"]:
213
+ raise ValueError("CIBERSORTx input manifest changed after preparation")
214
+ bdir = out / "inputs" / s["cohort"] / f"{split_name(s)}_full"
215
+ cdir = out / "cibersortx" / s["cohort"] / split_name(s)
216
+ for directory, filename, field in ((bdir, "SPLIT.json", "files"), (cdir, "INPUT.json", "files")):
217
+ entries = json.loads((directory / filename).read_text())[field]
218
+ for name, digest in entries.items():
219
+ if sha(directory / name) != digest:
220
+ raise ValueError(f"prepared input changed: {directory / name}")
221
+ return rec
222
+
223
+
224
+ def stage_dir(s: dict, out: Path, stage: str) -> Path:
225
+ out = method_root(s, out)
226
+ if stage == "bayesprism":
227
+ return out / "inputs" / s["cohort"] / f"{split_name(s)}_full" / "bp"
228
+ if stage in {"fractions", "hires"}:
229
+ return out / "cibersortx" / s["cohort"] / split_name(s) / f"out_{stage}"
230
+ raise ValueError(f"unknown method stage {stage}")
231
+
232
+
233
+ def stage_outputs(s: dict, out: Path, stage: str) -> list[Path]:
234
+ d = stage_dir(s, out, stage)
235
+ if stage == "bayesprism":
236
+ zfiles = sorted(d.glob("Z_type_*.tsv.gz"))
237
+ if not zfiles:
238
+ raise FileNotFoundError("BayesPrism type expression Z files missing")
239
+ files = [d / "theta_final.csv", d / "theta_first.csv", d / "genes_used.txt", *zfiles]
240
+ elif stage == "fractions":
241
+ files = [d / "CIBERSORTx_Adjusted.txt"]
242
+ if len(s["test_sample_ids"]) > 8:
243
+ sig = next(iter(sorted(d.glob("*inferred_refsample.bm.K999.txt"))), None)
244
+ if sig is None:
245
+ raise FileNotFoundError("CIBERSORTx Fractions HiRes signature missing")
246
+ files.extend([sig, d / "CIBERSORTx_cell_type_sourceGEP.txt"])
247
+ else:
248
+ files = []
249
+ for typ in ("T cell", "B cell", "Monocyte", "NK cell"):
250
+ f = next(iter(sorted(d.glob(f"CIBERSORTxHiRes_*_{typ.replace(' ', '')}_Window*.txt"))), None)
251
+ if f is None:
252
+ raise FileNotFoundError(f"CIBERSORTx HiRes required type output missing: {typ}")
253
+ files.append(f)
254
+ files.extend(p for p in sorted(d.glob("CIBERSORTxHiRes_*.txt")) if p not in files)
255
+ if not files or any(not f.is_file() for f in files):
256
+ raise FileNotFoundError(f"{stage} required output missing")
257
+ return files
258
+
259
+
260
+ def stage_input_hashes(s: dict, out: Path, stage: str) -> dict[str, str]:
261
+ hashes = {"prepared_inputs": sha(out / "INPUTS.json")}
262
+ if stage == "hires":
263
+ d = out / "cibersortx" / s["cohort"] / split_name(s)
264
+ files = [d / "out_fractions" / "RECEIPT.json", d / "sigmatrix.txt",
265
+ d / "source_geps.txt", d / "out_hires" / "fractions_results.txt"]
266
+ if any(not f.is_file() for f in files):
267
+ raise FileNotFoundError("HiRes source inputs or Fractions receipt missing")
268
+ hashes.update({str(f.relative_to(d)): sha(f) for f in files})
269
+ return hashes
270
+
271
+
272
+ def write_stage_receipt(s: dict, out: Path, stage: str) -> None:
273
+ require_inputs(s, out)
274
+ d = stage_dir(s, out, stage)
275
+ if not (d / "DONE").is_file():
276
+ raise FileNotFoundError(f"{stage} completion marker missing")
277
+ files = stage_outputs(s, out, stage)
278
+ receipt = {"schema": "pbisc.deconvolution.method-receipt.v1", "stage": stage,
279
+ "support_sha256": s["sha256"], "input_hashes": stage_input_hashes(s, out, stage),
280
+ "outputs_sha256": {f.name: sha(f) for f in files}}
281
+ (d / "RECEIPT.json").write_text(json.dumps(receipt, indent=2) + "\n")
282
+
283
+
284
+ def verify_stage_receipt(s: dict, out: Path, stage: str) -> dict:
285
+ if s["cohort"] == "ye2026_sepsis":
286
+ return require_inputs(s, out)
287
+ require_inputs(s, out)
288
+ d = stage_dir(s, out, stage)
289
+ if not (d / "DONE").is_file():
290
+ raise FileNotFoundError(f"{stage} completion marker missing")
291
+ p = d / "RECEIPT.json"
292
+ if not p.is_file():
293
+ raise ValueError(f"{stage} has DONE without a support/input-bound receipt")
294
+ rec = json.loads(p.read_text())
295
+ expected = {"schema": "pbisc.deconvolution.method-receipt.v1", "stage": stage,
296
+ "support_sha256": s["sha256"], "input_hashes": stage_input_hashes(s, out, stage),
297
+ "outputs_sha256": {f.name: sha(f) for f in stage_outputs(s, out, stage)}}
298
+ if rec != expected:
299
+ raise ValueError(f"{stage} receipt differs from prepared inputs or method outputs")
300
+ return rec
301
+
302
+
303
+ def method_output_hashes(s: dict, out: Path, method: str) -> dict[str, str]:
304
+ """Fail closed on extra or missing mixtures; hash every output used by scoring."""
305
+ ds = s["cohort"]
306
+ out = method_root(s, out)
307
+ if method == "bayesprism":
308
+ d = out / "inputs" / ds / f"{split_name(s)}_full" / "bp"
309
+ primary = d / "theta_final.csv"
310
+ files = [primary, d / "theta_first.csv", *sorted(d.glob("Z_type_*.tsv.gz"))]
311
+ if not (d / "DONE").is_file():
312
+ raise FileNotFoundError("BayesPrism DONE missing")
313
+ samples = pd.read_csv(primary, index_col=0).index.astype(str).tolist()
314
+ else:
315
+ d = out / "cibersortx" / ds / split_name(s)
316
+ primary = d / "out_fractions" / "CIBERSORTx_Adjusted.txt"
317
+ files = [primary, *sorted((d / "out_hires").glob("CIBERSORTxHiRes_*.txt"))]
318
+ if not (d / "out_fractions" / "DONE").is_file():
319
+ raise FileNotFoundError("CIBERSORTx Fractions DONE missing")
320
+ samples = pd.read_csv(primary, sep="\t", index_col=0).index.astype(str).tolist()
321
+ if len(samples) != len(s["test_sample_ids"]) or set(samples) != set(s["test_sample_ids"]):
322
+ raise ValueError(f"{method} output mixtures differ from strict support")
323
+ return {str(p): sha(p) for p in files}
324
+
325
+
326
+ def bayesprism(s: dict, out: Path, threads: int) -> None:
327
+ if s["cohort"] == "ye2026_sepsis":
328
+ adopt_completed(s, out)
329
+ return
330
+ require_inputs(s, out)
331
+ split = out / "inputs" / s["cohort"] / f"{split_name(s)}_full"
332
+ if (split / "bp" / "DONE").is_file():
333
+ verify_stage_receipt(s, out, "bayesprism")
334
+ return
335
+ if (split / "bp").is_dir() and any((split / "bp").iterdir()):
336
+ raise ValueError("partial BayesPrism output exists without a completion receipt")
337
+ subprocess.run(["/home/sj_server_1/miniforge3/bin/Rscript", str(OLD_TOOLS / "run_bp.R"), str(split), str(threads)],
338
+ check=True, env={**os.environ, "CUDA_VISIBLE_DEVICES": ""})
339
+ if not (split / "bp" / "DONE").is_file():
340
+ raise RuntimeError("BayesPrism completion marker missing")
341
+ write_stage_receipt(s, out, "bayesprism")
342
+
343
+
344
+ def credentials(path: Path) -> tuple[str, str]:
345
+ txt = path.read_text()
346
+ user = re.search(r"(?im)^\s*(?:email|username|user)\s*[:=]\s*(\S+)", txt)
347
+ token = re.search(r"(?im)^\s*token\s*[:=]\s*(\S+)", txt)
348
+ bare = [x.strip() for x in txt.splitlines() if x.strip() and not re.match(r"(?i)^\s*(email|username|user)\s*[:=]", x)]
349
+ value = token.group(1) if token else (bare[0] if len(bare) == 1 and re.fullmatch(r"[0-9a-fA-F]{20,}", bare[0]) else None)
350
+ if not user or not value:
351
+ raise ValueError("CIBERSORTx credential file lacks email or token")
352
+ return user.group(1), value
353
+
354
+
355
+ def cx_argv(image: str, binary: str, work: Path, dest: Path, env_file: Path,
356
+ threads: int, flags: list[str]) -> list[str]:
357
+ """Credentials expand only inside the container and never enter host argv."""
358
+ script = f'exec ./{binary} --username "$CX_USER" --token "$CX_TOKEN" "$@"'
359
+ return ["docker", "run", "--rm", "--ulimit", "core=0", "--platform", "linux/amd64",
360
+ "--memory=16g", "--memory-swap=16g", f"--cpus={threads}", "--env-file", str(env_file),
361
+ "-v", f"{work}:/src/data:ro", "-v", f"{dest}:/src/outdir", "--entrypoint", "/bin/bash",
362
+ image, "-c", script, "_", *flags]
363
+
364
+
365
+ def run_cx(argv: list[str], log: Path, user: str, token: str) -> None:
366
+ log.parent.mkdir(parents=True, exist_ok=True)
367
+ with log.open("w") as f, subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
368
+ text=True, bufsize=1) as p:
369
+ assert p.stdout is not None
370
+ for line in p.stdout:
371
+ line = line.replace(user, "[REDACTED]").replace(token, "[REDACTED]")
372
+ line = re.sub(r"(?i)^(>\[Options\]\s*(?:token|username)[^:]*:).*", r"\1 [REDACTED]", line)
373
+ f.write(line)
374
+ if p.wait() != 0:
375
+ raise RuntimeError(f"CIBERSORTx failed; see redacted log {log}")
376
+ if "Abort!" in log.read_text():
377
+ raise RuntimeError(f"CIBERSORTx aborted; see redacted log {log}")
378
+
379
+
380
+ def cibersortx(s: dict, out: Path, threads: int) -> dict:
381
+ if s["cohort"] == "ye2026_sepsis":
382
+ adopt_completed(s, out)
383
+ return {"fractions": "complete", "hires": "complete", "execution": "adopted_legacy"}
384
+ require_inputs(s, out)
385
+ d = out / "cibersortx" / s["cohort"] / split_name(s)
386
+ meta = json.loads((d / "INPUT.json").read_text())
387
+ if meta["mixture_samples"] != s["test_sample_ids"]:
388
+ raise ValueError("CIBERSORTx mixture differs from strict support")
389
+ images = ["cibersortx/fractions:latest"]
390
+ if len(s["test_sample_ids"]) > 8:
391
+ images.append("cibersortx/hires:latest")
392
+ for image in images:
393
+ subprocess.run(["docker", "image", "inspect", image], stdout=subprocess.DEVNULL, check=True)
394
+ user, token = credentials(KEY)
395
+ with tempfile.TemporaryDirectory(prefix="cx_env_", dir=out) as tmp:
396
+ envfile = Path(tmp) / "env"
397
+ envfile.write_text(f"CX_USER={user}\nCX_TOKEN={token}\n")
398
+ envfile.chmod(0o600)
399
+ fd = d / "out_fractions"
400
+ fd.mkdir(exist_ok=True)
401
+ if (fd / "DONE").exists():
402
+ verify_stage_receipt(s, out, "fractions")
403
+ else:
404
+ if any(fd.iterdir()):
405
+ raise ValueError("partial CIBERSORTx Fractions output exists without a completion receipt")
406
+ flags = ["--single_cell", "TRUE", "--refsample", "refsample.txt", "--mixture", "mixture.txt",
407
+ "--rmbatchSmode", "TRUE", "--fraction", "0", "--replicates", "5", "--sampling", "0.5",
408
+ "--G.min", "300", "--G.max", "500", "--q.value", "0.01", "--perm", "0", "--QN", "FALSE", "--verbose", "TRUE"]
409
+ run_cx(cx_argv("cibersortx/fractions:latest", "CIBERSORTxFractions", d, fd, envfile, threads, flags), fd / "run.redacted.log", user, token)
410
+ if not (fd / "CIBERSORTx_Adjusted.txt").is_file():
411
+ raise RuntimeError("CIBERSORTx fractions output missing")
412
+ (fd / "DONE").write_text("ok\n")
413
+ write_stage_receipt(s, out, "fractions")
414
+ status = {"fractions": "complete", "hires": "pending"}
415
+ if len(s["test_sample_ids"]) <= 8:
416
+ status.update(hires="not_estimable", reason="HiRes needs more than eight mixture samples")
417
+ else:
418
+ hd = d / "out_hires"
419
+ hd.mkdir(exist_ok=True)
420
+ if (hd / "DONE").exists():
421
+ verify_stage_receipt(s, out, "hires")
422
+ else:
423
+ if any(hd.iterdir()):
424
+ raise ValueError("partial CIBERSORTx HiRes output exists without a completion receipt")
425
+ sig = next(iter(sorted(fd.glob("*inferred_refsample.bm.K999.txt"))), None)
426
+ src = fd / "CIBERSORTx_cell_type_sourceGEP.txt"
427
+ res = fd / "CIBERSORTx_Adjusted.txt"
428
+ if sig is None or not src.is_file() or not res.is_file():
429
+ raise RuntimeError("CIBERSORTx Fractions signature/source/results missing for HiRes")
430
+ (d / "sigmatrix.txt").write_bytes(sig.read_bytes())
431
+ (d / "source_geps.txt").write_bytes(src.read_bytes())
432
+ fr = pd.read_csv(res, sep="\t", index_col=0)
433
+ fr[[c for c in fr if c not in ("P-value", "Correlation", "RMSE")]].to_csv(hd / "fractions_results.txt", sep="\t")
434
+ flags = ["--mixture", "mixture.txt", "--sigmatrix", "sigmatrix.txt", "--cibresults", "fractions_results.txt",
435
+ "--rmbatchSmode", "TRUE", "--sourceGEPs", "source_geps.txt", "--subsetgenes", "hires_genes.txt", "--threads", str(threads)]
436
+ run_cx(cx_argv("cibersortx/hires:latest", "CIBERSORTxHiRes", d, hd, envfile, threads, flags), hd / "run.redacted.log", user, token)
437
+ if not list(hd.glob("CIBERSORTxHiRes_*.txt")):
438
+ raise RuntimeError("CIBERSORTx HiRes output missing")
439
+ (hd / "DONE").write_text("ok\n")
440
+ write_stage_receipt(s, out, "hires")
441
+ status["hires"] = "complete"
442
+ (d / "STATUS.json").write_text(json.dumps(status, indent=2) + "\n")
443
+ return status
444
+
445
+
446
+ CONTRAST_GROUPS = {
447
+ "ye2026_sepsis": ({"adult_sepsis", "ped_sepsis"}, {"adult_HC", "adult_ICU_ctrl", "ped_HC", "ped_ICU_ctrl"}),
448
+ "ji2025_chili": ({"TOL", "FU1"}, {"BC", "AC"}),
449
+ "imperial_eskd": ({"covid_positive"}, {"covid_negative"}),
450
+ "giroux2022": ({"severe"}, {"mild"}),
451
+ }
452
+
453
+ LIMMA_R = r'''suppressPackageStartupMessages(library(limma))
454
+ args <- commandArgs(trailingOnly=TRUE)
455
+ if (length(args) != 4L) stop("usage: limma.R metadata.csv observed.tsv.gz method.tsv.gz outdir")
456
+ meta <- read.csv(args[1], stringsAsFactors=FALSE)
457
+ out <- args[4]
458
+ dir.create(out, recursive=TRUE, showWarnings=FALSE)
459
+ group <- factor(meta$condition, levels=c("control", "case"))
460
+ design <- model.matrix(~group)
461
+ blocked <- any(table(meta$donor_id) > 1L)
462
+ for (side in c("observed", "method")) {
463
+ path <- if (side == "observed") args[2] else args[3]
464
+ tab <- read.delim(gzfile(path), row.names=1, check.names=FALSE)
465
+ X <- as.matrix(tab)
466
+ if (ncol(X) != nrow(meta) || nrow(X) < 3L || any(!is.finite(X))) stop("invalid matched expression matrix")
467
+ if (blocked) {
468
+ dc <- duplicateCorrelation(X, design, block=meta$donor_id)
469
+ if (!is.finite(dc$consensus.correlation)) stop("duplicateCorrelation undefined")
470
+ fit <- lmFit(X, design, block=meta$donor_id, correlation=dc$consensus.correlation)
471
+ } else fit <- lmFit(X, design)
472
+ fit <- eBayes(fit)
473
+ top <- topTable(fit, coef=2L, number=Inf, sort.by="none", adjust.method="BH")
474
+ top$gene_id <- rownames(top)
475
+ write.csv(top[,c("gene_id","logFC","P.Value","adj.P.Val")], file.path(out,paste0(side,"_limma.csv")), row.names=FALSE)
476
+ }
477
+ '''
478
+
479
+
480
+ def _log2_cpm(x: np.ndarray) -> np.ndarray:
481
+ x = np.asarray(x, np.float64)
482
+ lib = x.sum(axis=1, keepdims=True)
483
+ if not np.isfinite(x).all() or (x < 0).any() or (lib <= 0).any():
484
+ raise ValueError("nonfinite, negative, or zero-library expression")
485
+ return np.log2(1 + np.divide(x * 1e6, lib, out=np.zeros_like(x), where=lib > 0))
486
+
487
+
488
+ def _collapse_donor_condition(s: dict, case: np.ndarray, ctrl: np.ndarray,
489
+ obs: np.ndarray, method: np.ndarray, bulk: np.ndarray) -> tuple[pd.DataFrame, np.ndarray, np.ndarray, np.ndarray]:
490
+ """Each donor contributes once per condition, regardless of visit count."""
491
+ donors = np.asarray(s["test_donor_ids"], dtype=str)
492
+ condition = np.where(case, "case", "control")
493
+ keys = sorted(set(zip(donors, condition)), key=lambda x: (x[0], x[1]))
494
+ O, M, U = (_log2_cpm(x) for x in (obs, method, bulk))
495
+ meta = pd.DataFrame(keys, columns=["donor_id", "condition"])
496
+ out = []
497
+ for x in (O, M, U):
498
+ out.append(np.stack([x[(donors == d) & (condition == c)].mean(axis=0) for d, c in keys]))
499
+ return meta, *out
500
+
501
+
502
+ def _pearson(x: np.ndarray, y: np.ndarray) -> float:
503
+ if x.size < 3 or np.std(x) == 0 or np.std(y) == 0:
504
+ return float("nan")
505
+ return float(np.corrcoef(x, y)[0, 1])
506
+
507
+
508
+ def _partial(x: np.ndarray, y: np.ndarray, bulk: np.ndarray) -> float:
509
+ centered = bulk - bulk.mean()
510
+ den = float(np.dot(centered, centered))
511
+ if den == 0:
512
+ return float("nan")
513
+ residual = lambda z: z - z.mean() - centered * (np.dot(z - z.mean(), centered) / den)
514
+ return _pearson(residual(x), residual(y))
515
+
516
+
517
+ def _top50(tab: pd.DataFrame) -> set[str]:
518
+ ok = tab.loc[tab["adj.P.Val"].astype(float) < 0.05].copy()
519
+ return set(ok.assign(abs_lfc=ok.logFC.abs()).sort_values("abs_lfc", ascending=False).head(50).gene_id.astype(str))
520
+
521
+
522
+ def corrected_expression(s: dict, B, v: dict, pred: dict, arm: str, out: Path) -> list[dict]:
523
+ """Matched donor-aware limma on continuous log2-CPM; never call this voom."""
524
+ F = B.F
525
+ C = importlib.import_module("common")
526
+ ds = s["cohort"]
527
+ cases, controls = CONTRAST_GROUPS[ds]
528
+ groups = np.asarray(v["groups"], str)
529
+ case, ctrl = np.isin(groups, list(cases)), np.isin(groups, list(controls))
530
+ feat = np.load(C.FT / "data" / ds / "features.npz", allow_pickle=False)
531
+ fsid = (feat["sample_ids"] if "sample_ids" in feat.files else feat["donor_ids"]).astype(str)
532
+ sidpos = {x: i for i, x in enumerate(fsid)}
533
+ genepos = {x: i for i, x in enumerate(feat["gene_ids"].astype(str))}
534
+ bulk = np.asarray(feat["bulk_raw"], np.float64)[[sidpos[x] for x in s["test_sample_ids"]]][:,
535
+ [genepos[x] for x in v["score_ids"]]]
536
+ covered = pred["covered_type"].all(0) if "covered_type" in pred else pred["covered"].all(0)
537
+ base_keep = np.asarray(v.get("keep", np.ones(len(v["score_ids"]), bool)), bool)
538
+ rows = []
539
+ for typ in v["deg_types"]:
540
+ gi = F.GATE.index(typ)
541
+ di = v["deg_types"].index(typ)
542
+ mask = base_keep & (covered[gi] if covered.ndim == 2 else covered)
543
+ observed = np.asarray(v["deg_sum"][:, di, :], np.float64)
544
+ method = np.asarray(pred["Z"][:, gi, :], np.float64)
545
+ mask &= observed.sum(axis=0) > 0
546
+ mask &= method.sum(axis=0) > 0
547
+ eligible = (v["deg_n"][:, di] > 0) & (method.sum(axis=1) > 0) & (case | ctrl)
548
+ donors = np.asarray(s["test_donor_ids"])
549
+ ncase = len(set(donors[eligible & case]))
550
+ nctrl = len(set(donors[eligible & ctrl]))
551
+ common = {"arm": arm, "cell_type": typ, "gene_variant": "donor_covered", "statistic": "limma_log2_cpm",
552
+ "n_genes": int(mask.sum()), "n_test_samples": int(eligible.sum()),
553
+ "n_independent_donors": len(set(donors[eligible])), "n_case_samples": int((eligible & case).sum()),
554
+ "n_control_samples": int((eligible & ctrl).sum()), "n_case_donors": ncase, "n_control_donors": nctrl,
555
+ "method_expression_unit": "continuous log2-CPM on matched observed/method profiles",
556
+ "deg_method": "limma lmFit/eBayes on donor-condition means; duplicateCorrelation for repeated donor conditions"}
557
+ metric_names = ("donor_logfc_r", "donor_partial_r_given_bulk", "donor_limma_top50_overlap")
558
+ if ncase < 2 or nctrl < 2 or mask.sum() < 3:
559
+ reason = "fewer than two independent donors per group or fewer than three common expressed genes"
560
+ rows.extend({**common, "metric": m, "value": "", "status": "not_estimable", "reason": reason} for m in metric_names)
561
+ continue
562
+ if any(np.any(x[eligible][:, mask].sum(axis=1) <= 0) for x in (observed, method, bulk)):
563
+ reason = "a matched profile has zero library on common covered genes"
564
+ rows.extend({**common, "metric": m, "value": "", "status": "not_estimable", "reason": reason} for m in metric_names)
565
+ continue
566
+ ss = {**s, "test_donor_ids": donors[eligible].tolist()}
567
+ meta, O, M, U = _collapse_donor_condition(ss, case[eligible], ctrl[eligible],
568
+ observed[eligible][:, mask], method[eligible][:, mask], bulk[eligible][:, mask])
569
+ iscase = meta.condition.eq("case").to_numpy()
570
+ obs_fc = O[iscase].mean(0) - O[~iscase].mean(0)
571
+ method_fc = M[iscase].mean(0) - M[~iscase].mean(0)
572
+ bulk_fc = U[iscase].mean(0) - U[~iscase].mean(0)
573
+ values = {"donor_logfc_r": _pearson(obs_fc, method_fc),
574
+ "donor_partial_r_given_bulk": _partial(obs_fc, method_fc, bulk_fc)}
575
+ work = out / "score" / "continuous_limma" / arm / typ.replace(" ", "_")
576
+ work.mkdir(parents=True, exist_ok=True)
577
+ meta.to_csv(work / "metadata.csv", index=False)
578
+ genes = np.asarray(v["score_ids"])[mask]
579
+ for side, matrix in (("observed", O), ("method", M)):
580
+ pd.DataFrame(matrix.T, index=pd.Index(genes, name="gene_id")).to_csv(work / f"{side}.tsv.gz", sep="\t")
581
+ script = out / "score" / "continuous_limma" / "limma_continuous.R"
582
+ script.write_text(LIMMA_R)
583
+ try:
584
+ run = subprocess.run(["/home/sj_server_1/miniforge3/bin/Rscript", str(script), str(work / "metadata.csv"), str(work / "observed.tsv.gz"),
585
+ str(work / "method.tsv.gz"), str(work)], capture_output=True, text=True)
586
+ except FileNotFoundError:
587
+ run = None
588
+ if run is None or run.returncode:
589
+ (work / "limma_error.txt").write_text(run.stderr[-8000:] if run is not None else "Rscript unavailable\n")
590
+ values["donor_limma_top50_overlap"] = float("nan")
591
+ reason = "limma continuous-expression fit unavailable; see unit limma_error.txt"
592
+ else:
593
+ obs_top = _top50(pd.read_csv(work / "observed_limma.csv"))
594
+ method_top = _top50(pd.read_csv(work / "method_limma.csv"))
595
+ values["donor_limma_top50_overlap"] = len(obs_top & method_top)
596
+ reason = ""
597
+ for m in metric_names:
598
+ value = values[m]
599
+ rows.append({**common, "metric": m, "value": value if np.isfinite(value) else "",
600
+ "status": "ok" if np.isfinite(value) else "pending" if m == "donor_limma_top50_overlap" else "not_estimable",
601
+ "reason": reason if not np.isfinite(value) else ""})
602
+ return rows
603
+
604
+
605
+ def score_readiness(methods: dict, metrics: dict) -> tuple[str, list[str]]:
606
+ required = ("bayesprism", "cibersortx")
607
+ pending = []
608
+ for name in required:
609
+ record = methods.get(name)
610
+ if record is None or record.get("status") != "complete":
611
+ pending.append(f"{name}: {record.get('reason', 'required method output incomplete') if record else 'required method output missing'}")
612
+ if record and record.get("hires", {}).get("status") == "pending":
613
+ pending.append(f"{name}: {record['hires']['reason']}")
614
+ correction = metrics.get(name, {}).get("corrected_deg", {})
615
+ if record and correction.get("status") not in {"complete", "not_estimable"}:
616
+ pending.append(f"{name}: corrected DEG infrastructure pending")
617
+ return ("pending" if pending else "complete", pending)
618
+
619
+
620
+ def expression_signal(s: dict, B, v: dict, pred: dict, arm: str) -> list[dict]:
621
+ """Legacy metric family on exact strict test samples; donor-aware DEG is separate."""
622
+ SF, F = B.SF, B.F
623
+ C = importlib.import_module("common")
624
+ ds = s["cohort"]
625
+ groups = np.asarray(v["groups"], dtype=str)
626
+ cases, controls = CONTRAST_GROUPS[ds]
627
+ case, ctrl = np.isin(groups, list(cases)), np.isin(groups, list(controls))
628
+ if not case.any() or not ctrl.any() or np.any(~(case | ctrl)):
629
+ raise ValueError("strict test samples do not match the declared case/control groups")
630
+ feat = np.load(C.FT / "data" / ds / "features.npz", allow_pickle=False)
631
+ fsid = (feat["sample_ids"] if "sample_ids" in feat.files else feat["donor_ids"]).astype(str)
632
+ sidpos = {x: i for i, x in enumerate(fsid)}
633
+ genepos = {x: i for i, x in enumerate(feat["gene_ids"].astype(str))}
634
+ sample_rows = [sidpos[x] for x in s["test_sample_ids"]]
635
+ gene_cols = [genepos[x] for x in v["score_ids"]]
636
+ valid = np.asarray(feat["bulk_valid"])[sample_rows][:, gene_cols].astype(bool)
637
+ if not valid.all():
638
+ raise ValueError("scoring genes must be bulk-valid for every strict mixture")
639
+ bulk = np.asarray(feat["bulk_raw"], dtype=np.float64)[sample_rows][:, gene_cols]
640
+ if not np.isfinite(bulk).all() or (bulk < 0).any():
641
+ raise ValueError("invalid strict bulk counts")
642
+ if ds == "giroux2022":
643
+ exclude = C.FT / "data/sex_linked_genes/sex_linked_genes_exclude.csv"
644
+ v["keep"], _ = SF.gene_exclusion(exclude, v["score_ids"])
645
+ contrast = {"enabled": True, "case": case, "ctrl": ctrl}
646
+ obs_deg = SF.observed_deg(v, contrast)
647
+ n_case_donors = len(set(np.asarray(s["test_donor_ids"])[case]))
648
+ n_control_donors = len(set(np.asarray(s["test_donor_ids"])[ctrl]))
649
+ base = {"arm": arm, "n_test_samples": len(s["test_sample_ids"]),
650
+ "n_independent_donors": len(set(s["test_donor_ids"])),
651
+ "n_case_samples": int(case.sum()), "n_control_samples": int(ctrl.sum()),
652
+ "n_case_donors": n_case_donors, "n_control_donors": n_control_donors,
653
+ "method_expression_unit": "BayesPrism posterior type expression" if arm == "bayesprism" else "CIBERSORTx HiRes imputed GEP",
654
+ "deg_method": "historical Welch top50 on method expression; corrected donor-aware DEG pending"}
655
+ if arm == "cibersortx" and (len(s["test_sample_ids"]) <= 8 or not pred.get("has_z") or not any(pred.get("imputed_genes", {}).values())):
656
+ return [{**base, "cell_type": "all", "metric": metric, "value": "", "status": "not_estimable",
657
+ "gene_variant": "covered", "statistic": "mean_cp10k", "n_genes": 0}
658
+ for metric in ("logfc_r", "partial_r_given_bulk", "top50_deg_overlap")]
659
+ G = len(v["score_ids"])
660
+ covered = pred["covered_type"].all(0) if "covered_type" in pred else pred["covered"].all(0)
661
+ masks = (("zero_filled", None), ("covered", covered))
662
+ rows = []
663
+ for variant, mask in masks:
664
+ contrast_rows, deg, _ = B.bp_metrics(v, pred, bulk, contrast, obs_deg, mask)
665
+ for _, r in contrast_rows.iterrows():
666
+ for metric, key in (("logfc_r", "r_generated"), ("partial_r_given_bulk", "partial_r_generated_given_broadcast")):
667
+ value = float(r[key])
668
+ rows.append({**base, "cell_type": r["celltype"], "metric": metric,
669
+ "value": value if np.isfinite(value) else "", "status": "ok" if np.isfinite(value) else "not_estimable",
670
+ "gene_variant": variant, "statistic": r["statistic"], "n_genes": int(r["n_genes"])})
671
+ for typ, overlap in deg.items():
672
+ n_genes = (int(mask[F.GATE.index(typ)].sum()) if mask is not None and mask.ndim == 2
673
+ else int(mask.sum()) if mask is not None else G)
674
+ rows.append({**base, "cell_type": typ, "metric": "top50_deg_overlap",
675
+ "value": int(overlap) if overlap is not None else "", "status": "ok" if overlap is not None else "not_estimable",
676
+ "gene_variant": variant, "statistic": F.DEG_STATISTIC,
677
+ "n_genes": n_genes})
678
+ return rows
679
+
680
+
681
+ def score(s: dict, out: Path) -> dict:
682
+ require_inputs(s, out)
683
+ C = patched_modules(s, out)
684
+ B = importlib.import_module("score_bp")
685
+ F = B.F
686
+ ds = s["cohort"]
687
+ ids = np.asarray(s["test_sample_ids"], dtype=str)
688
+ ref, man = F.load_reference(F.CACHE_ROOT / F.DATASETS[ds].name)
689
+ ref["deg"] = F.load_deg_reference(F.CACHE_ROOT / F.DATASETS[ds].name, man, ref)
690
+ if not set(ids) <= set(ref["donors"].astype(str)):
691
+ raise ValueError("strict test IDs absent from observed reference")
692
+ v = B.light_view(ref, ids.tolist())
693
+ rows, signals, metrics, methods = [], [], {}, {}
694
+ for name in ("bayesprism", "cibersortx"):
695
+ hires_pending = False
696
+ try:
697
+ if name == "bayesprism":
698
+ verify_stage_receipt(s, out, "bayesprism")
699
+ else:
700
+ verify_stage_receipt(s, out, "fractions")
701
+ if len(ids) > 8:
702
+ try:
703
+ verify_stage_receipt(s, out, "hires")
704
+ except FileNotFoundError:
705
+ hires_pending = True
706
+ hashes = method_output_hashes(s, out, name)
707
+ pred = B.load_bp(ds, [f"{split_name(s)}_full"], ids, v["score_ids"]) if name == "bayesprism" else B.load_cx(ds, [split_name(s)], ids, v["score_ids"])
708
+ except (SystemExit, FileNotFoundError) as e:
709
+ methods[name] = {"status": "pending", "reason": str(e)}
710
+ continue
711
+ fractions = B.to_cells(pred["theta"]["final"], pred["size"])
712
+ if not np.isfinite(fractions).all():
713
+ raise ValueError(f"{name} fractions contain nonfinite values")
714
+ l1 = F.IC.l1(fractions, v["comp"])
715
+ metrics[name] = {"composition_l1_mean": float(np.mean(l1)), "n_samples": len(ids),
716
+ "n_independent_donors": len(set(s["test_donor_ids"]))}
717
+ methods[name] = {"status": "pending" if hires_pending else "complete",
718
+ "composition": "cell_fraction_size_corrected", "output_sha256": hashes}
719
+ for i, sample in enumerate(ids):
720
+ for j, typ in enumerate(F.GATE):
721
+ rows.append({"arm": name, "sample_id": sample, "donor_id": s["test_donor_ids"][i],
722
+ "cell_type": typ, "observed": float(v["comp"][i, j]), "predicted": float(fractions[i, j]),
723
+ "composition_l1": float(l1[i])})
724
+ if name == "cibersortx":
725
+ imputed = pred.get("imputed_genes", {})
726
+ if hires_pending:
727
+ methods[name]["hires"] = {"status": "pending", "reason": "required HiRes output missing"}
728
+ elif len(ids) <= 8:
729
+ methods[name]["hires"] = {"status": "not_estimable", "reason": "at most eight mixture samples"}
730
+ elif not pred.get("has_z"):
731
+ methods[name]["hires"] = {"status": "pending", "reason": "required HiRes result files missing"}
732
+ methods[name]["status"] = "pending"
733
+ elif not any(imputed.values()):
734
+ methods[name]["hires"] = {"status": "not_estimable", "reason": "verified HiRes result has zero imputed genes"}
735
+ else:
736
+ methods[name]["hires"] = {"status": "available", "imputed_genes": imputed}
737
+ method_view = v.copy()
738
+ if hires_pending or (name == "cibersortx" and methods[name]["hires"]["status"] == "pending"):
739
+ corrected = [{"arm": name, "cell_type": typ, "metric": metric, "value": "", "status": "pending",
740
+ "reason": "required HiRes output missing", "gene_variant": "donor_covered",
741
+ "statistic": "limma_log2_cpm", "n_genes": 0,
742
+ "n_test_samples": len(ids), "n_independent_donors": len(set(s["test_donor_ids"])),
743
+ "method_expression_unit": "CIBERSORTx HiRes imputed GEP"}
744
+ for typ in v["deg_types"] for metric in
745
+ ("donor_logfc_r", "donor_partial_r_given_bulk", "donor_limma_top50_overlap")]
746
+ else:
747
+ signals.extend(expression_signal(s, B, method_view, pred, name))
748
+ corrected = corrected_expression(s, B, method_view, pred, name, out)
749
+ signals.extend(corrected)
750
+ deg_rows = [r for r in corrected if r["metric"] == "donor_limma_top50_overlap"]
751
+ metrics[name]["corrected_deg"] = {"method": "limma on matched donor-condition continuous log2-CPM",
752
+ "status": "pending" if any(r["status"] == "pending" for r in deg_rows)
753
+ else "complete" if any(r["status"] == "ok" for r in deg_rows)
754
+ else "not_estimable",
755
+ "n_types_estimable": sum(r["status"] == "ok" for r in deg_rows),
756
+ "n_types_total": len(deg_rows)}
757
+ status, pending = score_readiness(methods, metrics)
758
+ result = {"schema": "pbisc.deconvolution.strict-score.v1", "cohort": ds, "unit": s["unit"],
759
+ "status": status,
760
+ "pending_reasons": pending, "required_methods": ["bayesprism", "cibersortx"],
761
+ "support_sha256": s["sha256"], "reference_sample_ids": s["train_sample_ids"],
762
+ "mixture_sample_ids": s["test_sample_ids"], "methods": methods, "metrics": metrics,
763
+ "observed_reference_sha256": man["reference_sha256"],
764
+ "source_sha256": {"adapter": sha(Path(__file__)), "score_bp": sha(OLD_TOOLS / "score_bp.py"),
765
+ "common": sha(OLD_TOOLS / "common.py"),
766
+ "legacy_aggregate": require_inputs(s, out)["aggregate_sha256"],
767
+ "features": sha(C.FT / "data" / ds / "features.npz"),
768
+ "observed_deg_reference": ref["deg"].get("sha256")}}
769
+ if s["cohort"] == "ye2026_sepsis":
770
+ result["method_execution"] = "historical_outputs_reused_no_method_execution"
771
+ result["adoption_manifest"] = str(out / "ADOPTION.json")
772
+ result["adoption_sha256"] = sha(out / "ADOPTION.json")
773
+ for method in methods.values():
774
+ method["execution"] = "adopted_legacy"
775
+ method["adoption_manifest"] = result["adoption_manifest"]
776
+ method["adoption_sha256"] = result["adoption_sha256"]
777
+ p = out / "score"
778
+ p.mkdir(exist_ok=True)
779
+ csvpath = p / "figure4_methods.csv"
780
+ if rows:
781
+ with csvpath.open("w", newline="") as f:
782
+ writer = csv.DictWriter(f, fieldnames=list(rows[0]))
783
+ writer.writeheader(); writer.writerows(rows)
784
+ result["figure4_csv"] = str(csvpath)
785
+ result["figure4_csv_sha256"] = sha(csvpath)
786
+ signalpath = p / "expression_signal.csv"
787
+ with signalpath.open("w", newline="") as f:
788
+ writer = csv.DictWriter(f, fieldnames=list(dict.fromkeys(k for row in signals for k in row)))
789
+ writer.writeheader(); writer.writerows(signals)
790
+ result["signal_csv"] = str(signalpath)
791
+ result["signal_sha256"] = sha(signalpath)
792
+ result["expression_metric_provenance"] = {
793
+ "gene_axis": "cohort scoring genes; Giroux sex-linked genes excluded",
794
+ "reference_expression": "observed sample-level cell-type aggregates on strict test samples",
795
+ "method_expression": "BayesPrism posterior type expression or CIBERSORTx HiRes imputed GEP",
796
+ "bulk": "strict test sample real bulk raw counts from features.npz",
797
+ "sample_unit": "sample; repeated visits retained with explicit donor IDs",
798
+ "top50_deg": "historical Welch benchmark statistic; not corrected patient-level inference",
799
+ "corrected_deg": "limma lmFit/eBayes on matched observed/method continuous log2-CPM donor-condition means; duplicateCorrelation if needed; sensitivity distinct from raw-count edgeR/limma-voom primary",
800
+ "corrected_profile_script_sha256": hashlib.sha256(LIMMA_R.encode()).hexdigest()}
801
+ (p / "SUMMARY.json").write_text(json.dumps(result, indent=2) + "\n")
802
+ if result["status"] == "complete":
803
+ update_figure4(s, result)
804
+ else:
805
+ invalidate_figure4(s, result["pending_reasons"])
806
+ return result
807
+
808
+
809
+ def invalidate_figure4(s: dict, reasons: list[str]) -> None:
810
+ """Retain a prior mapping as inactive so pending reruns cannot look complete."""
811
+ path = PLAN / "deconvolution" / "deconvolution_manifest.json"
812
+ if not path.is_file():
813
+ return
814
+ data = json.loads(path.read_text())
815
+ rel = f'{s["cohort"]}/disease/{s["unit"].replace("_n5", "")}'
816
+ previous = data.get("units", {}).get(rel)
817
+ if previous is None:
818
+ return
819
+ data.setdefault("inactive_units", {})[rel] = {"previous": previous, "reason": reasons}
820
+ del data["units"][rel]
821
+ with tempfile.NamedTemporaryFile("w", dir=path.parent, prefix=".deconv_", delete=False) as f:
822
+ json.dump(data, f, indent=2)
823
+ f.write("\n")
824
+ tmp = Path(f.name)
825
+ tmp.replace(path)
826
+
827
+
828
+ def update_figure4(s: dict, result: dict) -> None:
829
+ """Atomic global index consumed by build_results_figures.py --deconvolution-manifest."""
830
+ path = PLAN / "deconvolution" / "deconvolution_manifest.json"
831
+ data = json.loads(path.read_text()) if path.exists() else {"schema": "pbisc.fig4.deconvolution-sources.v1", "units": {}}
832
+ rel = f'{s["cohort"]}/disease/{s["unit"].replace("_n5", "")}'
833
+ data["units"][rel] = {"csv": result["figure4_csv"], "sha256": result["figure4_csv_sha256"],
834
+ "signal_csv": result["signal_csv"], "signal_sha256": result["signal_sha256"],
835
+ "support_sha256": s["sha256"], "reference_sample_ids": s["train_sample_ids"],
836
+ "mixture_sample_ids": s["test_sample_ids"], "methods": result["methods"],
837
+ "metrics": result["metrics"], "source_sha256": result["source_sha256"],
838
+ "expression_metric_provenance": result["expression_metric_provenance"]}
839
+ data.get("inactive_units", {}).pop(rel, None)
840
+ with tempfile.NamedTemporaryFile("w", dir=path.parent, prefix=".deconv_", delete=False) as f:
841
+ json.dump(data, f, indent=2)
842
+ f.write("\n")
843
+ tmp = Path(f.name)
844
+ tmp.replace(path)
845
+
846
+
847
+ def main(argv: list[str] | None = None) -> int:
848
+ parser = argparse.ArgumentParser(description=__doc__)
849
+ parser.add_argument("--support-manifest", type=Path, required=True)
850
+ parser.add_argument("--action", choices=("adopt", "prepare", "bayesprism", "cibersortx", "score", "all"), required=True)
851
+ parser.add_argument("--out", type=Path)
852
+ parser.add_argument("--threads", type=int, default=4)
853
+ a = parser.parse_args(argv)
854
+ if not 1 <= a.threads <= 16:
855
+ parser.error("--threads must be 1..16")
856
+ s = support(a.support_manifest)
857
+ out = unit_out(s, a.out)
858
+ if a.action == "adopt":
859
+ if s["cohort"] != "ye2026_sepsis":
860
+ raise ValueError("adoption is only established for Sepsis")
861
+ proof = adopt_completed(s, out)
862
+ print(json.dumps({"schema": proof["schema"], "unit": s["unit"], "method_execution": proof["method_execution"]}))
863
+ return 0
864
+ if s["cohort"] != "ye2026_sepsis" or a.action in ("score", "all"):
865
+ host_preflight()
866
+ if a.action in ("prepare", "all"):
867
+ prepare(s, out)
868
+ if a.action in ("bayesprism", "all"):
869
+ bayesprism(s, out, a.threads)
870
+ if a.action in ("cibersortx", "all"):
871
+ cibersortx(s, out, a.threads)
872
+ if a.action in ("score", "all"):
873
+ result = score(s, out)
874
+ print(json.dumps(result, indent=2))
875
+ if result["status"] != "complete":
876
+ return 1
877
+ return 0
878
+
879
+
880
+ if __name__ == "__main__":
881
+ raise SystemExit(main())