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_archive_completed.py +56 -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_score_strict.py +260 -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_scsemi_export_strict.py +51 -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_support_manifest.py +223 -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_archive_completed.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Small negative controls for archive-only snapshot safety."""
|
| 2 |
+
import importlib.util
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import tempfile
|
| 5 |
+
import unittest
|
| 6 |
+
from unittest.mock import patch
|
| 7 |
+
|
| 8 |
+
SCRIPT = Path(__file__).resolve().parents[1] / 'tools/archive_completed.py'
|
| 9 |
+
spec = importlib.util.spec_from_file_location('archive_completed', SCRIPT)
|
| 10 |
+
archive = importlib.util.module_from_spec(spec)
|
| 11 |
+
spec.loader.exec_module(archive)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class ArchiveSnapshotTests(unittest.TestCase):
|
| 15 |
+
def test_live_operation_is_not_labeled_planned(self):
|
| 16 |
+
with tempfile.TemporaryDirectory() as temp:
|
| 17 |
+
root = Path(temp)
|
| 18 |
+
(root / 'receipts').mkdir()
|
| 19 |
+
(root / 'receipts/global-sepsis-raw.json').write_text('{"state":"running"}')
|
| 20 |
+
with patch.object(archive, 'PLAN', root):
|
| 21 |
+
self.assertEqual(archive.operation_state('global-sepsis-raw'), 'running')
|
| 22 |
+
self.assertEqual(archive.operation_state('missing'), 'planned')
|
| 23 |
+
|
| 24 |
+
def test_symlink_payload_is_refused(self):
|
| 25 |
+
with tempfile.TemporaryDirectory() as temp:
|
| 26 |
+
root = Path(temp)
|
| 27 |
+
source = root / 'source.txt'
|
| 28 |
+
source.write_text('private scientific metadata')
|
| 29 |
+
alias = root / 'alias.txt'
|
| 30 |
+
alias.symlink_to(source)
|
| 31 |
+
with self.assertRaisesRegex(ValueError, 'symlink refused'):
|
| 32 |
+
archive.stable_hash(alias)
|
| 33 |
+
|
| 34 |
+
def test_hash_rejects_changed_source(self):
|
| 35 |
+
with tempfile.TemporaryDirectory() as temp:
|
| 36 |
+
source = Path(temp) / 'source.txt'
|
| 37 |
+
source.write_text('old')
|
| 38 |
+
def changing_hash(path):
|
| 39 |
+
path.write_text('changed after read')
|
| 40 |
+
return '0' * 64
|
| 41 |
+
with patch.object(archive, 'sha', changing_hash):
|
| 42 |
+
with self.assertRaisesRegex(RuntimeError, 'changed during hash'):
|
| 43 |
+
archive.stable_hash(source)
|
| 44 |
+
|
| 45 |
+
def test_partial_finalization_cannot_be_archived_as_complete(self):
|
| 46 |
+
with patch.object(archive, 'json_load', return_value={'stage': 'render', 'state': 'completed'}):
|
| 47 |
+
with self.assertRaisesRegex(ValueError, 'all-stage'):
|
| 48 |
+
archive.completion_gate()
|
| 49 |
+
|
| 50 |
+
def test_invalid_identifier_does_not_create_snapshot(self):
|
| 51 |
+
with self.assertRaisesRegex(ValueError, 'invalid update'):
|
| 52 |
+
archive.build('../escape', 'in-progress')
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
if __name__ == '__main__':
|
| 56 |
+
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_score_strict.py
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The strict adapter must bind scored samples and isolate every output tree."""
|
| 2 |
+
import importlib.util
|
| 3 |
+
import json
|
| 4 |
+
import shutil
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
import pandas as pd
|
| 9 |
+
import pytest
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
PATH = Path(__file__).resolve().parents[1] / "tools/score_strict.py"
|
| 13 |
+
spec = importlib.util.spec_from_file_location("score_strict", PATH)
|
| 14 |
+
adapter = importlib.util.module_from_spec(spec)
|
| 15 |
+
spec.loader.exec_module(adapter)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def test_manifest_test_samples_are_scoring_samples(tmp_path):
|
| 19 |
+
data = {"schema": "pbisc.paper.strict-support.v1", "cohort": "giroux2022",
|
| 20 |
+
"unit": "draw0_n5", "n_pairs": 1, "test_sample_ids": ["p1_d0", "p1_d7", "p2_d0"],
|
| 21 |
+
"test_donor_ids": ["p1", "p1", "p2"],
|
| 22 |
+
"train_sample_ids": ["t1_d0"], "train_donor_ids": ["t1"],
|
| 23 |
+
"excluded_sample_ids": ["t1_d7"]}
|
| 24 |
+
data["sha256"] = adapter.manifest_digest(data)
|
| 25 |
+
p = tmp_path / "support.json"
|
| 26 |
+
p.write_text(json.dumps(data))
|
| 27 |
+
got = adapter.read_support(p)
|
| 28 |
+
assert got["test_sample_ids"] == ["p1_d0", "p1_d7", "p2_d0"]
|
| 29 |
+
assert adapter.patient_mapping(got).to_dict("records") == [
|
| 30 |
+
{"sample_id": "p1_d0", "donor_id": "p1"},
|
| 31 |
+
{"sample_id": "p1_d7", "donor_id": "p1"},
|
| 32 |
+
{"sample_id": "p2_d0", "donor_id": "p2"}]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def test_bad_identity_and_legacy_output_path_fail_closed(tmp_path):
|
| 36 |
+
data = {"schema": "pbisc.paper.strict-support.v1", "cohort": "immicro",
|
| 37 |
+
"unit": "fold0_n5", "n_pairs": 1, "test_sample_ids": ["x"], "test_donor_ids": ["A"],
|
| 38 |
+
"train_sample_ids": ["y"], "train_donor_ids": ["A"], "excluded_sample_ids": []}
|
| 39 |
+
data["sha256"] = adapter.manifest_digest(data)
|
| 40 |
+
p = tmp_path / "support.json"
|
| 41 |
+
p.write_text(json.dumps(data))
|
| 42 |
+
with pytest.raises(ValueError, match="train/test donor overlap"):
|
| 43 |
+
adapter.read_support(p)
|
| 44 |
+
with pytest.raises(ValueError, match="strict-pairs plan"):
|
| 45 |
+
adapter.safe_out(adapter.LEGACY / "scores/new_run")
|
| 46 |
+
with pytest.raises(ValueError, match="dedicated result"):
|
| 47 |
+
adapter.safe_out(adapter.PLAN / "tools")
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def test_route_scored_extras_to_new_root():
|
| 51 |
+
out = adapter.PLAN / "scores" / "fixture"
|
| 52 |
+
assert adapter.extra_root(out) == out / "extras"
|
| 53 |
+
assert adapter.contrast_root(out) == out / "contrast"
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def test_score_reuse_requires_exact_support_hash(tmp_path):
|
| 57 |
+
score = tmp_path / "score"
|
| 58 |
+
score.mkdir()
|
| 59 |
+
(score / "summary.json").write_text(json.dumps({"dataset": "immicro", "donors": ["s1"], "arms": ["a"]}))
|
| 60 |
+
(tmp_path / "scoring_support.json").write_text(json.dumps({"support_sha256": "old"}))
|
| 61 |
+
with pytest.raises(ValueError, match="support hash"):
|
| 62 |
+
adapter._existing_score(score, {"cohort": "immicro", "test_sample_ids": ["s1"], "sha256": "new"}, ["a"])
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def test_score_reuse_rejects_unbound_arm_even_when_test_samples_match(tmp_path):
|
| 66 |
+
score = tmp_path / "score"
|
| 67 |
+
score.mkdir()
|
| 68 |
+
(score / "summary.json").write_text(json.dumps({"dataset": "immicro", "donors": ["s1"],
|
| 69 |
+
"arms": ["a"], "per_arm": {"a": {"npz": "/x", "npz_sha256": "h"}}}))
|
| 70 |
+
(tmp_path / "scoring_support.json").write_text(json.dumps({"support_sha256": "strict"}))
|
| 71 |
+
with pytest.raises(ValueError, match="generation binding"):
|
| 72 |
+
adapter._existing_score(score, {"cohort": "immicro", "test_sample_ids": ["s1"], "sha256": "strict"}, ["a"])
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def test_pending_corrected_deg_fails_stats_action():
|
| 76 |
+
with pytest.raises(ValueError, match="donor-aware DEG pending"):
|
| 77 |
+
adapter.require_corrected_deg({"status": "partial_or_pending"})
|
| 78 |
+
adapter.require_corrected_deg({"status": "ok"})
|
| 79 |
+
adapter.require_corrected_deg({"status": "complete_with_not_estimable", "n_not_estimable": 1})
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def test_observed_is_reserved_side_name():
|
| 83 |
+
with pytest.raises(ValueError, match="reserved"):
|
| 84 |
+
adapter._arms(["observed=/tmp/a.npz"])
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def test_manifest_cannot_claim_five_pairs_with_six_fit_rows(tmp_path):
|
| 88 |
+
data = {"schema": "pbisc.paper.strict-support.v1", "cohort": "immicro", "unit": "fold0_n5",
|
| 89 |
+
"n_pairs": 5, "train_sample_ids": [f"fit{i}" for i in range(6)],
|
| 90 |
+
"train_donor_ids": [f"p{i}" for i in range(6)],
|
| 91 |
+
"test_sample_ids": ["held"], "test_donor_ids": ["test"], "excluded_sample_ids": []}
|
| 92 |
+
data["sha256"] = adapter.manifest_digest(data)
|
| 93 |
+
p = tmp_path / "support.json"
|
| 94 |
+
p.write_text(json.dumps(data))
|
| 95 |
+
with pytest.raises(ValueError, match="n_pairs"):
|
| 96 |
+
adapter.read_support(p)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def test_old_ten_pair_run_cannot_be_relabelled_with_same_heldout_samples():
|
| 100 |
+
support = {"sha256": "strict5", "train_sample_ids": [f"fit{i}" for i in range(5)],
|
| 101 |
+
"train_donor_ids": [f"p{i}" for i in range(5)],
|
| 102 |
+
"test_sample_ids": ["held1", "held2"], "excluded_sample_ids": [],
|
| 103 |
+
"n_pairs": 5}
|
| 104 |
+
run = {"support_sha256": "strict5", "train_rows": [f"fit{i}" for i in range(10)],
|
| 105 |
+
"train_donor_ids": [f"p{i}" for i in range(10)],
|
| 106 |
+
"test_rows_never_loaded_for_training": ["held1", "held2"],
|
| 107 |
+
"inner_val_rows": [], "fixed_steps": 3000, "steps_run": 3000,
|
| 108 |
+
"selected_step": 3000, "mode": "lora", "trainable": {"lora_rank": 16},
|
| 109 |
+
"source_checkpoint_sha256": adapter.BASE_SHA,
|
| 110 |
+
"checkpoint_sha256": "a"*64}
|
| 111 |
+
with pytest.raises(ValueError, match="train_rows"):
|
| 112 |
+
adapter.validate_lora_run(run, support)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def test_current_pilot_lora_run_matches_strict_support_without_running_score():
|
| 116 |
+
support_path = adapter.PLAN / "protocol/splits/immicro/healthy/fold0/n5/support.json"
|
| 117 |
+
support = adapter.read_support(support_path)
|
| 118 |
+
run_path = adapter.PLAN / "runs/immicro/healthy/fold0/n5/lora/RUN.json"
|
| 119 |
+
adapter.validate_lora_run(json.loads(run_path.read_text()), support)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def test_pilot_lora_and_pairedcal_generation_bindings_are_source_bound():
|
| 123 |
+
support = adapter.read_support(adapter.PLAN / "protocol/splits/immicro/healthy/fold0/n5/support.json")
|
| 124 |
+
root = adapter.PLAN / "generated/immicro/healthy/fold0/n5"
|
| 125 |
+
lora = adapter.validate_generation_arm("lora", root / "lora.npz", support)
|
| 126 |
+
paired = adapter.validate_generation_arm("pairedcal", root / "pairedcal.npz", support)
|
| 127 |
+
assert lora["support_sha256"] == paired["support_sha256"] == support["sha256"]
|
| 128 |
+
assert lora["condition_sha256"] != paired["condition_sha256"]
|
| 129 |
+
assert lora["checkpoint_sha256"] != paired["checkpoint_sha256"]
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def test_legacy_generated_path_is_rejected_even_with_same_test_ids():
|
| 133 |
+
support = adapter.read_support(adapter.PLAN / "protocol/splits/giroux2022/disease/draw0/support.json")
|
| 134 |
+
old = adapter.LEGACY / "generated/giroux2022/fewshot_n5/draw0/lora__raw.npz"
|
| 135 |
+
with pytest.raises(ValueError, match="canonical strict arm path"):
|
| 136 |
+
adapter.validate_generation_arm("lora", old, support)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def test_global_build_rejects_changed_reference_input(tmp_path):
|
| 140 |
+
source = tmp_path / "reference.txt"
|
| 141 |
+
source.write_text("changed")
|
| 142 |
+
with pytest.raises(ValueError, match="global BUILD input"):
|
| 143 |
+
adapter.validate_global_build_inputs({"input_hashes": {str(source): "0"*64}})
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def test_draw_long_requires_canonical_same_cohort_bound_distinct_draw(tmp_path, monkeypatch):
|
| 147 |
+
monkeypatch.setattr(adapter, "PLAN", tmp_path)
|
| 148 |
+
def support(draw):
|
| 149 |
+
obj = {"schema": "pbisc.paper.strict-support.v1", "cohort": "ji2025_chili",
|
| 150 |
+
"design": "disease_existing_draw", "unit": f"draw{draw}_n5", "n_pairs": 5,
|
| 151 |
+
"train_sample_ids": [f"train{draw}_{i}" for i in range(5)],
|
| 152 |
+
"train_donor_ids": [f"tp{draw}_{i}" for i in range(5)],
|
| 153 |
+
"test_sample_ids": [f"test{draw}_a", f"test{draw}_b"],
|
| 154 |
+
"test_donor_ids": ["A", "B"], "excluded_sample_ids": []}
|
| 155 |
+
obj["sha256"] = adapter.manifest_digest(obj)
|
| 156 |
+
return obj
|
| 157 |
+
current, other = support(0), support(1)
|
| 158 |
+
source = tmp_path / "protocol/splits/ji2025_chili/disease/draw1/support.json"
|
| 159 |
+
source.parent.mkdir(parents=True)
|
| 160 |
+
source.write_text(json.dumps(other))
|
| 161 |
+
base = tmp_path / "scores/ji2025_chili/disease/draw1"
|
| 162 |
+
(base / "score").mkdir(parents=True)
|
| 163 |
+
(base / "statistics").mkdir()
|
| 164 |
+
arm_source = {"npz": "/strict/lora.npz", "npz_sha256": "validhash", "support_sha256": other["sha256"]}
|
| 165 |
+
(base / "scoring_support.json").write_text(json.dumps({"schema": "pbisc.paper.strict-score-binding.v1",
|
| 166 |
+
"support_sha256": other["sha256"],
|
| 167 |
+
"cohort": other["cohort"], "unit": other["unit"],
|
| 168 |
+
"test_sample_ids": other["test_sample_ids"], "test_donor_ids": other["test_donor_ids"],
|
| 169 |
+
"arm_bindings": {"lora": arm_source}}))
|
| 170 |
+
(base / "score/summary.json").write_text(json.dumps({"dataset": other["cohort"],
|
| 171 |
+
"donors": other["test_sample_ids"], "arms": ["lora"],
|
| 172 |
+
"per_arm": {"lora": {"npz": arm_source["npz"], "npz_sha256": arm_source["npz_sha256"]}}}))
|
| 173 |
+
pd.DataFrame({"donor": other["test_sample_ids"], "arm": ["lora"]*2,
|
| 174 |
+
"comp_l1": [0.2, 0.3]}).to_csv(base / "score/per_donor.csv", index=False)
|
| 175 |
+
table = base / "statistics/per_donor_long.csv"
|
| 176 |
+
pd.DataFrame({"draw": [other["unit"]]*2, "sample_id": other["test_sample_ids"],
|
| 177 |
+
"donor_id": other["test_donor_ids"], "arm": ["lora"]*2,
|
| 178 |
+
"metric": ["comp_l1"]*2, "value": [0.2, 0.3]}).to_csv(table, index=False)
|
| 179 |
+
monkeypatch.setattr(adapter, "validate_generation_arm", lambda name, path, manifest: arm_source)
|
| 180 |
+
assert len(adapter.validate_draw_long(table, current, ["lora"])) == 2
|
| 181 |
+
monkeypatch.setattr(adapter, "validate_generation_arm", lambda name, path, manifest:
|
| 182 |
+
{**arm_source, "npz_sha256": "different"})
|
| 183 |
+
with pytest.raises(ValueError, match="provenance"):
|
| 184 |
+
adapter.validate_draw_long(table, current, ["lora"])
|
| 185 |
+
monkeypatch.setattr(adapter, "validate_generation_arm", lambda name, path, manifest: arm_source)
|
| 186 |
+
changed = pd.read_csv(table)
|
| 187 |
+
changed.loc[0, "value"] = 999
|
| 188 |
+
changed.to_csv(table, index=False)
|
| 189 |
+
with pytest.raises(ValueError, match="scored metrics"):
|
| 190 |
+
adapter.validate_draw_long(table, current, ["lora"])
|
| 191 |
+
changed.loc[0, "value"] = 0.2
|
| 192 |
+
changed.to_csv(table, index=False)
|
| 193 |
+
with pytest.raises(ValueError, match="canonical"):
|
| 194 |
+
adapter.validate_draw_long(tmp_path / "source_data/arbitrary.csv", current, ["lora"])
|
| 195 |
+
with pytest.raises(ValueError, match="cohort"):
|
| 196 |
+
adapter.validate_draw_long(table, {**current, "cohort": "giroux2022"}, ["lora"])
|
| 197 |
+
with pytest.raises(ValueError, match="arms"):
|
| 198 |
+
adapter.validate_draw_long(table, current, ["lora", "pairedcal"])
|
| 199 |
+
with pytest.raises(ValueError, match="distinct"):
|
| 200 |
+
adapter.validate_draw_long(table, {**current, "unit": other["unit"]}, ["lora"])
|
| 201 |
+
(base / "scoring_support.json").unlink()
|
| 202 |
+
with pytest.raises(ValueError, match="binding"):
|
| 203 |
+
adapter.validate_draw_long(table, current, ["lora"])
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def test_draw_long_list_rejects_same_other_draw_twice(monkeypatch):
|
| 207 |
+
rows = pd.DataFrame({"draw": ["draw1_n5"], "sample_id": ["s"], "donor_id": ["p"],
|
| 208 |
+
"arm": ["lora"], "metric": ["comp_l1"], "value": [0.2]})
|
| 209 |
+
rows.attrs["unit"] = "draw1_n5"
|
| 210 |
+
monkeypatch.setattr(adapter, "validate_draw_long", lambda path, support, arms: rows)
|
| 211 |
+
with pytest.raises(ValueError, match="duplicate draw"):
|
| 212 |
+
adapter.validate_draw_longs([Path("a"), Path("a")], {"unit": "draw0_n5"}, ["lora"])
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def test_automatic_deg_uses_scored_readout_and_patient_block(tmp_path, monkeypatch):
|
| 216 |
+
if not shutil.which("Rscript"):
|
| 217 |
+
pytest.skip("Rscript unavailable")
|
| 218 |
+
F = adapter._legacy_module("ft_common")
|
| 219 |
+
ids = np.array(["A_c", "A_t", "B_c", "B_t", "C_c", "D_t"])
|
| 220 |
+
patient = np.array(["A", "A", "B", "B", "C", "D"])
|
| 221 |
+
condition = np.array(["BC", "TOL", "BC", "TOL", "BC", "TOL"])
|
| 222 |
+
genes = np.array([f"g{i}" for i in range(20)])
|
| 223 |
+
observed = np.array([[(i+3)*(2 if c == "TOL" else 1)+(i%3) for i in range(20)]
|
| 224 |
+
for c in condition], dtype=float)
|
| 225 |
+
ref = {"donors": ids, "panel_ids": genes, "score_ids": genes, "score_idx": np.arange(20)}
|
| 226 |
+
man = {"reference_sha256": "fixture-reference"}
|
| 227 |
+
deg = {"types": ("T cell",), "n": np.ones((6, 1), dtype=int), "sum": observed[:, None, :]}
|
| 228 |
+
monkeypatch.setattr(F, "load_reference", lambda cache: (ref, man))
|
| 229 |
+
monkeypatch.setattr(F, "load_deg_reference", lambda cache, manifest, reference: deg)
|
| 230 |
+
npz = tmp_path / "generated.npz"
|
| 231 |
+
np.savez(npz, gene_ids=genes, sample_ids=ids, bulk_index=np.arange(6),
|
| 232 |
+
generated_counts=observed.astype(np.float32), metadata_json="{}")
|
| 233 |
+
scored_cells = tmp_path / "score/arms/model"
|
| 234 |
+
scored_cells.mkdir(parents=True)
|
| 235 |
+
pd.DataFrame({"npz_row": np.arange(6), "donor": ids, "label": "T cell"}).to_parquet(
|
| 236 |
+
scored_cells / "generated_cells.parquet", index=False)
|
| 237 |
+
summary = {"reference": {"cache": str(tmp_path), "reference_sha256": "fixture-reference"},
|
| 238 |
+
"donors": ids.tolist(), "contrast_definition": {"groups": condition.tolist(),
|
| 239 |
+
"case_groups": ["TOL"], "control_groups": ["BC"]}, "arms": ["model"],
|
| 240 |
+
"per_arm": {"model": {"npz": str(npz), "npz_sha256": F.sha(npz)}}}
|
| 241 |
+
support = {"cohort": "ji2025_chili", "test_sample_ids": ids.tolist(),
|
| 242 |
+
"test_donor_ids": patient.tolist()}
|
| 243 |
+
result = adapter._automatic_deg(support, tmp_path, summary, 1)
|
| 244 |
+
assert result["status"] == "ok"
|
| 245 |
+
row = pd.read_csv(tmp_path / "statistics/donor_deg/donor_deg_summary.csv").iloc[0]
|
| 246 |
+
assert row.status == "ok"
|
| 247 |
+
assert row.method_observed.endswith("duplicateCorrelation")
|
| 248 |
+
assert row.n_case_donors_observed == 3
|
| 249 |
+
assert row.n_control_donors_observed == 3
|
| 250 |
+
absent = tmp_path / "absent_type"
|
| 251 |
+
cells2 = absent / "score/arms/model"
|
| 252 |
+
cells2.mkdir(parents=True)
|
| 253 |
+
pd.DataFrame({"npz_row": np.arange(6), "donor": ids, "label": "Other"}).to_parquet(
|
| 254 |
+
cells2 / "generated_cells.parquet", index=False)
|
| 255 |
+
missing = adapter._automatic_deg(support, absent, summary, 1)
|
| 256 |
+
row = pd.read_csv(absent / "statistics/donor_deg/donor_deg_summary.csv").iloc[0]
|
| 257 |
+
assert missing["status"] == "complete_with_not_estimable"
|
| 258 |
+
assert row.status == "not_estimable"
|
| 259 |
+
assert row.generated_status == "no_population"
|
| 260 |
+
assert pd.isna(row.top50_overlap_count) if "top50_overlap_count" in row else True
|
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_scsemi_export_strict.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import importlib.util
|
| 2 |
+
import os
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import sys
|
| 5 |
+
import unittest
|
| 6 |
+
|
| 7 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 8 |
+
sys.path.insert(0, str(ROOT / "tools"))
|
| 9 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = ""
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class ExportTests(unittest.TestCase):
|
| 13 |
+
def function(self):
|
| 14 |
+
path = ROOT / "tools/export_scsemi_strict.py"
|
| 15 |
+
self.assertTrue(path.exists(), "strict exporter not implemented")
|
| 16 |
+
spec = importlib.util.spec_from_file_location("strict_export", path)
|
| 17 |
+
mod = importlib.util.module_from_spec(spec)
|
| 18 |
+
spec.loader.exec_module(mod)
|
| 19 |
+
return mod.strict_arm_metadata
|
| 20 |
+
|
| 21 |
+
def fixture(self):
|
| 22 |
+
support = {"cohort": "immicro", "unit": "fold0_n5", "sha256": "bound",
|
| 23 |
+
"n_pairs": 5, "train_sample_ids": [f"s{i}" for i in range(5)],
|
| 24 |
+
"train_donor_ids": [f"d{i}" for i in range(5)], "test_sample_ids": ["test"]}
|
| 25 |
+
man = {"mode": "strict", "dataset": "immicro", "support_sha256": "bound",
|
| 26 |
+
"representatives": [{"sample_id": s} for s in support["train_sample_ids"]],
|
| 27 |
+
"train_donors": support["train_donor_ids"], "target_order_test_samples": ["test"]}
|
| 28 |
+
return support, man
|
| 29 |
+
|
| 30 |
+
def test_strict_mode_exports_bound_canonical_arm(self):
|
| 31 |
+
support, man = self.fixture()
|
| 32 |
+
result = self.function()(man, support)
|
| 33 |
+
self.assertEqual(result["arm"], "scsemi")
|
| 34 |
+
self.assertEqual(result["support_sha256"], "bound")
|
| 35 |
+
self.assertEqual(result["n_pairs"], 5)
|
| 36 |
+
|
| 37 |
+
def test_extra_representative_rejected(self):
|
| 38 |
+
support, man = self.fixture()
|
| 39 |
+
man["representatives"].append({"sample_id": "extra_visit"})
|
| 40 |
+
with self.assertRaises(ValueError):
|
| 41 |
+
self.function()(man, support)
|
| 42 |
+
|
| 43 |
+
def test_legacy_mode_cannot_be_exported_as_strict(self):
|
| 44 |
+
support, man = self.fixture()
|
| 45 |
+
man["mode"] = "fewshot"
|
| 46 |
+
with self.assertRaises(ValueError):
|
| 47 |
+
self.function()(man, support)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
if __name__ == "__main__":
|
| 51 |
+
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_support_manifest.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Contract tests for exact paired support (CPU only)."""
|
| 2 |
+
import copy
|
| 3 |
+
import hashlib
|
| 4 |
+
import importlib.util
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
import pandas as pd
|
| 10 |
+
import pytest
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 14 |
+
spec = importlib.util.spec_from_file_location("support_manifest", ROOT / "tools/support_manifest.py")
|
| 15 |
+
support = importlib.util.module_from_spec(spec)
|
| 16 |
+
spec.loader.exec_module(support)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@pytest.fixture
|
| 20 |
+
def folds():
|
| 21 |
+
return pd.DataFrame([
|
| 22 |
+
("a0", "a", "case", 0), ("a1", "a", "case", 0),
|
| 23 |
+
("b0", "b", "case", 1), ("c0", "c", "case", 1),
|
| 24 |
+
("d0", "d", "control", 2), ("e0", "e", "control", 2),
|
| 25 |
+
("f0", "f", "case", 3), ("g0", "g", "control", 4),
|
| 26 |
+
("bad", "z", "case", -1),
|
| 27 |
+
], columns=["sample_id", "donor_id", "group", "fold"])
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def test_healthy_deterministic_nested_exact_budget(folds):
|
| 31 |
+
small = support.build_healthy(folds, 0, 2, seed=20261012)
|
| 32 |
+
large = support.build_healthy(folds, 0, 4, seed=20261012)
|
| 33 |
+
assert small == support.build_healthy(folds, 0, 2, seed=20261012)
|
| 34 |
+
assert len(small["train_sample_ids"]) == len(small["train_donor_ids"]) == 2
|
| 35 |
+
assert set(small["train_sample_ids"]) <= set(large["train_sample_ids"])
|
| 36 |
+
assert "a0" in small["test_sample_ids"] and "a1" in small["test_sample_ids"]
|
| 37 |
+
assert "bad" not in small["test_sample_ids"]
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def test_rejects_duplicate_donor_and_test_leakage(folds):
|
| 41 |
+
m = support.build_healthy(folds, 0, 2, seed=3)
|
| 42 |
+
m["train_sample_ids"].append(m["train_sample_ids"][0])
|
| 43 |
+
with pytest.raises(ValueError): support.validate_manifest(m, folds)
|
| 44 |
+
m = support.build_healthy(folds, 0, 2, seed=3)
|
| 45 |
+
m["test_sample_ids"].append(m["train_sample_ids"][0])
|
| 46 |
+
with pytest.raises(ValueError): support.validate_manifest(m, folds)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def test_rejects_malicious_sample_donor_mismatch_and_hash(folds):
|
| 50 |
+
m = support.build_healthy(folds, 0, 2, seed=3)
|
| 51 |
+
m["train_donor_ids"][0] = "a"
|
| 52 |
+
with pytest.raises(ValueError): support.validate_manifest(m, folds)
|
| 53 |
+
m = support.build_healthy(folds, 0, 2, seed=3)
|
| 54 |
+
m["train_sample_ids"].reverse()
|
| 55 |
+
with pytest.raises(ValueError): support.validate_manifest(m, folds)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def test_disease_earliest_same_stratum_and_excludes_other_visits(folds):
|
| 59 |
+
pairs = pd.DataFrame([
|
| 60 |
+
("a0", 14, True), ("a1", 0, True),
|
| 61 |
+
("b0", 1, True), ("c0", 0, True), ("d0", 0, True), ("e0", 0, True),
|
| 62 |
+
], columns=["sample_id", "timepoint", "identity_pass"])
|
| 63 |
+
m = support.build_disease(folds, pairs, ["a", "b", "c", "d", "e"], "toy", 0)
|
| 64 |
+
assert m["train_sample_ids"][:2] == ["a1", "b0"]
|
| 65 |
+
assert "a0" in m["excluded_sample_ids"]
|
| 66 |
+
assert "a0" not in m["test_sample_ids"]
|
| 67 |
+
assert m["selection_audit"][0]["candidates"][0]["sample_id"] == "a1"
|
| 68 |
+
support.validate_manifest(m, folds)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def test_disease_requires_stratum_match_and_parseable_time(folds):
|
| 72 |
+
pairs = pd.DataFrame([("a0", "nonsense", True), ("a1", "nonsense", True),
|
| 73 |
+
("b0", 0, True), ("c0", 0, True), ("d0", 0, True), ("e0", 0, True)],
|
| 74 |
+
columns=["sample_id", "timepoint", "identity_pass"])
|
| 75 |
+
with pytest.raises(ValueError): support.build_disease(folds, pairs, ["a", "b", "c", "d", "e"], "toy", 0)
|
| 76 |
+
with pytest.raises(ValueError): support.build_disease(folds, pairs, ["a", "b"], "toy", 0)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def test_disease_rejects_missing_identity_or_mismatched_pair_metadata(folds):
|
| 80 |
+
pairs = pd.DataFrame([("a0", "a", "case", 0, None), ("a1", "a", "case", 1, False),
|
| 81 |
+
("b0", "b", "case", 0, True), ("c0", "c", "case", 0, True),
|
| 82 |
+
("d0", "d", "control", 0, True), ("e0", "e", "control", 0, True)],
|
| 83 |
+
columns=["sample_id", "donor_id", "group", "timepoint", "identity_pass"])
|
| 84 |
+
with pytest.raises(ValueError):
|
| 85 |
+
support.build_disease(folds, pairs, ["a", "b", "c", "d", "e"], "toy", 0)
|
| 86 |
+
pairs.loc[pairs.sample_id == "a0", "identity_pass"] = True
|
| 87 |
+
pairs.loc[pairs.sample_id == "a0", "donor_id"] = "b"
|
| 88 |
+
with pytest.raises(ValueError):
|
| 89 |
+
support.build_disease(folds, pairs, ["a", "b", "c", "d", "e"], "toy", 0)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def test_imperial_dates_share_one_calendar_axis(folds):
|
| 93 |
+
f = folds.copy()
|
| 94 |
+
f.loc[f.donor_id == "a", "group"] = "covid_positive"
|
| 95 |
+
pairs = pd.DataFrame([
|
| 96 |
+
("a0", 1.0, "25/02/2021", True), ("a1", None, "30/04/2020", True),
|
| 97 |
+
("b0", 1.0, "01/01/2021", True), ("c0", 1.0, "01/01/2021", True),
|
| 98 |
+
("d0", 1.0, "01/01/2021", True), ("e0", 1.0, "01/01/2021", True),
|
| 99 |
+
], columns=["sample_id", "timepoint", "sample_date", "identity_pass"])
|
| 100 |
+
m = support.build_disease(f, pairs, ["a", "b", "c", "d", "e"], "imperial_eskd", 4)
|
| 101 |
+
assert m["train_sample_ids"][0] == "a1"
|
| 102 |
+
assert {c["time_field"] for c in m["selection_audit"][0]["candidates"]} == {"sample_date"}
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def test_exclusion_includes_identity_failed_other_visit(folds):
|
| 106 |
+
f = folds.copy()
|
| 107 |
+
f.loc[f.sample_id == "bad", "donor_id"] = "a"
|
| 108 |
+
pairs = pd.DataFrame([("a0", 14, True), ("a1", 0, True),
|
| 109 |
+
("b0", 0, True), ("c0", 0, True),
|
| 110 |
+
("d0", 0, True), ("e0", 0, True)],
|
| 111 |
+
columns=["sample_id", "timepoint", "identity_pass"])
|
| 112 |
+
m = support.build_disease(f, pairs, ["a", "b", "c", "d", "e"], "toy", 0)
|
| 113 |
+
assert set(m["excluded_sample_ids"]) == {"a0", "bad"}
|
| 114 |
+
support.validate_manifest(m, f)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def test_immutable_write(tmp_path, folds):
|
| 118 |
+
m = support.build_healthy(folds, 0, 2, seed=3)
|
| 119 |
+
p = tmp_path / "SUPPORT.json"
|
| 120 |
+
support.write_manifest(p, m)
|
| 121 |
+
assert support.load_manifest(p, folds) == m
|
| 122 |
+
with pytest.raises(FileExistsError): support.write_manifest(p, copy.deepcopy(m))
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def test_selector_never_reads_inner_validation_or_other_visits(folds):
|
| 126 |
+
pairs = pd.DataFrame([("a0", 14, True), ("a1", 0, True), ("b0", 1, True),
|
| 127 |
+
("c0", 0, True), ("d0", 0, True), ("e0", 0, True)],
|
| 128 |
+
columns=["sample_id", "timepoint", "identity_pass"])
|
| 129 |
+
m = support.build_disease(folds, pairs, ["a", "b", "c", "d", "e"], "toy", 0)
|
| 130 |
+
train, test = support.select_rows(m, folds)
|
| 131 |
+
assert folds.loc[train, "sample_id"].tolist()[:2] == ["a1", "b0"]
|
| 132 |
+
assert "a0" not in folds.loc[test, "sample_id"].tolist()
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def test_rejects_missing_and_empty_ids(folds):
|
| 136 |
+
broken = folds.copy()
|
| 137 |
+
broken.loc[0, "sample_id"] = None
|
| 138 |
+
with pytest.raises(ValueError): support.build_healthy(broken, 0, 2, seed=3)
|
| 139 |
+
broken.loc[0, "sample_id"] = " "
|
| 140 |
+
with pytest.raises(ValueError): support.build_healthy(broken, 0, 2, seed=3)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def test_rejects_stale_existing_trainer_run(folds):
|
| 144 |
+
m = support.build_healthy(folds, 0, 2, seed=3)
|
| 145 |
+
run = {"support_sha256": m["sha256"], "train_rows": m["train_sample_ids"],
|
| 146 |
+
"train_donor_ids": m["train_donor_ids"],
|
| 147 |
+
"test_rows_never_loaded_for_training": m["test_sample_ids"],
|
| 148 |
+
"inner_val_rows": [], "fixed_steps": 3000, "steps_run": 3000,
|
| 149 |
+
"selected_step": 3000, "mode": "lora", "trainable": {"lora_rank": 16},
|
| 150 |
+
"source_checkpoint_sha256": "sourcehash"}
|
| 151 |
+
run.update(condition_npz_sha256="conditionhash", lr=1e-4, warmup=200, batch_size=256,
|
| 152 |
+
ema_decay=0.999, seed=123)
|
| 153 |
+
run["trainable"]["lora_alpha"] = 16.0
|
| 154 |
+
support.validate_existing_run(m, run, fixed_steps=3000, lora_rank=16,
|
| 155 |
+
source_checkpoint_sha256="sourcehash", condition_npz_sha256="conditionhash",
|
| 156 |
+
lr=1e-4, lora_alpha=16.0, warmup=200, batch_size=256,
|
| 157 |
+
ema_decay=0.999, seed=123)
|
| 158 |
+
for key, val in (("support_sha256", "wrong"), ("train_rows", []),
|
| 159 |
+
("fixed_steps", 2000), ("steps_run", 2000),
|
| 160 |
+
("source_checkpoint_sha256", "wrong"), ("condition_npz_sha256", "wrong"),
|
| 161 |
+
("lr", 1e-3), ("warmup", 100), ("batch_size", 128),
|
| 162 |
+
("ema_decay", 0.9), ("seed", 234)):
|
| 163 |
+
bad = copy.deepcopy(run)
|
| 164 |
+
bad[key] = val
|
| 165 |
+
with pytest.raises(ValueError):
|
| 166 |
+
support.validate_existing_run(m, bad, fixed_steps=3000, lora_rank=16,
|
| 167 |
+
source_checkpoint_sha256="sourcehash", condition_npz_sha256="conditionhash",
|
| 168 |
+
lr=1e-4, lora_alpha=16.0, warmup=200, batch_size=256,
|
| 169 |
+
ema_decay=0.999, seed=123)
|
| 170 |
+
bad = copy.deepcopy(run)
|
| 171 |
+
bad["trainable"]["lora_alpha"] = 8.0
|
| 172 |
+
with pytest.raises(ValueError):
|
| 173 |
+
support.validate_existing_run(m, bad, fixed_steps=3000, lora_rank=16,
|
| 174 |
+
source_checkpoint_sha256="sourcehash", condition_npz_sha256="conditionhash",
|
| 175 |
+
lr=1e-4, lora_alpha=16.0, warmup=200, batch_size=256,
|
| 176 |
+
ema_decay=0.999, seed=123)
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def test_scsemi_opt_in_keeps_legacy_fewshot_behavior(monkeypatch):
|
| 180 |
+
monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "")
|
| 181 |
+
old = ROOT.parent / "paired_finetune_intradataset_20260927"
|
| 182 |
+
source = old / "scsemi/tools/prepare_draw_inputs.py"
|
| 183 |
+
module_spec = importlib.util.spec_from_file_location("strict_scsemi_inputs", source)
|
| 184 |
+
module = importlib.util.module_from_spec(module_spec)
|
| 185 |
+
module_spec.loader.exec_module(module)
|
| 186 |
+
ds = old / "data/giroux2022"
|
| 187 |
+
f = pd.read_csv(ds / "folds.csv", dtype={"sample_id": str, "donor_id": str})
|
| 188 |
+
ids = f.sample_id.to_numpy(str)
|
| 189 |
+
legacy = module.split_rows("giroux2022", "fewshot", 0, ids, f)
|
| 190 |
+
support_path = ROOT / "protocol/splits/giroux2022/disease/draw0/support.json"
|
| 191 |
+
strict = module.split_rows("giroux2022", "strict", 0, ids, f, support_manifest=support_path)
|
| 192 |
+
assert len(strict["rep"]) == 5
|
| 193 |
+
assert len(legacy["rep"]) > len(strict["rep"])
|
| 194 |
+
assert [ids[i] for i in strict["rep"]] == support.load_manifest(support_path, f)["train_sample_ids"]
|
| 195 |
+
assert strict["support_sha256"] == support.load_manifest(support_path, f)["sha256"]
|
| 196 |
+
assert legacy["condition"].name == "test_raw.npz"
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def test_scsemi_strict_wrapper_validates_support_and_legacy_runner_is_unchanged(tmp_path):
|
| 200 |
+
wrapper_path = ROOT / "tools/run_scsemi_strict.py"
|
| 201 |
+
wrapper_spec = importlib.util.spec_from_file_location("scsemi_strict_wrapper", wrapper_path)
|
| 202 |
+
wrapper = importlib.util.module_from_spec(wrapper_spec)
|
| 203 |
+
wrapper_spec.loader.exec_module(wrapper)
|
| 204 |
+
old = ROOT.parent / "paired_finetune_intradataset_20260927"
|
| 205 |
+
original = ROOT / "backups/plans/paired_finetune_intradataset_20260927/scsemi/tools/run_scsemi_paired.py"
|
| 206 |
+
assert hashlib.sha256((old / "scsemi/tools/run_scsemi_paired.py").read_bytes()).digest() == \
|
| 207 |
+
hashlib.sha256(original.read_bytes()).digest()
|
| 208 |
+
path = ROOT / "protocol/splits/giroux2022/disease/draw0/support.json"
|
| 209 |
+
f = pd.read_csv(old / "data/giroux2022/folds.csv", dtype={"sample_id": str, "donor_id": str})
|
| 210 |
+
m = support.load_manifest(path, f)
|
| 211 |
+
inp = tmp_path / "inputs"
|
| 212 |
+
inp.mkdir()
|
| 213 |
+
man = {"mode": "strict", "dataset": "giroux2022", "support_sha256": m["sha256"],
|
| 214 |
+
"representatives": [{"sample_id": s} for s in m["train_sample_ids"]],
|
| 215 |
+
"targets": m["test_sample_ids"], "train_donors": m["train_donor_ids"],
|
| 216 |
+
"sources": {"support.json": hashlib.sha256(path.read_bytes()).hexdigest()}}
|
| 217 |
+
(inp / "inputs_manifest.json").write_text(json.dumps(man))
|
| 218 |
+
wrapper.validate_strict_inputs(path, tmp_path, phase="prepare", reuse_from=None)
|
| 219 |
+
with pytest.raises(ValueError): wrapper.validate_strict_inputs(path, tmp_path, phase="prepare", reuse_from=tmp_path)
|
| 220 |
+
with pytest.raises(ValueError): wrapper.validate_strict_inputs(path, tmp_path, phase="link", reuse_from=None)
|
| 221 |
+
man["representatives"][0]["sample_id"] = "wrong"
|
| 222 |
+
(inp / "inputs_manifest.json").write_text(json.dumps(man))
|
| 223 |
+
with pytest.raises(ValueError): wrapper.validate_strict_inputs(path, tmp_path, phase="pretrain", reuse_from=None)
|