"""Fit and apply a constant offset for global CT-FM slab embeddings.""" import argparse from pathlib import Path from tempfile import NamedTemporaryFile import numpy as np def exam_residual(measurement, reference): if ( measurement.ndim != 2 or not len(measurement) or measurement.shape != reference.shape or measurement.shape[1] != 512 ): raise ValueError("Expected paired nonempty arrays of 512 features per slab") if not np.isfinite(measurement).all() or not np.isfinite(reference).all(): raise ValueError("Nonfinite calibration feature") return (reference.astype(np.float64) - measurement).mean(axis=0) def load_scan(path): with np.load(path) as scan: z, slab = scan["z0"], scan["slab"] if z.ndim != 1 or len(z) == 0 or slab.shape != (len(z), 512): raise ValueError(f"{path}: inconsistent slab coordinates or features") if ( not np.isfinite(z).all() or len(np.unique(z)) != len(z) or not np.isfinite(slab).all() ): raise ValueError(f"{path}: invalid slab coordinates or features") return z, slab def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) subs = parser.add_subparsers(dest="action", required=True) fit = subs.add_parser( "fit", help="pair equally named exam files from each directory" ) fit.add_argument("measurement_dir", type=Path) fit.add_argument("reference_dir", type=Path) fit.add_argument("out", type=Path) apply = subs.add_parser( "apply", help="write corrected global embeddings for one scan" ) apply.add_argument("offset", type=Path) apply.add_argument("scan", type=Path) apply.add_argument("out", type=Path) args = parser.parse_args(argv) if args.action == "fit": measurement = {p.name: p for p in args.measurement_dir.glob("*.npz")} reference = {p.name: p for p in args.reference_dir.glob("*.npz")} if not measurement or measurement.keys() != reference.keys(): parser.error( "Expected one matched pair of files per calibration examination" ) if args.out.resolve() in { p.resolve() for p in [*measurement.values(), *reference.values()] }: parser.error("Choose an offset file separate from the calibration scans") residuals = [] for name in sorted(measurement): z, x = load_scan(measurement[name]) rz, y = load_scan(reference[name]) if not np.array_equal(z, rz): raise ValueError(f"{name}: calibration slab coordinates differ") residuals.append(exam_residual(x, y)) arrays = {"offset": np.mean(residuals, axis=0), "examinations": len(residuals)} else: if args.out.resolve() in (args.scan.resolve(), args.offset.resolve()): parser.error("Choose an output path separate from the scan and offset") z, x = load_scan(args.scan) with np.load(args.offset) as saved: offset = saved["offset"] if offset.shape != (512,) or not np.isfinite(offset).all(): raise ValueError("Expected a finite 512-feature offset") arrays = {"z0": z, "slab": x.astype(float) + offset} with NamedTemporaryFile(dir=args.out.parent, delete=False) as file: tmp = Path(file.name) try: np.savez_compressed(file, **arrays) file.flush() tmp.replace(args.out) finally: tmp.unlink(missing_ok=True) if __name__ == "__main__": main()