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_rare_metrics.py +381 -0
- 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_reference_calibration.py +42 -0
- 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_rescore_pretrain_ablations.py +48 -0
- 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_runtime.py +115 -0
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_rare_metrics.py
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pandas as pd
|
| 6 |
+
import pytest
|
| 7 |
+
|
| 8 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools"))
|
| 9 |
+
from rare_metrics import (aggregate_donors, abundance_summary, bootstrap_mae,
|
| 10 |
+
call_marker_state, validate_marker_coverage, validate_design)
|
| 11 |
+
from build_figure5 import analyze_unit, require_complete_strict
|
| 12 |
+
from rare_cache_builder import _stream_poisson, build_arm, sha256
|
| 13 |
+
from figure5_panels import render, validate_plot_data
|
| 14 |
+
from export_rare_visuals import choose_donor_draws, build_visuals
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def test_missing_mandatory_marker_fails_closed():
|
| 18 |
+
state = {"name": "C1Q", "kind": "markers", "genes": ["C1QA", "C1QB", "C1QC"],
|
| 19 |
+
"k": 2, "require_any": [["CD38", "HLA-DRA"]], "exclude": ["CR2"]}
|
| 20 |
+
with pytest.raises(ValueError, match="C1QC"):
|
| 21 |
+
validate_marker_coverage(state, ["C1QA", "C1QB", "CD38", "HLA-DRA", "CR2"])
|
| 22 |
+
with pytest.raises(ValueError, match="CR2"):
|
| 23 |
+
validate_marker_coverage(state, ["C1QA", "C1QB", "C1QC", "CD38", "HLA-DRA"])
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def test_multimarker_codetection_needs_all_rule_parts():
|
| 27 |
+
state = {"name": "C1Q", "kind": "markers", "genes": ["C1QA", "C1QB", "C1QC"],
|
| 28 |
+
"k": 2, "require_any": [["CD38", "HLA-DRA"]], "exclude": ["CR2"]}
|
| 29 |
+
genes = ["C1QA", "C1QB", "C1QC", "CD38", "HLA-DRA", "CR2"]
|
| 30 |
+
counts = np.array([[1, 1, 0, 1, 0, 0], [1, 1, 0, 0, 0, 0],
|
| 31 |
+
[1, 1, 0, 1, 0, 1]])
|
| 32 |
+
assert call_marker_state(counts, genes, state).tolist() == [True, False, False]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def test_longitudinal_samples_aggregate_to_actual_donor_and_zero_is_included():
|
| 36 |
+
rows = pd.DataFrame([
|
| 37 |
+
dict(sample_id="a_t0", donor_id="a", obs_parent=10, obs_state=2, gen_parent=10, gen_state=0),
|
| 38 |
+
dict(sample_id="a_t1", donor_id="a", obs_parent=10, obs_state=2, gen_parent=10, gen_state=0),
|
| 39 |
+
dict(sample_id="b_t0", donor_id="b", obs_parent=10, obs_state=1, gen_parent=10, gen_state=1),
|
| 40 |
+
])
|
| 41 |
+
donor = aggregate_donors(rows)
|
| 42 |
+
assert len(donor) == 2
|
| 43 |
+
assert donor.set_index("donor_id").loc["a", "gen_pct"] == 0
|
| 44 |
+
summary = abundance_summary(rows)
|
| 45 |
+
assert summary["n_samples"] == 3 and summary["n_donors"] == 2
|
| 46 |
+
assert summary["generated_zero_samples"] == 2
|
| 47 |
+
assert summary["gen_pct"] == pytest.approx(100 / 30)
|
| 48 |
+
assert summary["mae_sample_pp"] == pytest.approx((20 + 20 + 0) / 3)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def test_zero_parent_has_undefined_conditional_rate_and_zero_overall_rate():
|
| 52 |
+
rows = pd.DataFrame([dict(sample_id="s", donor_id="d", obs_parent=4, obs_state=0,
|
| 53 |
+
gen_parent=0, gen_state=0, obs_total=10, gen_total=10)])
|
| 54 |
+
donor = aggregate_donors(rows)
|
| 55 |
+
assert np.isnan(donor.iloc[0].gen_pct)
|
| 56 |
+
assert donor.iloc[0].gen_overall_pct == 0
|
| 57 |
+
assert np.isnan(abundance_summary(rows)["gen_pct"])
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def test_donor_bootstrap_is_deterministic_and_clusters_samples():
|
| 61 |
+
rows = pd.DataFrame([
|
| 62 |
+
dict(sample_id="a0", donor_id="a", obs_parent=10, obs_state=1, gen_parent=10, gen_state=0),
|
| 63 |
+
dict(sample_id="a1", donor_id="a", obs_parent=10, obs_state=1, gen_parent=10, gen_state=0),
|
| 64 |
+
dict(sample_id="b0", donor_id="b", obs_parent=10, obs_state=3, gen_parent=10, gen_state=2),
|
| 65 |
+
])
|
| 66 |
+
assert bootstrap_mae(rows, seed=7, n_boot=100) == bootstrap_mae(rows, seed=7, n_boot=100)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def test_longitudinal_donor_can_change_clinical_group_without_becoming_two_donors():
|
| 70 |
+
rows = pd.DataFrame([
|
| 71 |
+
dict(sample_id="d0", donor_id="d", group="mild", obs_parent=10, obs_state=1,
|
| 72 |
+
gen_parent=10, gen_state=0),
|
| 73 |
+
dict(sample_id="d14", donor_id="d", group="severe", obs_parent=10, obs_state=3,
|
| 74 |
+
gen_parent=10, gen_state=1),
|
| 75 |
+
])
|
| 76 |
+
donor = aggregate_donors(rows)
|
| 77 |
+
assert len(donor) == 1
|
| 78 |
+
assert donor.iloc[0].group == "mixed"
|
| 79 |
+
assert donor.iloc[0].obs_state == 4
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def test_strict_design_rejects_duplicate_training_donors():
|
| 83 |
+
with pytest.raises(ValueError, match="unique donor"):
|
| 84 |
+
validate_design({"design": "strict5pair", "train_sample_ids": ["a0", "a1", "b", "c", "d"],
|
| 85 |
+
"train_donor_ids": ["a", "a", "b", "c", "d"]})
|
| 86 |
+
assert validate_design({"design": "legacy_5donor", "train_sample_ids": ["a0", "a1"],
|
| 87 |
+
"train_donor_ids": ["a", "a"]}) == "diagnostic"
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def test_strict_cache_requires_bound_support_manifest(tmp_path):
|
| 91 |
+
sample_ids = ["test"]
|
| 92 |
+
np.savez(tmp_path / "cache.npz", markers=np.array([[1, 1, 0]], dtype=np.int32),
|
| 93 |
+
marker_symbols=np.array(["C1QA", "C1QB", "C1QC"]),
|
| 94 |
+
lib_measured=np.array([10]), sample_id=np.array(sample_ids),
|
| 95 |
+
aifi_l1=np.array(["Monocyte"]), aifi_l2=np.array(["CD14 monocyte"]),
|
| 96 |
+
receipt="test")
|
| 97 |
+
pd.DataFrame([dict(sample_id=f"train{i}", donor_id=f"d{i}", group="case")
|
| 98 |
+
for i in range(5)] +
|
| 99 |
+
[dict(sample_id="test", donor_id="dt", group="case")]).to_csv(
|
| 100 |
+
tmp_path / "metadata.csv", index=False)
|
| 101 |
+
unit = dict(cohort="toy", unit="draw0", design="strict5pair",
|
| 102 |
+
train_sample_ids=[f"train{i}" for i in range(5)],
|
| 103 |
+
train_donor_ids=[f"d{i}" for i in range(5)],
|
| 104 |
+
test_sample_ids=["test"], sample_metadata="metadata.csv",
|
| 105 |
+
observed_cache="cache.npz", generated_caches={"lora5": "cache.npz"},
|
| 106 |
+
cell_budget=1, depth_target=10)
|
| 107 |
+
state = dict(name="C1Q", kind="markers", genes=["C1QA", "C1QB", "C1QC"],
|
| 108 |
+
parent=["Monocyte"], k=2)
|
| 109 |
+
with pytest.raises(ValueError, match="support_manifest"):
|
| 110 |
+
analyze_unit(unit, tmp_path, [state])
|
| 111 |
+
support = dict(cohort="toy", unit="draw0_n5", train_sample_ids=unit["train_sample_ids"],
|
| 112 |
+
train_donor_ids=unit["train_donor_ids"], test_sample_ids=["test"],
|
| 113 |
+
test_donor_ids=["dt"], schema="pbisc.paper.strict-support.v1")
|
| 114 |
+
import hashlib
|
| 115 |
+
import json
|
| 116 |
+
support["sha256"] = hashlib.sha256(json.dumps(
|
| 117 |
+
support, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()).hexdigest()
|
| 118 |
+
(tmp_path / "support.json").write_text(__import__("json").dumps(support))
|
| 119 |
+
unit["support_manifest"] = "support.json"
|
| 120 |
+
score = tmp_path / "score"
|
| 121 |
+
labels = score / "arms/lora5/labels"
|
| 122 |
+
labels.mkdir(parents=True)
|
| 123 |
+
generated = tmp_path / "source.npz"
|
| 124 |
+
generated.write_bytes(b"source content")
|
| 125 |
+
cells = labels.parent / "generated_cells.parquet"
|
| 126 |
+
cells.write_bytes(b"scored cells")
|
| 127 |
+
label_path = labels / "labels.parquet"
|
| 128 |
+
label_path.write_bytes(b"scored labels")
|
| 129 |
+
source_sha = sha256(generated)
|
| 130 |
+
score_summary = score / "summary.json"
|
| 131 |
+
score_summary.write_text(json.dumps({
|
| 132 |
+
"schema": "paired_ft_scores.v1", "dataset": "toy", "donors": ["test"],
|
| 133 |
+
"per_arm": {"lora5": {"npz": str(generated), "npz_sha256": source_sha,
|
| 134 |
+
"receipt_verified": True,
|
| 135 |
+
"poisson": {"seed": 20260916,
|
| 136 |
+
"rule": "whole NPZ, rows in NPZ order"}}}}))
|
| 137 |
+
binding = score.parent / "scoring_support.json"
|
| 138 |
+
binding.write_text(json.dumps({
|
| 139 |
+
"schema": "pbisc.paper.strict-score-binding.v1",
|
| 140 |
+
"support_sha256": support["sha256"], "cohort": "toy", "unit": "draw0_n5",
|
| 141 |
+
"test_sample_ids": ["test"], "test_donor_ids": ["dt"]}))
|
| 142 |
+
rec = dict(schema="pbisc.figure5.marker-cache.v1", cohort="toy", unit="draw0_n5",
|
| 143 |
+
arm="lora5", support_sha256=support["sha256"], poisson_seed=20260916,
|
| 144 |
+
benchmark_umi_reproduced=True, cells=1, generated_npz=str(generated),
|
| 145 |
+
generated_npz_sha256=source_sha, score_summary=str(score_summary),
|
| 146 |
+
score_summary_sha256=sha256(score_summary), score_generated_cells=str(cells),
|
| 147 |
+
score_generated_cells_sha256=sha256(cells),
|
| 148 |
+
score_labels_sha256=sha256(label_path),
|
| 149 |
+
scoring_support=str(binding), scoring_support_sha256=sha256(binding))
|
| 150 |
+
np.savez(tmp_path / "cache.npz", markers=np.array([[1, 1, 0]], dtype=np.int32),
|
| 151 |
+
marker_symbols=np.array(["C1QA", "C1QB", "C1QC"]),
|
| 152 |
+
lib_measured=np.array([10]), sample_id=np.array(["test"]),
|
| 153 |
+
aifi_l1=np.array(["Monocyte"]), aifi_l2=np.array(["CD14 monocyte"]),
|
| 154 |
+
receipt=json.dumps(rec))
|
| 155 |
+
unit["generated_cache_sha256"] = {"lora5": sha256(tmp_path / "cache.npz")}
|
| 156 |
+
unit["observed_cache_sha256"] = sha256(tmp_path / "cache.npz")
|
| 157 |
+
rows, summary, provenance = analyze_unit(unit, tmp_path, [state])
|
| 158 |
+
assert len(rows) == len(summary) == 1
|
| 159 |
+
assert provenance["support_sha256"] == support["sha256"]
|
| 160 |
+
assert rows[0]["gen_state"] == 1
|
| 161 |
+
rec["arm"] = "wrong_arm"
|
| 162 |
+
np.savez(tmp_path / "cache.npz", markers=np.array([[1, 1, 0]], dtype=np.int32),
|
| 163 |
+
marker_symbols=np.array(["C1QA", "C1QB", "C1QC"]),
|
| 164 |
+
lib_measured=np.array([10]), sample_id=np.array(["test"]),
|
| 165 |
+
aifi_l1=np.array(["Monocyte"]), aifi_l2=np.array(["CD14 monocyte"]),
|
| 166 |
+
receipt=json.dumps(rec))
|
| 167 |
+
unit["generated_cache_sha256"]["lora5"] = sha256(tmp_path / "cache.npz")
|
| 168 |
+
unit["observed_cache_sha256"] = sha256(tmp_path / "cache.npz")
|
| 169 |
+
with pytest.raises(ValueError, match="receipt mismatch: arm"):
|
| 170 |
+
analyze_unit(unit, tmp_path, [state])
|
| 171 |
+
rec["arm"] = "lora5"
|
| 172 |
+
np.savez(tmp_path / "cache.npz", markers=np.array([[1, 1, 0]], dtype=np.int32),
|
| 173 |
+
marker_symbols=np.array(["C1QA", "C1QB", "C1QC"]),
|
| 174 |
+
lib_measured=np.array([10]), sample_id=np.array(["test"]),
|
| 175 |
+
aifi_l1=np.array(["Monocyte"]), aifi_l2=np.array(["CD14 monocyte"]),
|
| 176 |
+
receipt=json.dumps(rec))
|
| 177 |
+
unit["generated_cache_sha256"]["lora5"] = sha256(tmp_path / "cache.npz")
|
| 178 |
+
unit["observed_cache_sha256"] = sha256(tmp_path / "cache.npz")
|
| 179 |
+
binding.write_text(json.dumps({
|
| 180 |
+
"schema": "pbisc.paper.strict-score-binding.v1",
|
| 181 |
+
"support_sha256": "wrong", "cohort": "toy", "unit": "draw0_n5",
|
| 182 |
+
"test_sample_ids": ["test"], "test_donor_ids": ["dt"]}))
|
| 183 |
+
with pytest.raises(ValueError, match="scoring support"):
|
| 184 |
+
analyze_unit(unit, tmp_path, [state])
|
| 185 |
+
binding.unlink()
|
| 186 |
+
with pytest.raises(ValueError, match="scoring support"):
|
| 187 |
+
analyze_unit(unit, tmp_path, [state])
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def test_chunked_cache_readout_matches_whole_npz_poisson_and_scored_row_order():
|
| 191 |
+
rates = np.arange(24, dtype=float).reshape(6, 4) / 8
|
| 192 |
+
selected = np.array([4, 1, 5])
|
| 193 |
+
full = np.random.default_rng(20260916).poisson(rates)
|
| 194 |
+
markers, libs, umis = _stream_poisson(
|
| 195 |
+
rates, selected, np.array([True, False, True, True]),
|
| 196 |
+
np.array([2, 0]), np.array([1, 3]), chunk_rows=2)
|
| 197 |
+
np.testing.assert_array_equal(markers, full[selected][:, [2, 0]])
|
| 198 |
+
np.testing.assert_array_equal(libs, full[selected][:, [0, 2, 3]].sum(1))
|
| 199 |
+
np.testing.assert_array_equal(umis, full[selected][:, [1, 3]].sum(1))
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def test_strict_figure_requires_every_cohort_and_five_draws():
|
| 203 |
+
with pytest.raises(ValueError, match="missing strict"):
|
| 204 |
+
require_complete_strict([{"cohort": "ye2026_sepsis", "unit": "draw0"}])
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def _complete_units():
|
| 208 |
+
return [dict(cohort=c, unit=f"draw{i}", design="strict5pair",
|
| 209 |
+
generated_caches={a: f"{a}.npz" for a in
|
| 210 |
+
("lora", "pairedcal", "scsemi", "raw", "refcal")},
|
| 211 |
+
cell_budget=500, depth_target=1000)
|
| 212 |
+
for c in ("ye2026_sepsis", "imperial_eskd", "giroux2022", "ji2025_chili")
|
| 213 |
+
for i in range(5)]
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def test_strict_figure_rejects_missing_arm_and_mixed_budget_or_depth():
|
| 217 |
+
units = _complete_units()
|
| 218 |
+
assert require_complete_strict(units) is None
|
| 219 |
+
units[0]["generated_caches"].pop("refcal")
|
| 220 |
+
with pytest.raises(ValueError, match="arms"):
|
| 221 |
+
require_complete_strict(units)
|
| 222 |
+
units = _complete_units()
|
| 223 |
+
units[1]["depth_target"] = 500
|
| 224 |
+
with pytest.raises(ValueError, match="depth_target"):
|
| 225 |
+
require_complete_strict(units)
|
| 226 |
+
units = _complete_units()
|
| 227 |
+
units[1]["cell_budget"] = 400
|
| 228 |
+
with pytest.raises(ValueError, match="cell_budget"):
|
| 229 |
+
require_complete_strict(units)
|
| 230 |
+
units = _complete_units()
|
| 231 |
+
units[1]["design"] = "legacy_5donor"
|
| 232 |
+
with pytest.raises(ValueError, match="strict5pair"):
|
| 233 |
+
require_complete_strict(units)
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def test_strict_renderer_uses_new_arm_names_and_has_nonempty_panels(tmp_path):
|
| 237 |
+
src = tmp_path / "source_data"
|
| 238 |
+
src.mkdir()
|
| 239 |
+
arms = ("raw", "refcal", "pairedcal", "scsemi", "lora")
|
| 240 |
+
sample = pd.DataFrame([
|
| 241 |
+
dict(cohort="ye2026_sepsis", unit="draw0", arm=a, donor_id="donorA",
|
| 242 |
+
state="C1Q-high monocyte (reference)", state_kind="markers",
|
| 243 |
+
obs_parent=10, obs_state=2, gen_parent=10, gen_state=i,
|
| 244 |
+
obs_codetection=.2, gen_codetection=i/10)
|
| 245 |
+
for i, a in enumerate(arms)])
|
| 246 |
+
donor = sample.assign(obs_pct=20, gen_pct=[i*10 for i in range(5)])
|
| 247 |
+
summary = sample.assign(evidence_tier="strict", obs_pct=20, spearman_donor=float('nan'),
|
| 248 |
+
mae_donor_pp=[20, 10, 10, 10, 0])
|
| 249 |
+
sample.to_csv(src / "rare_per_sample.csv", index=False)
|
| 250 |
+
donor.to_csv(src / "rare_per_donor.csv", index=False)
|
| 251 |
+
summary.to_csv(src / "rare_summary.csv", index=False)
|
| 252 |
+
assert validate_plot_data(sample, donor, summary, "strict") == list(arms)
|
| 253 |
+
render(tmp_path)
|
| 254 |
+
assert (tmp_path / "figures/fig5_rare_states_strict.png").stat().st_size > 1000
|
| 255 |
+
with pytest.raises(ValueError, match="visual"):
|
| 256 |
+
render(tmp_path, require_complete=True)
|
| 257 |
+
import json
|
| 258 |
+
reports = tmp_path / "reports"
|
| 259 |
+
reports.mkdir(exist_ok=True)
|
| 260 |
+
(reports / "rare_provenance.json").write_text(json.dumps(
|
| 261 |
+
{"units": [{"evidence_tier": "strict"}] * 20, "visuals": {"status": "complete"}}))
|
| 262 |
+
(reports / "rare_visual_provenance.json").write_text(json.dumps(
|
| 263 |
+
{"schema": "pbisc.figure5.marker-visuals.v1", "status": "complete",
|
| 264 |
+
"examples": [{"status": "available"}] * 3}))
|
| 265 |
+
for ext in ("pdf", "svg", "png"):
|
| 266 |
+
(tmp_path / "figures" / f"fig5_rare_visuals_strict.{ext}").write_bytes(b"fixture")
|
| 267 |
+
render(tmp_path, require_complete=True)
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def test_donor_draw_selection_is_stable_and_shared_across_methods():
|
| 271 |
+
units = [
|
| 272 |
+
dict(cohort="ye2026_sepsis", unit=f"draw{i}",
|
| 273 |
+
test_sample_ids=["s1", "s2"], sample_metadata="unused")
|
| 274 |
+
for i in (0, 1, 2)]
|
| 275 |
+
metadata = pd.DataFrame(dict(sample_id=["s1", "s2"], donor_id=["d1", "d2"]))
|
| 276 |
+
first = choose_donor_draws(units, "ye2026_sepsis", metadata)
|
| 277 |
+
assert first == choose_donor_draws(list(reversed(units)), "ye2026_sepsis", metadata)
|
| 278 |
+
assert set(first) == {"d1", "d2"}
|
| 279 |
+
assert all(v in {"draw0", "draw1", "draw2"} for v in first.values())
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def test_tiny_cpu_visual_export_uses_real_reference_and_marker_heatmap(tmp_path):
|
| 283 |
+
import json
|
| 284 |
+
from export_rare_visuals import EXAMPLES
|
| 285 |
+
states = json.loads((Path(__file__).resolve().parents[2] /
|
| 286 |
+
"rare_states_screen_20261004/tools/states.json").read_text())
|
| 287 |
+
names = {ex["state"] for ex in EXAMPLES}
|
| 288 |
+
needed = sorted({g for s in states if s["name"] in names
|
| 289 |
+
for g in s.get("genes", []) +
|
| 290 |
+
[g for group in s.get("require_any", []) for g in group] + s.get("exclude", [])})
|
| 291 |
+
units = []
|
| 292 |
+
for cohort, l1, l2 in [("ye2026_sepsis", "Monocyte", "CD14 monocyte"),
|
| 293 |
+
("imperial_eskd", "T cell", "Memory CD4 T cell")]:
|
| 294 |
+
root = tmp_path / cohort
|
| 295 |
+
root.mkdir()
|
| 296 |
+
sample = f"{cohort}_sample"
|
| 297 |
+
pd.DataFrame([dict(sample_id=sample, donor_id=f"{cohort}_donor",
|
| 298 |
+
group="case")]).to_csv(root / "meta.csv", index=False)
|
| 299 |
+
rng = np.random.default_rng(7)
|
| 300 |
+
matrix = rng.poisson(1.5, size=(32, len(needed))).astype(np.int32)
|
| 301 |
+
kwargs = dict(markers=matrix, marker_symbols=np.array(needed),
|
| 302 |
+
lib_measured=np.full(32, 1000), sample_id=np.array([sample] * 32),
|
| 303 |
+
aifi_l1=np.array([l1] * 32), aifi_l2=np.array([l2] * 32))
|
| 304 |
+
np.savez(root / "observed.npz", **kwargs)
|
| 305 |
+
caches = {}
|
| 306 |
+
for arm in ("raw", "refcal", "pairedcal", "scsemi", "lora"):
|
| 307 |
+
np.savez(root / f"{arm}.npz", **kwargs)
|
| 308 |
+
caches[arm] = str(root / f"{arm}.npz")
|
| 309 |
+
units.append(dict(cohort=cohort, unit="draw0", design="strict5pair",
|
| 310 |
+
test_sample_ids=[sample], sample_metadata=str(root / "meta.csv"),
|
| 311 |
+
observed_cache=str(root / "observed.npz"),
|
| 312 |
+
generated_caches=caches, cell_budget=25, depth_target=1000))
|
| 313 |
+
result = build_visuals(units, tmp_path, require_complete=False, validate_sources=False,
|
| 314 |
+
cells_per_sample=25)
|
| 315 |
+
assert result["status"] == "complete"
|
| 316 |
+
assert (tmp_path / "figures/fig5_rare_visuals_strict.png").stat().st_size > 1000
|
| 317 |
+
cells = pd.read_csv(tmp_path / "source_data/rare_visual_cells.csv")
|
| 318 |
+
heat = pd.read_csv(tmp_path / "source_data/rare_visual_heatmap.csv")
|
| 319 |
+
assert set(cells.arm) == {"observed", "raw", "refcal", "pairedcal", "scsemi", "lora"}
|
| 320 |
+
assert not heat.empty
|
| 321 |
+
assert set(cells.projection_fit_source) == {"observed_only"}
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def test_cache_builder_checks_scored_umi_and_preserves_scored_row_order(tmp_path):
|
| 325 |
+
import json
|
| 326 |
+
rates = np.arange(12, dtype=float).reshape(3, 4) / 4
|
| 327 |
+
source = tmp_path / "generated.npz"
|
| 328 |
+
np.savez_compressed(source, generated_counts=rates,
|
| 329 |
+
gene_ids=np.array(["g0", "g1", "g2", "g3"]),
|
| 330 |
+
sample_ids=np.array(["test"]), bulk_index=np.zeros(3, dtype=int))
|
| 331 |
+
source.with_suffix(".log").write_text(json.dumps({"output_sha256": sha256(source)}))
|
| 332 |
+
score = tmp_path / "score"
|
| 333 |
+
work = score / "arms/lora5"
|
| 334 |
+
(work / "labels").mkdir(parents=True)
|
| 335 |
+
full = np.random.default_rng(20260916).poisson(rates)
|
| 336 |
+
selected = np.array([2, 0])
|
| 337 |
+
pd.DataFrame(dict(npz_row=selected, donor=["test", "test"],
|
| 338 |
+
umi_scoring_genes=full[selected][:, [1, 3]].sum(1))).to_parquet(
|
| 339 |
+
work / "generated_cells.parquet")
|
| 340 |
+
pd.DataFrame(dict(sample_id=["test|generated"] * 2, aifi_l1=["Monocyte"] * 2,
|
| 341 |
+
aifi_l2=["CD14 monocyte"] * 2)).to_parquet(work / "labels/labels.parquet")
|
| 342 |
+
(score / "summary.json").write_text(json.dumps({
|
| 343 |
+
"schema": "paired_ft_scores.v1", "dataset": "toy", "donors": ["test"],
|
| 344 |
+
"arms": ["lora5"], "per_arm": {"lora5": {
|
| 345 |
+
"npz": str(source), "npz_sha256": sha256(source),
|
| 346 |
+
"receipt_verified": True,
|
| 347 |
+
"poisson": {"seed": 20260916, "rule": "whole NPZ, rows in NPZ order"}}}}))
|
| 348 |
+
support = {"cohort": "toy", "unit": "draw0_n5", "test_sample_ids": ["test"],
|
| 349 |
+
"test_donor_ids": ["donor"], "sha256": "support"}
|
| 350 |
+
with pytest.raises(ValueError, match="scoring support"):
|
| 351 |
+
build_arm(source, score, "lora5", support, tmp_path / "markers.npz",
|
| 352 |
+
np.array(["g0", "g1", "g2", "g3"]), np.array([1, 0, 1, 1], bool),
|
| 353 |
+
["A", "B"], np.array([2, 0]), np.array([1, 3]))
|
| 354 |
+
binding = score.parent / "scoring_support.json"
|
| 355 |
+
binding.write_text(json.dumps({
|
| 356 |
+
"schema": "pbisc.paper.strict-score-binding.v1",
|
| 357 |
+
"support_sha256": "support", "cohort": "toy", "unit": "draw0_n5",
|
| 358 |
+
"test_sample_ids": ["test"], "test_donor_ids": ["donor"]}))
|
| 359 |
+
output = tmp_path / "markers.npz"
|
| 360 |
+
receipt = build_arm(source, score, "lora5",
|
| 361 |
+
support, output,
|
| 362 |
+
np.array(["g0", "g1", "g2", "g3"]), np.array([1, 0, 1, 1], bool),
|
| 363 |
+
["A", "B"], np.array([2, 0]), np.array([1, 3]))
|
| 364 |
+
assert receipt["benchmark_umi_reproduced"]
|
| 365 |
+
with np.load(output) as cache:
|
| 366 |
+
np.testing.assert_array_equal(cache["markers"], full[selected][:, [2, 0]])
|
| 367 |
+
wrong = json.loads((score / "summary.json").read_text())
|
| 368 |
+
wrong["per_arm"]["lora5"]["npz_sha256"] = "0" * 64
|
| 369 |
+
(score / "summary.json").write_text(json.dumps(wrong))
|
| 370 |
+
with pytest.raises(ValueError, match="scorer arm provenance"):
|
| 371 |
+
build_arm(source, score, "lora5",
|
| 372 |
+
support, output,
|
| 373 |
+
np.array(["g0", "g1", "g2", "g3"]), np.array([1, 0, 1, 1], bool),
|
| 374 |
+
["A", "B"], np.array([2, 0]), np.array([1, 3]))
|
| 375 |
+
wrong = json.loads(binding.read_text())
|
| 376 |
+
wrong["test_donor_ids"] = ["other"]
|
| 377 |
+
binding.write_text(json.dumps(wrong))
|
| 378 |
+
with pytest.raises(ValueError, match="scoring support"):
|
| 379 |
+
build_arm(source, score, "lora5", support, output,
|
| 380 |
+
np.array(["g0", "g1", "g2", "g3"]), np.array([1, 0, 1, 1], bool),
|
| 381 |
+
["A", "B"], np.array([2, 0]), np.array([1, 3]))
|
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_reference_calibration.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import importlib.util
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import unittest
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class ReferenceCalibrationTests(unittest.TestCase):
|
| 10 |
+
def function(self):
|
| 11 |
+
path = ROOT / "tools/prepare_controls.py"
|
| 12 |
+
self.assertTrue(path.exists(), "external-reference condition builder is not implemented")
|
| 13 |
+
spec = importlib.util.spec_from_file_location("prepare_controls", path)
|
| 14 |
+
mod = importlib.util.module_from_spec(spec)
|
| 15 |
+
spec.loader.exec_module(mod)
|
| 16 |
+
return mod.external_multiplier
|
| 17 |
+
|
| 18 |
+
def test_external_reference_changes_shape_without_any_target_sc(self):
|
| 19 |
+
fn = self.function()
|
| 20 |
+
alpha = fn(np.array([[80., 20.], [60., 40.]]), np.ones((2, 2), bool),
|
| 21 |
+
np.array([[10., 90.], [30., 70.]]), np.ones(2, bool))
|
| 22 |
+
np.testing.assert_allclose(alpha, [2 / 7, 8 / 3])
|
| 23 |
+
|
| 24 |
+
def test_unmeasured_reference_gene_is_not_estimated(self):
|
| 25 |
+
fn = self.function()
|
| 26 |
+
alpha = fn(np.array([[80., 20.]]), np.ones((1, 2), bool),
|
| 27 |
+
np.array([[10., 90.]]), np.array([True, False]))
|
| 28 |
+
self.assertEqual(alpha[1], 1.)
|
| 29 |
+
|
| 30 |
+
def test_missing_bulk_measurement_cannot_invent_signal(self):
|
| 31 |
+
fn = self.function()
|
| 32 |
+
alpha = fn(np.array([[80., 20.], [100., 0.]]), np.array([[True, True], [True, False]]),
|
| 33 |
+
np.array([[10., 90.]]), np.ones(2, bool))
|
| 34 |
+
self.assertEqual(alpha[1], 1.)
|
| 35 |
+
|
| 36 |
+
def test_zero_total_rejected(self):
|
| 37 |
+
with self.assertRaises(ValueError):
|
| 38 |
+
self.function()(np.zeros((1, 2)), np.ones((1, 2), bool), np.ones((1, 2)), np.ones(2, bool))
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
if __name__ == "__main__":
|
| 42 |
+
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_rescore_pretrain_ablations.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Small CPU checks for the Figure 2 P/C rescore."""
|
| 2 |
+
|
| 3 |
+
import importlib.util
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import pytest
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
SCRIPT = Path(__file__).parents[1] / "tools" / "rescore_pretrain_ablations.py"
|
| 11 |
+
spec = importlib.util.spec_from_file_location("rescore_pretrain_ablations", SCRIPT)
|
| 12 |
+
mod = importlib.util.module_from_spec(spec)
|
| 13 |
+
spec.loader.exec_module(mod)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def test_missing_genes_fail_closed():
|
| 17 |
+
assert mod.gene_columns(["a", "b", "c"], ["c", "a"]).tolist() == [2, 0]
|
| 18 |
+
with pytest.raises(ValueError, match="missing"):
|
| 19 |
+
mod.gene_columns(["a", "b"], ["a", "c"])
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def test_zero_and_reference_distributions():
|
| 23 |
+
r = np.arange(30, dtype=np.float32).reshape(10, 3)
|
| 24 |
+
same = mod.score_pc(r, r.copy(), k=2)
|
| 25 |
+
assert same["coverage"] == 1.0
|
| 26 |
+
assert same["precision"] == 1.0
|
| 27 |
+
distant = mod.score_pc(r, r + 10000, k=2)
|
| 28 |
+
assert distant["coverage"] == 0.0
|
| 29 |
+
assert distant["precision"] == 0.0
|
| 30 |
+
zeros = mod.score_pc(np.zeros((10, 3), np.float32), np.zeros((10, 3), np.float32), k=2)
|
| 31 |
+
assert zeros["coverage"] == 1.0
|
| 32 |
+
assert zeros["precision"] == 1.0
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def test_disjoint_balanced_split_and_hash():
|
| 36 |
+
labels = np.repeat(["d1", "d2"], 12)
|
| 37 |
+
a, b = mod.balanced_real_split(labels, ["d1", "d2"], 5, 3)
|
| 38 |
+
assert len(a) == len(b) == 10
|
| 39 |
+
assert not set(a).intersection(b)
|
| 40 |
+
assert mod.sha_array(a) == mod.sha_array(a.copy())
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def test_streamed_npz_keeps_requested_row_and_gene_order(tmp_path):
|
| 44 |
+
path = tmp_path / "small.npz"
|
| 45 |
+
matrix = np.arange(30, dtype=np.float32).reshape(6, 5)
|
| 46 |
+
np.savez_compressed(path, generated_counts=matrix)
|
| 47 |
+
got = mod.stream_selected_npz(path, np.array([4, 0, 5]), np.array([3, 1]), batch=2)
|
| 48 |
+
np.testing.assert_array_equal(got, matrix[[4, 0, 5]][:, [3, 1]])
|
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_runtime.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Safety and resume invariants for the scientific campaign runner."""
|
| 2 |
+
import importlib.util
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import tempfile
|
| 7 |
+
import unittest
|
| 8 |
+
|
| 9 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class RuntimeTests(unittest.TestCase):
|
| 13 |
+
def load(self):
|
| 14 |
+
self.assertTrue((ROOT / "tools/runtime.py").is_file(), "campaign runtime is not implemented")
|
| 15 |
+
spec = importlib.util.spec_from_file_location("campaign_runtime", ROOT / "tools/runtime.py")
|
| 16 |
+
self.assertIsNotNone(spec, "runtime implementation missing")
|
| 17 |
+
mod = importlib.util.module_from_spec(spec)
|
| 18 |
+
spec.loader.exec_module(mod)
|
| 19 |
+
return mod
|
| 20 |
+
|
| 21 |
+
def test_changed_scientific_input_cannot_reuse_completed_operation(self):
|
| 22 |
+
mod = self.load()
|
| 23 |
+
with tempfile.TemporaryDirectory() as td:
|
| 24 |
+
root = Path(td)
|
| 25 |
+
inp, output = root / "support.json", root / "output.csv"
|
| 26 |
+
inp.write_text('{"train_sample_ids":["a"]}')
|
| 27 |
+
output.write_text("value\n1\n")
|
| 28 |
+
runtime = mod.Runtime(root)
|
| 29 |
+
signature = runtime.signature(["tool", "--support", str(inp)], [inp])
|
| 30 |
+
runtime.record_completed("score", signature, [output], 0.1)
|
| 31 |
+
inp.write_text('{"train_sample_ids":["b"]}')
|
| 32 |
+
changed = runtime.signature(["tool", "--support", str(inp)], [inp])
|
| 33 |
+
with self.assertRaises(mod.ReceiptError):
|
| 34 |
+
runtime.can_skip("score", changed, [output])
|
| 35 |
+
|
| 36 |
+
def test_modified_output_is_not_silently_accepted(self):
|
| 37 |
+
mod = self.load()
|
| 38 |
+
with tempfile.TemporaryDirectory() as td:
|
| 39 |
+
root = Path(td)
|
| 40 |
+
output = root / "output.csv"
|
| 41 |
+
output.write_text("value\n1\n")
|
| 42 |
+
runtime = mod.Runtime(root)
|
| 43 |
+
sig = runtime.signature(["tool"], [])
|
| 44 |
+
runtime.record_completed("score", sig, [output], 0.1)
|
| 45 |
+
self.assertTrue(runtime.can_skip("score", sig, [output]))
|
| 46 |
+
output.write_text("value\n999\n")
|
| 47 |
+
with self.assertRaises(mod.ReceiptError):
|
| 48 |
+
runtime.can_skip("score", sig, [output])
|
| 49 |
+
|
| 50 |
+
def test_unreceipted_existing_output_is_preserved_and_rejected(self):
|
| 51 |
+
mod = self.load()
|
| 52 |
+
with tempfile.TemporaryDirectory() as td:
|
| 53 |
+
root = Path(td)
|
| 54 |
+
output = root / "output.npz"
|
| 55 |
+
output.write_bytes(b"partial output must survive")
|
| 56 |
+
runtime = mod.Runtime(root)
|
| 57 |
+
with self.assertRaises(mod.ReceiptError):
|
| 58 |
+
runtime.can_skip("sample", runtime.signature(["tool"], []), [output])
|
| 59 |
+
self.assertEqual(output.read_bytes(), b"partial output must survive")
|
| 60 |
+
|
| 61 |
+
def test_same_size_and_timestamp_do_not_hide_replaced_scientific_output(self):
|
| 62 |
+
mod = self.load()
|
| 63 |
+
with tempfile.TemporaryDirectory() as td:
|
| 64 |
+
root = Path(td)
|
| 65 |
+
output = root / "output.csv"
|
| 66 |
+
output.write_bytes(b"value\n1\n")
|
| 67 |
+
runtime = mod.Runtime(root)
|
| 68 |
+
signature = runtime.signature(["score"], [])
|
| 69 |
+
runtime.record_completed("score", signature, [output], .1)
|
| 70 |
+
before = output.stat()
|
| 71 |
+
output.write_bytes(b"value\n9\n")
|
| 72 |
+
os.utime(output, ns=(before.st_atime_ns, before.st_mtime_ns))
|
| 73 |
+
with self.assertRaises(mod.ReceiptError):
|
| 74 |
+
runtime.can_skip("score", signature, [output])
|
| 75 |
+
|
| 76 |
+
def test_failed_action_requires_review_before_retry(self):
|
| 77 |
+
mod = self.load()
|
| 78 |
+
with tempfile.TemporaryDirectory() as td:
|
| 79 |
+
root = Path(td)
|
| 80 |
+
runtime = mod.Runtime(root)
|
| 81 |
+
runtime.write_receipt("sample", {"state": "failed", "exit_code": 1})
|
| 82 |
+
with self.assertRaises(mod.ReceiptError):
|
| 83 |
+
runtime.can_skip("sample", "new", [])
|
| 84 |
+
|
| 85 |
+
def test_preview_replacement_requires_verified_preserved_copy(self):
|
| 86 |
+
mod = self.load()
|
| 87 |
+
with tempfile.TemporaryDirectory() as td:
|
| 88 |
+
root = Path(td)
|
| 89 |
+
current = root / "reports/readiness.json"
|
| 90 |
+
current.parent.mkdir()
|
| 91 |
+
current.write_text('{"status":"pending"}')
|
| 92 |
+
backup = root / "preview.json"
|
| 93 |
+
backup.write_bytes(current.read_bytes())
|
| 94 |
+
runtime = mod.Runtime(root)
|
| 95 |
+
proof = {str(current): {"backup": str(backup), "sha256": mod.sha256(current)}}
|
| 96 |
+
self.assertFalse(runtime.can_skip("render", "new", [current], previous_outputs=proof))
|
| 97 |
+
backup.write_text("changed")
|
| 98 |
+
with self.assertRaises(mod.ReceiptError):
|
| 99 |
+
runtime.can_skip("render", "new", [current], previous_outputs=proof)
|
| 100 |
+
|
| 101 |
+
def test_cuda_and_cpu_commands_are_contained(self):
|
| 102 |
+
mod = self.load()
|
| 103 |
+
with tempfile.TemporaryDirectory() as td:
|
| 104 |
+
runtime = mod.Runtime(Path(td))
|
| 105 |
+
gpu = runtime.wrapped_command("train", ["python", "train.py"], "gpu", 16, 4)
|
| 106 |
+
cpu = runtime.wrapped_command("score", ["python", "score.py"], "cpu", 16, 4)
|
| 107 |
+
self.assertEqual(Path(gpu[0]).name, "ml-run")
|
| 108 |
+
self.assertIn("CUDA_VISIBLE_DEVICES=0", gpu)
|
| 109 |
+
self.assertIn("MemorySwapMax=0", cpu)
|
| 110 |
+
self.assertIn("OOMPolicy=kill", cpu)
|
| 111 |
+
self.assertIn("CUDA_VISIBLE_DEVICES=", cpu)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
if __name__ == "__main__":
|
| 115 |
+
unittest.main()
|