webapps / hmc /reference /scripts /motion_params.py
gdevenyi's picture
hmc: NiFreeze 3bcfb00 and QSIPrep 26.1.1 SHORELine reference runs on ds005577 sub-107 (part 9)
a4ba047 verified
Raw History Blame Contribute Delete
5.13 kB
"""Motion parameters from a NiFreeze HDF5 (M0).
The decomposition is QSIPrep 26.1.1 `get_ras_motion_params`
(qsiprep/interfaces/gradients.py, the RAS+ path), applied to NiFreeze's
`motion_affines`, which are already RAS matrices (reference -> scan):
- rotation: rotation vector (rad) of the rotation factor of transforms3d
`decompose44(m_ras)`;
- translation (mm): displacement of the point `center_mm = A[:3,:3] @ c`,
c = (shape - 1) / 2, by `m_ras`:
t = (m_ras[:3, 3] - center_mm) + m_ras[:3, :3] @ center_mm.
This is QSIPrep's formula verbatim: center_mm excludes the affine origin.
- framewise_displacement: SPM/Power convention, 50 mm radius, on these six
parameters, 0 for the first row (in volume order).
As a cross-check, each kept ITK `ants-NNNNN0GenericAffine.mat` is read with
scipy.io.loadmat, converted LPS -> RAS as QSIPrep does, mapped to the same
convention as NiFreeze (nitransforms `to_ras(reference=fixed, moving=moving)`;
both images share one grid), and compared with the HDF5 matrix.
Usage: python -I motion_params.py RUN_DIR
Writes RUN_DIR/motion.tsv and RUN_DIR/motion-check.json.
"""
import json
import sys
from pathlib import Path
import h5py
import nibabel as nb
import numpy as np
import pandas as pd
from scipy.io import loadmat
from scipy.spatial.transform import Rotation
from transforms3d.affines import decompose44
LPS2RAS = np.diag([-1.0, -1.0, 1.0, 1.0])
def ras_motion(m_ras: np.ndarray, shape, affine: np.ndarray) -> np.ndarray:
"""QSIPrep get_ras_motion_params on a RAS 4x4: scale, shear, rotvec, trans."""
_, rotmat, scale, shear = decompose44(m_ras)
rotation = Rotation.from_matrix(rotmat).as_rotvec()
src_center = (np.array(shape[:3]) - 1) / 2
center_mm = nb.affines.apply_affine(affine, src_center) - affine[:3, 3]
translation = np.zeros(3)
for i in range(3):
translation[i] = (m_ras[i, 3] - center_mm[i]) + (
m_ras[i, 0] * center_mm[0]
+ m_ras[i, 1] * center_mm[1]
+ m_ras[i, 2] * center_mm[2]
)
return np.concatenate([scale, shear, rotation, translation])
def itk_mat_to_ras(path: Path) -> np.ndarray:
"""ITK MatrixOffsetTransformBase .mat (LPS, about a centre) to a RAS 4x4."""
m = loadmat(str(path))
key = next(k for k in m if k.startswith("AffineTransform"))
params = m[key].ravel()
fixed = m["fixed"].ravel()
mat = params[:9].reshape(3, 3)
trans = params[9:12]
m_lps = np.eye(4)
m_lps[:3, :3] = mat
m_lps[:3, 3] = trans + fixed - mat @ fixed
return LPS2RAS @ m_lps @ LPS2RAS
def framewise_displacement(params: np.ndarray, radius: float = 50.0) -> np.ndarray:
"""Power et al. FD from (rot_x..z [rad], trans_x..z [mm]) rows."""
d = np.abs(np.diff(params, axis=0))
fd = d[:, 3:].sum(1) + radius * d[:, :3].sum(1)
return np.concatenate([[0.0], fd])
def main(run_dir: Path) -> None:
(h5_path,) = sorted((run_dir / "out").glob("*.h5"))
with h5py.File(h5_path, "r") as f:
root = f[next(iter(f.keys()))] if "dataobj" not in f else f
affines = np.asarray(root["motion_affines"])
affine = np.asarray(root["affine"])
shape = tuple(root["dataobj"].shape[:3])
rows = []
checks = []
work = run_dir / "work"
for i, m_ras in enumerate(affines):
p = ras_motion(m_ras, shape, affine)
rows.append(p)
mat = work / f"ants-{i:05d}0GenericAffine.mat"
if mat.exists():
from_itk = itk_mat_to_ras(mat)
# nitransforms to_ras gives the RAS map of the ITK (fixed -> moving) points.
checks.append(float(np.abs(from_itk - m_ras).max()))
rows = np.array(rows)
six = rows[:, [6, 7, 8, 9, 10, 11]]
facts = json.loads(Path("/var/tmp/dwi-hmc/inputs/input-facts.json").read_text())
b0 = set(facts["nifreeze_b0_indices"])
original = [k for k in range(facts["shape"][3]) if k not in b0]
df = pd.DataFrame(
{
"original_index": original,
"trans_x": rows[:, 9],
"trans_y": rows[:, 10],
"trans_z": rows[:, 11],
"rot_x": rows[:, 6],
"rot_y": rows[:, 7],
"rot_z": rows[:, 8],
"framewise_displacement": framewise_displacement(six),
"scale_x": rows[:, 0],
"scale_y": rows[:, 1],
"scale_z": rows[:, 2],
}
)
df.to_csv(run_dir / "motion.tsv", sep="\t", index=False, float_format="%.8f")
summary = {
"h5": str(h5_path),
"volumes": len(affines),
"grid_shape": list(shape),
"itk_mat_files_compared": len(checks),
"itk_vs_h5_max_abs": max(checks) if checks else None,
"max_abs_trans_mm": float(np.abs(rows[:, 9:12]).max()),
"max_abs_rot_deg": float(np.degrees(np.abs(rows[:, 6:9])).max()),
"max_abs_scale_minus_1": float(np.abs(rows[:, 0:3] - 1).max()),
"max_abs_shear": float(np.abs(rows[:, 3:6]).max()),
}
(run_dir / "motion-check.json").write_text(json.dumps(summary, indent=2))
print(json.dumps(summary, indent=1))
if __name__ == "__main__":
main(Path(sys.argv[1]))