File size: 3,603 Bytes
76eb7b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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()