File size: 2,315 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 | """Record input facts of the DWI as NiFreeze loads it (M0, Q55).
Usage: python -I input_facts.py DWI.nii.gz BVEC BVAL OUT.json
"""
import json
import sys
import nibabel as nb
import numpy as np
from nifreeze.data.dmri import from_nii
from nifreeze.data.dmri.utils import DEFAULT_LOWB_THRESHOLD, format_gradients
dwi_path, bvec_path, bval_path, out_path = sys.argv[1:5]
img = nb.load(dwi_path)
hdr = img.header
slope, inter = hdr.get_slope_inter()
raw_slope = float(hdr["scl_slope"])
raw_inter = float(hdr["scl_inter"])
bvals = np.loadtxt(bval_path)
bvecs = np.loadtxt(bvec_path)
# NiFreeze rule: b-vectors with |g| not 1 (atol 1e-2) are normalised and b *= |g|;
# near-zero vectors are zeroed; b <= 50 is a b0.
grad = format_gradients(
np.column_stack((bvecs.T.astype("float32"), bvals.astype("float32")))
)
nf_b = grad[:, -1]
nf_b0 = nf_b <= DEFAULT_LOWB_THRESHOLD
norms = np.linalg.norm(bvecs.T, axis=1)
ds = from_nii(dwi_path, bvec_file=bvec_path, bval_file=bval_path)
facts = {
"file": dwi_path,
"shape": list(img.shape),
"zooms": [float(z) for z in hdr.get_zooms()],
"on_disk_dtype": str(hdr.get_data_dtype()),
"scl_slope_raw": raw_slope,
"scl_inter_raw": raw_inter,
"nibabel_slope_inter": [slope, inter],
"qform_code": int(hdr["qform_code"]),
"sform_code": int(hdr["sform_code"]),
"affine": img.affine.tolist(),
"bvals_unique": sorted({round(float(b)) for b in bvals}),
"bvec_norm_min_nonzero": float(norms[norms > 1e-2].min()),
"bvec_norm_max": float(norms.max()),
"nifreeze_b0_threshold": DEFAULT_LOWB_THRESHOLD,
"nifreeze_b0_count": int(nf_b0.sum()),
"nifreeze_b0_indices": np.flatnonzero(nf_b0).tolist(),
"plain_b_lt_50_count": int((bvals < 50).sum()),
"nifreeze_dwi_count": int((~nf_b0).sum()),
"nifreeze_dataobj_dtype": str(ds.dataobj.dtype),
"nifreeze_dataobj_is_float": bool(np.issubdtype(ds.dataobj.dtype, np.floating)),
"nifreeze_dataobj_shape": list(ds.dataobj.shape),
"nifreeze_bzero_dtype": str(ds.bzero.dtype),
"nifreeze_bzero_is_float": bool(np.issubdtype(ds.bzero.dtype, np.floating)),
"nifreeze_gradients_dtype": str(ds.gradients.dtype),
}
with open(out_path, "w") as f:
json.dump(facts, f, indent=2)
print(json.dumps({k: v for k, v in facts.items() if k != "affine"}, indent=1))
|