Welcome to QUIT’s documentation!¶
Welcome to the QUantitative Imaging Tools, a set of C++ tools for analysing quantitative MR images. QUIT is provided as a single executable named qi
which contains numerous commands for processing images (similar to bart
or git
). These commands are grouped in the following modules:
Categories¶
B1¶
The B1 (RF) fields inside the scanner are not perfectly flat (homogeneous), particularly at field strengths of 3T or above. Hence in methods where the local flip-angle must be known (e.g. Relaxometry) the B1 field must be measured or fitted for. A distinction is drawn between B1+ (the transmit coil inhomogeneity) and B1- (the receive coil inhomogeneity). Generally it is B1+ that is important to know for quantitative techniques, and throughout QUIT
it is expressed as a fraction - a value of 1 means the desired flip-angle was achieved in a voxel, and values lower/higher than this imply a lower/higher flip-angle. B1- is important if you are interested in measuring the Proton Density (PD / M0).
The following commands are available:
qi afi¶
Calculates a B1+ map using the Actual Flip-angle Imaging method.
Example Command Line
qi afi input_file.nii.gz
Does not read any input from stdin
. The input file should contain two volumes, corresponding to TR1 and TR2.
Outputs
AFI_B1.nii.gz
- The relative flip-angle map.
Important Options
--flip, -f
The nominal flip-angle that should have been achieved, default 55 degrees.
--ratio, -r
The ratio of TR2 to TR1, default 5.
--save, -s
Output AFI_angle.nii.gz, the actual achieved angle in each voxel.
References
qi dream¶
Calculates a B1+ map using the DREAM method.
Example Command Line
qi dream input_file.nii.gz
Does not read any input from stdin. The input file should contain two volumes, the FID and stimulated echo (STE).
Outputs
DREAM_B1.nii.gz
- The relative flip-angle map.DREAM_angle.nii.gz
- The actual achieved angle in each voxel.
Important Options
--alpha, -a
The nominal flip-angle that should have been achieved, default 55 degrees.
--order, -O
- f - FID is the first volume, STE is second
- s - STE is the first volume, FID is second
- v - VST (Virtual Stimulated Echo) is the first volume, FID is second
References
qi b1_papp¶
Implements the method of measuring B1- from Papp et al, which takes the ratio of an image acquired with the body coil as receiver and one with the receive coil that was used to acquire the quantitative images.
Example Command Line
qi b1_papp input_file.nii.gz
Does not read any input from stdin
. The input file should contain two volumes, corresponding to the body coil image and the receive coil respectively.
Outputs
B1minus.nii.gz
- The relative receive coil intensity. Images should be divided by this to correct for receive coil profile.
References
Relaxometry¶
Relaxometry is the measurement of the longitudinal and transverse relaxation times T1 and T2. There are a multitude of different techniques for measuring both. The main focus of QUIT has been on the Driven-Equilibrium Single-Pulse Observation of T1 (DESPOT1) family of techniques, but the classic multi-echo T2 method and the more recent MP2RAGE T1 measurement method are also implemented. It is common for relaxometry methods to need a B1 map.
The following commands are available:
- qi despot1
- qi despot1hifi
- qi despot2
- qi despot2fm
- qi jsr
- qi mcdespot
- qi multiecho
- qi mp2rage
- qi mpm_r2s
- qi ssfp_ellipse
- qi planet
qi despot1¶
This command implements the classic Driven Equilibrium Single-Pulse Observation of T1 (DESPOT1) algorithm, also known as the Variable Flip-Angle (VFA) method in the literature. This is a fast way to measure longitudinal relaxation using a spoiled steady-state sequence, which is know by a different name by every scanner manufacturer just to be helpful. On GE, it’s SPoiled Gradient Recalled echo (SPGR), on Siemens it’s Fast Low-Angle SHot (FLASH) and on Phillips the sequence is Fast Field Echo (FFE).

Example Command Line
qi despot1 input_file.nii.gz --mask=mask_file.nii.gz --B1=b1_file.nii.gz < input.json
Example JSON File
{
"SPGR": {
"TR": 0.01,
"FA": [3, 18]
}
}
Outputs
D1_T1.nii.gz
- The T1 map. Units are the same as those used for TR in the input.D1_PD.nii.gz
- The apparent Proton Density map. No units.
Important Options
--B1, -b
Specify an effective flip-angle or B1 map. This must be expressed as a fraction, e.g. a value of 1 in a voxel implies the nominal flip-angle was achieved.
--algo, -a
This specifies which precise algorithm to use. There are 3 choices, classic linear least-squares (l), weighted linear least-squares (w), and non-linear least-squares (n). If you only have 2 flip-angles then LLS is the only meaningful choice. The other 2 choices should produce better (less noisy, more accurate) T1 maps when you have more input flip-angles. WLLS is faster than NLLS for the same number of iterations. However, modern processors are sufficiently powerful that the difference is bearable. Hence NLLS is recommended for the highest possible quality.
References
qi despot1hifi¶
This is an extension of DESPOT1 to fit a map simultaneously using an MP-RAGE / IR-SPGR type sequence. Although DESPOT1-HIFI can produce a rough estimate of B1, it often fails to produce reasonable values in the ventricles, and the fact that the MP-RAGE image is often acquired at lower resolution than the SPGR/FLASH data can also cause problems. Hence you should either smooth the B1 map produced as output, or fit it with a polynomial (Utilities), then recalculate T1 using the qi despot1 command. Note that if your MP-RAGE image is not acquired at the same resolution as your SPGR data, it must be resampled to the same spacing before processing (and it should also be registered to your SPGR data).
Example Command Line
qi despot1hifi spgr_file.nii.gz irspgr_file.nii.gz --mask=mask_file.nii.gz < input.json
Example JSON File
{
"SPGR": {
"TR": 0.01,
"FA": [3, 18]
},
"MPRAGE": {
"FA": 5,
"TR": 0.01,
"TI": 0.45,
"TD": 0,
"eta": 1,
"ETL": 64,
"k0": 0
}
}
For the MPRAGE sequence, the TR is the spacing between readouts/echoes, not the overall segment TR. TI is the Inversion Time, and TD is the Delay Time after the echo-train (often 0). Eta is the Inversion Efficiency, which should be set to 1. ETL is the Echo-Train Length - usually the number of phase encode steps in one segment. k0 defines the position in the echo-train that the center line of k-space is acquired. This is 0 for centric acquisition and ETL/2 for linear.
Outputs
HIFI_T1.nii.gz
- The T1 map. Units are the same as those used for TR in the input.HIFI_PD.nii.gz
- The apparent Proton Density map. No units.HIFI_B1.nii.gz
- The relative flip-angle map.
References
qi despot2¶
DESPOT2 uses SSFP data and a separate T1 map to calculate T2, using the same maths as DESPOT1. It does not account for the banding artefacts present in SSFP data at field-strengths of 3T and above. See qi despot2fm for a method that does account for them, or if you have at least 4 phase-increments and complex data then see qi ssfp_bands in Utilities for a way to remove them before using this command.

Example Command Line
qi despot2 t1_map.nii.gz input_file.nii.gz --mask=mask_file.nii.gz --B1=b1_file.nii.gz < input.json
Example JSON File
{
"SSFP": {
"TR": 0.005,
"PhaseInc": [180],
"FA": [12, 60]
}
}
Both PhaseInc
and FA
are measured in degrees. If the ellipse option is specified, then the sequence type must be SSFPGS
, which does not require a PhaseInc
. The units of TR
must match the input T1 map.
Outputs
D2_T2.nii.gz
- The T2 map. Units are the same as those used for TR in the input.D2_PD.nii.gz
- The apparent Proton Density map. No units. Will be corrected for T2 decay at the echo time.
Important Options
--B1, -b
Specify an effective flip-angle or B1 map. This must be expressed as a fraction, e.g. a value of 1 in a voxel implies the nominal flip-angle was achieved.
--algo, -a
This specifies which precise algorithm to use. There are 3 choices, classic linear least-squares (l), weighted linear least-squares (w), and non-linear least-squares (n). If you only have 2 flip-angles then LLS is the only meaningful choice. The other 2 choices should produce better (less noisy, more accurate) T1 maps when you have more input flip-angles. WLLS is faster than NLLS for the same number of iterations. However, modern processors are sufficiently powerful that the difference is bearable. Hence NLLS is recommended for the highest possible quality.
--ellipse, -e
This specifies that the input data is the SSFP Ellipse Geometric Solution, i.e. that multiple phase-increment data has already been combined to produce band free images.
References
qi despot2fm¶
DESPOT2-FM uses SSFP data with mulitple phase-increments (also called phase-cycles or phase-cycling patterns) to produce T2 maps without banding artefacts.
Example Command Line
qi despot2fm t1_map.nii.gz input_file.nii.gz --mask=mask_file.nii.gz --B1=b1_file.nii.gz < input.json
The input file should contain all SSFP images concatenated together as a 4D file. The preferred ordering is flip-angle, then phase-increment (i.e. all flip-angles at one phase-increment, then all flip-angles at the next phase-increment).
Example JSON File
{
"SSFP": {
"TR": 0.005,
"PhaseInc": [180, 180, 0, 0],
"FA": [12, 60, 12, 60]
}
}
Both PhaseInc
and FA
are measured in degrees. The length of PhaseInc
and FA
must match.
Outputs
FM_T2.nii.gz
- The T2 map. Units are the same as those used for TR in the input.FM_PD.nii.gz
- The apparent Proton Density map. No units. Will be corrected for T2 decay at the echo time.
Important Options
--B1, -b
Specify an effective flip-angle or B1 map. This must be expressed as a fraction, e.g. a value of 1 in a voxel implies the nominal flip-angle was achieved.
--asym, -A
With the commonly used phase-increments of 180 and 0 degrees, due to symmetries in the SSFP magnitude profile, it is not possible to distinguish positive and negative off-resonance. Hence by default
qi despot2fm
only tries to fit for positive off-resonance frequences. If you acquire most phase-increments, e.g. 180, 0, 90 & 270, then add this switch to fit both negative and positive off-resonance frequencies.
References
qi jsr¶
Join-System Relaxometry fits T1 and T2 to spoiled and balanced gradient echo (SPGR and SSFP) data simultaneously, which improves the accuracy and precision in the fit of both.
Example Command Line
qi jsr spgr.nii.gz ssfp.nii.gz < input.json
Example JSON File
{
"SPGR": {
"TR": 0.01,
"TE": 0.003,
"FA": [12]
},
"SSFP": {
"TR": 0.01,
"Trf": 0.003,
"FA": [10, 20, 20, 40],
"PhaseInc": [180, 180, 0, 180]
}
}
Note that the pulse-length for SSFP is required in order to apply to finite-pulse correction of Crooijmans et al. For hard-pulses this should be set to the actual length of the pulse, for other pulses an adjusted pulse-length is required as discussed in the paper.
Outputs
JSR_PD.nii.gz
- The apparent Proton Density map. No units.JSR_T1.nii.gz
- The T1 map. Units are the same as those used for TR in the input.JSR_T2.nii.gz
- The T2 map. Units are the same as those used for TR in the input.JSR_f0.nii.gz
- The off-resonance map.
References
qi mcdespot¶
Multi-component DESPOT aims to separate SPGR and SSFP signals into multiple discrete pools with different T1 and T2. In the brain, the pool with shorter values is attributed to myelin water, while pools with longer values can be either intra/extra-cellular water or CSF.
It is recommended to have an off-resonance map to stabilise the fitting. This can be generated by using qi despot1 and then qi despot2fm above. A B1 map is also essential for good results.

Example Command Line
qi mcdespot spgr_file.nii.gz ssfp_file.nii.gz --mask=mask_file.nii.gz --B1=b1_file.nii.gz --f0=f0_file.nii.gz --scale < input.json
The SSFP input file should contain all SSFP images concatenated together as a 4D file (see qi despot2fm above).
Example JSON File
{
{
"SPGR": {
"TR": 0.01,
"FA": [3,4,5,7,9,12,15,18]
}
},
{
"SSFP": {
"TR": 0.05,
"FA": [12,16,20,24,30,40,50,60,12,16,20,24,30,40,50,60],
"PhaseInc": [180,180,180,180,180,180,180,180,0,0,0,0,0,0,0,0]
}
}
}
Outputs
Note - the output prefix will change depending on the model selected (see below). The outputs listed here are for the 3 component model.
3C_T1_m.nii.gz
- T1 of myelin water3C_T2_m.nii.gz
- T2 of myelin water3C_T1_ie.nii.gz
- T1 of intra/extra-cellular water3C_T2_ie.nii.gz
- T2 of intra/extra-cellular water3C_T1_csf.nii.gz
- T1 of CSF3C_T2_csf.nii.gz
- T2 of CSF3C_tau_m.nii.gz
- The residence time of myelin water (reciprocal of forward exchange rate)3C_f_m.nii.gz
- The Myelin Water Fraction (MWF)3C_f_csf.nii.gz
- The CSF Fraction3C_f0.nii.gz
- The off-resonance frequency. If this was specified on the command line, it will be a copy of that file3C_B1.nii.gz
- The relative flip-angle map. If this was specified on the command line, it will be a copy of that file
The intra/extra-cellular water fraction is not output, as it is not a free parameter (only 2 of the 3 pool fractions are required for the calculations). It is easy to calculate this post-hoc by subtracting the MWF and CSFF from 1.
Important Options
--algo, -a
- S - Stochastic Region Contraction
- G - Gaussian Region Contraction
Gaussian is recommended.
--tesla, -t
Specify the field-strength so sensible fitting ranges can be used. Currently only ranges for (3) and (7)T are defined. If you wish to specify your own ranges, set this option as (u) and then the ranges will be read from your input file.
--model, -m
- 1 - 1 component model (no fractions, just a single T1/T2)
- 2 - 2 component model. Myelin and intra/extra-cellular water
- 2nex - 2 component model without exchange
- 3 - 3 component model. Myelin water, IE water & CSF
- 3nex - 3 component model without exchange
- 3f0 - 3 component model, allow an additional off-resonance offset between myelin and IE water pools
References
qi mp2rage¶
MP2RAGE adds a second inversion time to the standard T1w MPRAGE sequence. Combining the (complex) images with the expression \(S_1 S_2^*/(|S_1^2 + S_2^2|)\) produces a real-valued image that is corrected for receive coil (B1-) inhomogeneity. In addition, if the two inversion times are carefully selected, a one-to-one mapping exists between the values in that image and T1, which is also robust to transmit (B1+) inhomogeneity. Finally, as the two images are implicitly registered, this method has several advantages over DESPOT1.
Example Command Line
qi mp2rage input_file.nii.gz --mask=mask_file.nii.gz < input.json
The input file must be complex-valued.
Example JSON File
{
"MP2RAGE" : {
"TR" : 0.006,
"TRPrep" : 5,
"TI" : [0.9, 2],
"SegLength" : 128,
"k0" : 64,
"FA": [6, 8]
}
}
TR
is the readout or acquisition repetition time, while TRPrep
is time between preparations/inversion pulses. SegLength
is the number of readouts in one segment, and k0
is the index within the segment when the center line of k-space is read. This is 0 for centric order, or \(SegLength / 2\) for linear (default Siemens) order. There should be two values of TI
and FA
.
Outputs
{input}_contrast.nii.gz
- The MP2 contrast image. The range of this image is -0.5 to 0.5.{input}_T1.nii.gz
- The T1 map. Units are the same as TR and SegTR.
Important Options
--beta, -b
Regularisation factor for robust contrast calculation (see references). It is recommended to experiment with this parameter to manually find an optimum value, which should then be kept constant for an entire dataset.
References
qi multiecho¶
Classic monoexponential decay fitting. Can be used to fit either T2 or T2*.
Example Command Line
qi multiecho input_file.nii.gz --algo=a < input.json
Example JSON File
For regularly spaced echoes:
{
"MultiEcho" : {
"TR" : 2.5,
"TE1" : 0.005,
"ESP" : 0.005,
"ETL" : 16
}
}
TE1
is the first echo-time, ESP
is the subsequent echo-spacing, ETL
is the echo-train length.
For irregularly spaced echoes:
{
"MultiEchoFlex" : {
"TR" : 2.5,
"TE" : [0.005, 0.01, 0.03, 0.05]
}
}
Note
The current implementation of the ARLO method will only work with regularly spaced echoes
Outputs
ME_T2.nii.gz
- The T2 map. Units are the same as TE1 and ESP.ME_PD.nii.gz
- The apparent proton-density map (intercept of the decay curve at TE=0)
Important Options
--algo, -a
- l - Standard log-linear fitting
- a - ARLO (see reference below)
- n - Non-linear fitting
References
qi mpm_r2s¶
Implements the ECSTATICS method for estimating R2*, part of Multi-Parametric Mapping (MPM). This performs a simultaneous fit to PD-, T1- and MT-weighted multi-echo data for R2*, improving the SNR of the resulting fit compared to individual fits. In contrast to the original paper, which used linear least-squares, a bounded non-linear fit is used.
Example Command Line
qi mpm_r2s PDw.nii.gz T1w.nii.gz MTw.nii.gz < input.json
Example JSON File
For regularly spaced echoes:
{
"PDw" : {
"TR" : 2.5,
"TE1" : 0.005,
"ESP" : 0.005,
"ETL" : 8
},
"T1w" : {
"TR" : 2.5,
"TE1" : 0.005,
"ESP" : 0.005,
"ETL" : 8
},
"MTw" : {
"TR" : 2.5,
"TE1" : 0.005,
"ESP" : 0.005,
"ETL" : 6
}
}
TE1
is the first echo-time, ESP
is the subsequent echo-spacing, ETL
is the echo-train length.
Outputs
MPM_R2s.nii.gz
- The R2* map. Same units asTE
.MPM_S0_PDw.nii.gz
- The PD-weighted signal atTE=0
.MPM_S0_T1w.nii.gz
- The PD-weighted signal atTE=0
.MPM_S0_MTw.nii.gz
- The PD-weighted signal atTE=0
.
References
qi ssfp_ellipse¶
This tool is not a relaxometry tool as such but a pre-processing step for qi planet.
Shcherbakova et al showed it was possible to recover the ellipse parameters G, a, b from at least six phase-increments. They then proceeded to recover T1 & T2 from the ellipse parameters. This utility calculates the ellipse parameters, and qi planet
then processes those parameters to calculate T1 & T2. A non-linear fit is used instead of the algebraic method used by Shcherbakova et al. This is slower, but robust across all flip-angles.

Example Command Line
qi ssfp_ellipse ssfp_data.nii.gz < input.json
The SSFP file must be complex-valued. At least three pairs of opposing phase-increments are recommended (six images in total).
Example JSON File
{
"SSFP": {
"TR": 0.005,
"PhaseInc": [180, 240, 300, 0, 60, 120],
"FA": [12, 12, 12, 12, 12, 12]
}
}
Both PhaseInc
and FA
are measured in degrees. The length of PhaseInc
and FA
must match, but the value of FA
is unused so a dummy value is permissible. If multiple ellipses with different flip-angles are present in the input data, do not specify the extra flip-angles.
Outputs
ES_G
- The Geometric Solution point of the ellipse. Influences the overall size of the ellipse. This is called (M) in the Hoff and Shcherbakova papers, but it is not a measurable magnetization and hence to distinguish it a different letter is used.ES_a
- The ellipse parameter that along with (G) controls the ellipse size.ES_b
- The ellipse parameter that determines how flat or circular the ellipse is.ES_theta_0
- The accrued phase due to off-resonance, divide by \(2\pi TE\) (or \(\pi TR\)) to find the off-resonance frequency.ES_phi_rf
- The effective phase of the RF pulse.
References
qi planet¶
Converts the SSFP Ellipse parameters into relaxation times.
Example Command Line
qi planet ES_G.nii.gz ES_a.nii.gz ES_b.nii.gz
Outputs
PLANET_T1.nii.gz
- Longitudinal relaxation timePLANET_T2.nii.gz
- Transverse relaxation timePLANET_PD.nii.gz
- Apparent Proton Density
References
Perfusion¶
Perfusion is the study of blood flow within the brain. This module contains tools to calculate Cerebral Blood Flow (CBF) and the Oxygen Extraction Fraction (OEF).
The following commands are available:
qi asl¶
This command implements the standard equation to calculate Cerebral Blood Flow (CBF) in units of ml/100 g/minute from either Continuous or pseudo-Continuous Arterial Spin Labelling data (CASL or pCASL). For the exact equation used, see the first reference below.

Example Command Line
qi asl asl_file.nii.gz --blood=2.429 --alpha=0.9 --average --slicetime --pd=reference_file.nii.gz <input.json
The input file must contain pairs of label & control volumes. Currently the order of these is hard-coded to label, then control. The file can contain multiple pairs if you are studying timeseries data. The arguments are discussed further below. It is highly recommended to provide either a separated Proton Density reference image or a tissue T1 map.
Example JSON File
{
"CASL" : {
"TR" : 4.0,
"label_time" : 3.0,
"post_label_delay" : [ 0.3, 0.6, 0.9 ]
}
}
The units for all these values must be consistent, seconds are preferred. If single-slice or 3D data was acquired, then post_label_delay
should contain a single value. For multi-slice data, specify the --slicetime
option and then provide the effective post-labelling delay for each slice.
Outputs
input_CBF
- The CBF value, given in mL/(100 g)/min
Important Options
--blood, -b
The T1 value of blood at the field strength used. The default value is 1.65 seconds, corresponding to 3T. For 1.5T the value should be 1.35 seconds and at 9.4T it should 2.429 seconds. See reference 2.
--pd, -p
Provide a separate image to estimate of the Proton Density of tissue. If this is not provided, the label images are used instead.
--tissue, -t
Provide a T1 map to correct the Proton Density estimate. If a separate PD reference is not given, then an alternative is to correct the label images for incomplete T1 relaxation.
--alpha, -a
The labelling efficiency of the sequence.
--lambda, -l
The blood-brain partition co-efficient, default 0.9 mL/g.
References
qi ase_oef¶
Estimates the Oxygen Extraction Fraction (OEF) from Asymmetric Spin-Echo (ASE) data. If the signal evolution each side of a spin-echo in the presence of blood vessels is observed carefully, it does not display simple monoexponential T2* decay close to the echo, but is instead quadratically exponential. By measuring the T2* decay in the linear regime using an ASE sequence, it is possible to extrapolate back to the echo and obtain an estimate of what the signal would be if no blood was presence. The difference between this and the observed signal can be attributed to the Deoxygenated Blood Volume (DBV), and from there the OEF can be calculated.
Example Command Line
qi ase_oef ase_file.nii.gz --B0=9.4 --fmap=fieldmap.nii.gz <input.json
Example JSON File
{
"MultiEcho" : {
"TR" : 2.0,
"TE1" : 0,
"ESP" : 0.002,
"ETL" : 10
}
}
TR
must be provided but is not used in the calculation. Echo-times below the critical time (Tc) will be excluded from the R2’ calculation.
Outputs
input_R2prime.nii.gz
The R2’ map. Units are the same as those used forTR
,TE1
andESP
.input_DBV.nii.gz
The Deoxygenated Blood Volume, in percent.input_OEF.nii.gz
The Oxygen Extraction Fraction, in percent.input_dHb.nii.gz
The Deoxyhaemoglobin concentration.
Important Options
--B0, -b
Field-strength the data was acquired at. This is used to calculate Tc and appears elsewhere in several equations.
--fmap, -f
Provide a field-map (in Hertz). This will be used to provide first-order correction of Macroscopic Field Gradients (MFGs). If this option is specified, the derivative of the field-map in all 3 directions will also be saved.
--slice,-s
If the data was acquired with a slice-gap, use this option to specify the actual slice-thickness for the MFG calculation.
References
Magnetization Transfer¶
MR voxels often contain complex microstructure with multiple different components or pools, each with unique relaxation properties. It is possible for magnetization to be transferred between these pools via several mechanisms, such as exchange of individual protons or entire molecules, or simple dipolar coupling from molecules that are in close proximity. These mechanisms can be studied in the related fields of Magnetization Transfer (MT) and Chemical Exchange Saturation Transfer (CEST). QUIT contains tools for quantitative MT (qi qmt, qi ssfp_emt), CEST (qi zspec_interp, qi lorentzian) and also for processing MPM data (qi mtsat). Example nipype workflows for CEST analysis are also provided.
qi lineshape¶
A utility to sample lineshapes and write them out to files, which can then be read by qi qmt and interpolated values used instead of calculating the lineshape during fitting. This is used principally to speed up fitting the Super-Lorentzian lineshape, which takes a long time to calculate but is smoothly valued, so can be accurately approximated using interpolation.
Example Command Line
qi lineshape --lineshape=SuperLorentzian --frq_start=500 --frq_space=500 --frq_count=150 superlorentz.json
The output will be written to the file specified on the command-line (in this case superlorentz.json).
Important Options
--lineshape, -l
Choose from a Gaussian, a Lorentzian or the Super-Lorentzian
--T2b, -t
Specify the nominal T2 of the lineshape. During fitting in qi qmt scaling will be used to find the actual value. Should be specified in seconds.
--frq_count
,--frq_start
,--frq_space
These Control the position and number of samples to take on the lineshape.
frq_start
andfrq_space
should be in Hertz.
qi qmt¶
Calculates Quantitative Magnetization Transfer parameters using the Ramani model from steady-state gradient-echo data acquired with multiple off-resonance saturation pulses.

Example Command Line
qi qmt MTSatData.nii.gz --T1=T1.nii.gz --mask brain_mask.nii.gz --lineshape=superlorentz.json --B1=B1_map.nii.gz --f0=B0_map.nii.gz --json=input.json
Note that the T1 map argument is required input to stabilise the fitting.
Example JSON File
{
"MTSat" : {
"TR": 0.055,
"Trf": 0.015,
"FA": 5,
"sat_f0": [56360, 47180, 12060, 1000, 1000, 2750, 2770, 2790, 2890, 1000, 1000],
"sat_angle": [332, 628, 628, 332, 333, 628, 628, 628, 628, 628, 628],
"pulse": { "name": "Gauss", "bandwidth": 100, "p1": 0.416, "p2": 0.295 }
}
}
Trf
is the pulse-width (RF Time). p1
and p2
are the ratio of the integral of \(B_1\) and \(B_1^2\) (the integrals of the pulse amplitude and the square of the pulse amplitude) to the maximum amplitude of the pulse. Both Trf
and TR
should be in seconds. sat_f0
is in Hertz. The bandwidth
parameter is currently unused, any value will do.
Outputs
QMT_f_b.nii.gz
- The bound pool fractionQMT_k.nii.gz
- The fundamental exchange rate between poolsQMT_k_bf.nii.gz
- The forward exchange rate from bound to free poolQMT_T1_f.nii.gz
- T1 of the free poolQMT_T2_f.nii.gz
- T2 of the free poolQMT_T2_b.nii.gz
- T2 of the bound poolQMT_PD.nii.gz
- The apparent Proton Density / size of the free pool
Important Options
--R1b, -r
Specify the relaxation rate of the bound pool. Default is 2.5 per second.
References
qi zspec_interp¶
Interpolates a Z-spectrum to arbitrary precision. Can output asymmetry values instead of a Z-spectrum.
Example Command Line
qi zspec_interp zspectrum.nii.gz --f0=LTZ_f0.nii.gz < input.json
The off-resonance map units must match the input frequencies (e.g. either PPM or Hertz)
Example JSON File
{
"input_freqs" : [ -5, -2.5, 0, 2.5, 5],
"output_freqs" : [ -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]
}
input_freqs
are the offset frequencies the Z-spectrum was acquired at. output_freqs
are the frequencies you want the asymmetry calculated at.
Outputs
{input}_interp.nii.gz
The interpolated Z-spectrum.
Important Options
--f0, -f
Specify an off-resonance map. Units must be the same as the input & asymmetry frequencies.
-O, --order
The order of Spline interpolation used. Default is 3 (cubic).
-a, --asym
Output asymmetry (:math`Z(+f) - Z(-f)`) values.
qi lorentzian¶
Fits sums of Lorentzian functions to a Z-spectrum. Highly customisable for the number of desired Lorentzian’s and their characteristics.
Example Command Line
qi lorentzian zspectrum.nii.gz < input.json
The Z-spectrum must be a 4D file with each volume acquired at a different offset frequency.
Example JSON File
{
"MTSat": {
"pulse": {
"p1": 0.4,
"p2": 0.3,
"bandwidth": 0.39
},
"Trf": 0.02,
"TR": 4,
"FA": 5,
"sat_f0": [0, 1, 2, 3, 4, 5],
"sat_angle": [180, 180, 180, 180, 180],
},
"pools" :
[
{
"name": "DS",
"df0": [0, -2.5, 2.5],
"fwhm": [1.0, 1.e-6, 3.0],
"A": [0.2, 1.e-3, 1.0],
"use_bandwidth": True
},
{
"name": "MT",
"df0": [-2.5, -5.0, -0.5],
"fwhm": [50.0, 35.0, 200.0],
"A": [0.3, 1.e-3, 1.0]
}
]
}
The input needs to include both the sequence parameters and the characteristics of the Lorentzian “pools” that you wish to fit. Currently the only important information used from the sequence are the saturation offsets, and optionally the bandwidth of the pulse. For each pool a name is required, and then triples of values representing the starting, lower and upper bound for the center frequency df0
, the Full-Width Half-Maximum fwhm
and amplitude A
of the Lorentzian. You can also specify that the modified Lorentzian including the pulse bandwidth should be used “use_bandwith” : True. See the reference for details.
Important Options
--add, -a
Specify an additive model instead of the default subtractive (saturation) model. Useful when a base-line has already been subtracted from the Z-spectrum. See reference for details.
--zref, -z
Change the reference value for the Z-spectrum. Default is 1.0, change to 0.0 for additive model.
Outputs
For each pool three outputs will be written, prefixed by the pool name. For a single pool representing direct-saturation (DS), the following will be written:
DS_f0.nii.gz
- The center frequency of the fitted Lorentzian.DS_fwhm.nii.gz
- The width of the fitted Lorentzian.DS_A.nii.gz
- The amplitdue of the fitted Lorentzian.
References
qi mtr¶
Calculates Magnetization Transfer Ratio (MTR) and related quantities, e.g. MTasym and ihMTR.
By default only the MTR is calculated, assuming that the input contains one MT-weighted and one PD-weighted (reference) volume. However it can be used to calculate other quantities by passing in a JSON file specifying the formulas to calculate these. An example is given below to calculate MTR, ihMTR and MTasym from an acquisition with five volumes which correspond to ihMTw (+/-), ihMTw (-/+), PDw, MTw (+), MTw (-) where +/- correspond to applying the saturation pulse at positive or negative frequency.
Example Command Line
qi mtr mt_volumes.nii.gz --json=contrasts.json
Example JSON File
{
"contrasts": [
{ "name" : "MTR", "ref": [2, 2], "add": [3, 4], "sub": [], "reverse": true },
{ "name" : "MTasym", "ref": [2], "add": [3], "sub": [4], "reverse": false },
{ "name" : "eMTR", "ref": [2, 2], "add": [0, 1], "sub": [], "reverse": true },
{ "name" : "ihMTR", "ref": [2, 2], "add": [3, 4], "sub": [0, 1], "reverse": false }
]
}
The fields ref, add, sub refer to the indices of volumes that should be used as a reference, added or subtracted. reverse means that the contrast is reversed, i.e. it should be subtracted from the reference value before output (which is standard for MTR because it is a negative quantity).
Outputs
All outputs are expressed as percentages (multiplied by 100). By default there is one output:
MTR.nii.gz
- The classic MTR, expressed as a percentage
If you use a custom contrasts file then the outputs will have the names specified in the .json file.
References
qi mtsat¶
Implementation of Gunther Helm’s MT-Sat method. Calculates R1, apparent PD and the semi-quantitative MT-Saturation parameter “delta”. This is the fractional reduction in the longitudinal magnetization during one TR, expressed as a percentage. Arguably could be included in the Relaxometry module instead. Outputs R1 instead of T1 as this is more common in the MTSat / MPM literature. If using multi-echo input data the input should be passed through qi mpm_r2s first and the output S0
files used as input to qi mtsat.
Example Command Line
qi mtsat PDw.nii.gz T1w.nii.gz MTw.nii.gz < input.json
Example JSON File
{
"MTSat": {
"TR_PDw": 0.025,
"TR_T1w": 0.025,
"TR_MTw": 0.028,
"FA_PDw": 5,
"FA_T1w": 25,
"FA_MTw": 5
}
}
Outputs
MTSat_R1.nii.gz
- Apparent longitudinal relaxation rateMTSat_S0.nii.gz
- Apparent proton density / equilibrium magnetizationMTSat_delta.nii.gz
- MT-Sat parameter, see above.
References
qi ssfp_emt¶
Due to the short TR commonly used with SSFP, at high flip-angles the sequence becomes MT weighted. It is hence possible to extract qMT parameters from SSFP data. More details will be in a forthcoming paper.
Example Command Line
qi ssfp_emt ES_G.nii.gz ES_a.nii.gz ES_b.nii.gz
Outputs
EMT_T1f.nii.gz
- Longitudinal relaxation time of the free water boolEMT_T2f.nii.gz
- Transverse relaxation time of the free water poolEMT_M0.nii.gz
- Apparent Proton DensityEMT_F.nii.gz
- Bound pool fractionEMT_kf.nii.gz
- Forward exchange rate
References
Susceptibility¶
Susceptibility is a fundamental magnetic property of a material, and determines whether materials are paramagnetic (positive susceptibility) or diamagnetic (negative susceptibility). Quantitative Susceptibility Mapping (QSM) is a branch of MRI that aims to measure the susceptiblity of objects from the phase of the MR data. QUIT currently does not contain a full QSM processing pipeline, but does contain some phase unwrapping tools.
qi unwrap_path¶
An implementation of the quality-guided path-based unwrapping of Abdul-Rahman et al. This is the recommended method to use (preferable over Laplacian).
Example Command Line
qi unwrap_path phase_file.nii.gz
The phase file must be specified in radians (i.e. between \(-\pi\) and \(+\pi\)). Does not read input from stdin
, and currently there are no arguments to control the algorithms behaviour.
Outputs
input_unwrapped.nii.gz
- The unwrapped phase value, in radians.
References
qi unwrap_laplace¶
Implements Laplacian-based phase-unwrapping. Along with phase-unwrapping, the Laplacian method implicitly removes background fields. This means it can alter phase values in undesirable ways and hence is not the preferred method.
Example Command Line
qi unwrap_laplace phase_file.nii.gz
The phase file must be specified in radians (i.e. between -pi and +pi). Does not read input from stdin.
Outputs
input_unwrapped.nii.gz
The unwrapped phase, in radians.
Important Options
--mask, -m
Specify a mask, the phase will only be unwrapped inside this.
--erode, -e
Radius to erode the input mask by (default 1 mm).
References
Statistics / GLM Tools¶
QUIT contains a few tools to help prepare your data for statistical analysis with outside tools, for instance non-parametric tests with Randomise or an ROI analysis using Pandas. These tools are:
qi glmsetup¶
FSL randomise takes a single 4D file with one volume per subject/timepoint as input, along with some simple text files that represent the GLM. Creating these files can be tedious, particularly with the FSL GUI. This tool makes it quick to create the relevant files.
Example Command Line
qi glmsetup --groups=groups.txt --covars="brain_volume.txt,brain_volume.txt" --design=glm.txt --out=merged.nii --sort subject_dirs*/D1_T1.nii
This command line will merge all the T1 maps in the directories matching the pattern. The file groups.txt
should contain a single number per line, one for each T1 map. The number represents the group or cell that image belongs to. A group of 0 means exclude this file (so you don’t have to work out a pattern that won’t match that file). For example, with 8 scans belonding to 3 groups with 1 excluded scan, the groups.txt
might look like:
1
3
3
2
0
1
2
1
The design matrix corresponding to the specified groups will be saved to the glm.txt
file (Note - this will still need to be processed with Text2Vest
to make it compatible with randomise
). If --sort
is specified, then the images and design matrix will be sorted into ascending order.
qi glmcontrasts¶
Randomise does not save any contrast
files, i.e. group difference maps, it only saves the statistical maps. For quantitative imaging, the contrasts can be informative to look at, as if scaled correctly, they can be interpreted as effect size maps. A group difference in human white matter T1 of only tens of milliseconds, even if it has a high p-value, is perhaps not terribly interesting as it corresponds to a change of about 1%. These contrast maps are particularly useful if used with the dual-coding visualisation technique.
Example Command Line
qi glmcontrasts merged_images.nii design.txt contrasts.txt --out=contrast_prefix
The design and contrasts files should be raw text (not passed through Text2Vest
). One contrast image will be generated for each row of the contrast matrix.
qi rois¶
An alternative to voxel-wise statistics is to average the values over a pre-defined, anatomically meaningful region-of-interest in each quantitative image, and the perform statistics on those ROI values. This approach has several advantages, as more traditional and robust statistical methods can be used than the simple parametric T-tests that voxel-wise analysis tools use.
To avoid resampling issues, it is preferable to warp the ROI definitions (atlas files) to the subject space and sample the quantitative maps at their native resolution. This can make extracting all the ROI values tedious. This tool can extract ROI values from multiple files at once and produce a Comma-Separated Value (.csv) file as output for use with a stats tool such as Pandas. It can also calculate the volumes of the warped ROIs, i.e. for a Tensor/Deformation Based Morphometry analysis. The registrations required for this should be carried out with external tools, e.g. ANTs or FSL.
Example Command Line
For quantitative ROIs:
qi rois labels_subject1.nii labels_subject2.nii ... labels_subjectN.nii data_subject1.nii data_subject2.nii ... data_subjectN.nii --ignore_zero --header=subject_ids.txt
For ROI volumes:
qi rois --volumes labels_subject1.nii labels_subject2.nii ... labels_subjectN.nii ---header=subject_ids.txt
Any header files should contain one line per subject, corresponding to the input image files. The output of qi rois
is fairly flexible, and can be controlled with the --transpose
, --delim
, --precision
, and --sigma
options.
Utilities¶
QUIT contains a number of utilities. Note that these are actually compiled in two separate modules - CoreProgs
contains the bare minimum of commands for the QUIT tests to run, while the actual Utils
modules contains a larger number of useful tools for neuro-imaging pipelines. Their documentation is combined here.
- qi coil_combine
- qi rfprofile
- qi affine
- qi complex
- qi hdr
- qi kfilter
- qi mask
- qi polyfit/qi polyimg
- qi diff
- qi newimage
- qi select
qi coil_combine¶
The command implements both the COMPOSER and Hammond methods for coil combination. For COMPOSER, a wrapper script that includes registration and resampling of low resolution reference data to the image data can be found in qi composer.sh
.
Example Command Line
qi coil_combine multicoil_data.nii.gz --composer=composer_reference.nii.gz
Both the input multi-coil file and the reference file must be complex valued. Does not read input from stdin
. If a COMPOSER reference file is not specifed, then the Hammond coil combination method is used.
Outputs
input_combined.nii.gz
- The combined complex-valued image.
Important Options
--composer, -c
Use the COMPOSER method. The reference file should be from a short-echo time reference scan, e.g. UTE or ZTE. If
--coils, -C
If your input data is a timeseries consisting of multiple volumes, then use this option to specify the number of coils used in the acquisition. Must match the number of volumes in the reference image. Does not currently work with the Hammond method.
--region, -r
The reference region for the Hammond method. Default is an 8x8x8 cube in the center of the acquisition volume.
References
qi rfprofile¶
This utility takes a B1+ (transmit field inhomogeneity) map, and reads an excitation slab profile from stdin
. The two are multiplied together along the slab direction (assumed to be Z), to produce a relative flip-angle or B1 map.
Example Command Line
qi rfprofile b1plus_map.nii.gz output_b1_map.nii.gz < input.json
Example Command Line
{
"rf_pos" : [ -5, 0, 5],
"rf_vals" : [[0, 1, 0],
[0, 2, 0]]
}
rf_pos
specifies the positions that values of the RF slab have been calculated at, which are specified in rf_vals
. Note that rf_vals
is an array of arrays - this allows qi rfprofile
to calculate profiles for multiple flip-angles in a single pass. The units for rf_pos
are the same as image spacing in the header (usually mm). rf_vals
is a unitless fraction, relative to the nominal flip-angle.
These values should be generated with a Bloch simulation. Internally, they are used to create a spline to represent the slab profile. This is then interpolated to each voxel’s Z position, and the value multiplied by the input B1+ value at that voxel to produce the output.
Outputs
output_b1map.nii.gz
- The relative flip-angle/B1 map
qi affine¶
This tool applies simple affine transformations to the header data of an image, i.e. rotations or scalings. It was written because of the inconsistent definitions of co-ordinate systems in pre-clinical imaging. Non-primate mammals are usually scanned prone instead of supine, and are quadrupeds instead of bipeds. This means the definitions of superior/inferior and anterior/posterior are different than in clinical scanning. However, several pre-clinical atlases, e.g. Dorr et al, rotate their data so that the clinical conventions apply. It is hence useful as a pre-processing step to adopt the same co-ordinate system. In addition, packages such as SPM or ANTs have several hard-coded assumptions about their input images that are only appropriate for human brains. It can hence be useful to scale up rodent brains by a factor of 10 so that they have roughly human dimensions.
Example Command Line
qi affine input_image.nii.gz --scale=10.0 --rotX=90
If no output image is specified, the output will be written back to the input filename.
Common Options
--scale, -s
Multiply the voxel spacing by a constant factor.
--rotX, --rotY, --rotZ
Rotate about the specified axis by the specified number of degrees. Note that currently, each rotation can only be specified once and the order will always be X, Y, then Z.
--offX, --offY, --offZ
Add the specified offset to the origin.
--center, -c
Set the image origin to be the Center of Gravity of the image.
qi complex¶
Manipulate complex/real/imaginary/magnitude/phase data. Created because I was fed up with how fslcomplex
works.
Example Command Line
qi complex -m input_magnitude.nii.gz -p input_phase.nii.gz -R output_real.nii.gz -I output_imaginary.nii.gz
Lower case arguments --mag, -m, --pha, -p, --real, -r, --imag, -i, --complex, -x
are inputs (of which it is only valid to specify certain combinations, complex OR magnitude/phase OR real/imaginary).
Upper case arguments --MAG, -M, --PHA, -P, --REAL, -R, --IMAG, -I, --COMPLEX, -X
are outputs, any or all of which can be specified.
An additional input argument, --realimag
is for Bruker “complex” data, which consists of all real volumes followed by all imaginary volumes, instead of a true complex datatype.
The --fixge
argument fixes the lack of an FFT shift in the slab direction on GE data by multiplying alternate slices by -1. --negate
multiplies the entire volume by -1. --double
reads and writes double precision data instead of floats.
qi hdr¶
Prints the header of input files as seen by ITK to stdout
. Can extract single header fields or print the entirety.
Example Command Line
qi hdr input_file1.nii.gz input_file2.nii.gz --verbose
Multiple files can be queried at the same time. The --verbose
flag will make sure you can tell which is which.
Important Options
If any of the following options are specified, then only those fields will be printed instead of the full header. This is useful if you want to use a header field in a script:
* --origin, -o
* --spacing, -S
- The voxel spacing
* --size, -s
- The matrix size
* --voxvol, -v
- The volume of one voxel
Another useful option is --meta, -m
. This will let you query specific image meta-data from the header. You must know the exact name of the meta-data field you wish to obtain.
qi kfilter¶
MR images often required smoothing or filtering. While this is best done during reconstruction, sometimes it is required as a post-processing step. Instead of filtering by performing a convolution in image space, this tool takes the Fourier Transfrom of input volumes, multiplies k-Space by the specified filter, and transforms back.
Example Command Line
qi kfilter input_file.nii.gz --filter=Gauss,0.5
Outputs
input_file_filtered.nii.gz
Important Options
--filter,-f
Specify the filter to use. For all filters below the value (r) is the fractional distance from k-Space center, i.e. \(r = \sqrt(((k_x / s_x)^2 + (k_y / s_y)^2 + (k_z / s_z)^2) / 3)\). Valid filters are:
Tukey,a,q
A Tukey filter with parameters a and q. Filter value is 1 for \(r < (1 - a)\) else the value is \(\frac{(1+q)+(1-q)\cos(\pi\frac{r - (1 - a)}{a})}{2}\)
Hamming,a,b
A Hamming filter, parameters a and b, value is \(a - b\cos(\pi(1+r))\)
Gauss,w
orGauss,x,y,z
A Gaussian filter with FWHM specified either isotropically or for each direction independantly.
Blackman
orBlackman,a
A Blackman filter, either with the default parameter of \(\alpha=0.16\) or the specified \(\alpha\). Refer to Wikipedia for the relevant equation.
Rectangle,Dim,Width,Inside,Outside
A rectangular or top-hat filter along the specified dimension (must be 0, 1 or 2).
If multiple filters are specified, they are concatenated, unless the
--filter_per_volume
option is specified.--filter_per_volume
For multiple flip-angle data, the difference in contrast between flip-angles can lead to different amounts of ringing. Hence you may wish to filter volumes with more ringing more heavily. If this option is specified, the number of filters on the command line must match the number of volumes in the input file, and they will be processed in order.
--complex_in
and--complex_out
Read / write complex data.
qi mask¶
Implements several different masking strategies. For human data, BET, antsBrainExtraction of 3dSkullStrip are likely better ideas. For pre-clinical data, the strategies below can provide a reasonable mask with some tweaking. There are potentially three stages to generating the mask:
1 - Binary thresholding. If lower or upper thresholds are specified, these are used to separate the image into foreground and background. If neither are specified, then Otsu’s method is used to automatically estimate a reasonable threshold value. 2 - (Optional) Run the RATs algorithm 3 - (Optional) Hole-filling
Example Command Line
qi mask input_image.nii.gz --lower=10 --rats=1200 --fillh=1
In this case an intensity value of 10 will be used as the threshold, RATs will be run with a target volume of 1200 mm^3, and then holes with a radius of 1 voxel will be filled.
Outputs
input_image_mask.nii.gz
Important Options
--lower,-l
/--upper,-u
Specify lower and/or upper intensity thresholds. Values below/above these values are set to 0, those inside are set 1. If this option is not specified, Otsu’s method will be used to generate a threshold value. If no thresholding is desired, specify
--lower=0
.--rats, -r
Use the RATs algorithm to remove non-brain tissue. The RATs algorithm uses erode & dilate filters of progressively increasing size until the largest connected component falls below a target size. For rats, target values of around 1000 mm^3 are reasonable.
--fillh, -F
Fill holes in the mask up to radius N voxels.
References
qi polyfit/qi polyimg¶
These tools work together to fit Nth order polynomials to images. This is typically used for smoothing a B1 field.
qi polyfit
will output the polynomial co-efficients and origin to stdout
. qi polyimg
can then read these to generate the polyimage image, using a different image as the reference space. In this way the polynomial image can be created without having to use upsampling.
Example Command Line
qi polyfit noisy_b1_map.nii.gz --mask=brain_mask.nii.gz --order=8 | qi polyimg hires_t1_image.nii.gz hires_smooth_b1_map.nii.gz --order=8
With the above command-line the output of qi polyfit
is piped directly to the output of qi polyimg
. You can instead redirect it to a file with >
and read it in separately. The --order
argument must match between the two commands.
Important Options
--order, -o
The order of the fitted polynomial. Default is 2 (quadratic)
--mask, -m
Only fit the data within a mask. This is usually the brain or only white-matter.
--robust
(qi polyimg
only)Use Robust Polynomial Fitting with Huber weights. There is a good discussion of this topic in the Matlab help files.
qi ssfp_bands¶
There are several different methods for removing SSFP bands in the literature. Most of them rely on acquiring multiple SSFP images with different phase-increments (also called phase-cycling or phase-cycling patterns). Changing the phase-increments moves the bands to a different location, after which the images can be combined to reduce the banding. The different approaches are discussed further below, but the recommended method is the Geometric Solution which requires complex data.
Example Command Line
qi ssfpbands ssfp.nii.gz --method=G --2pass --magnitude
The SSFP file must be complex-valued to use the Geometric Solution or Complex Average methods. For the other methods magnitude data is sufficient. Phase-increments should be in opposing pairs, e.g. 180 & 0 degrees, 90 & 270 degrees. These should either be ordered in two blocks, e.g. 180, 90, 0, 270, or alternating, e.g. 180, 0, 90, 270.
Outputs
The output filename is the input filename with a suffix that will depend on the method selected (see below).
Important Options
--method
Choose the band removal method. Choices are:
G
Geometric solution. Suffix will beGSL
orGSM
- X` Complex Average. Suffix will be
CS
(for Complex Solution) R
Root-mean-square. Suffix will beRMS
M
Maximum of magnitudes. Suffix will beMax
N
Mean of magnitudes. Suffix will beMagMean
--regularise
The Geometric Solution requires regularisation in noisy areas. Available methods are:
M
Magnitude regularisation as in original paperL
Line regularisation (unpublished)N
None
The default is
L
. IfL
orM
are selected, then that character will be appended to the suffix.--2pass, -2
Apply the second-pass energy-minimisation filter from the original paper. Can be likened to smoothing the phase data. If selected will append
2
to the suffix.--alt-order
Phase-increments alternate, e.g. 180, 0, 90, 270. The default is the opposite (two blocks), e.g. 180, 90, 0, 270.
--ph-incs
Number of phase-increments. The default is 4. If you have multiple phase-increments and (for example) multiple flip-angles,
qi ssfpbands
can process them all in one pass.--ph-order
The data order is phase-increment varying fastest, flip-angle slowest. The default is the opposite.
References
qi diff¶
Calculates the mean square difference between two images and checks if it is below a tolerance value. Used in the QUIT tests to ensure that calculated parameter maps are close to their baseline values.
Example Command Line
qi diff --baseline=original.nii --input=calculated.nii --noise=0.01
The command returns the dimensionless noise factor on stdout, which is read by the test suite. Note, to make useage clearer, unlike most other QUIT commands all input is specified as arguments.
Important Options
--baseline
The baseline image. Required.
--image
The image to compare to the baseline. Required.
--noise
The added noise level.
--tolerance
The tolerance is relative to the added noise level (i.e. it is a noise amplification factor).
--abs, -a
Use absolute difference instead of fractional difference (i.e. do not divide by the baseline image). Useful when images contain genuine zeros (e.g. off resonance maps).
qi newimage¶
Creates new images filled with specified patterns. Used for generating test data.
Example Command Line
qi newimage --size 32,32,32 --grad "0 0.5 1.5" output_image.nii.gz
The file specified on the command line is the output file.
Important Options
--dims, -d
The output dimension. Valid values are 3 and 4.
--size, -s
Matrix size of the output image.
--fill, -f
Set all voxels in the image to the specified value.
--grad, -g "DIM,LOW,HIGH"
Fill voxels with a gradient along the specified dimension, starting at the low value at one edge and finishing at the high value on the other. It is recommended to encase
DIM,LOW,HIGH
with quotation marks as they must be passed as a single string to be interpreted properly.--step, -t "DIM,LOW,HIGH,STEPS"
Similar to
--grad
, but instead of a smooth gradient will with a number of discrete steps.--wrap, -w
Wrap output voxels at the specified value. Useful for simulating phase data.
qi select¶
Selects a set of volumes from a 4D file and writes them to a new 4D file (a reimplemention of fslselectvols).
Example Command Line
qi select in_file.nii out_file.nii 2,4,6,8
The last argument is a comma-separated list of the volumes you wish to select.
Developer¶
Below are a few introductory notes for anyone who wants to compile QUIT from source or might be interested in contributing to QUIT. Although I hope that most QUIT code is fairly clear, the following is provided to give a high-level overview of how most QUIT commands are structured.
Basic Requirements¶
- A C++17 compliant compiler (GCC 7.0.0+, Clang 3.9+)
- CMake version 3.10.2 or higher (http://www.cmake.org)
WARNING - You will require a recent compiler for QUIT as it uses C++17 features. On Mac simply having the most recent software updates is enough, on Linux you will need GCC 7.0.0. No one has been brave enough to compile QUIT on Windows to date.
Installing GCC 7¶
Most Linux systems currently ship with GCC 4.8 or lower as their system compiler. As of QUIT 2.1 you will require GCC 7 as QUIT uses C++17 features. Joost Kuijer has kindly provided the following recipe for installing newer GCC versions in a user directory and using it to compile QUIT.
Follow the GCC guide here: https://gcc.gnu.org/wiki/InstallingGCC
- Before running the
build.sh
script let cmake know about the new compiler export PATH=$HOME/GCC-7.0.0/bin:$PATH export LD_LIBRARY_PATH=$HOME/GCC-7.0.0/lib:$HOME/GCC-7.0.0/lib64:$LD_LIBRARY_PATH export CC=$HOME/GCC-7.0.0/bin/gcc export CXX=$HOME/GCC-7.0.0/bin/g++
- Before running the
- Before executing the compiled code also do (you can add this line to your .bashrc file:
export LD_LIBRARY_PATH=$HOME/GCC-7.0.0/lib:$HOME/GCC-7.0.0/lib64:$LD_LIBRARY_PATH
External Libraries¶
QUIT is built using several C++ libraries. These are currently included in the project as git submodules. The easiest way to initialise these is with the build.sh
script. However, if you are already have some of them available you may wish to not run the script and instead configure them yourself. This is discussed further below. The libraries are:
-
A high performace linear algebra library. Used for all signal equations in QUIT.
-
A high performace, high quality collection of non-linear least squares solvers.
-
The Insight Tool-Kit. This is intended as a registration library for medical images. Although the registration features are not used in QUIT, the overall framework is extremely useful. In particular, ITK reads a large variety of common file-formats, and all ITK filters automatically check that their inputs share a common space / co-ordinate definition. This single feature alone prevents the vast majority of easy user mistakes - e.g. trying to use a B1 map that has a different voxel spacing to the input data.
Compilation¶
If you are unfamiliar with C++/CMake/git etc. a script is provided that should be able to build the tools provided the right software is available on your system. To use it, in a terminal window, change directory to where you unpacked QUIT. Then type ./build.sh
. This should correctly checkout the git repositories for each external library, build Ceres and ITK, and then configure and build QUIT.
CMake projects separate the build
and install
phases. The binaries are only moved to a single folder during install
. By default, the install directory is /usr/local/bin
. If you run ./build.sh -i``it will run the install step to this directory. You can also ``cd
into the build/
directory and then type make install
(or ninja install
) to avoid re-running the entire build.sh
script.
If you want to change where the binaries are installed, you can either:
- Run ./build.sh -i -p /path/to/install
- cd /build; ccmake ./
, change the INSTALL_PREFIX_DIR
, configure (press c), generate (press g), exit, then make install
Note that the binaries will end up in /bin
inside the install prefix.
If you are familiar with C++/CMake/git etc. then compiling QUIT should be straightforward. The rough steps are:
- Ensure you have all the libraries above available. If you do not have system versions, then run
git submodule init; git submodule update
in the QUIT directory. - Compile the Ceres library. Make sure it uses the same version of Eigen that you will use for QUIT.
- Compile ITK following their instructions.
- Create a build directory for QUIT and use cmake/ccmake to configure the project. Specify the paths to the library when prompted. It is likely that CMake will report an error on the first ‘Configure’ attempt if it cannot locate Eigen, specify the correct directory and run the configure step again.
- Compile QUIT.
File Formats¶
The available file formats are controlled by the main CMakeLists.txt
in the root QUIT directory, by listing them as COMPONENTS
in the ITK find_package()
step. Add any additional file formats you wish to use here.
Tests¶
QUIT commands are tested using the nipype
wrappers and unittest
. To run the tests, first build and install QUIT
(so that the executables are available in your $PATH
variable), then cd
into Python/Tests
and then run python -m unittest discover
, which will run all of the tests. It is possible to run the test files individually as well.
Most QUIT commands are tested by generating ground-truth parameter files with qi newimage
, feeding these into each QUIT
command with the --simulate
argument to generate simulated MR images with added noise, and then running them back through the QUIT
command to calculate the parameter maps, and comparing these to the ground-truth with qi diff
. qi diff
calculates a figure-of-merit based on noise factors, i.e. they are a measure of how much the signal noise is amplified in the final maps. In this way the tests also serve to illustrate the quality of the methods as well as whether the commands run correctly. For commands where a ground-truth image cannot be generated easily, the tests at least ensure that the command runs and does not crash.
The ModelFitFilter¶
The core part of QUIT is the ModelFitFilter
and its dependent type FitFunction
, found in Source/Core/
. This is a sub-class of the ITK ImageToImageFilter
. The vast majority of QUIT commands declare an Model and FitFunction sub-class and use these to process the data. ModelFitFilter
abstracts out most of the heavy lifting of extracting voxel-wise data from multiple inputs and writing it out to multiple outputs, leaving the FitFunction
to process a single-voxel. A Model
defines the number of expected inputs and their size, the number of fixed & varying parameters, and the number of outputs.
Example: qi despot1
¶
The structure of qi despot1
is similar to most QUIT commands, and is a good example of most features. At the start are the includes (obviously). After that several FitFunction
subclasses are defined, as well as a Ceres cost-function. The Ceres documentation is excellent, so refer to that for more information. After all the FitFunction
classes are defined, the main command body begins. At the start of the command, all the command-line options are defined and then parsed. Then the various inputs are read and passed to the ModelFitFilter
, which is then updated. Finally, the outputs are written back to disk.
Citing¶
QUIT has been published in the Journal of Open Source Software. If you use it, please cite:
Note
Wood, (2018). QUIT: QUantitative Imaging Tools. Journal of Open Source Software, 3(26), 656, https://doi.org/10.21105/joss.00656
Thank you.
Installation¶
Pre-compiled binaries are provided for Linux and Mac OS X from http://github.com/spinicist/QUIT/releases.
Download the correct archive for your platform, untar it and then ensure that the binaries can be found via your PATH environment variable. Either edit your shell profile (e.g. .bashrc
) and add the QUIT directory your $PATH
variable there, or copy the files to somewhere that will be on your path, e.g. /usr/local/bin
(this will likely require sudo
permissions).
The Linux binaries are built with Ubuntu 16.04 with GCC 7 and glibc
version 2.17. If you need to run on an older version of Linux with a previous version of glibc
then you may need to compile from source.
Compile From Source¶
Compiling from source is recommended to keep up to date with the master
branch. A build.sh
script is provided that should automate this process. By default, build.sh
only builds the binary commands. To install these to a single directory, you must run ./build.sh -i
. The default install location is /usr/local/bin
, but this can be changed by running ./build.sh -i -p /path/to/install/prefix/
.
For more details see the Developer documentation.
General Usage¶
If you run qi
a list of available commands will be printed to the terminal. QUIT commands take their input as a combination of command-line arguments and text files passed to stdin
. If you run a QUIT command with no arguments then will see a message like this:
~: qi despot1
SPGR FILE was not specified. Use --help to see usage.
>
If you then run it with --help
, you will see some usage instructions:
~: qi despot1 --help
qi despot1 {OPTIONS} [SPGR FILE]
Calculates T1 maps from SPGR data
http://github.com/spinicist/QUIT
OPTIONS:
SPGR FILE Path to SPGR data
-h, --help Show this help message
-v, --verbose Print more information
-T[THREADS], --threads=[THREADS] Use N threads (default=4, 0=hardware
limit)
-o[OUTPREFIX], --out=[OUTPREFIX] Add a prefix to output filenames
-b[B1], --B1=[B1] B1 map (ratio) file
-m[MASK], --mask=[MASK] Only process voxels within the mask
-s[SUBREGION],
--subregion=[SUBREGION] Process subregion starting at voxel
I,J,K with size SI,SJ,SK
-r, --resids Write out residuals for each data-point
-a[ALGO], --algo=[ALGO] Choose algorithm (l/w/n)
-i[ITERS], --its=[ITERS] Max iterations for WLLS/NLLS (default
15)
-p[CLAMP PD], --clampPD=[CLAMP
PD] Clamp PD between 0 and value
-t[CLAMP T1], --clampT2=[CLAMP
T1] Clamp T1 between 0 and value
"--" can be used to terminate flag options and force all following
arguments to be treated as positional options
The first line shows that DESPOT1 expects a single input image, in this case SPGR/FLASH/FFE, specified on the command line. However, if you naively run:
~: qi despot1 some_spgr_data.nii.gz
Nothing will happen. This is because most imaging formats do not store parameters that are required for quantitative imaging, e.g. the repetition time and flip-angles in their headers. QUIT commands hence expect to read this information in a text file passed to stdin
. If you create a small text file spgr.json
containing the following:
{
"SPGR": {
"TR": 0.01,
"FA": [3, 18]
}
}
and run the following:
~: qi despot1 some_spgr_data.nii.gz < spgr.json
then - provided your input data does contain two volumes corresponding to flip-angles 3 and 18 degrees - DESPOT1 will run, and you should see two files created (D1_T1.nii.gz
and D1_PD.nii.gz
). If you want to see what the commands are doing while running, specify the --verbose
or -v
options.
Common Options¶
The following options are supported by most, but not necessarily all, QUIT commands.
--out, -o
Add a prefix to the output parameter files. By default, most QUIT commands write their output files using filenames in a pattern command_PARAMETER.nii.gz. They will overwrite any existing files with the same names. If you need to save the output from multiple runs of the same command, or want to save output to a particular directory, use this option to add an addtional prefix to the output names.
--mask, -m
Specify a mask file, where non-zero values indicate that voxels should be processed, and zero values indicate that voxels should not be processed. The background voxels will be set to zero in the final image. This is useful for two reasons, first is to simply speed up processing for long-running commands (e.g. qi mcdespot), second is that outside the head fitting data is non-sensical, as there is no signal. Hence these regions appear very noisy on output maps, which can make visualization difficult.
--threads, -t
Control the maximum number of threads used. The majority of QUIT commands are multi-threaded across voxels to improve processing times. In some parallel computing environments (e.g. Sun Grid Engine), it is possible to set the maximum number of cores available to a command, and it is hence good for CPU utilisation to match the number of threads to the number of cores. The default is 4. Note that HyperThreading may make the number of logical cores appear to be double the number of physical cores - QUIT commands are CPU bound, not IO bound, and hence gain no benefit from HyperThreading. You are better to specify the number of physical cores available rather than the number of logical cores.
--subregion, -s
Similar to –mask, this command will only process a sub-region of the input images. The argument needs to be in the format “start_i,start_j,start_k,size_i,size_j,size_k” where i,j,k are voxel indices (not physical co-ordinates). This is useful to speed up processing for trial-runs of pipelines.
--resids, -r
Most QUIT commands will write out a single root-sum-squared residual image along with their parameter maps. Use this option to also output residuals for each data-point to look for systematic offsets. Note that if multiple inputs are specified (e.g. qi mcdespot), then this option will write out a single cocatenated file for all input data-points in order.
--B1, -b
&--f0, -f
Several of the QUIT commands take B1 (relative flip-angle) and f0 (off-resonance in Hz) maps as correction factors.
File Formats¶
By default, QUIT is compiled with support for NIFTI and NRRD formats. The preferred file-format is NIFTI for compatibility with FSL and SPM. By default QUIT will output .nii.gz
files. This can be controlled by the QUIT_EXT environment variable. Valid values for this are any file extension supported by ITK that QUIT has been compiled to support, e.g. .nii
or .nrrd
, or the FSL values NIFTI
, NIFTI_PAIR
, NIFTI_GZ
, NIFTI_PAIR_GZ
.
The ITK library supports a much wider variety of file formats, but adding support for all of these almost triples the size of the compiled binaries. Hence by default they are excluded. You can add support for more file formats by compiling QUIT yourself, see the Developer documentation. Note that ITK cannot write every format it can read (e.g. it can read Bruker 2dseq datasets, but it cannot write them).
Python Integration / Scripting¶
A set of nipype
wrappers for all QUIT commands is provided, which can be found in the Python/QUIT
subdirectory. The current recommended way to use these is to clone the QUIT git repository, then cd
to the Python/QUIT
directory and type pip install -e .
. This will allow you to update the wrappers with a git pull
in the future. If anyone is an expert at Python packaging and knows how to upload the wrappers to pip
or conda-forge
, please get in touch.