File size: 5,123 Bytes
a4ba047
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
"""Q53 extra view: --float 1 vs double on a well-posed problem (b0 to b0).

Each of the 11 raw b0 volumes is registered to the trivial model's prediction
(the b0 reference that NiFreeze uses, predicted_00000 of run a1) with the exact
antsRegistration command line that NiFreeze ran (work/cmd-00000.sh of run a1),
once in double and once with --float 1. Same mask, one ITK thread.
The motion of each pair is compared (RAS, about the world grid centre, and with
QSIPrep's verbatim formula) against the gate 0.2 mm / 0.2 deg per axis.

Usage: python -I q53_b0.py OUT_DIR ANTS_BIN
"""

import json
import os
import shlex
import subprocess
import sys
from pathlib import Path

import nibabel as nb
import numpy as np
from scipy.io import loadmat
from scipy.spatial.transform import Rotation

A1 = Path("/var/tmp/dwi-hmc/runs/nifreeze-trivial-a1/work")
DWI = Path("/var/tmp/dwi-data/ds005577/sub-107_dir-AP_dwi.nii.gz")
FACTS = Path("/var/tmp/dwi-hmc/inputs/input-facts.json")
LPS2RAS = np.diag([-1.0, -1.0, 1.0, 1.0])


def itk_to_ras(path: Path) -> np.ndarray:
    m = loadmat(str(path))
    key = next(k for k in m if k.startswith("AffineTransform"))
    p = m[key].ravel()
    fixed = m["fixed"].ravel()
    mat = p[:9].reshape(3, 3)
    m_lps = np.eye(4)
    m_lps[:3, :3] = mat
    m_lps[:3, 3] = p[9:12] + fixed - mat @ fixed
    return LPS2RAS @ m_lps @ LPS2RAS


def params(m: np.ndarray, centre: np.ndarray) -> np.ndarray:
    rot = np.degrees(Rotation.from_matrix(m[:3, :3]).as_rotvec())
    t = m[:3, :3] @ centre + m[:3, 3] - centre
    return np.concatenate([t, rot])


def main(out: Path, ants_bin: Path) -> None:
    out.mkdir(parents=True, exist_ok=True)
    img = nb.load(DWI)
    b0 = json.loads(FACTS.read_text())["nifreeze_b0_indices"]
    template = shlex.split((A1 / "cmd-00000.sh").read_text().strip())
    fixed = str(A1 / "predicted_00000.nii.gz")
    env = dict(os.environ, ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS="1")
    shape = img.shape[:3]
    c = (np.array(shape) - 1) / 2
    world_c = nb.affines.apply_affine(img.affine, c)
    qsi_c = world_c - img.affine[:3, 3]
    rows = []
    for k in b0:
        vol = np.asanyarray(img.dataobj[..., k]).astype(np.float32)
        moving = out / f"b0_{k:03d}.nii.gz"
        nb.Nifti1Image(vol, img.affine, img.header).to_filename(moving)
        res = {}
        # NiFreeze sets ANTS_RANDOM_SEED=--seed; the second seed measures how much
        # the Random sampling alone moves the result (noise floor for Q53).
        for name, prec, seed in (
            ("double", "double", "1234"),
            ("float", "float", "1234"),
            ("double_seed1235", "double", "1235"),
        ):
            prefix = str(out / f"{name}-{k:03d}_")
            argv = []
            for a in template:
                a = a.replace(str(A1 / f"sample_{0:05d}.nii.gz"), str(moving))
                a = a.replace(str(A1 / f"predicted_{0:05d}.nii.gz"), fixed)
                argv.append(a)
            argv[0] = str(ants_bin / "antsRegistration")
            argv[argv.index("--output") + 1] = prefix
            if prec == "float":
                argv += ["--float", "1"]
            run_env = dict(env, ANTS_RANDOM_SEED=seed)
            subprocess.run(argv, check=True, capture_output=True, env=run_env, cwd=out)
            m = itk_to_ras(Path(prefix + "0GenericAffine.mat"))
            res[name] = (params(m, world_c), params(m, qsi_c))
        row = {
            "original_index": k,
            "double_world_t_mm": res["double"][0][:3].tolist(),
            "double_rot_deg": res["double"][0][3:].tolist(),
        }
        for label, other in (("float", "float"), ("seed", "double_seed1235")):
            d_world = np.abs(res["double"][0] - res[other][0])
            d_qsi = np.abs(res["double"][1] - res[other][1])
            row[f"{label}_max_abs_dt_world_mm"] = float(d_world[:3].max())
            row[f"{label}_max_abs_dt_qsiprep_mm"] = float(d_qsi[:3].max())
            row[f"{label}_max_abs_drot_deg"] = float(d_world[3:].max())
            row[f"{label}_within_gate_world"] = bool(
                d_world[:3].max() <= 0.2 and d_world[3:].max() <= 0.2
            )
            row[f"{label}_within_gate_qsiprep"] = bool(
                d_qsi[:3].max() <= 0.2 and d_qsi[3:].max() <= 0.2
            )
        rows.append(row)
        print(json.dumps(rows[-1]))
    summary = {
        "fixed": fixed,
        "template": str(A1 / "cmd-00000.sh"),
        "ants_random_seed": "1234 (both precisions); 1235 for the seed view",
        "volumes": len(rows),
    }
    for label in ("float", "seed"):
        for key in (
            "max_abs_dt_world_mm",
            "max_abs_dt_qsiprep_mm",
            "max_abs_drot_deg",
        ):
            summary[f"{label}_{key}"] = max(r[f"{label}_{key}"] for r in rows)
        for key in ("within_gate_world", "within_gate_qsiprep"):
            summary[f"{label}_n_{key}"] = sum(r[f"{label}_{key}"] for r in rows)
    summary["rows"] = rows
    (out / "q53-b0-summary.json").write_text(json.dumps(summary, indent=2))


if __name__ == "__main__":
    main(Path(sys.argv[1]), Path(sys.argv[2]))