How to Use¶
Incorporating NiFreeze into a Python module or script¶
To utilize NiFreeze functionalities within your Python module or script, follow these steps:
Import NiFreeze Components: Start by importing necessary components from the NiFreeze package:
To use NiFreeze you will typically need to use three main components:
Some data: allows to build a construct over your data that allows the model and the estimator objects to deal with the data in a standardized manner.
A model: establishes the predictive model used to estimate the generate the registration target. It will typically implement the
fitandpredictmethods. It is specified when instantiating the estimator.An estimator: orchestrates the registration target prediction.
The same approach applies to any 4D modality data. For illustrative purposes, we will use some dMRI data:
# Import required components from the nifreeze package from nifreeze.data import dmri from nifreeze.estimator import Estimator
Load 4D Data: Load your 4D data into a dataset object using the
load()function.Use the appropriate parameters for the particular imaging modality (e.g. dMRI, fMRI, or PET) that you are using.
For example, for dMRI data, ensure the gradient table is provided. NiFreeze expects the table to have one row per diffusion-weighted image, with the first three columns storing the gradient direction in world RAS+ coordinates and the last column indicating the timing and strength of the gradients in units of s/mm²
[ R A S+ b ]. FSL’s.bvecand.bvalfiles are converted with the image’s affine.# Load dMRI data into a DWI object dataset = dmri.load("/path/to/your/dwi_data.nii.gz", gradients_file="/path/to/your/gradient_file") # Or from FSL's files dataset = dmri.load("/path/to/your/dwi_data.nii.gz", bvec_file="/path/to/your/dwi.bvec", bval_file="/path/to/your/dwi.bval")
Note
To run the examples and tests from this page, find sample data on OSF. To load from an nfHDF5 file, use:
dataset = dmri.DWI.from_filename("/path/to/downloaded/dwi_full.h5")
Note
Datasets store the volumes on the first axis:
dataset.dataobjhas shape(N, X, Y, Z)anddataset[i]returns volumei. NIfTI files store the volumes last;from_nii()andto_nifti()convert between the two. NiFreeze saves datasets as nfHDF5 files, which are memory-mapped when loaded, so volumes are read from disk as they are accessed. Files written by earlier versions of NiFreeze (format version 1) still load, but they are converted into a temporary file first; save them again withto_filenameto skip that step.Instantiate an NiFreeze Estimator Object: Create an instance of the
Estimatorclass, which encapsulates tools for estimating rigid-body head motion and distortions due to eddy currents.# Create an instance of the Estimator class estimator = Estimator( model, strategy="random", )
The estimator takes a model that determines how the target volume will be estimated.
model: specifies the model used to generate the registration target for each gradient map (dMRI) or frame (dMRI, PET). For a list of available models, see nifreeze.model package.strategy: strategy used to traverse the 4D sequence. The list of supported strategies can be found at nifreeze.utils.iterators module.prev: estimators can be stacked and be run sequentially.single_fit: whenTrue, fit the model once on all volumes instead of refitting per held-out volume. Use carefully.registration: the registration backend,"elastix"or"ants"(default: elastix whereitk-elastix, theelastixextra, is installed, ANTs otherwise). With the same extra,"itk"estimates eddy currents as head motion followed by a field along the phase-encoding direction (9 parameters,ITK), from theitksection ofAFFINE; the dataset must know its phase-encoding direction, and the eddy-current pass then refines the head motion and stores the field.align_config: the registration settings, a mapping or a YAML file with a section per backend. NiFreeze ships two:RIGID(the default, for head motion) andAFFINE(for eddy currents). To change a setting, copy one and edit it.
Fit the Models to Estimate the Affine Transformation:
Use the
run()method of theEstimatorobject to estimate the affine transformation parameters:# Estimate affine transformation parameters _ = estimator.run( dataset, align_kwargs=align_kwargs, omp_nthreads=omp_nthreads, n_jobs=n_jobs, seed=seed, )
The
runmethod employs the Leave-One-Volume-Out (LOVO) splitting technique to iteratively process DWI data volumes for each specified model: each volume is registered to a prediction fit on all the other volumes, so the target is independent of the volume being aligned. Affine transformations align the volumes, updating the DWI object with the estimated parameters. This method accepts several parameters:dataset: The target dataset, represented by this tool’s internal type.align_kwargs: Registration settings for every estimator of a chain that was not given its own, e.g.{"align_config": "my-settings.yaml"}.omp_nthreads: Maximum number of threads an individual process may use.n_jobs: Number of parallel jobs.seed: Seed for the random number generator (necessary for deterministic estimation).
The estimates are stored in the dataset, each as an \(N \times 4 \times 4\) array of affine matrices: the head motion in
motion, and the eddy currents of a DWI ineddy. A volume’s mapping composes them,eddy @ motion(get_transform()), and the outputs are resampled with it. The b-vectors turn with the head motion alone: eddy currents displace the image without turning the head.Example:
estimator = Estimator( model="b0", strategy="random", ) # Example of estimating the motion parameters _ = estimator.run( dataset, omp_nthreads=4, n_jobs=4, seed=42, )
Eddy currents are estimated by a second pass, which starts from the head-motion estimates stored in the dataset and stores what it adds in
eddy. On the command line,--eddyruns it with the cascade’s last model, and--eddy-modelwith another (--models gp-loo --eddy-model gqi-krr). It registers with the affine settings,AFFINE, unless given its ownalign_config:Estimator("gqi-krr", estimates="eddy").run(dataset, seed=42)
Save Results: Once transformations are estimated, save the realigned data in your preferred output format, either nfHDF5 or NIfTI:
# Save realigned DWI data in HDF5 format output_filename = "/path/to/save/your/output.h5" dataset.to_filename(output_filename)
or as a NIfTI file:
# Save realigned DWI data in NIfTI format output_filename = "/path/to/save/your/output.nii.gz" dataset.to_nifti(output_filename, write_estimates=True)
With
write_estimates=True, the estimates are written next to it, into one X5 file (output.x5): the head motion first, which plain X5 readers get, and the eddy currents after it, chained in the order they apply (eddy @ motion).Plotting: Visualize data and results:
Estimated motion results can be visualized using nifreeze.viz.motion_viz module functions. This includes visualizing framewise displacement, motion overlay, and volume-wise motion.
Data results can be visualized using the NiReports functions, e.g.:
Use
nireports.reportlets.mosaic.plot_mosaic()to visualize one direction of the dMRI dataset or a frame of an fMRI or PET dataset.Employ
nireports.reportlets.modality.dwi.plot_gradients()to visualize diffusion gradients.
Example Usage:
# Visualize 4D data at a specific index dataset.plot_mosaic(index=0)
For dMRI gradients, we can visualize diffusion gradients using:
# Visualize gradients dwi_data.plot_gradients()