Download hmc/reference/scripts/qc_registration.py from neurodeskorg/webapps: direct link, hf CLI and curl.
- Browser
- Download file 9.37 kB
-
https://huggingface.co/datasets/neurodeskorg/webapps/resolve/main/hmc/reference/scripts/qc_registration.py
- Command line
-
hf download hf://datasets/neurodeskorg/webapps/hmc/reference/scripts/qc_registration.py
-
curl -L -o qc_registration.py https://huggingface.co/datasets/neurodeskorg/webapps/resolve/main/hmc/reference/scripts/qc_registration.py
9.37 kB
| """QC of NiFreeze per-volume registrations (M0, stage 1). | |
| For each volume of a run (kept work/ intermediates): | |
| - motion from the HDF5 matrix (RAS, reference -> scan): | |
| rotation angle (deg), translation by QSIPrep's verbatim formula (about the | |
| point A[:3,:3] @ c, origin excluded), translation of the true world grid | |
| centre A @ c (origin included), mean and max displacement of the mask voxels; | |
| - image agreement inside the mask, before (sample as is) and after | |
| (sample resampled with antsApplyTransforms and the kept ITK .mat): | |
| Pearson r and NMI with the prediction (registration target), and Pearson r | |
| with the mean of the raw volumes of the same shell (an independent target: | |
| for a still subject the raw volumes are already aligned). | |
| Usage: python -I qc_registration.py RUN_DIR OUT_DIR ANTS_BIN | |
| Writes OUT_DIR/<run>-qc.tsv and OUT_DIR/<run>-qc-summary.json, and PNG overlays. | |
| """ | |
| import json | |
| import subprocess | |
| import sys | |
| from pathlib import Path | |
| import h5py | |
| import matplotlib | |
| import nibabel as nb | |
| import numpy as np | |
| from scipy.spatial.transform import Rotation | |
| matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt | |
| FACTS = Path("/var/tmp/dwi-hmc/inputs/input-facts.json") | |
| BVAL = Path("/var/tmp/dwi-data/ds005577/sub-107_dir-AP_dwi.bval") | |
| def nmi(a: np.ndarray, b: np.ndarray, bins: int = 64) -> float: | |
| h, _, _ = np.histogram2d(a, b, bins=bins) | |
| p = h / h.sum() | |
| px = p.sum(1) | |
| py = p.sum(0) | |
| nz = p > 0 | |
| hxy = -np.sum(p[nz] * np.log(p[nz])) | |
| hx = -np.sum(px[px > 0] * np.log(px[px > 0])) | |
| hy = -np.sum(py[py > 0] * np.log(py[py > 0])) | |
| return float((hx + hy) / hxy) | |
| def corr(a: np.ndarray, b: np.ndarray) -> float: | |
| return float(np.corrcoef(a, b)[0, 1]) | |
| def warp(ants_bin: Path, sample: Path, ref: Path, mat: Path, out: Path) -> None: | |
| cmd = [ | |
| str(ants_bin / "antsApplyTransforms"), | |
| "-d", | |
| "3", | |
| "-i", | |
| str(sample), | |
| "-r", | |
| str(ref), | |
| "-t", | |
| str(mat), | |
| "-n", | |
| "Linear", | |
| "-o", | |
| str(out), | |
| "--float", | |
| "0", | |
| ] | |
| subprocess.run(cmd, check=True, capture_output=True) | |
| def png(path: Path, title: str, pred, samp, warped, mask) -> None: | |
| k = pred.shape[2] // 2 | |
| j = pred.shape[1] // 2 | |
| fig, axes = plt.subplots(2, 3, figsize=(12, 8)) | |
| for row, sl in enumerate( | |
| [lambda v: v[:, :, k].T, lambda v: v[:, j, :].T], | |
| ): | |
| for col, (name, vol) in enumerate( | |
| [ | |
| ("prediction (target)", pred), | |
| ("sample before", samp), | |
| ("sample after", warped), | |
| ] | |
| ): | |
| ax = axes[row, col] | |
| img = sl(vol) | |
| lo, hi = np.percentile(vol[mask], [1, 99]) | |
| ax.imshow(img, cmap="gray", origin="lower", vmin=lo, vmax=hi) | |
| ax.contour(sl(mask.astype(float)), levels=[0.5], colors="r", linewidths=0.6) | |
| ax.contour( | |
| sl(pred), | |
| levels=[np.percentile(pred[mask], 60)], | |
| colors="c", | |
| linewidths=0.5, | |
| ) | |
| ax.set_title(name, fontsize=9) | |
| ax.axis("off") | |
| fig.suptitle(title + "\nred: mask; cyan: prediction iso-line", fontsize=9) | |
| fig.tight_layout() | |
| fig.savefig(path, dpi=90) | |
| plt.close(fig) | |
| def main(run_dir: Path, out_dir: Path, ants_bin: Path) -> None: | |
| name = run_dir.name | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| wdir = out_dir / f"{name}-warped" | |
| wdir.mkdir(exist_ok=True) | |
| facts = json.loads(FACTS.read_text()) | |
| b0 = set(facts["nifreeze_b0_indices"]) | |
| bvals = np.rint(np.loadtxt(BVAL)).astype(int).tolist() | |
| original = [k for k in range(len(bvals)) if k not in b0] | |
| (h5_path,) = sorted((run_dir / "out").glob("*.h5")) | |
| with h5py.File(h5_path, "r") as h5: | |
| f = h5.get("0", h5) | |
| affines = np.asarray(f["motion_affines"]) | |
| affine = np.asarray(f["affine"]) | |
| work = run_dir / "work" | |
| mimg = nb.load(work / "brainmask.nii.gz") | |
| mask = np.asanyarray(mimg.dataobj) > 0 | |
| shape = mask.shape | |
| c = (np.array(shape) - 1) / 2 | |
| center_world = nb.affines.apply_affine(affine, c) | |
| center_qsiprep = center_world - affine[:3, 3] | |
| ijk = np.argwhere(mask) | |
| xyz = nb.affines.apply_affine(affine, ijk) | |
| samples = {} | |
| for i in range(len(affines)): | |
| samples[i] = np.asanyarray( | |
| nb.load(work / f"sample_{i:05d}.nii.gz").dataobj | |
| ).astype(np.float64) | |
| shell_mean = {} | |
| for b in sorted({bvals[k] for k in original}): | |
| idx = [i for i, k in enumerate(original) if bvals[k] == b] | |
| shell_mean[b] = np.mean([samples[i] for i in idx], axis=0) | |
| rows = [] | |
| for i, m in enumerate(affines): | |
| k = original[i] | |
| b = bvals[k] | |
| rotvec = Rotation.from_matrix(m[:3, :3]).as_rotvec() | |
| t_qsi = m[:3, :3] @ center_qsiprep + m[:3, 3] - center_qsiprep | |
| t_ctr = m[:3, :3] @ center_world + m[:3, 3] - center_world | |
| disp = np.linalg.norm(xyz @ m[:3, :3].T + m[:3, 3] - xyz, axis=1) | |
| pred_path = work / f"predicted_{i:05d}.nii.gz" | |
| samp_path = work / f"sample_{i:05d}.nii.gz" | |
| mat = work / f"ants-{i:05d}0GenericAffine.mat" | |
| wpath = wdir / f"warped_{i:05d}.nii.gz" | |
| warp(ants_bin, samp_path, pred_path, mat, wpath) | |
| pred = np.asanyarray(nb.load(pred_path).dataobj).astype(np.float64) | |
| warped = np.asanyarray(nb.load(wpath).dataobj).astype(np.float64) | |
| samp = samples[i] | |
| sm = shell_mean[b] | |
| rows.append( | |
| { | |
| "vol": i, | |
| "original_index": k, | |
| "bval": b, | |
| "rot_deg": float(np.degrees(np.linalg.norm(rotvec))), | |
| "t_qsiprep_norm_mm": float(np.linalg.norm(t_qsi)), | |
| "t_world_centre_norm_mm": float(np.linalg.norm(t_ctr)), | |
| "t_world_centre_x": float(t_ctr[0]), | |
| "t_world_centre_y": float(t_ctr[1]), | |
| "t_world_centre_z": float(t_ctr[2]), | |
| "mask_disp_mean_mm": float(disp.mean()), | |
| "mask_disp_max_mm": float(disp.max()), | |
| "r_pred_before": corr(pred[mask], samp[mask]), | |
| "r_pred_after": corr(pred[mask], warped[mask]), | |
| "nmi_pred_before": nmi(pred[mask], samp[mask]), | |
| "nmi_pred_after": nmi(pred[mask], warped[mask]), | |
| "r_shellmean_before": corr(sm[mask], samp[mask]), | |
| "r_shellmean_after": corr(sm[mask], warped[mask]), | |
| } | |
| ) | |
| keys = list(rows[0].keys()) | |
| with open(out_dir / f"{name}-qc.tsv", "w") as f: | |
| f.write("\t".join(keys) + "\n") | |
| for r in rows: | |
| f.write( | |
| "\t".join( | |
| f"{r[k]:.6f}" if isinstance(r[k], float) else str(r[k]) | |
| for k in keys | |
| ) | |
| ) | |
| f.write("\n") | |
| summary = {"run": str(run_dir), "volumes": len(rows), "by_shell": {}} | |
| for b in sorted(shell_mean): | |
| rs = [r for r in rows if r["bval"] == b] | |
| def stat(key, rs=rs): | |
| v = np.array([r[key] for r in rs]) | |
| return { | |
| "median": float(np.median(v)), | |
| "min": float(v.min()), | |
| "max": float(v.max()), | |
| } | |
| worse = [ | |
| r["original_index"] | |
| for r in rs | |
| if r["r_shellmean_after"] < r["r_shellmean_before"] - 0.02 | |
| ] | |
| summary["by_shell"][str(b)] = { | |
| "volumes": len(rs), | |
| **{ | |
| k: stat(k) | |
| for k in [ | |
| "rot_deg", | |
| "t_qsiprep_norm_mm", | |
| "t_world_centre_norm_mm", | |
| "mask_disp_mean_mm", | |
| "r_pred_before", | |
| "r_pred_after", | |
| "nmi_pred_before", | |
| "nmi_pred_after", | |
| "r_shellmean_before", | |
| "r_shellmean_after", | |
| ] | |
| }, | |
| "n_shellmean_r_drop_gt_0.02": len(worse), | |
| "shellmean_r_drop_gt_0.02_original_index": worse, | |
| } | |
| (out_dir / f"{name}-qc-summary.json").write_text(json.dumps(summary, indent=2)) | |
| # PNGs: largest-displacement b3000, median b3000, largest b1000. | |
| picks = [] | |
| for b in (3000, 1000): | |
| rs = sorted( | |
| (r for r in rows if r["bval"] == b), key=lambda r: r["mask_disp_mean_mm"] | |
| ) | |
| if rs: | |
| picks.append(rs[-1]) | |
| if b == 3000: | |
| picks.append(rs[len(rs) // 2]) | |
| for r in picks: | |
| i = r["vol"] | |
| pred = np.asanyarray(nb.load(work / f"predicted_{i:05d}.nii.gz").dataobj) | |
| warped = np.asanyarray(nb.load(wdir / f"warped_{i:05d}.nii.gz").dataobj) | |
| title = ( | |
| f"{name} vol {r['original_index']} b{r['bval']}: mean mask disp " | |
| f"{r['mask_disp_mean_mm']:.1f} mm, rot {r['rot_deg']:.2f} deg; " | |
| f"r(shell mean) {r['r_shellmean_before']:.3f} -> {r['r_shellmean_after']:.3f}" | |
| ) | |
| png( | |
| out_dir / f"{name}-vol{r['original_index']:03d}-b{r['bval']}.png", | |
| title, | |
| pred, | |
| samples[i], | |
| warped, | |
| mask, | |
| ) | |
| print(json.dumps(summary, indent=1)) | |
| if __name__ == "__main__": | |
| main(Path(sys.argv[1]), Path(sys.argv[2]), Path(sys.argv[3])) | |