edschen's picture
EAGLE model u_pair_2c v1 (part 3)
473c56f verified
Raw History Blame Contribute Delete
6.61 kB
"""Pinnacle v2 helper functions. VERBATIM copies (so the runner is self-contained for external runs; the smoke job checks them against
the originals):
- kmeans1d, _nconv, tissue, hyst, connected_to, gate_add:
whisper_synth/outputs/direction2/diag_external/t3_generosity/scripts/t3_common.py
- main_peak, attached:
whisper_synth/outputs/direction2/diag_external/t3_swap_ladder/scripts/ladder_score2.py
plus the join / hysteresis compositions used by run_pinv2.py (ladder_score2.run 'att' / 'mainpk', t3_test HGATE / sgate).
"""
import numpy as np
import scipy.ndimage as ndi
# ------------------------------------------------------------------------------------------------ t3_common.py (verbatim)
def _nconv(x, w, sig_vox):
num = ndi.gaussian_filter(x * w, sig_vox); den = ndi.gaussian_filter(w.astype(np.float32), sig_vox)
return num, den
def kmeans1d(v, k=3, it=40):
c = np.quantile(v, [0.1, 0.5, 0.9])
for _ in range(it):
a = np.argmin(np.abs(v[:, None] - c[None]), 1)
c2 = np.array([v[a == j].mean() if (a == j).any() else c[j] for j in range(k)])
if np.allclose(c2, c): break
c = c2
return np.sort(c)
def tissue(t1, brain, sp, rng_seed=0):
sp = np.asarray(sp, float)
b = brain.astype(np.float32)
num, den = _nconv(t1.astype(np.float32), b, 1.0 / sp)
t1s = np.where(den > 1e-3, num / np.maximum(den, 1e-3), 0).astype(np.float32)
v = t1s[brain]
floor = float(np.percentile(v, 2))
rng = np.random.default_rng(rng_seed)
sub = v[rng.integers(0, v.size, min(v.size, 300000))]
mu = kmeans1d(sub)
wm = brain & (t1s > 0.5 * (mu[1] + mu[2]))
num, den = _nconv(t1s, wm.astype(np.float32), 10.0 / sp)
nawm = np.where(den > 0.05, num / np.maximum(den, 1e-6), mu[2]).astype(np.float32)
rec = np.where(brain, (t1s - floor) / np.maximum(nawm - floor, 1e-3), 9.0).astype(np.float32)
aux = dict(floor=floor, mu_csf=float(mu[0]), mu_gm=float(mu[1]), mu_wm=float(mu[2]),
gm_rec=float((mu[1] - floor) / max(mu[2] - floor, 1e-3)), csf_rec=float((mu[0] - floor) / max(mu[2] - floor, 1e-3)))
aux["thr_cg"] = 0.5 * (aux["gm_rec"] + aux["csf_rec"]); aux["thr_gw"] = 0.5 * (aux["gm_rec"] + 1.0)
return rec, wm, aux
def hyst(prob, hi, lo):
import cc3d
seed = prob >= hi
if not seed.any():
return seed
lab = cc3d.connected_components((prob >= lo).astype(np.uint8), connectivity=26)
ids = np.unique(lab[seed]); ids = ids[ids > 0]
return np.isin(lab, ids)
def connected_to(seed, cand):
"""voxels of (seed | cand) in 26-components that contain seed voxels."""
import cc3d
u = seed | cand
if not seed.any():
return seed.copy()
lab = cc3d.connected_components(u.astype(np.uint8), connectivity=26)
ids = np.unique(lab[seed]); ids = ids[ids > 0]
return np.isin(lab, ids)
def gate_add(b, big, rec, thr):
"""keep b, plus the part of (big \\ b) with rec < thr that stays 26-connected to b (T1-gated version of a growth step)."""
add = big & ~b & (rec < thr)
return connected_to(b, add)
# ------------------------------------------------------------------------------------------------ ladder_score2.py (verbatim)
def main_peak(P, la, heat, main):
"""one piece per prompt: per accepted candidate, the forced-draw component containing the candidate's heat-peak voxel; if no
component contains it, the largest component linked to the candidate (= int_compose.extras_map main piece)."""
import cc3d, int_compose as IC
base, _ = IC.forced_draw(P, la)
lab = cc3d.connected_components(base.astype(np.uint8), connectivity=26)
keep = set(); lm = cc3d.connected_components(main.astype(np.uint8), connectivity=26) # noqa: F841 (verbatim)
for c, o in enumerate(ndi.find_objects(la), start=1):
if o is None:
continue
m = la[o] == c
if not m.any():
continue
hh = np.where(m, heat[o], -1.0); pk = np.unravel_index(int(np.argmax(hh)), hh.shape)
k = int(lab[o][pk])
if k:
keep.add(k); continue
sl = tuple(slice(max(x.start - 3, 0), min(x.stop + 3, n)) for x, n in zip(o, la.shape))
mm = la[sl] == c; md = IC.cube_dil(mm, 2)
ids = np.unique(lab[sl][md & main[sl]]); keep.update(int(i) for i in ids if i > 0)
return np.isin(lab, sorted(keep)) if keep else np.zeros_like(base)
def attached(base, add):
import cc3d
a = add & ~base
if not base.any() or not a.any():
return np.zeros_like(base)
lab = cc3d.connected_components((base | a).astype(np.uint8), connectivity=26)
ids = np.unique(lab[base]); ids = ids[ids > 0]
return np.isin(lab, ids) & a
# ------------------------------------------------------------------------------------------------ pinv2 compositions
def drawer_joins(P, la, heat):
"""-> {join: drawing contribution} for the three joins (before the union with a base):
none = int_compose.compose_full(P, la, 'dm') (legacy PIN: drawn components touching cube-dil-2 of an accepted candidate)
onepiece = main_peak (the forced-draw piece containing each accepted candidate's heat-peak voxel)
'attached' depends on the base and is made by join_with_base."""
import int_compose as IC
dm = IC.compose_full(P, la, "dm")
main, _ = IC.extras_map(P, la)
mpk = main_peak(P, la, heat, main)
return {"none": np.asarray(dm, bool), "onepiece": np.asarray(mpk, bool)}
def join_with_base(join, B, J):
"""final drawing contribution for join given base mask B and drawer_joins() output J (ladder_score2 'att' formula for attached)."""
import cc3d
if join in ("none", "onepiece"):
return J[join]
assert join == "attached", join
aL = attached(B, J["none"]); det = J["none"] & ~B & ~aL
Ld = cc3d.connected_components(det.astype(np.uint8), connectivity=26)
idm = np.unique(Ld[det & J["onepiece"]]); idm = idm[idm > 0]
return aL | (np.isin(Ld, idm) if len(idm) else np.zeros_like(det))
def hyst_base(B, pB, rec, thr, hi=0.5, lo=0.1):
"""t3_generosity HGATE: B + T1-gated (rec < thr) part of hyst(pB, hi, lo), connected to B."""
return gate_add(B, hyst(pB, hi, lo), rec, thr)
def hyst_drawing(D, P, rec, thr, brain, sp, lo=0.1):
"""t3_generosity 'sgate': D + T1-gated part of its S* growth (int_softjoin.generous(D, P, lo, 0): connected drawer p >= lo)."""
import int_softjoin as SJ
if not D.any():
return D.copy()
return gate_add(D, np.asarray(SJ.generous(D, P, lo, 0, None, None, None, brain, sp), bool), rec, thr)