Download runtime/code/whisper_synth/src/direction2/c4b_mirror.py from edschen/eagle-u-pair-2c: direct link, hf CLI and curl.
- Browser
- Download file 3.44 kB
-
https://huggingface.co/edschen/eagle-u-pair-2c/resolve/main/runtime/code/whisper_synth/src/direction2/c4b_mirror.py
- Command line
-
hf download hf://edschen/eagle-u-pair-2c/runtime/code/whisper_synth/src/direction2/c4b_mirror.py
-
curl -L -o c4b_mirror.py https://huggingface.co/edschen/eagle-u-pair-2c/resolve/main/runtime/code/whisper_synth/src/direction2/c4b_mirror.py
3.44 kB
| #!/usr/bin/env python | |
| """classifier4/B: mid-sagittal MIRROR TRANSFORMS (stk_mirror.fit_mirror: L-R flip + exhaustive rigid search, label-free, per image) | |
| for every case the B3-mirror evidence network touches: D331 TRAIN keys (training), DEV-A, CONTRA, test (inference). Only the transform | |
| (lr axis, 3x3 R, offset, ncc) is stored (a few numbers per case); the mirrored volume is rebuilt at load time with | |
| ndi.affine_transform (stk_mirror's own formula), so no volumes are written (storage). | |
| c4b_mirror.py --pop train|dev|contra|test --chunk i --nchunk n -> classifier4/B/mirror/<pop>_<i>_of_<n>.pkl | |
| c4b_mirror.py --merge -> classifier4/B/mirror/transforms.pkl (key -> lr, R, off, ncc) | |
| """ | |
| 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 | |
| def load(pop, key): | |
| import pickle | |
| if pop == "train": | |
| x = Q.load_b2(Q.D331P / f"{key}.b2nd", 0).astype(np.float32); sg = Q.load_b2(Q.D331P / f"{key}_seg.b2nd", 0) | |
| props = pickle.load(open(Q.guard(Q.D331P / f"{key}.pkl"), "rb")); brain = sg != -1 | |
| return np.where(brain, x, 0), brain, props | |
| import c4b_fm4feat as FF | |
| return FF.load(pop, key) | |
| def lr_of(props): | |
| import diag2_common as G | |
| return [a for a, (ph, sg) in enumerate(G.phys_axes(props)) if ph == 0][0] | |
| def apply_mirror(vol, tr, order=1): | |
| from scipy import ndimage as ndi | |
| v = np.ascontiguousarray(np.flip(vol.astype(np.float32), tr["lr"])) | |
| return ndi.affine_transform(v, np.array(tr["R"]), offset=np.array(tr["off"]), order=order, mode="constant", cval=0.0) | |
| def main(): | |
| import stk_mirror as MI | |
| ap = argparse.ArgumentParser(); ap.add_argument("--pop", default="train"); ap.add_argument("--chunk", type=int, default=0) | |
| ap.add_argument("--nchunk", type=int, default=1); ap.add_argument("--merge", action="store_true") | |
| a = ap.parse_args(); od = Q.OUT / "mirror" | |
| if a.merge: | |
| df = pd.concat([pd.read_pickle(f) for f in sorted(od.glob("*_of_*.pkl"))], ignore_index=True).drop_duplicates("key") | |
| df.to_pickle(Q.guard_write(od / "transforms.pkl")) | |
| print(df.groupby("pop").agg(n=("key", "size"), ncc_med=("ncc", "median"), ncc_p05=("ncc", lambda v: v.quantile(.05))).to_string()) | |
| return | |
| import dethead_common as H, dethead_cand as K, cls2_common as C2 | |
| keys = {"train": Q.train_keys, "dev": K.dev_keys, "contra": H.contra_keys, "test": C2.test_cids}[a.pop]()[a.chunk::a.nchunk] | |
| rows = []; t0 = time.time() | |
| for key in keys: | |
| try: | |
| t1, brain, props = load(a.pop, key) | |
| lr = lr_of(props) | |
| mirror, ncc = MI.fit_mirror(t1, brain, lr) | |
| cv = dict(zip(mirror.__code__.co_freevars, (c.cell_contents for c in mirror.__closure__))) | |
| rows.append(dict(pop=a.pop, key=key, lr=int(lr), R=np.asarray(cv["R"]).tolist(), off=np.asarray(cv["off"]).tolist(), ncc=float(ncc))) | |
| print("MIR", a.pop, key, f"ncc {ncc:.3f}", f"{time.time() - t0:.0f}s", flush=True) | |
| except Exception as e: # noqa: BLE001 | |
| print("FAIL", key, repr(e)[:200], flush=True) | |
| p = od / f"{a.pop}_{a.chunk}_of_{a.nchunk}.pkl"; Q.guard_write(p); p.parent.mkdir(parents=True, exist_ok=True) | |
| pd.DataFrame(rows).to_pickle(p) | |
| if __name__ == "__main__": | |
| main() | |