File size: 3,398 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
76
77
78
79
80
81
82
83
84
85
86
87
"""classifier3 (direction2, 2026-11-18): candidate ceiling (lower heat threshold, detector combination) + stronger classifier.

Builds on classifier2 (cls2_*.py, reused read-only). Test cohorts NORTH / ATLAS-43 / LAB = development pseudo-test: scored and
selected on, NEVER trained / fitted / calibrated on. Operating points chosen off-test (CONTRA OOF, DEV-A) and recorded in
V8_TRANSFER_PREREG.md before test scoring. XHOLDOUT firewalled, SABRE excluded. Writes only under outputs/direction2/classifier3/.
"""
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 cls2_common as Q   # noqa: E402

C = Q.C
WS = Q.WS
OUT = WS / "outputs/direction2/classifier3"
OUT2 = Q.OUT
HT = C.HEAT_TEST
HOOF = C.HEAT_OOF
TAUS = (0.5, 0.4, 0.3)
guard = Q.guard


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


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)


# ---------------------------------------------------------------- test-time heat variants (raw T1 grid, float in [0, 1])
def _rd(p):
    a = Q.read_nii(p)
    return a / 250.0 if a.max() > 1.5 else a


def test_heat(cid, var):
    """var: ii3 (= runbook mean of 3 mix folds), ii2 / iv2 (mean of folds 0,1), iv3, max_ii3_iv2, max_ii3_iv3, max_ii2_iv2,
    mean5 (mean of ii f0-2 + iv f0-1), each rounded to 1/250 like the stored mean."""
    def mean_of(tag, sub, folds):
        return np.mean([_rd(HT / tag / f"fold_c2x_{sub}_f{f}" / f"{cid}.nii.gz") for f in folds], 0)
    if var == "ii3":
        return Q.read_nii(HT / "detA_ii_x" / "mean" / f"{cid}.nii.gz")
    parts = {"ii3": lambda: Q.read_nii(HT / "detA_ii_x" / "mean" / f"{cid}.nii.gz"),
             "ii2": lambda: mean_of("detA_ii_x", "ii", (0, 1)), "iv2": lambda: mean_of("detA_iv_x", "iv", (0, 1)),
             "iv3": lambda: mean_of("detA_iv_x", "iv", (0, 1, 2))}
    if var in parts:
        h = parts[var]()
    elif var.startswith("max_"):
        _, a, b = var.split("_"); h = np.maximum(parts[a](), parts[b]())
    elif var == "mean5":
        h = (3 * parts["ii3"]() + 2 * parts["iv2"]()) / 5
    else:
        raise KeyError(var)
    return (np.round(h * 250) / 250).astype(np.float32)


def two_tier(h, brain, tau):
    """L5 = classifier2 candidates (heat >= 0.5, >= 10 vox). Lt = components at tau. Faint-only = tau components containing no
    L5 candidate voxel (new candidates); halo = tau components that contain an L5 candidate."""
    import dethead_cand as K
    L5, n5 = K.candidates(h, brain, 0.5)
    Lt, nt = K.candidates(h, brain, tau)
    has5 = np.zeros(nt + 1, bool)
    if n5:
        has5[np.unique(Lt[L5 > 0])] = True
    has5[0] = False
    faint = [k for k in range(1, nt + 1) if not has5[k]]
    remap = np.zeros(nt + 1, np.int32); remap[faint] = np.arange(1, len(faint) + 1)
    LF = remap[Lt]
    return L5, n5, Lt, nt, LF, len(faint)