File size: 5,176 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
128
129
130
131
132
133
134
135
"""Q53 seed-spread rule: compare gp-float against gp with the gp vs gp-seed1235 spread.

Per volume and per axis (trans x/y/z in mm, rot x/y/z in deg), it computes
|float - double| and |double seed 1234 - double seed 1235|, with the translation about the
world grid centre and by QSIPrep's formula (pivot A[:3,:3] @ c on the raw DWI grid).
It evaluates three candidate rules and prints the per-axis spread limits. It also checks
that the 90 GP predictions are byte-identical in the three GP runs and prints the pivots.

Usage: python -I q53_seed_rule.py OUT.json
"""

import hashlib
import json
import sys
from pathlib import Path

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

R = Path("/var/tmp/dwi-hmc/runs")
BVAL = Path("/var/tmp/dwi-data/ds005577/sub-107_dir-AP_dwi.bval")
DWI = Path("/var/tmp/dwi-data/ds005577/sub-107_dir-AP_dwi.nii.gz")
B0MEAN = (
    R / "qsiprep-e1/work/qsiprep_26_1_wf/sub_107_wf/dwi_preproc_dir_AP_wf"
    "/qsiprep_hmcsdc_wf/dwi_hmc_wf/dwi_model_hmc_wf/b0_mean/b0_mean.nii.gz"
)
AXES = ("tx", "ty", "tz", "rx", "ry", "rz")


def sha(p):
    return hashlib.sha256(p.read_bytes()).hexdigest()


def load(run):
    (p,) = sorted((R / run / "out").glob("*.h5"))
    with h5py.File(p, "r") as h5:
        return np.asarray(h5["0/motion_affines"]), np.asarray(h5["0/affine"])


def params(ms, pivot):
    out = []
    for m in ms:
        t = m[:3, :3] @ pivot + m[:3, 3] - pivot
        r = np.degrees(Rotation.from_matrix(m[:3, :3]).as_rotvec())
        out.append(np.concatenate([t, r]))
    return np.array(out)


def main(out):
    preds = {}
    for run in ("nifreeze-gp", "nifreeze-gp-float", "nifreeze-gp-seed1235"):
        preds[run] = [
            sha(p) for p in sorted((R / run / "work").glob("predicted_*.nii.gz"))
        ]
    ref = preds["nifreeze-gp"]
    pred_equal = {k: v == ref for k, v in preds.items()}
    pred_count = {k: len(v) for k, v in preds.items()}

    img = nb.load(DWI)
    c = (np.array(img.shape[:3]) - 1) / 2
    piv_nifreeze = img.affine[:3, :3] @ c
    b0m = nb.load(B0MEAN)
    cb = (np.array(b0m.shape[:3]) - 1) / 2
    piv_qsiprep = b0m.affine[:3, :3] @ cb
    pivots = {
        "nifreeze_raw_grid": {
            "axcodes": "".join(nb.aff2axcodes(img.affine)),
            "pivot_A3c": piv_nifreeze.round(2).tolist(),
            "norm_mm": float(np.linalg.norm(piv_nifreeze)),
            "world_centre": (piv_nifreeze + img.affine[:3, 3]).round(2).tolist(),
        },
        "qsiprep_b0_mean_grid": {
            "axcodes": "".join(nb.aff2axcodes(b0m.affine)),
            "shape": list(b0m.shape),
            "pivot_A3c": piv_qsiprep.round(2).tolist(),
            "norm_mm": float(np.linalg.norm(piv_qsiprep)),
            "world_centre": (piv_qsiprep + b0m.affine[:3, 3]).round(2).tolist(),
        },
    }

    bvals = np.rint(np.loadtxt(BVAL)).astype(int)
    dwi_b = bvals[bvals > 50]
    md, aff = load("nifreeze-gp")
    mf, _ = load("nifreeze-gp-float")
    ms, _ = load("nifreeze-gp-seed1235")
    world_c = nb.affines.apply_affine(aff, c)
    res = {"pred_equal_to_gp": pred_equal, "pred_count": pred_count, "pivots": pivots}
    for conv, pivot in (("world", world_c), ("qsiprep", aff[:3, :3] @ c)):
        pd, pf, ps = params(md, pivot), params(mf, pivot), params(ms, pivot)
        d_float = np.abs(pf - pd)
        d_seed = np.abs(ps - pd)
        r = {}
        # Rule A: each cell, |float - double| <= |seed1235 - seed1234| of that cell.
        cell = d_float <= d_seed
        r["A_cell_fail_cells"] = int((~cell).sum())
        r["A_cell_fail_volumes"] = int((~cell.all(axis=1)).sum())
        # Rule B: per shell and axis, limit = max over the shell's volumes of d_seed.
        lim_b = {}
        fail_b = np.zeros(len(dwi_b), bool)
        for s in sorted(set(dwi_b.tolist())):
            sel = dwi_b == s
            lim = d_seed[sel].max(axis=0)
            lim_b[str(s)] = dict(zip(AXES, lim.round(4).tolist(), strict=True))
            fail_b[sel] = (d_float[sel] > lim).any(axis=1)
        r["B_shell_axis_max_limits"] = lim_b
        r["B_fail_volumes"] = int(fail_b.sum())
        # Rule C: per axis over all 90 volumes, limit = max of d_seed.
        lim_c = d_seed.max(axis=0)
        r["C_axis_max_limits"] = dict(zip(AXES, lim_c.round(4).tolist(), strict=True))
        r["C_fail_volumes"] = int((d_float > lim_c).any(axis=1).sum())
        r["float_max_per_axis"] = dict(
            zip(AXES, d_float.max(axis=0).round(4).tolist(), strict=True)
        )
        r["seed_median_per_axis"] = dict(
            zip(AXES, np.median(d_seed, axis=0).round(4).tolist(), strict=True)
        )
        r["float_median_per_axis"] = dict(
            zip(AXES, np.median(d_float, axis=0).round(4).tolist(), strict=True)
        )
        r["ratio_float_over_seed_limit_B_max"] = float(
            max(
                (d_float[dwi_b == s] / d_seed[dwi_b == s].max(axis=0)).max()
                for s in set(dwi_b.tolist())
            )
        )
        res[conv] = r
    Path(out).write_text(json.dumps(res, indent=1) + "\n")
    print(json.dumps(res, indent=1))


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