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

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/tests/test_ablation_composition.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Composition must share the exact selected readout and retain zero classes."""
2
+
3
+ import importlib.util
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ import numpy as np
8
+ import pandas as pd
9
+ import pytest
10
+
11
+ TOOLS = Path(__file__).parents[1] / "tools"
12
+ sys.path.insert(0, str(TOOLS))
13
+ spec = importlib.util.spec_from_file_location("ablation_composition", TOOLS / "ablation_composition.py")
14
+ mod = importlib.util.module_from_spec(spec)
15
+ spec.loader.exec_module(mod)
16
+
17
+
18
+ def test_truth_labels_require_exact_unique_row_and_donor_identity():
19
+ frame = pd.DataFrame({"cell_index": [1, 0], "sample_id": ["d2", "d1"],
20
+ "celltype_l1_pred": ["B cell", "T cell"]})
21
+ got = mod.align_truth_labels(frame, np.array(["d1", "d2"]))
22
+ assert got.tolist() == ["T cell", "B cell"]
23
+ with pytest.raises(ValueError, match="donor"):
24
+ mod.align_truth_labels(frame, np.array(["d2", "d1"]))
25
+ with pytest.raises(ValueError, match="unique"):
26
+ mod.align_truth_labels(pd.concat([frame, frame.iloc[[0]]]), np.array(["d1", "d2"]))
27
+
28
+
29
+ def test_composition_includes_absent_types_and_weights_donors_equally():
30
+ reference = np.array(["T cell", "B cell", "T cell", "T cell"])
31
+ candidate = np.array(["T cell", "T cell", "B cell", "B cell"])
32
+ donors = np.array(["d1", "d1", "d2", "d2"])
33
+ rows, proportions = mod.composition_rows(reference, candidate, donors, donors, ["d1", "d2"],
34
+ ["T cell", "B cell", "DC"])
35
+ assert [r["comp_l1"] for r in rows] == [1.0, 2.0]
36
+ assert len(proportions) == 6
37
+ assert all(r["observed_fraction"] == r["candidate_fraction"] == 0 for r in proportions if r["cell_type"] == "DC")
38
+
39
+
40
+ def test_composition_rejects_missing_donors_and_unknown_labels():
41
+ with pytest.raises(ValueError, match="candidate cells"):
42
+ mod.composition_rows(np.array(["T"]), np.array(["T"]), np.array(["d1"]),
43
+ np.array(["d2"]), ["d1"], ["T"])
44
+ with pytest.raises(ValueError, match="label"):
45
+ mod.composition_rows(np.array(["T"]), np.array(["mystery"]), np.array(["d1"]),
46
+ np.array(["d1"]), ["d1"], ["T"])
47
+
48
+
49
+ def test_selected_readout_must_match_pc_hash():
50
+ counts = np.array([[1, 0], [0, 3]], dtype=np.float32)
51
+ mod.assert_array_hash(counts, mod.pc.sha_array(counts), "selected counts")
52
+ with pytest.raises(ValueError, match="P/C"):
53
+ mod.assert_array_hash(counts + 1, mod.pc.sha_array(counts), "selected counts")
paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/tests/test_campaign.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib.util
2
+ from pathlib import Path
3
+ import sys
4
+ import unittest
5
+
6
+ ROOT = Path(__file__).resolve().parents[1]
7
+ sys.path.insert(0, str(ROOT / "tools"))
8
+
9
+
10
+ class CampaignTests(unittest.TestCase):
11
+ def module(self):
12
+ path = ROOT / "tools/campaign.py"
13
+ self.assertTrue(path.exists(), "campaign is not implemented")
14
+ spec = importlib.util.spec_from_file_location("strict_campaign", path)
15
+ mod = importlib.util.module_from_spec(spec)
16
+ spec.loader.exec_module(mod)
17
+ return mod
18
+
19
+ def test_training_command_enforces_fixed_steps_and_exact_support(self):
20
+ mod = self.module()
21
+ support = ROOT / "protocol/splits/immicro/healthy/fold0/n5/support.json"
22
+ argv = mod.train_command(support)
23
+ self.assertEqual(argv[argv.index("--fixed-steps") + 1], "3000")
24
+ self.assertEqual(argv[argv.index("--support-manifest") + 1], str(support))
25
+ self.assertNotIn("--train-donors-file", argv)
26
+ self.assertNotIn("--train-n", argv)
27
+ self.assertEqual(argv[argv.index("--lora-rank") + 1], "16")
28
+
29
+ def test_no_figure6_units_can_enter_campaign(self):
30
+ mod = self.module()
31
+ units = mod.discover_units()
32
+ self.assertEqual(len(units), 40)
33
+ self.assertTrue(all("bulkonly" not in str(p) for p in units))
34
+ self.assertEqual({mod.read_support(p)["cohort"] for p in units}, set(mod.COHORTS))
35
+
36
+ def test_only_whole_campaign_can_finalize(self):
37
+ mod = self.module()
38
+ units = mod.discover_units()
39
+ self.assertTrue(mod.is_full_campaign("all", units))
40
+ self.assertFalse(mod.is_full_campaign("all", units[:1]))
41
+ self.assertFalse(mod.is_full_campaign("score", units))
42
+
43
+ def test_scssemi_commands_do_not_reuse_larger_reference(self):
44
+ mod = self.module()
45
+ path = ROOT / "protocol/splits/immicro/healthy/fold0/n5/support.json"
46
+ argv = mod.scsemi_command(path, "prepare")
47
+ self.assertIn("--support-manifest", argv)
48
+ self.assertIn("--lean-hvset", argv)
49
+ self.assertNotIn("--reuse-from", argv)
50
+ self.assertIn("run_scsemi_strict.py", " ".join(argv))
51
+
52
+
53
+ if __name__ == "__main__":
54
+ unittest.main()
paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/tests/test_completion_gate.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib.util
2
+ from pathlib import Path
3
+ import sys
4
+ import unittest
5
+ import json
6
+ import pytest
7
+
8
+ ROOT = Path(__file__).resolve().parents[1]
9
+ sys.path.insert(0, str(ROOT / "tools"))
10
+
11
+
12
+ class CompletionTests(unittest.TestCase):
13
+ def function(self):
14
+ path = ROOT / "tools/finalize_campaign.py"
15
+ self.assertTrue(path.exists(), "campaign finalizer not implemented")
16
+ spec = importlib.util.spec_from_file_location("campaign_finalizer", path)
17
+ mod = importlib.util.module_from_spec(spec)
18
+ spec.loader.exec_module(mod)
19
+ return mod.assert_publication_ready
20
+
21
+ def test_diagnostic_rare_panel_cannot_finish_manuscript(self):
22
+ with self.assertRaises(ValueError):
23
+ self.function()({"status": "complete"}, {"design": "legacy_5donor", "units": 20})
24
+
25
+ def test_pending_metrics_cannot_finish_manuscript(self):
26
+ with self.assertRaises(ValueError):
27
+ self.function()({"status": "pending"}, {"design": "strict5pair", "units": 20})
28
+
29
+ def test_all_five_figures_required_but_figure6_is_explicitly_waiting(self):
30
+ self.function()({"status": "complete"}, {"design": "strict5pair", "units": 20})
31
+
32
+
33
+ if __name__ == "__main__":
34
+ unittest.main()
35
+
36
+
37
+ def test_final_documents_run_only_after_strict_gates_and_target_final_outputs(tmp_path, monkeypatch):
38
+ import finalize_campaign as F
39
+ monkeypatch.setattr(F, "ROOT", tmp_path)
40
+ monkeypatch.setattr(F, "preserve_preview_outputs", lambda runtime, name, paths: {})
41
+ calls = []
42
+ class RuntimeFake:
43
+ def execute(self, name, argv, **kwargs):
44
+ calls.append((name, argv, kwargs))
45
+ runtime = RuntimeFake()
46
+ with pytest.raises(ValueError):
47
+ F.final_documents(runtime, {"status": "pending"}, {"design": "strict5pair", "units": 20})
48
+ assert calls == []
49
+ F.final_documents(runtime, {"status": "complete"}, {"design": "strict5pair", "units": 20})
50
+ assert [x[0] for x in calls] == ["render-final-review-deck", "assemble-verified-manuscript",
51
+ "compile-final-manuscript-pdfs", "convert-final-deck-pdf"]
52
+ assert calls[0][2]["outputs"][0] == tmp_path / "deck/paper_figures_final.pptx"
53
+ assert calls[2][2]["outputs"] == [tmp_path / "manuscript/main.pdf", tmp_path / "manuscript/supplementary.pdf"]
54
+ assert calls[3][2]["outputs"] == [tmp_path / "deck/paper_figures_final.pdf"]
55
+ assert "--require-complete" in calls[0][1] and "--require-complete" in calls[1][1]
56
+
57
+
58
+ def test_cross_draw_requires_five_verified_draws_and_preserves_donor_dependence(tmp_path, monkeypatch):
59
+ import finalize_outputs as O
60
+ import score_strict as S
61
+ monkeypatch.setattr(O, "ROOT", tmp_path)
62
+ supports = []
63
+ for draw in range(5):
64
+ support = {"schema": "pbisc.paper.strict-support.v1", "cohort": "ji2025_chili",
65
+ "design": "disease_existing_draw", "unit": f"draw{draw}_n5", "n_pairs": 5,
66
+ "train_sample_ids": [f"tr{draw}{i}" for i in range(5)],
67
+ "train_donor_ids": [f"td{draw}{i}" for i in range(5)],
68
+ "test_sample_ids": ["sA", "sB"], "test_donor_ids": ["A", "B"],
69
+ "excluded_sample_ids": []}
70
+ support["sha256"] = S.manifest_digest(support)
71
+ p = tmp_path / f"protocol/splits/ji2025_chili/disease/draw{draw}/support.json"
72
+ p.parent.mkdir(parents=True)
73
+ p.write_text(json.dumps(support))
74
+ table = tmp_path / f"scores/ji2025_chili/disease/draw{draw}/statistics/per_donor_long.csv"
75
+ table.parent.mkdir(parents=True)
76
+ table.write_text("draw,sample_id,donor_id,arm,metric,value\n")
77
+ (table.parent / "status.json").write_text(json.dumps({"support_sha256": support["sha256"],
78
+ "bootstrap_replicates": 2000, "disease_deg": {"status": "complete_with_not_estimable"}}))
79
+ (table.parents[1] / "scoring_support.json").write_text("{}\n")
80
+ (table.parents[1] / "score").mkdir()
81
+ (table.parents[1] / "score/summary.json").write_text("{}\n")
82
+ supports.append(support)
83
+ def verified(path, current, arms):
84
+ draw = path.parents[1].name
85
+ arms = ("lora", "pairedcal", "scsemi", "raw", "refcal")
86
+ records = [{"draw": f"{draw}_n5", "sample_id": sample, "donor_id": donor,
87
+ "arm": arm, "metric": "comp_l1", "value": 0. if arm == "raw" else
88
+ (1. if donor == "A" else 3.)}
89
+ for sample, donor in (("sA","A"),("sB","B")) for arm in arms]
90
+ rows = O.pd.DataFrame(records)
91
+ rows.attrs["unit"] = f"{draw}_n5"
92
+ rows.attrs["support_sha256"] = supports[int(draw.replace('draw',''))]["sha256"]
93
+ return rows
94
+ monkeypatch.setattr(O, "validate_draw_long", verified)
95
+ with pytest.raises(ValueError, match="five"):
96
+ O.cohort_draw_ci("ji2025_chili", draws=(0,1,2,3))
97
+ table, receipt = O.cohort_draw_ci("ji2025_chili", draws=range(5))
98
+ row = table.loc[(table.arm == "lora") & (table.metric == "comp_l1")].iloc[0]
99
+ assert row.estimate == 2.0
100
+ assert row.n_donors == 2
101
+ assert receipt["draws"] == [f"draw{i}_n5" for i in range(5)]
102
+ pending = tmp_path / "scores/ji2025_chili/disease/draw3/statistics/status.json"
103
+ pending.write_text(json.dumps({"support_sha256": supports[3]["sha256"],
104
+ "bootstrap_replicates": 2000, "disease_deg": {"status": "partial_or_pending"}}))
105
+ with pytest.raises(ValueError, match="corrected donor DEG pending"):
106
+ O.cohort_draw_ci("ji2025_chili", draws=range(5))
107
+
108
+
109
+ def test_frontmatter_refresh_accepts_only_approved_source_changes():
110
+ import assemble_manuscript as A
111
+ before = {"sections/abstract.tex": "old", "sections/introduction.tex": "i", "main.tex": "m",
112
+ "sections/methods_model.tex": "x"}
113
+ now = {**before, "sections/abstract.tex": "new"}
114
+ assert A.allowed_frontmatter_refresh(before, now) == {"sections/abstract.tex": {"previous_sha256": "old", "current_sha256": "new"}}
115
+ with pytest.raises(ValueError, match="outside approved frontmatter"):
116
+ A.allowed_frontmatter_refresh(before, {**now, "sections/methods_model.tex": "y"})
117
+ old_main = "\\title{Old}\n\\input{authors}\n"
118
+ new_main = "\\title{New}\n\\input{authors}\n"
119
+ A.allowed_frontmatter_refresh(before, {**before, "main.tex": "n"}, old_main=old_main, new_main=new_main)
120
+ with pytest.raises(ValueError, match="main.tex changed beyond"):
121
+ A.allowed_frontmatter_refresh(before, {**before, "main.tex": "n"}, old_main=old_main,
122
+ new_main="\\title{New}\n\\input{other}\n")
123
+
124
+
125
+ def test_preview_is_preserved_with_runtime_previous_outputs_proof(tmp_path, monkeypatch):
126
+ import finalize_campaign as F
127
+ monkeypatch.setattr(F, "ROOT", tmp_path)
128
+ preview = tmp_path / "manuscript/main.pdf"
129
+ preview.parent.mkdir()
130
+ preview.write_bytes(b"%PDF-preview")
131
+ class RuntimeFake:
132
+ def receipt_path(self, name):
133
+ return tmp_path / "receipts" / f"{name}.json"
134
+ proof = F.preserve_preview_outputs(RuntimeFake(), "compile-final-manuscript-pdfs", [preview])
135
+ backup = Path(proof[str(preview)]["backup"])
136
+ assert backup.read_bytes() == preview.read_bytes()
137
+ assert proof[str(preview)]["backup"] == str(backup)
138
+ assert proof[str(preview)]["sha256"] == F.sha256(preview)
139
+
140
+
141
+ def test_failed_supplement_compile_keeps_both_preview_pdfs(tmp_path, monkeypatch):
142
+ import finalize_outputs as O
143
+ import subprocess
144
+ monkeypatch.setattr(O, "ROOT", tmp_path)
145
+ monkeypatch.setattr(O, "_require_staged_manuscript", lambda: None)
146
+ stage = tmp_path / "manuscript"
147
+ stage.mkdir()
148
+ (stage / "main.pdf").write_bytes(b"main preview")
149
+ (stage / "supplementary.pdf").write_bytes(b"supp preview")
150
+ def fake_run(argv, **kwargs):
151
+ if "supplementary.tex" in argv:
152
+ raise subprocess.CalledProcessError(1, argv)
153
+ target = Path(argv[argv.index("--outdir") + 1]) / "main.pdf"
154
+ target.write_bytes(b"%PDF-" + b"x" * 1024)
155
+ monkeypatch.setattr(O.subprocess, "run", fake_run)
156
+ with pytest.raises(subprocess.CalledProcessError):
157
+ O.compile_manuscript_pdfs()
158
+ assert (stage / "main.pdf").read_bytes() == b"main preview"
159
+ assert (stage / "supplementary.pdf").read_bytes() == b"supp preview"
paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/tests/test_deconv_strict.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Exact support and credential-boundary tests for deconvolution adapter."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ import importlib.util
6
+ import json
7
+ import shutil
8
+ import subprocess
9
+ from pathlib import Path
10
+
11
+ import numpy as np
12
+ import pandas as pd
13
+ import pytest
14
+
15
+ ROOT = Path(__file__).resolve().parents[1]
16
+ SPEC = importlib.util.spec_from_file_location("deconv_strict", ROOT / "tools/deconv_strict.py")
17
+ assert SPEC and SPEC.loader
18
+ D = importlib.util.module_from_spec(SPEC)
19
+ SPEC.loader.exec_module(D)
20
+
21
+
22
+ def manifest(tmp_path: Path, *, excluded_in_test: bool = False) -> Path:
23
+ data = {"schema": "pbisc.paper.strict-support.v1", "cohort": "ji2025_chili",
24
+ "design": "disease_existing_draw", "unit": "draw0_n5", "n_pairs": 5,
25
+ "train_sample_ids": [f"P{i}_BC" for i in range(5)],
26
+ "train_donor_ids": [f"P{i}" for i in range(5)],
27
+ "test_sample_ids": ["P5_AC", "P5_FU1", "P6_AC"],
28
+ "test_donor_ids": ["P5", "P5", "P6"],
29
+ "excluded_sample_ids": ["P0_AC"]}
30
+ if excluded_in_test:
31
+ data["test_sample_ids"][0] = "P0_AC"
32
+ data["sha256"] = hashlib.sha256(json.dumps(data, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
33
+ p = tmp_path / "support.json"
34
+ p.write_text(json.dumps(data))
35
+ return p
36
+
37
+
38
+ def test_exact_five_samples_and_excluded_visits(tmp_path: Path) -> None:
39
+ s = D.validate_support_data(json.loads(manifest(tmp_path).read_text()))
40
+ split = D.strict_split(s)
41
+ assert split["reference"] == [f"P{i}_BC" for i in range(5)]
42
+ assert split["mixture"] == ["P5_AC", "P5_FU1", "P6_AC"]
43
+ assert split["excluded_samples"] == ["P0_AC"]
44
+ assert "P0_AC" not in split["reference"] + split["mixture"]
45
+ with pytest.raises(ValueError, match="excluded visits"):
46
+ D.validate_support_data(json.loads(manifest(tmp_path, excluded_in_test=True).read_text()))
47
+
48
+
49
+ def test_output_isolation_and_binding(tmp_path: Path) -> None:
50
+ path = manifest(tmp_path)
51
+ s = D.validate_support_data(json.loads(path.read_text()))
52
+ out = D.unit_out(s, None)
53
+ assert out == ROOT / "deconvolution/ji2025_chili/disease/draw0"
54
+ with pytest.raises(ValueError, match="strict unit output"):
55
+ D.unit_out(s, tmp_path / "other")
56
+ with pytest.raises(ValueError, match="canonical protocol file"):
57
+ D.support(path)
58
+ hostile = dict(s, unit="../../../../../outside_n5")
59
+ hostile.pop("sha256")
60
+ hostile["sha256"] = hashlib.sha256(json.dumps(hostile, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
61
+ with pytest.raises(ValueError, match="canonical disease draw unit"):
62
+ D.unit_out(hostile, None)
63
+
64
+
65
+ def test_method_output_rejects_extra_or_missing_mixture(tmp_path: Path) -> None:
66
+ s = D.validate_support_data(json.loads(manifest(tmp_path).read_text()))
67
+ bp = tmp_path / "inputs/ji2025_chili/fewshot0_full/bp"
68
+ bp.mkdir(parents=True)
69
+ (bp / "DONE").write_text("ok\n")
70
+ rows = s["test_sample_ids"] + ["P0_AC"]
71
+ pd.DataFrame({"T cell": [0.5] * len(rows)}, index=rows).to_csv(bp / "theta_final.csv")
72
+ with pytest.raises(ValueError, match="mixtures differ"):
73
+ D.method_output_hashes(s, tmp_path, "bayesprism")
74
+ pd.DataFrame({"T cell": [0.5] * len(s["test_sample_ids"])},
75
+ index=s["test_sample_ids"]).to_csv(bp / "theta_final.csv")
76
+ (bp / "theta_first.csv").write_text("sample,T cell\n")
77
+ (bp / "Z_type_T_cell.tsv.gz").write_bytes(b"fixture")
78
+ hashes = D.method_output_hashes(s, tmp_path, "bayesprism")
79
+ assert str(bp / "theta_final.csv") in hashes
80
+
81
+
82
+ def test_prepare_never_rewrites_existing_inputs_and_refuses_unreceipted_output(tmp_path: Path, monkeypatch) -> None:
83
+ s = D.validate_support_data(json.loads(manifest(tmp_path).read_text()))
84
+ out = tmp_path / "unit"
85
+ D.bind(s, out)
86
+ (out / "INPUTS.json").write_text('{"fixture":true}\n')
87
+ monkeypatch.setattr(D, "require_inputs", lambda *_a: {"verified": True})
88
+ assert D.prepare(s, out) == {"verified": True}
89
+ assert (out / "INPUTS.json").read_text() == '{"fixture":true}\n'
90
+ (out / "INPUTS.json").unlink()
91
+ bp = out / "inputs/ji2025_chili/fewshot0_full/bp"
92
+ bp.mkdir(parents=True)
93
+ (bp / "DONE").write_text("ok\n")
94
+ with pytest.raises(ValueError, match="refusing to rewrite inputs"):
95
+ D.prepare(s, out)
96
+
97
+
98
+ def test_method_receipt_binds_prepared_inputs_and_outputs(tmp_path: Path, monkeypatch) -> None:
99
+ s = D.validate_support_data(json.loads(manifest(tmp_path).read_text()))
100
+ (tmp_path / "INPUTS.json").write_text('{"input":"v1"}\n')
101
+ monkeypatch.setattr(D, "require_inputs", lambda *_a: {})
102
+ bp = D.stage_dir(s, tmp_path, "bayesprism")
103
+ bp.mkdir(parents=True)
104
+ for name in ("DONE", "theta_final.csv", "theta_first.csv", "genes_used.txt", "Z_type_T_cell.tsv.gz"):
105
+ (bp / name).write_text("fixture\n")
106
+ with pytest.raises(ValueError, match="without a support/input-bound receipt"):
107
+ D.verify_stage_receipt(s, tmp_path, "bayesprism")
108
+ D.write_stage_receipt(s, tmp_path, "bayesprism")
109
+ assert D.verify_stage_receipt(s, tmp_path, "bayesprism")["support_sha256"] == s["sha256"]
110
+ (tmp_path / "INPUTS.json").write_text('{"input":"v2"}\n')
111
+ with pytest.raises(ValueError, match="receipt differs"):
112
+ D.verify_stage_receipt(s, tmp_path, "bayesprism")
113
+
114
+
115
+ def test_partial_method_output_is_preserved_without_relaunch(tmp_path: Path, monkeypatch) -> None:
116
+ s = D.validate_support_data(json.loads(manifest(tmp_path).read_text()))
117
+ bp = D.stage_dir(s, tmp_path, "bayesprism")
118
+ bp.mkdir(parents=True)
119
+ (bp / "theta_final.csv").write_text("partial\n")
120
+ monkeypatch.setattr(D, "require_inputs", lambda *_a: {})
121
+ monkeypatch.setattr(D.subprocess, "run", lambda *_a, **_k: pytest.fail("method relaunched"))
122
+ with pytest.raises(ValueError, match="partial BayesPrism output"):
123
+ D.bayesprism(s, tmp_path, 2)
124
+ assert (bp / "theta_final.csv").read_text() == "partial\n"
125
+
126
+
127
+ def test_missing_required_hires_type_is_an_error(tmp_path: Path) -> None:
128
+ s = D.support(ROOT / "protocol/splits/ye2026_sepsis/disease/draw0/support.json")
129
+ assert len(s["test_sample_ids"]) > 8
130
+ hd = D.stage_dir(s, tmp_path, "hires")
131
+ hd.mkdir(parents=True)
132
+ (hd / "CIBERSORTxHiRes_NA_Tcell_Window1.txt").write_text("fixture\n")
133
+ with pytest.raises(FileNotFoundError, match="required type output missing"):
134
+ D.stage_outputs(s, tmp_path, "hires")
135
+
136
+
137
+ def test_pending_correction_takes_precedence_and_cli_returns_nonzero(monkeypatch, capsys) -> None:
138
+ methods = {name: {"status": "complete"} for name in ("bayesprism", "cibersortx")}
139
+ metrics = {"bayesprism": {"corrected_deg": {"status": "pending", "n_types_estimable": 2}},
140
+ "cibersortx": {"corrected_deg": {"status": "complete"}}}
141
+ status, reasons = D.score_readiness(methods, metrics)
142
+ assert status == "pending" and any("bayesprism" in r for r in reasons)
143
+ metrics["bayesprism"]["corrected_deg"]["status"] = "not_estimable"
144
+ assert D.score_readiness(methods, metrics) == ("complete", [])
145
+ path = ROOT / "protocol/splits/ji2025_chili/disease/draw0/support.json"
146
+ monkeypatch.setattr(D, "host_preflight", lambda: None)
147
+ monkeypatch.setattr(D, "score", lambda *_a: {"status": "pending", "methods": methods, "metrics": metrics})
148
+ assert D.main(["--support-manifest", str(path), "--action", "score"]) == 1
149
+ assert '"status": "pending"' in capsys.readouterr().out
150
+
151
+
152
+ def test_pending_score_invalidates_prior_figure_mapping_without_losing_receipt(tmp_path: Path, monkeypatch) -> None:
153
+ s = D.validate_support_data(json.loads(manifest(tmp_path).read_text()))
154
+ monkeypatch.setattr(D, "PLAN", tmp_path)
155
+ path = tmp_path / "deconvolution/deconvolution_manifest.json"
156
+ path.parent.mkdir()
157
+ rel = "ji2025_chili/disease/draw0"
158
+ old = {"csv": "/prior/score.csv", "sha256": "old", "support_sha256": s["sha256"]}
159
+ path.write_text(json.dumps({"schema": "pbisc.fig4.deconvolution-sources.v1", "units": {rel: old}}))
160
+ D.invalidate_figure4(s, ["corrected DEG pending"])
161
+ changed = json.loads(path.read_text())
162
+ assert rel not in changed["units"]
163
+ assert changed["inactive_units"][rel]["previous"] == old
164
+
165
+
166
+ def test_docker_host_argv_and_redacted_log_contain_no_credentials(tmp_path: Path, monkeypatch) -> None:
167
+ username, token = "private@example.org", "deadbeef" * 8
168
+ envfile = tmp_path / "env"
169
+ argv = D.cx_argv("cibersortx/fractions:latest", "CIBERSORTxFractions", tmp_path,
170
+ tmp_path / "out", envfile, 2, ["--mixture", "mixture.txt"])
171
+ rendered = " ".join(argv)
172
+ assert username not in rendered and token not in rendered
173
+ assert '"$CX_USER"' in rendered and '"$CX_TOKEN"' in rendered
174
+
175
+ class FakeStdout:
176
+ def __iter__(self):
177
+ return iter([f">[Options] username: {username}\n", f">[Options] token: {token}\n",
178
+ f"more {username} {token}\n"])
179
+
180
+ class FakeProcess:
181
+ stdout = FakeStdout()
182
+ def __enter__(self):
183
+ return self
184
+ def __exit__(self, *_args):
185
+ return False
186
+ def wait(self):
187
+ return 0
188
+
189
+ monkeypatch.setattr(D.subprocess, "Popen", lambda *_a, **_k: FakeProcess())
190
+ log = tmp_path / "run.log"
191
+ D.run_cx(argv, log, username, token)
192
+ saved = log.read_text()
193
+ assert username not in saved and token not in saved
194
+ assert saved.count("[REDACTED]") >= 4
195
+
196
+
197
+ def test_real_supports_are_exact_and_donor_disjoint() -> None:
198
+ files = sorted((ROOT / "protocol/splits").glob("*/disease/draw*/support.json"))
199
+ assert len(files) == 20
200
+ for path in files:
201
+ s = D.support(path)
202
+ assert len(s["train_sample_ids"]) == len(s["train_donor_ids"]) == 5
203
+ assert not set(s["train_donor_ids"]) & set(s["test_donor_ids"])
204
+ assert not set(s["excluded_sample_ids"]) & set(s["test_sample_ids"])
205
+
206
+
207
+ def test_repeated_visits_collapse_to_one_donor_condition() -> None:
208
+ s = {"test_donor_ids": ["A", "A", "B", "C"]}
209
+ case = np.array([True, True, False, False])
210
+ ctrl = ~case
211
+ profiles = np.array([[9., 1.], [1., 9.], [2., 8.], [7., 3.]])
212
+ meta, observed, method, bulk = D._collapse_donor_condition(s, case, ctrl,
213
+ profiles, profiles, profiles)
214
+ assert len(meta) == 3
215
+ assert meta.to_dict("records") == [
216
+ {"donor_id": "A", "condition": "case"},
217
+ {"donor_id": "B", "condition": "control"},
218
+ {"donor_id": "C", "condition": "control"}]
219
+ expected = D._log2_cpm(profiles[:2]).mean(axis=0)
220
+ np.testing.assert_allclose(observed[0], expected)
221
+ np.testing.assert_allclose(method, observed)
222
+ np.testing.assert_allclose(bulk, observed)
223
+
224
+
225
+ @pytest.mark.skipif(shutil.which("Rscript") is None, reason="Rscript unavailable")
226
+ def test_continuous_limma_fixture(tmp_path: Path) -> None:
227
+ probe = subprocess.run(["Rscript", "-e", 'quit(status=if (requireNamespace("limma", quietly=TRUE)) 0 else 1)'])
228
+ if probe.returncode:
229
+ pytest.skip("limma unavailable")
230
+ metadata = pd.DataFrame({"donor_id": [f"D{i}" for i in range(8)],
231
+ "condition": ["control"] * 4 + ["case"] * 4})
232
+ metadata.to_csv(tmp_path / "metadata.csv", index=False)
233
+ genes = [f"G{i}" for i in range(8)]
234
+ observed = np.array([[1.0, 1.1, 0.9, 1.05, 4.0, 4.1, 3.9, 4.05],
235
+ [2.0, 2.1, 1.9, 2.05, 5.0, 5.1, 4.9, 5.05],
236
+ *([np.linspace(1.0, 2.0, 8)] * 6)])
237
+ for name, matrix in (("observed", observed), ("method", observed + 0.01)):
238
+ pd.DataFrame(matrix, index=genes).to_csv(tmp_path / f"{name}.tsv.gz", sep="\t")
239
+ script = tmp_path / "limma.R"
240
+ script.write_text(D.LIMMA_R)
241
+ subprocess.run(["Rscript", str(script), str(tmp_path / "metadata.csv"),
242
+ str(tmp_path / "observed.tsv.gz"), str(tmp_path / "method.tsv.gz"), str(tmp_path / "out")],
243
+ check=True, capture_output=True, text=True)
244
+ obs = pd.read_csv(tmp_path / "out/observed_limma.csv")
245
+ method = pd.read_csv(tmp_path / "out/method_limma.csv")
246
+ assert set(obs.gene_id) == set(method.gene_id) == set(genes)
247
+ assert float(obs.set_index("gene_id").loc["G0", "logFC"]) > 2.0
248
+ assert D._top50(obs) & D._top50(method)
249
+ metadata["donor_id"] = [f"D{i}" for i in range(4)] * 2
250
+ metadata.to_csv(tmp_path / "metadata.csv", index=False)
251
+ subprocess.run(["Rscript", str(script), str(tmp_path / "metadata.csv"),
252
+ str(tmp_path / "observed.tsv.gz"), str(tmp_path / "method.tsv.gz"), str(tmp_path / "paired")],
253
+ check=True, capture_output=True, text=True)
254
+ assert (tmp_path / "paired/method_limma.csv").is_file()