File size: 4,521 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
"""boundary2 designer B (2026-11-18): shared helpers. Annotator-style statistics ("adventurousness" dial), convention labels,
paths. Writes only under outputs/direction2/boundary2/B/. XHOLDOUT / SABRE firewalled; test labels only read for SCORING.

Dial ("adventurousness", per lesion): where, between the lesion core intensity and the surrounding tissue intensity, did the
tracer put the edge?  a = (thr - I_core) / (I_tissue - I_core),  thr = mean(median T1 on the inner mask surface, median T1 on
the 1-voxel outer shell).  a ~ 0.5: edge at half contrast; a > 0.5: generous (includes partial-volume / gliotic rim);
a < 0.5: conservative. Contrast-normalised by construction (invariant to affine intensity changes).
"""
from __future__ import annotations
import os, sys, json
from pathlib import Path
import numpy as np
import scipy.ndimage as ndi

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
B = Path("/__EAGLE_BUNDLE_ROOT__")
WS = B / "whisper_synth"
OUT = WS / "outputs/direction2/boundary2/B"
S6 = ndi.generate_binary_structure(3, 1)
CONVENTIONS = ("atlas", "acute", "contra")      # one-hot order = LABEL PROVENANCE: T1-traced / DWI-traced / FLAIR-traced
# (user decision 2026-11-18: tokens encode provenance only; inference uses ONE fixed T1 setting for every cohort)
PROVENANCE_ALIAS = {"lab": "atlas"}             # LAB masks are T1-traced -> the T1-traced token


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 boundary2/B: {p}"
    return p


def convention_of_key(key: str) -> str:
    k = key
    for pre in ("syn_t1_", "syn_", "r_", "test_"):
        if k.startswith(pre):
            k = k[len(pre):]
            break
    c = k.split("_")[0]
    c = PROVENANCE_ALIAS.get(c, c)
    return c if c in CONVENTIONS else "unknown"


def _dil(m, r):
    return ndi.binary_dilation(m, S6, iterations=r) if r > 0 else m


def lesion_style(t1, comp, other=None, brain=None, ring=(2, 6), q_tissue=75):
    """t1 float (any affine scaling), comp bool (one lesion component), other bool (other lesions, excluded), brain bool.
    -> dict(a, i_core, i_tissue, thr, contrast) or None when undefined. Works on a local crop (call with a bbox crop)."""
    if comp.sum() < 3:
        return None
    if brain is None:
        brain = np.ones_like(comp)
    if other is None:
        other = np.zeros_like(comp)
    er = ndi.binary_erosion(comp, S6)
    core = er if er.sum() >= 3 else comp
    inner = comp & ~er
    outer = _dil(comp, 1) & ~comp & brain & ~other
    rg = _dil(comp, ring[1]) & ~_dil(comp, ring[0]) & brain & ~other
    if inner.sum() < 3 or outer.sum() < 3 or rg.sum() < 10:
        return None
    ic = float(np.median(t1[core])); it = float(np.percentile(t1[rg], q_tissue))
    thr = 0.5 * (float(np.median(t1[inner])) + float(np.median(t1[outer])))
    den = it - ic
    if abs(den) < 1e-6:
        return None
    return {"a": float(np.clip((thr - ic) / den, -1.0, 2.0)), "i_core": ic, "i_tissue": it, "thr": thr, "contrast": float(den)}


def comp_crop(lab, k, obj, pad, shape):
    sl = tuple(slice(max(0, s.start - pad), min(n, s.stop + pad)) for s, n in zip(obj, shape))
    return sl


def case_styles(t1, gt, brain=None, min_vox=10, pad=8):
    """per GT component (26-conn, >= min_vox): id, voxels, style dict. t1 in any scaling (z-scored over brain is used)."""
    import cc3d
    if brain is None:
        brain = t1 > 0
    z = (t1 - t1[brain].mean()) / (t1[brain].std() + 1e-6)
    lab = cc3d.connected_components(gt.astype(np.uint8), connectivity=26)
    sz = np.bincount(lab.ravel()); objs = ndi.find_objects(lab)
    out = []
    for k in range(1, len(sz)):
        if sz[k] < min_vox or objs[k - 1] is None:
            continue
        sl = comp_crop(lab, k, objs[k - 1], pad, gt.shape)
        L = lab[sl]
        st = lesion_style(z[sl], L == k, (L > 0) & (L != k), brain[sl])
        out.append({"id": int(k), "vox": int(sz[k]), **(st or {"a": np.nan})})
    return out, lab


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 stable_seed(*parts) -> int:
    import zlib
    return zlib.crc32("|".join(str(p) for p in parts).encode()) & 0x7FFFFFFF