File size: 2,454 Bytes
473c56f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
"""classifier2 (direction2, 2026-11-17): stronger per-candidate detection head for Pipeline B.

Builds on dethead (dethead_*.py; reused read-only). New in classifier2: the current test cohorts (NORTH, ATLAS-43 official,
LAB) are a DEVELOPMENT test set (prereg 35q): they may be scored, never trained on (no labels / images / statistics /
thresholds / calibration fitted on them). LAB is generator-seen -> reported separately. SABRE excluded; XHOLDOUT firewalled.
Writes only under outputs/direction2/classifier2/.
"""
from __future__ import annotations
import json, os, sys
from pathlib import Path
import numpy as np

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import cascade2_common as C   # noqa: E402

B = C.B
WS = C.WS
OUT = WS / "outputs/direction2/classifier2"
DH = WS / "outputs/direction2/dethead"
D943R = C.D943R
HEAT_TEST = C.HEAT_TEST / "detA_ii_x" / "mean"
D331_TEST = WS / "outputs/direction2/arch2stage/t1prob"
TEST_COHORTS = ("atlas", "north", "lab")
PRIMARY = ("atlas", "north")


def guard(p):
    s = str(p).lower()
    assert "xholdout" not in s, f"XHOLDOUT firewall: {p}"
    assert "sabre" not in s, f"SABRE excluded: {p}"
    return p


def guard_write(p):
    guard(p)
    assert str(Path(p).resolve()).startswith(str(OUT.resolve())), f"write outside classifier2: {p}"
    return p


def test_cids(cohorts=TEST_COHORTS):
    cs = sorted(p.name[:-7] for p in HEAT_TEST.glob("*.nii.gz"))
    cs = [c for c in cs if c.split("_")[0] in cohorts]
    for c in cs:
        guard(c)
    return cs


def label_path(cid):
    """same convention as cascade2_score.label_path (ATLAS-43 -> official masks)."""
    assert cid.split("_")[0] in TEST_COHORTS, cid
    if cid.startswith("atlas_"):
        return guard(C.OFF / f"{cid}.nii.gz")
    tm = json.load(open(D943R / "test_label_map.json"))
    return guard(tm[f"test_{cid}"])


def save_npz(path, **kw):
    guard_write(path)
    Path(path).parent.mkdir(parents=True, exist_ok=True)
    tmp = str(path) + f".tmp{os.getpid()}.npz"
    np.savez_compressed(tmp, **kw); os.replace(tmp, path)


def jdump(obj, path):
    guard_write(path)
    Path(path).parent.mkdir(parents=True, exist_ok=True)
    tmp = str(path) + f".tmp{os.getpid()}"
    json.dump(obj, open(tmp, "w"), indent=1, default=float); os.replace(tmp, path)


def read_nii(p, dtype=np.float32):
    import SimpleITK as sitk
    return sitk.GetArrayFromImage(sitk.ReadImage(str(guard(p)))).astype(dtype)