eagle-u-pair-2c / runtime /code /whisper_synth /src /direction2 /boundary2_B_mirror.py
edschen's picture
EAGLE model u_pair_2c v1 (part 3)
473c56f verified
Raw History Blame Contribute Delete
6.47 kB
#!/usr/bin/env python
"""boundary2 designer B, design B3 (anatomy): CONTRALATERAL MIRROR channel on the nnU-Net preprocessed (1 mm) grid.
FORENSICS ("Anatomical-abnormality cues vs the missed rim"): contralateral asymmetry is the only structural cue that separates
the missed rim from normal tissue at equal T1 (matched-T1 AUC 0.58-0.63 on DEV-A ATLAS / ATLAS-43 / NORTH / LAB); texture /
entropy / GM-WM blur ~ chance. Mirror = flip along the array axis closest to physical L-R, rigidly registered back onto the image
(SimpleITK Euler3D, Mattes MI, 2 levels; registration on the sigma-1 smoothed T1 = boundary2_forensics_struct.mirror_aligned's
recipe, transform applied to the unsmoothed T1). Label-free, per image (no atlas, no other subject).
Drawer channel (computed after spatial augmentation from T1 and the stored mirror M; see boundary2_B_nnunet.MirrorDiffTransform):
D = T1 - clip(T1, minpool3(M), maxpool3(M)) (signed deviation beyond the +-1-voxel local range of the mirror; 0 = symmetric)
boundary2_B_mirror.py precompute --chunk i --nchunk n -> B/mirror/<stem>.b2nd (uint8, (M + 4) * 25, clipped) for every
drawer TRAINING key (syn_t1_* -> D961 dxb_<X>, r_contra_* -> D945 r_<X>)
"""
from __future__ import annotations
import argparse, json, os, pickle, sys, time
from pathlib import Path
import numpy as np
import scipy.ndimage as ndi
sys.path.insert(0, str(Path(__file__).resolve().parent))
import boundary2_B_common as BC # noqa: E402
MDIR = BC.OUT / "mirror"
Q_OFF, Q_SC = 4.0, 25.0
def lr_axis(direction):
D = np.array(direction, float).reshape(3, 3)
return int(np.argmax([abs(D[0, 2 - a]) for a in range(3)]))
def mirror_pp(t1, direction, spacing=(1.0, 1.0, 1.0)):
"""t1: pp-grid array (z-scored, 0 outside brain). -> M (same grid), metric."""
import SimpleITK as sitk
sitk.ProcessObject.SetGlobalDefaultNumberOfThreads(int(os.environ.get("SITK_THREADS", "2")))
brain = t1 != 0
lr = lr_axis(direction)
ts = ndi.gaussian_filter(t1.astype(np.float32), 1.0)
ts = np.where(brain, ts - (ts[brain].min() if brain.any() else 0) + 0.1, 0).astype(np.float32) # positive (MOMENTS init needs it)
def img(a):
im = sitk.GetImageFromArray(a.astype(np.float32)); im.SetSpacing(tuple(float(s) for s in spacing[::-1])); im.SetDirection(tuple(float(d) for d in direction))
return im
fixed = img(ts); moving = img(np.flip(ts, axis=lr).copy()); raw_mov = img(np.flip(t1, axis=lr).copy())
fm = sitk.GetImageFromArray(brain.astype(np.uint8)); fm.CopyInformation(fixed)
init = sitk.CenteredTransformInitializer(fixed, moving, sitk.Euler3DTransform(), sitk.CenteredTransformInitializerFilter.MOMENTS)
R = sitk.ImageRegistrationMethod()
R.SetMetricAsMattesMutualInformation(32); R.SetMetricSamplingStrategy(R.RANDOM); R.SetMetricSamplingPercentage(0.05, seed=0)
R.SetMetricFixedMask(fm)
R.SetOptimizerAsRegularStepGradientDescent(1.0, 1e-3, 60); R.SetOptimizerScalesFromPhysicalShift()
R.SetShrinkFactorsPerLevel([4, 2]); R.SetSmoothingSigmasPerLevel([2, 1]); R.SetInterpolator(sitk.sitkLinear)
R.SetInitialTransform(init, inPlace=False)
try:
tx = R.Execute(fixed, moving); metric = R.GetMetricValue()
except Exception:
tx = init; metric = float("nan")
out = sitk.Resample(raw_mov, fixed, tx, sitk.sitkLinear, 0.0)
return sitk.GetArrayFromImage(out).astype(np.float32), float(metric)
def mirror_diff_np(t1, M):
lo = ndi.minimum_filter(M, 3); hi = ndi.maximum_filter(M, 3)
d = t1 - np.clip(t1, lo, hi)
d[(t1 == 0) | (M == 0)] = 0
return d.astype(np.float32)
def quant(M):
return np.clip(np.round((M + Q_OFF) * Q_SC), 0, 255).astype(np.uint8) * (M != 0)
def dequant(q):
q = np.asarray(q, np.float32)
return np.where(q > 0, q / Q_SC - Q_OFF, 0.0).astype(np.float32)
def training_stems():
"""(folder, stem) for every drawer training key (Dataset979 split of the C2PCrop trainers)."""
import cascade2_common as C
keys = json.load(open(BC.B / "nnunet_preprocessed/Dataset979_D2C2Del/splits_final.json"))
fold = C.fold_index(C.DEL, "c2s2x_detA_ii_x")
tr = keys[fold]["train"]
out = []
for k in tr:
BC.guard(k); C.assert_train_key(k)
f, st = C.base_key(k)
out.append((str(f), st))
for k in keys[fold]["val"]: # monitoring-only val_* keys (never select weights)
BC.guard(k)
ks = key_stem(k)
if ks is not None:
out.append(ks)
return sorted(set(out))
def key_stem(key):
"""(folder, stem) holding a Dataset979 key's T1: syn_t1_* / r_* via cascade2_common.base_key; val_<X> (monitoring keys) are
symlinks to Dataset961 t0_<X>. -> None if unknown."""
import cascade2_common as C
if key.startswith("val_"):
return str(C.D961P), "t0_" + key[4:]
try:
f, st = C.base_key(key)
return str(f), st
except ValueError:
return None
def mirror_path(stem):
return MDIR / f"{stem}.b2nd"
def precompute(a):
import blosc2
MDIR.mkdir(parents=True, exist_ok=True)
stems = training_stems()[a.chunk::a.nchunk]
for f, st in stems:
op = mirror_path(st)
if op.exists():
continue
t0 = time.time()
arr = blosc2.open(urlpath=f"{f}/{st}.b2nd", mode="r")
t1 = np.asarray(arr[0], np.float32)
seg = np.asarray(blosc2.open(urlpath=f"{f}/{st}_seg.b2nd", mode="r")[0])
t1[seg == -1] = 0 # C2_ZERO_OUTSIDE convention
props = pickle.load(open(f"{f}/{st}.pkl", "rb"))
M, metric = mirror_pp(t1, props["sitk_stuff"]["direction"])
q = quant(M)
tmp = str(op) + f".tmp{os.getpid()}.b2nd"
blosc2.asarray(np.ascontiguousarray(q[None]), urlpath=tmp, mode="w", cparams={"codec": blosc2.Codec.ZSTD, "clevel": 5})
os.replace(tmp, op)
print(time.strftime("%H:%M:%S"), "MIRROR", st, t1.shape, f"metric {metric:.3f}", f"{time.time() - t0:.1f}s", flush=True)
print("MIRROR_DONE", a.chunk, a.nchunk, flush=True)
def main():
ap = argparse.ArgumentParser(); ap.add_argument("mode", choices=["precompute"])
ap.add_argument("--chunk", type=int, default=0); ap.add_argument("--nchunk", type=int, default=1)
a = ap.parse_args()
{"precompute": precompute}[a.mode](a)
if __name__ == "__main__":
main()