File size: 10,177 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 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 | #!/usr/bin/env python
"""classifier4/B: apply the independent T1 evidence network to every off-test / dev-test case and pool it per candidate.
All populations are OUT-OF-SAMPLE for the network (it trained only on D331 fold-0 TRAIN keys): CONTRA (58), DEV-A (276 = D331 fold-0
val), dev-test (ATLAS-43, NORTH, LAB; evaluation only). One fixed inference setting for all cohorts: sliding window 128^3, step 64,
Gaussian weighting, no TTA, input = the same D331-preprocessed z-scored T1 every other part uses (cls3_cand.load_case), zero outside brain.
Outputs:
ev/<pop>/<key>.npz evidence map (fg prob x250 uint8, preprocessed grid)
feat/<pop>/chunk_i_of_n.pkl per candidate (key, src=setting, cid): ev_max / mean / p90 / top10 / frac05 / mass / ring / inring /
dilmax / lmax (logit of max) for renderer-only settings (contra iv_t0.5/0.3, dev v1/v2_t0.5/0.3,
test iv2_t0.5/0.3); candidates = dethead_cand.candidates (identical ids to classifier3/full tables)
les/<pop>/chunk_i_of_n.pkl per GT lesion (>= 10 vox, 26-conn; gid as in les tables): vox, ev_max, d331_max (voxel-level
decorrelation read-out)
c4b_apply.py --tag b1 --pop dev|contra|test --chunk i --nchunk n
"""
from __future__ import annotations
import argparse, sys, time
from pathlib import Path
import numpy as np
import pandas as pd
sys.path.insert(0, str(Path(__file__).resolve().parent))
import c4b_common as Q # noqa: E402
import torch
SETS = {"contra": ("iv_t0.5", "iv_t0.3"), "dev": ("v1_t0.5", "v2_t0.5", "v1_t0.3", "v2_t0.3"), "test": ("iv2_t0.5", "iv2_t0.3")}
def gauss(P, dev):
s = P / 8; c = (P - 1) / 2
g = torch.exp(-((torch.arange(P, device=dev, dtype=torch.float32) - c) ** 2) / (2 * s * s))
w = g[:, None, None] * g[None, :, None] * g[None, None, :]
return (w / w.max()).clamp(min=1e-3)
@torch.no_grad()
def infer(net, t1, brain, dev, P=128, step=64, extra=None, ncls=2):
"""extra: optional 2nd input channel (mirror difference); ncls: stroke classes (outputs beyond = training-only aux head)."""
x = torch.from_numpy(np.where(brain, t1, 0).astype(np.float32)).to(dev)
shp = x.shape
pad = [max(P - s, 0) for s in shp]
x = torch.nn.functional.pad(x, (0, pad[2], 0, pad[1], 0, pad[0]))
if extra is not None:
e = torch.nn.functional.pad(torch.from_numpy(extra.astype(np.float32)).to(dev), (0, pad[2], 0, pad[1], 0, pad[0]))
x = torch.stack([x, e], 0)
S = x.shape[-3:]
acc = torch.zeros(S, device=dev); wac = torch.zeros(S, device=dev); w = gauss(P, dev)
starts = [sorted(set(list(range(0, s - P + 1, step)) + [s - P])) for s in S]
batch, locs = [], []
def flush():
xb = torch.stack(batch)
xb = xb[:, None] if xb.dim() == 4 else xb
with torch.autocast(dev.type, dtype=torch.bfloat16, enabled=dev.type == "cuda"):
o = net(xb)
o = o[0] if isinstance(o, (list, tuple)) else o
p = torch.softmax(o[:, :ncls].float(), 1)[:, 1]
for pi, (a, b, c) in zip(p, locs):
acc[a:a + P, b:b + P, c:c + P] += pi * w; wac[a:a + P, b:b + P, c:c + P] += w
batch.clear(); locs.clear()
for a in starts[0]:
for b in starts[1]:
for c in starts[2]:
if not brain[a:a + P, b:b + P, c:c + P].any():
continue
batch.append(x[..., a:a + P, b:b + P, c:c + P]); locs.append((a, b, c))
if len(batch) == 4:
flush()
if batch:
flush()
p = (acc / wac.clamp(min=1e-6))[:shp[0], :shp[1], :shp[2]].cpu().numpy()
return p * brain
def pool(ev, L, n, brain, t1):
from scipy import ndimage as ndi
rows = []
objs = ndi.find_objects(L)
for k in range(1, n + 1):
sl = objs[k - 1]
lo = [max(s.start - 4, 0) for s in sl]; hi = [min(s.stop + 4, L.shape[i]) for i, s in enumerate(sl)]
sl = tuple(slice(a, b) for a, b in zip(lo, hi))
m = L[sl] == k; e = ev[sl]; br = brain[sl]; tt = t1[sl]
v = e[m]
d1 = ndi.binary_dilation(m, iterations=1); d2 = ndi.binary_dilation(d1, iterations=1); d3 = ndi.binary_dilation(d2, iterations=1)
ring = d3 & ~m & br
rm = float(e[ring].mean()) if ring.any() else 0.0
srt = np.sort(v)[::-1]; kk = max(1, int(round(0.1 * len(v))))
mx = float(v.max())
# most evidence-dense / most hypointense COMPACT sub-region inside the (possibly bloated) candidate
bf = br.astype(np.float32); nb3 = ndi.uniform_filter(bf, 3); nb5 = ndi.uniform_filter(bf, 5)
e3 = ndi.uniform_filter(e * bf, 3) / np.maximum(nb3, 1e-3); e5 = ndi.uniform_filter(e * bf, 5) / np.maximum(nb5, 1e-3)
t3 = ndi.uniform_filter(tt * bf, 3) / np.maximum(nb3, 1e-3)
rt = tt[ring] if ring.any() else tt[br & ~m]
rmed = float(np.median(rt)) if rt.size else 0.0; rsd = float(rt.std()) + 0.1 if rt.size else 1.0
inner = m & (nb3 > 0.5)
if not inner.any():
inner = m
t3min = float(t3[inner].min()); jmin = np.argwhere(inner)[np.argmin(t3[inner])]
rows.append(dict(cid=k, ev_max=mx, ev_mean=float(v.mean()), ev_p90=float(np.quantile(v, 0.9)), ev_top10=float(srt[:kk].mean()),
ev_frac05=float((v > 0.5).mean()), ev_mass=float(v.sum()), ev_ring=rm, ev_inring=float(v.mean()) - rm,
ev_dilmax=float(e[d2 & br].max()), ev_box3max=float(e3[m].max()), ev_box5max=float(e5[m].max()),
t1_box3min_rel=(t3min - rmed) / rsd, t1_box3min_d=t3min - rmed, ev_at_t1min=float(e3[tuple(jmin)]),
t1_mean_rel=(float(tt[m].mean()) - rmed) / rsd, ev_lmax=float(np.log(np.clip(mx, 1e-4, 1 - 1e-4) / (1 - np.clip(mx, 1e-4, 1 - 1e-4))))))
return rows
def main():
import cls3_cand as CC, dethead_cand as K, cc3d, c4b_train as T
ap = argparse.ArgumentParser(); ap.add_argument("--tag", default="b1"); ap.add_argument("--pop", required=True)
ap.add_argument("--chunk", type=int, default=0); ap.add_argument("--nchunk", type=int, default=1); ap.add_argument("--limit", type=int, default=0)
a = ap.parse_args()
import dethead_common as H, cls2_common as C2
keys = {"contra": H.contra_keys, "dev": K.dev_keys, "test": C2.test_cids}[a.pop]()[a.chunk::a.nchunk]
if a.limit:
keys = keys[:a.limit]
dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
import json as _j
nets = []
for mt in a.tag.split("+"): # 'b2+b2s1' = seed ensemble (mean probability)
mj = Q.OUT / "models" / f"{mt}.json"
meta = _j.load(open(mj)) if mj.exists() else {"ncls": 2, "patch": 128}
import c4b_train3 as T3
n_ = T3.make_net(False, meta.get("nout", meta["ncls"]), meta.get("in_ch", 1)).to(dev)
n_.load_state_dict(torch.load(Q.OUT / "models" / f"{mt}.pt", map_location=dev, weights_only=False)); n_.eval()
nets.append((n_, int(meta.get("patch", 128)), meta))
MTR = None
if any(m.get("mirror") for _, _, m in nets):
import pandas as _pd, c4b_mirror as MR
_tf = Q.OUT / "mirror" / "transforms.pkl"
MTR = _pd.read_pickle(_tf).set_index("key") if _tf.exists() else _pd.DataFrame(columns=["lr", "R", "off"])
od = Q.OUT / a.tag
fo = od / "feat" / a.pop / f"chunk_{a.chunk}_of_{a.nchunk}.pkl"; lo_ = od / "les" / a.pop / f"chunk_{a.chunk}_of_{a.nchunk}.pkl"
if fo.exists() and not a.limit:
print("exists"); return
CC.ONLY = list(SETS[a.pop])
F, Ls, ST = [], [], []; t0 = time.time()
for key in keys:
try:
t1, brain, gt, props, refs, sets, probs = CC.load_case(a.pop, key)
except Exception as e:
print("FAIL_LOAD", key, repr(e)[:200], flush=True); continue
tb = t1[brain]
ST.append(dict(key=key, shape=list(t1.shape), brain_vox=int(brain.sum()), t1_mean=float(tb.mean()), t1_sd=float(tb.std()),
t1_p01=float(np.quantile(tb, .01)), t1_p50=float(np.median(tb)), t1_p99=float(np.quantile(tb, .99)),
outside_nonzero=int((t1[~brain] != 0).sum())))
assert abs(ST[-1]["t1_mean"]) < 0.5 and 0.6 < ST[-1]["t1_sd"] < 1.6, ("preprocessing mismatch (not brain-masked z-score)", ST[-1])
dmap = None
if MTR is not None:
t1m = np.where(brain, t1, 0).astype(np.float32)
mm = MR.apply_mirror(t1m, MTR.loc[key]) if key in MTR.index else t1m
from scipy import ndimage as ndi
dmap = (t1m - np.clip(t1m, ndi.minimum_filter(mm, 3), ndi.maximum_filter(mm, 3))) * brain
ev = np.mean([infer(n_, t1, brain, dev, P=pp, step=pp // 2, extra=dmap if m.get("mirror") else None, ncls=m["ncls"])
for n_, pp, m in nets], 0)
Q.save_npz(od / "ev" / a.pop / f"{key}.npz", ev=np.clip(np.round(ev * 250), 0, 250).astype(np.uint8))
for s in SETS[a.pop]:
if s not in sets:
continue
_, h, tau = sets[s]
L, n = K.candidates(h, brain, tau)
for r in pool(ev, L, n, brain, t1):
F.append(dict(key=key, src=s, **r))
G, ng = cc3d.connected_components(gt.astype(np.uint8), connectivity=26, return_N=True)
if ng:
sz = np.bincount(G.ravel(), minlength=ng + 1)
from scipy import ndimage as ndi
emax = ndi.maximum(ev, G, np.arange(1, ng + 1)); pmax = ndi.maximum(probs["d331"], G, np.arange(1, ng + 1))
for g in range(1, ng + 1):
if sz[g] >= 10:
Ls.append(dict(key=key, gid=g, vox=int(sz[g]), ev_max=float(emax[g - 1]), d331_max=float(pmax[g - 1])))
print("C4B_APPLY", a.pop, key, len(F), len(Ls), f"{time.time() - t0:.0f}s", flush=True)
for p_, rows in ((fo, F), (lo_, Ls), (od / "stats" / a.pop / f"chunk_{a.chunk}_of_{a.nchunk}.pkl", ST)):
Q.guard_write(p_); p_.parent.mkdir(parents=True, exist_ok=True)
pd.DataFrame(rows).to_pickle(p_)
print("C4B_APPLY_DONE", a.pop, a.chunk, len(F), flush=True)
if __name__ == "__main__":
main()
|