Programs · FSL
mcflirt
mcflirt corrects head motion in a 4D series.
- Original
- FSL 6.0.7.23
- Command line
larmorx fsl mcflirt- Python
lx.mri.hmc- Ports
- replica
larmorx-ncFSL Licence: non-commercial use only validated - clean room
larmorxApache-2.0 experimental
- replica
- Evidence
- every comparison with FSL
- Source
- made from docs/api/mri-hmc.md and the code
What it does
It registers every volume to the reference with a rigid-body transform (or up to 12 degrees
of freedom with dof) by mcflirt’s schedule: one sweep of line searches on the reference
sampled every 8 mm, then every 4 mm, then 4 mm with an eight times tighter tolerance; each
volume’s first search starts from its predecessor’s result. The cost is mcflirt’s normalised
correlation. It then resamples the series with the transforms. mcflirt’s defects are corrected
by default; upstream_defects="reproduce" gives mcflirt’s matrices
(Defects of the original).
Command line
larmorx fsl mcflirt -in <infile> [options]Everything after larmorx fsl mcflirt is the original’s command line: the arguments of FSL 6.0.7.23’s mcflirt, as FSL takes them. LARMORX’s own options stand between larmorx and the family fsl, so they never meet the original’s (below):
larmorx
[--n-threads N]
[--implementation auto|replica|clean-room]
[--upstream-defects fix|reproduce]
fsl mcflirt ...From the next release. In 0.1.0rc1, set the variables instead: OMP_NUM_THREADS, LARMORX_IMPLEMENTATION (original for the clean room) and LARMORX_UPSTREAM_DEFECTS.
mcflirt's usage text, as the clean room prints it
Usage: larmorx mri hmc -in <infile> [options]
Head-motion correction (larmorx, clean-room; accepts mcflirt-style options)
Available options are:
-out, -o <outfile> (default is infile_mcf)
-cost {mutualinfo,woods,corratio,normcorr,normmi,leastsquares} (default is normcorr)
-bins <number of histogram bins> (default is 256)
-dof <number of transform dofs> (default is 6)
-refvol <number of reference volume> (default is no_vols/2)- registers to (n+1)th volume in series
-reffile, -r <filename> use a separate 3d image file as the target for registration (overrides refvol option)
-scaling <num> (accepted and ignored)
-smooth <num> (1.0 is default - controls smoothing in cost function)
-rotation <num> specify scaling factor for rotation optimization tolerances
-verbose <num> (0 is least and default)
-stages <number of search levels> (default is 3 - specify 4 for final sinc interpolation)
-fov <num> (default is 20mm - specify size of field of view when padding 2d volume)
-2d Force padding of volume
-sinc_final (applies final transformations using sinc interpolation)
-spline_final (applies final transformations using spline interpolation)
-nn_final (applies final transformations using Nearest Neighbour interpolation)
-init <filename> (initial transform matrix to apply to all vols)
-meanvol register timeseries to mean volume (overrides refvol and reffile options)
-stats produce variance and std. dev. images
-mats save transformation matricies in subdirectory outfilename.mat
-plots save transformation parameters in file outputfilename.par
-report report progress to screen
-help
Output images use the extension of FSLOUTPUTTYPE (default NIFTI_GZ). Threads: OMP_NUM_THREADS
(default: all logical CPUs); the results do not depend on it.Python
lx.mri.hmc(
bold: Any,
*,
reference: Any = None,
ref_index: int | None = None,
mean: bool = False,
stages: int = 3,
final: Final = "trilinear",
dof: int = 6,
cost: Cost = "normcorr",
smooth: float = 1.0,
rotation: float = 1.0,
bins: int = 256,
fudge: bool = False,
in_plane: Literal["auto", "always", "never"] = "auto",
fov: int = 20,
init: np.ndarray | None = None,
resample: bool = True,
n_threads: int = 1,
upstream_defects: UpstreamDefectsName = "fix",
normcorr_count: NormCorrCount = "mcflirt",
implementation: ImplementationName = "auto",
) -> HmcResultWhere Final is one of "trilinear", "sinc", "spline", "nearest"; Cost is one of "normcorr", "leastsquares", "corratio", "woods", "mutualinfo", "normmi"; UpstreamDefectsName is one of "fix", "reproduce"; NormCorrCount is one of "mcflirt", "weights"; ImplementationName is one of "auto", "replica", "clean-room", "original" (0.1.0rc1’s spelling of "clean-room").
Correct head motion in a 4D series (mcflirt’s algorithm).
bold is a path (read with mcflirt’s rules, below) or an in-memory image (lx.Image, nibabel
image, (array, affine)); reference likewise. The result, an HmcResult, also writes
mcflirt’s files: save_mats(directory) and save_par(path), and save_itk(path) writes itk
as fMRIPrep’s mat2itk.txt; affine_series wraps affines as lx.transforms.AffineSeries. Its
implementation is lx.Implementation("clean-room", "larmorx", ...) or the replica’s
("replica", "larmorx-nc", its version, "LicenseRef-FSL", its program).
lx.mri.read_mats(directory) reads an mcflirt-style .mat directory into an (N, 4, 4) array.
Reading. As mcflirt: values become float32 (scl_slope/scl_inter applied when they ask
for it), voxel sizes come from pixdim, and images whose sform (or qform) has a positive
determinant have their x axis reversed in memory, so the matrices refer to “radiological”
order. Obliquity does not matter: the estimation works in voxel coordinates. The world
transforms (affines, itk) undo all of this.
Threads. n_threads (0 = all logical CPUs). The first stage is a chain within each sweep,
so its volumes run one after another with each cost evaluation’s slices in parallel; the later
stages run the volumes in parallel. The result does not depend on the thread count.
import larmorx as lx
# fMRIPrep's head-motion step: the HMC reference, the matrices only.
hmc = lx.mri.hmc("sub-01_task-rest_bold.nii.gz", reference="hmc_boldref.nii.gz",
resample=False, n_threads=8)
hmc.matrices # (N, 4, 4) FSL matrices, as mcflirt's MAT_* files
hmc.affines # (N, 4, 4) RAS transforms, reference -> volume (nitransforms)
hmc.save_itk("mat2itk.txt") # fMRIPrep's ITKLinearTransformArray (LPS)
hmc.fd # Power's framewise displacement (radius 50 mm)
# Everything mcflirt writes
res = lx.mri.hmc("bold.nii.gz") # reference: volume N // 2
res.image.save("bold_mcf.nii.gz")
res.save_mats("bold_mcf.mat"); res.save_par("bold_mcf.par")
# One-shot resampling with the motion (fMRIPrep's way)
lx.transforms.resample_series(..., transforms=[res.affine_series, ...])Its result, HmcResult, holds the result of hmc.
| Field | Type | What it holds |
|---|---|---|
matrices |
np.ndarray |
(N, 4, 4): one matrix per volume in mcflirt's .mat convention, mapping the volume’s FSL-mm coordinates (voxel index times voxel size, x reversed for images whose affine has a positive determinant) to the reference’s. |
affines |
np.ndarray |
(N, 4, 4): the same motion in RAS world coordinates, mapping reference points to the volume’s points (nitransforms’ LinearTransformsMapping convention, as fMRIPrep stores head motion). affine_series wraps them for resample_series. |
itk |
np.ndarray |
(N, 4, 4): affines in LPS (ITK and ANTs). |
params |
np.ndarray |
(N, 6): rx ry rz tx ty tz (radians, mm) about the reference’s intensity-weighted centre, as mcflirt -plots writes them. |
rms_abs |
np.ndarray |
mcflirt's RMS displacements (radius 80 mm): from the reference (N) and from the previous volume (N - 1). |
rms_rel |
np.ndarray |
mcflirt's RMS displacements (radius 80 mm): from the reference (N) and from the previous volume (N - 1). |
fd |
np.ndarray |
Power’s framewise displacement from params (radius 50 mm; 0 for the first volume). |
reference_index |
int | None |
The reference volume of the series, or None (a separate reference or the mean). |
in_plane |
bool |
Whether the in-plane mode for thin slabs was used (only rz, tx, ty move). |
image |
Image | None |
The corrected series (float32) when resample was asked for, else None. |
mean |
Image | None |
The mean volume of mean=True (the first pass’s corrected mean), else None. |
implementation |
_replica.Implementation |
The implementation that computed the result: larmorx’s clean room, or the larmorx-nc replica with its version (Implementation). |
Options
Each row joins an option of the original’s command line with the Python argument that does the same. The rows are checked against the code at every test run: the options mcflirt accepts (crates/larmorx-mri/src/cli/hmc.rs) and the arguments of lx.mri.hmc (python/larmorx/mri/hmc.py), whose defaults and descriptions are taken from it. Under each option, in grey, its line of the usage text the clean room prints, in the clean room’s own words.
mcflirt option |
Python | Default | Notes |
|---|---|---|---|
-in (or a bare argument) |
bold |
the series | |
-out, -o |
command line only | the outputs’ namesThe clean room’s usage: “(default is infile_mcf)” | |
-reffile, -r |
reference |
None |
a separate reference volume: the first volume of a 4D file, with mcflirt’s warningThe clean room’s usage: “use a separate 3d image file as the target for registration (overrides refvol option)” |
-refvol |
ref_index |
None |
-1: the default N/2The clean room’s usage: “(default is no_vols/2)- registers to (n+1)th volume in series” |
-meanvol |
mean=True |
False |
Register to the mean of the series after a first registration (-meanvol) to reference if given, else to volume ref_index.The clean room’s usage: “register timeseries to mean volume (overrides refvol and reffile options)” |
-stages |
stages |
3 |
1 to 4; 4 adds the sinc stageThe clean room’s usage: “(default is 3 - specify 4 for final sinc interpolation)” |
-mats, -plots, -rmsrel, -rmsabs |
the result: HmcResult.matrices, .params, .rms_rel, .rms_abs |
the same files and text formats; through the replica, Python returns the files’ values (matrices to 6 decimals, parameters and RMS to 6 significant digits)The clean room’s usage: “save transformation matricies in subdirectory outfilename.mat”The clean room’s usage: “save transformation parameters in file outputfilename.par” | |
-stats |
command line only | _meanvol, _variance, _sigma; every slice, named after -out without its extension; mcflirt’s end slices at 0 and names with reproduce (FSL-08), in both portsThe clean room’s usage: “produce variance and std. dev. images” |
|
-sinc_final, -spline_final, -nn_final |
final="sinc", "spline", "nearest" |
"trilinear" |
The final interpolation: one of INTERPOLATIONS.The clean room’s usage: “(applies final transformations using sinc interpolation)”The clean room’s usage: “(applies final transformations using spline interpolation)”The clean room’s usage: “(applies final transformations using Nearest Neighbour interpolation)” |
-dof |
dof |
6 |
6 to 12; the command line clamps with mcflirt’s messageThe clean room’s usage: “(default is 6)” |
-cost |
cost |
"normcorr" |
the clean room: normcorr (its count’s running total takes each point’s weight as the point is visited, since 2026-11-07), mutualinfo, normmi (exactly as the spec’s appendix B: mcflirt’s evaluated matrices, evaluation by evaluation); corratio, woods (FLIRT’s, since 2026-11-02), leastsquares (FLIRT’s leastsq: three single-precision levels, since 2026-11-07); the replica: every cost, bit-identicalThe clean room’s usage: “(default is normcorr)” |
-bins |
bins |
256 |
below 8 with a histogram cost: refused by default (FSL-21)The clean room’s usage: “(default is 256)” |
-smooth |
smooth |
1.0 |
0: unweighted, Pearson’s correlationThe clean room’s usage: “(1.0 is default - controls smoothing in cost function)” |
-rotation |
rotation |
1.0 |
Divides the rotation tolerances (-rotation).The clean room’s usage: “specify scaling factor for rotation optimization tolerances” |
-fudge |
fudge=True |
False |
also makes the first stage fully parallel, in both ports |
-2d, -fov |
in_plane="always", fov |
in_plane="auto", fov=20 |
in_plane="never" is LARMORX’s own: under "auto" the clean room runs itThe clean room’s usage: “Force padding of volume”The clean room’s usage: “(default is 20mm - specify size of field of view when padding 2d volume)” |
-init |
init |
None |
final resampling only, as mcflirtThe clean room’s usage: “(initial transform matrix to apply to all vols)” |
-scaling, -hist, -v, -verbose, -report |
command line only | accepted; -scaling and -hist have no effect (in mcflirt either; a warning says so, FSL-05); the clean room’s -report prints progress messages (not mcflirt’s exact text); the replica prints mcflirt’s messages to the byte (-verbose 20 prints every evaluated matrix)The clean room’s usage: “(accepted and ignored)”The clean room’s usage: “(0 is least and default)”The clean room’s usage: “report progress to screen” |
|
-gdt |
command line only | not supported by the clean room (exit 1); the replica refuses it by default, and with reproduce registers the gradient images as mcflirt does (FSL-04) |
|
-help |
command line only | the usage, exit 0; without arguments: exit 1 (-help alone exits 0; mcflirt’s exit 1 with reproduce, FSL-07); the same in both ports |
|
| (none: mcflirt always resamples) | resample=False |
True |
the matrices only, as fMRIPrep needs; it saves no time with the replica |
| (none) | normcorr_count="mcflirt" |
"mcflirt" |
"weights": the corrected correlation count (FSL-02), opt-in (The correlation count); the clean room’s only (the replica counts as mcflirt; under "auto" the clean room runs it) |
FSLOUTPUTTYPE |
command line only | the output format (Output types and file names) | |
LARMORX_UPSTREAM_DEFECTS |
upstream_defects |
"fix" |
mcflirt’s defects corrected (default) or reproduced; the replica’s reproduce gives mcflirt’s bytes |
LARMORX’s own options
From the next release. In 0.1.0rc1, set the variables instead: OMP_NUM_THREADS, LARMORX_IMPLEMENTATION (original for the clean room) and LARMORX_UPSTREAM_DEFECTS.
They stand between larmorx and fsl on the command line (larmorx --n-threads 4 fsl mcflirt ...) and are arguments of lx.mri.hmc. Each one given wins over its environment variable, which keeps working.
| Command line, then Python | What it does |
|---|---|
--n-threads Nn_threads=1 |
Worker threads (0 = all logical CPUs). The result does not depend on it. Default: every logical CPU on the command line (0), 1 in Python. The variable OMP_NUM_THREADS in 0.1.0rc1. |
--implementation auto|replica|clean-roomimplementation="auto" |
"auto" (default): the bit-exact replica when the larmorx-nc package is installed (FSL Licence: non-commercial use only; pip install larmorx-nc), else the clean room; "replica" or "clean-room" ("original", 0.1.0rc1’s spelling, still works) force one. The replica runs mcflirt's command line as a separate program on files in a temporary directory and returns mcflirt's outputs as written (the matrices with 6 decimals, the parameters and RMS values with 6 significant digits, the corrected series as float32 from the file in the input’s data type). Options with no command-line equivalent (in_plane="never", normcorr_count="weights") run the clean room under "auto" and are an error with "replica". resample=False saves no time with the replica (mcflirt always resamples); the series is then not returned. The variable LARMORX_IMPLEMENTATION in 0.1.0rc1. |
--upstream-defects fix|reproduceupstream_defects="fix" |
"fix" (default) corrects mcflirt’s defects: the last volume of the series starts its first stage from its predecessor’s result like every other volume (FSL-01), the in-plane mode pads the first stage’s grid once (FSL-03), and NaN or infinite voxels are left out of the centre of mass and the cost instead of making the matrix NaN (FSL-14). "reproduce" gives mcflirt’s matrices. A UpstreamDefectWarning names each defect that changed the result (or would have been corrected). The variable LARMORX_UPSTREAM_DEFECTS in 0.1.0rc1. |
Examples
The tests run every example below (validation/tests/test_reference.py), each section in a new folder where these inputs are made first: bold.nii.gz (a synthetic series of 4 such heads), ref.nii.gz (a synthetic head of 40 × 48 × 40 voxels of 4 mm). The command lines run as python -m larmorx.
import larmorx as lx
# fMRIPrep's way: a separate reference, the matrices only.
hmc = lx.mri.hmc("bold.nii.gz", reference="ref.nii.gz", resample=False)
hmc.matrices.shape # -> (4, 4, 4)
hmc.image is None # -> Truelarmorx fsl mcflirt -in bold.nii.gz -reffile ref.nii.gz -mats -plots -rmsrel -rmsabs
larmorx mri hmc -in bold.nii.gz -out bold_mcf -meanvolOutput types and file names
FSLOUTPUTTYPE chooses the output format as for mcflirt 6.0.7.23 (NIFTI, NIFTI2, the pair
types NIFTI_PAIR and NIFTI2_PAIR, each also _GZ, _ZST and _BZ2: gzip, zstd and bzip2,
pure Rust); an unknown value prints FSL’s message (ERROR:: Unrecognised value (…) of environment variable FSLOUTPUTTYPE and the legal values) and exits 1 before any work. Inputs are read by
their content (gzip, zstd, bzip2 or uncompressed), whatever their names, and a name without an
image extension is completed as FSL completes it (.nii.gz, .nii, .hdr, .hdr.gz,
.nii.zst, .hdr.zst, .nii.bz2, .hdr.bz2; two matches or none are FSL’s errors), also by
the Python API. The CLI’s threads come from OMP_NUM_THREADS (default: all).
Ports
mcflirt has two ports: a replica and a clean room.
| Port | Package | Licence | Status | Records |
|---|---|---|---|---|
| replica | larmorx-nc |
FSL Licence: non-commercial use only | validated | fsl-mcflirt-replica, fsl-mcflirt-replica-full |
| clean room | larmorx |
Apache-2.0 | experimental | mri-hmc |
The replica against mcflirt 6.0.7.23 itself (its record,
the standard comparison, 2026-11-02): 205 of 205 compared cases bit-identical (every file, the
exit status and both streams, the replica in reproduce mode), 32 where both end with the same
error. Against FSL 6.0.7.17 before the version update (its full record,
2026-10-25): 137 of the 137 recorded mcflirt runs, with the same messages and exit status where
both fail (12 of them), fMRIPrep’s own mcflirt calls on the 12 fMRIPrep runs with BOLD series (22
of 22, the data panel’s included; fMRIPrep’s 4,517 matrices are identical too) and 35 edge cases:
173 of 173 compared cases bit-identical, 21 rejected alike.
The clean room against mcflirt 6.0.7.23 (its record, the
standard comparison, 2026-11-11): every recorded run of mcflirt replayed and compared, 170
cases: 145 within the thresholds, 21 rejected by both alike, 4 expected divergences (each with
its reason in the record), 0 failures. On fMRIPrep’s command the matrices differ from mcflirt’s
by less than mcflirt differs from itself when its input is perturbed slightly (half an intensity
unit of noise, the volume order reversed): for nine real runs, the 95th percentile of the matrix
RMS deviation is 0.0151–0.0274 mm (mcflirt’s own band: 0.0164–0.1014 mm), on each run at or
below mcflirt’s own. On every run with -mats (116) the worst 95th percentile is 0.1186 mm (the
thresholds: 0.1 mm, or mcflirt’s band where wider, as on 26 runs). The differences are explained
under Agreement with mcflirt.
FSL is distributed under the FSL Licence (non-commercial use only), so mcflirt has two ports, a
replica and a clean room, in different packages (licensing):
- The replica is bit-exact:
larmorx-nc fsl mcflirt, in the packagelarmorx-nc(crates-nc/), under the FSL Licence’s terms, translated from mcflirt’s source (fsl-mcflirt 2111.0 and the libraries it uses). It gives mcflirt’s output files byte for byte (The replica). - The clean room is in the main package (Apache-2.0, crate
larmorx-mri), written from the behaviour specspecs/mcflirt.md, the published papers,mcflirt -helpand black-box runs of FSL’s program, without FSL’s source (PROVENANCE). It is named by what it does,mri hmc, not after the program it is compatible with (decision D4).
Both follow mcflirt 6.0.7.23 and are compared with it; the clean room follows its -sinc_final
and -nn_final (FSL-59), its zstd and bzip2 output types, its reading of files by content and
its names (FSL-60), and computes -cost mutualinfo and normmi exactly as the spec’s appendix B
describes them (2026-10-29).
implementation="auto" (the default) runs the replica when larmorx-nc is installed, else the
clean room; "replica" or "clean-room" ("original", 0.1.0rc1’s spelling, still works) force
one. The command line chooses alike (--implementation before the family, or
LARMORX_IMPLEMENTATION).
Evidence
How each of mcflirt’s ports was measured against FSL, case by case: its evidence.
More in the repository
The API page docs/api/mri-hmc.md holds what mcflirt shares with the page’s other programs: