File size: 3,029 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
"""classifier4 / builder B (2026-11-19): INDEPENDENT T1 EVIDENCE NETWORK, decorrelated from D331.

A from-scratch (random init) ResEnc U-Net trained on D331's OWN training data (Dataset331 fold-0 TRAIN keys, D331's preprocessed
T1 + labels; <id> dropped) with a recipe built against the causes of D331's blindness (B_LOG.md §1):
lesion-balanced patch sampling, lesion-wise loss terms (blob Dice + per-lesion max-evidence), synthetic tiny / faint lesions painted
into real T1 anatomy, and extreme domain randomisation (GIN, gamma, bias, thick slices, noise) done on the GPU.
Never: D331 weights / init / features; DEV-A, CONTRA or dev-test cohorts in training (DEV-A = D331's own fold-0 validation keys,
the off-test judge). Test cohorts (ATLAS-43, NORTH, LAB) are evaluation only. XHOLDOUT firewalled; SABRE excluded.
Writes only under outputs/direction2/classifier4/B/.
"""
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/classifier4/B"
D331 = "Dataset331_Whisper_T1unpaired"
D331P = C.PREP / D331 / "nnUNetPlans_3d_fullres"
SPLITS = C.PREP / D331 / "splits_final.json"


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


def guard_write(p):
    guard(p)
    assert str(Path(p).resolve()).startswith(str(OUT.resolve())), f"write outside classifier4/B: {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)


_A43 = None


def train_keys():
    """D331 fold-0 TRAIN keys (= D331's training data), minus lab_ (LAB is a test cohort; <id> is not a test subject but is
    dropped anyway). Asserted disjoint from DEV-A (D331 fold-0 val), ATLAS-43 subjects, NORTH, CONTRA."""
    global _A43
    s = json.load(open(guard(SPLITS)))
    tr = [k for k in s[0]["train"] if not k.startswith("lab_")]
    va = set(s[0]["val"])
    assert not (set(tr) & va)
    if _A43 is None:
        import diag2_common as G
        _A43 = G.atlas43()
    for k in tr:
        kl = k.lower()
        assert kl.startswith("atlas_") or kl.startswith("acute_"), k
        assert not any(b in kl for b in ("north", "sabre", "xholdout", "lab_", "test_", "contra")), k
        assert not any(a in k for a in _A43), f"ATLAS-43 subject in training: {k}"
    return tr


def load_b2(p, ch=None):
    import blosc2
    a = blosc2.open(urlpath=str(guard(p)), mode="r")
    return np.asarray(a[:] if ch is None else a[ch])