Programs · FSL
fslmaths
fslmaths reads one image, applies a chain of operations to it from left to right and writes the result.
- Original
- FSL 6.0.7.23
- Command line
larmorx fsl fslmaths- Python
lx.fsl.fslmaths- Ports
- replica
larmorx-ncFSL Licence: non-commercial use only experimental - clean room
larmorxApache-2.0 experimental
- replica
- Evidence
- every comparison with FSL
- Source
- made from docs/api/fsl-maths.md and the code
What it does
Its operations: maths with numbers and other images, thresholds, binarisation and masks, voxelwise functions, random noise, kernels and spatial filters (morphology, convolution, subsampling, edges, hole filling), reductions along a dimension, statistical transforms, regions, temporal band-pass filtering, threshold-free cluster enhancement, ROC analysis and tensor decomposition.
Command line
larmorx fsl fslmaths [-dt <datatype>] <first_input> [operations and inputs] <output> [-odt <datatype>]Everything after larmorx fsl fslmaths is the original’s command line: the arguments of FSL 6.0.7.23’s fslmaths, 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 fslmaths ...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.
fslmaths's usage text, as the clean room prints it
Usage: fslmaths [-dt <datatype>] <first_input> [operations and inputs] <output> [-odt <datatype>]
Datatype information:
-dt sets the datatype used internally for calculations (default float for all except double images)
-odt sets the output datatype ( default is float )
Possible datatypes are: char short int float double input
"input" will set the datatype to that of the original image
Binary operations:
(some inputs can be either an image or a number)
-add <number> | <image> : add following input to current image
-sub <number> | <image> : subtract following input from current image
-mul <number> | <image> : multiply current image by following input
-div <number> | <image> : divide current image by following input
-rem <number> | <image> : modulus remainder - divide current image by following input and take remainder
-mas <image> : use (following image>0) to mask current image
-thr <number> : threshold below the following number (zero anything below the number)
-thrp <number> : threshold below the following percentage (0-100) of ROBUST RANGE
-thrP <number> : threshold below the following percentage (0-100) of the positive voxels' ROBUST RANGE
-uthr <number> : upper-threshold above the following number (zero anything above the number)
-uthrp <number> : upper-threshold above the following percentage (0-100) of the ROBUST RANGE
-uthrP <number> : upper-threshold above the following percentage (0-100) of the positive voxels' ROBUST RANGE
-max <number> | <image> : take maximum of following input and current image
-min <number> | <image> : take minimum of following input and current image
-seed : seed random number generator with following number
-restart : replace the current image with input for future processing operations
-save : save the current working image to the input filename
Basic unary operations:
-exp : exponential
-log : natural logarithm
-sin : sine function
-cos : cosine function
-tan : tangent function
-asin : arc sine function
-acos : arc cosine function
-atan : arc tangent function
-sqr : square
-sqrt : square root
-recip : reciprocal (1/current image)
-abs : absolute value
-bin : use (current image>0) to binarise
-binv : binarise and invert (binarisation and logical inversion)
-fillh : fill holes in a binary mask (holes are internal - i.e. do not touch the edge of the FOV)
-fillh26 : fill holes using 26 connectivity
-index : replace each nonzero voxel with a unique (subject to wrapping) index number
-grid <value> <spacing> : add a 3D grid of intensity <value> with grid spacing <spacing>
-edge : edge strength
-dog_edge <sigma1> <sigma2> : difference of gaussians edge filter. Typical sigma1 is 1.0 and sigma2 is 1.6
-tfce <H> <E> <connectivity>: enhance with TFCE, e.g. -tfce 2 0.5 6 (maybe change 6 to 26 for skeletons)
-tfceS <H> <E> <connectivity> <X> <Y> <Z> <tfce_thresh>: show support area for voxel (X,Y,Z)
-nan : replace NaNs (improper numbers) with 0
-nanm : make NaN (improper number) mask with 1 for NaN voxels, 0 otherwise
-rand : add uniform noise (range 0:1)
-randn : add Gaussian noise (mean=0 sigma=1)
-inm <mean> : (-i i ip.c) intensity normalisation (per 3D volume mean)
-ing <mean> : (-I i ip.c) intensity normalisation, global 4D mean)
-range : set the output calmin/max to full data range
Matrix operations:
-tensor_decomp : convert a 4D (6-timepoint )tensor image into L1,2,3,FA,MD,MO,V1,2,3 (remaining image in pipeline is FA)
Kernel operations (set BEFORE filtering operation if desired):
-kernel 3D : 3x3x3 box centered on target voxel (set as default kernel)
-kernel 2D : 3x3x1 box centered on target voxel
-kernel box <size> : all voxels in a cube of width <size> mm centered on target voxel
-kernel boxv <size> : all voxels in a cube of width <size> voxels centered on target voxel, CAUTION: size should be an odd number
-kernel boxv3 <X> <Y> <Z>: all voxels in a cuboid of dimensions X x Y x Z centered on target voxel, CAUTION: size should be an odd number
-kernel gauss <sigma> : gaussian kernel (sigma in mm, not voxels)
-kernel sphere <size> : all voxels in a sphere of radius <size> mm centered on target voxel
-kernel file <filename> : use external file as kernel
Spatial Filtering operations: N.B. all options apart from -s use the default kernel or that _previously_ specified by -kernel
-dilM : Mean Dilation of non-zero voxels
-dilD : Modal Dilation of non-zero voxels
-dilF : Maximum filtering of all voxels
-dilall : Apply -dilM repeatedly until the entire FOV is covered
-ero : Erode by zeroing non-zero voxels when zero voxels found in kernel
-eroF : Minimum filtering of all voxels
-fmedian : Median Filtering
-fmean : Mean filtering, kernel weighted (conventionally used with gauss kernel)
-fmeanu : Mean filtering, kernel weighted, un-normalised (gives edge effects)
-s <sigma> : create a gauss kernel of sigma mm and perform mean filtering
-subsamp2 : downsamples image by a factor of 2 (keeping new voxels centred on old)
-subsamp2offc : downsamples image by a factor of 2 (non-centred)
Dimensionality reduction operations:
(the "T" can be replaced by X, Y or Z to collapse across a different dimension)
-Tmean : mean across time
-Tstd : standard deviation across time
-Tmax : max across time
-Tmaxn : time index of max across time
-Tmin : min across time
-Tmedian : median across time
-Tperc <percentage> : nth percentile (0-100) of FULL RANGE across time
-Tar1 : temporal AR(1) coefficient (use -odt float and probably demean first)
Basic statistical operations:
-pval : Nonparametric uncorrected P-value, assuming timepoints are the permutations; first timepoint is actual (unpermuted) stats image
-pval0 : Same as -pval, but treat zeros as missing data
-cpval : Same as -pval, but gives FWE corrected P-values
-ztop : Convert Z-stat to (uncorrected) P
-ptoz : Convert (uncorrected) P to Z
-rank : Convert data to ranks (over T dim)
-ranknorm: Transform to Normal dist via ranks
Multi-argument operations:
-roi <xmin> <xsize> <ymin> <ysize> <zmin> <zsize> <tmin> <tsize> : zero outside roi (using voxel coordinates). Inputting -1 for a size will set it to the full image extent for that dimension.
-bptf <hp_sigma> <lp_sigma> : (-t in ip.c) Bandpass temporal filtering; nonlinear highpass and Gaussian linear lowpass (with sigmas in volumes, not seconds); set either sigma<0 to skip that filter
-roc <AROC-thresh> <outfile> [4Dnoiseonly] <truth> : take (normally binary) truth and test current image in ROC analysis against truth. <AROC-thresh> is usually 0.05 and is limit of Area-under-ROC measure FP axis. <outfile> is a text file of the ROC curve (triplets of values: FP TP threshold). If the truth image contains negative voxels these get excluded from all calculations. If <AROC-thresh> is positive then the [4Dnoiseonly] option needs to be set, and the FP rate is determined from this noise-only data, and is set to be the fraction of timepoints where any FP (anywhere) is seen, as found in the noise-only 4d-dataset. This is then controlling the FWE rate. If <AROC-thresh> is negative the FP rate is calculated from the zero-value parts of the <truth> image, this time averaging voxelwise FP rate over all timepoints. In both cases the TP rate is the average fraction of truth=positive voxels correctly found.
Combining 4D and 3D images:
If you apply a Binary operation (one that takes the current image and a new image together), when one is 3D and the other is 4D,
the 3D image is cloned temporally to match the temporal dimensions of the 4D image.
e.g. fslmaths inputVolume -add inputVolume2 output_volume
fslmaths inputVolume -add 2.5 output_volume
fslmaths inputVolume -add 2.5 -mul inputVolume2 output_volume
fslmaths 4D_inputVolume -Tmean -mul -1 -add 4D_inputVolume demeaned_4D_inputVolumePython
lx.fsl.fslmaths(
image: Any,
*operations: Any,
dt: DataType | None = None,
odt: DataType | None = None,
n_threads: int = 1,
implementation: ImplementationName = "auto",
upstream_defects: UpstreamDefectsName = "fix",
) -> ImageWhere DataType is one of "char", "short", "int", "float", "double", "input"; ImplementationName is one of "auto", "replica", "clean-room", "original" (0.1.0rc1’s spelling of "clean-room"); UpstreamDefectsName is one of "fix", "reproduce".
Run fslmaths’ operations on image, as fslmaths [-dt <dt>] <image> <operations...> <output> [-odt <odt>] does, and return the output image.
It returns the output as an lx.Image (fslmaths’ data type and geometry).
imageand the image operands arelx.Images, nibabel images,(array, affine)pairs or paths; in-memory images are written for the program in their own data type (int8, uint16, … too; booleans as uint8; other kinds as float32), which matters withdt="input"andodt="input".- Operations are fslmaths’ own words (
"-mul","-kernel","gauss","-Tmean", …); numbers are passed as their shortest round-trip text, strings as they are. - The program runs in the caller’s working directory: relative file names are read there,
and the files an operation names (
-save <name>,-roc’s curve) are written there, as uncompressed NIfTI-1, as the command line would write them. The output itself goes to a temporary directory and is read back. - FSL’s environment variables are settings of the call, never read from the process
(CLAUDE.md rule 6): the program writes NIfTI-1 (
FSLOUTPUTTYPE=NIFTI) and noFSL*variable reaches it. - FSL’s fslmaths and the replica run on one thread; the clean room runs on
n_threads, with the same results at any count. - Errors:
ValueErrorfor invalid arguments,larmorx.ReplicaErrorwhen the replica fails (its message in the error, without the usage text),RuntimeErrorwhen the clean room does,larmorx.ReplicaNotFoundErrorwithoutlarmorx-nc.
import larmorx as lx
# niworkflows' combine_masks, in every BOLD reference's mask: fslmaths <a> -mul <b> <out>
mask = lx.fsl.arithmetic("mask_a.nii.gz", "multiply", "mask_b.nii.gz")
# fMRIPrep's goodvoxels mask, its first steps
std = lx.fsl.collapse("bold.nii.gz", "std") # -Tstd
mean = lx.fsl.collapse("bold.nii.gz", "mean") # -Tmean
cov = lx.fsl.arithmetic(std, "divide", mean) # -div <image>
cov_ribbon = lx.fsl.apply_mask(cov, "ribbon.nii.gz") # -mas
# any chain, in fslmaths' own words: the generic function mirrors the command line
smoothed = lx.fsl.fslmaths(cov_ribbon, "-s", 5, "-div", "smooth_norm.nii.gz", "-dilD")
binary = lx.fsl.fslmaths("t1w.nii.gz", "-thrp", 10, "-bin", odt="char")Its result, Image, holds a voxel array placed in world space by an affine.
| Field | Type | What it holds |
|---|---|---|
data |
np.ndarray |
|
affine |
np.ndarray |
|
header |
NiftiHeader | None |
|
implementation |
Implementation | None |
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 fslmaths accepts (crates/larmorx-fsl/src/cli/fslmaths.rs) and the arguments of lx.fsl.fslmaths (python/larmorx/fsl/maths.py), whose defaults and descriptions are taken from it. Under each option, in grey, FSL’s own help for it.
fslmaths option |
Python | Default | Notes |
|---|---|---|---|
the first word after -dt |
image |
the input imageFSL: “sets the datatype used internally for calculations (default float for all except double images)” | |
the last word before -odt |
the result | the output image, returned as an lx.ImageFSL: “sets the output datatype ( default is float )” |
|
-dt, -datatype |
dt |
None |
the type the chain computes in: "char", "short", "int", "float", "double", "input" (float, or double for a double image, by default; Data types)FSL: “sets the datatype used internally for calculations (default float for all except double images)” |
-odt, -output_datatype |
odt |
None |
the output’s type, the same names (float, or double, by default)FSL: “sets the output datatype ( default is float )” |
-add, -sub, -mul, -div, -rem, -max, -min |
operations; lx.fsl.arithmetic(image, operation, operand) |
voxelwise with a number or an image (a 3D image against a 4D one is used for every volume); -rem is an integer remainder; -div by an image gives 0 where it is 0FSL: “add following input to current image”FSL: “subtract following input from current image”FSL: “multiply current image by following input”FSL: “divide current image by following input”FSL: “modulus remainder - divide current image by following input and take remainder”FSL: “take maximum of following input and current image”FSL: “take minimum of following input and current image” |
|
-mas |
operations; lx.fsl.apply_mask(image, mask) |
zero where the mask is not above 0FSL: “use (following image>0) to mask current image” | |
-thr, -uthr |
operations; lx.fsl.threshold(image, lower=None, upper=None) |
zero below lower (kept from it, inclusive), then above upperFSL: “threshold below the following number (zero anything below the number)”FSL: “upper-threshold above the following number (zero anything above the number)” |
|
-thrp, -uthrp |
operations; lx.fsl.threshold(..., of="robust_range") |
the limits as percentages (0-100) of the robust 2 %-98 % rangeFSL: “threshold below the following percentage (0-100) of ROBUST RANGE”FSL: “upper-threshold above the following percentage (0-100) of the ROBUST RANGE” | |
-thrP, -uthrP |
operations; lx.fsl.threshold(..., of="positive_robust_range") |
of the positive voxels’ robust rangeFSL: “threshold below the following percentage (0-100) of the positive voxels’ ROBUST RANGE”FSL: “upper-threshold above the following percentage (0-100) of the positive voxels’ ROBUST RANGE” | |
-exp, -log, -sin, -cos, -tan, -asin, -acos, -atan, -sqr, -sqrt, -recip, -abs, -fillh, -fillh26, -index, -edge, -nan, -nanm, -range |
operations; lx.fsl.unary(image, operation) |
the maths functions (-log leaves values ≤ 0 unchanged; -sqrt makes them 0; GLIBC-07), hole filling of a binary mask, numbering of the positive voxels, edge strength, NaN to 0 and the NaN mask, the display range set to the data’sFSL: “exponential”FSL: “natural logarithm”FSL: “sine function”FSL: “cosine function”FSL: “tangent function”FSL: “arc sine function”FSL: “arc cosine function”FSL: “arc tangent function”FSL: “square”FSL: “square root”FSL: “reciprocal (1/current image)”FSL: “absolute value”FSL: “fill holes in a binary mask (holes are internal - i.e. do not touch the edge of the FOV)”FSL: “fill holes using 26 connectivity”FSL: “replace each nonzero voxel with a unique (subject to wrapping) index number”FSL: “edge strength”FSL: “replace NaNs (improper numbers) with 0”FSL: “make NaN (improper number) mask with 1 for NaN voxels, 0 otherwise”FSL: “set the output calmin/max to full data range” |
|
-pow |
operations |
(hidden in FSL’s usage) the power that follows (specs/fslmaths.md §7) |
|
-bin, -binv |
operations; lx.fsl.binarise(image, invert=False) |
1 where above 0 (invert: where not above 0)FSL: “use (current image>0) to binarise”FSL: “binarise and invert (binarisation and logical inversion)” |
|
-invbin |
operations |
(hidden in FSL’s usage) 1 where the value is 0, else 0; NaN is not 0 (specs/fslmaths.md §6.2) |
|
-rand, -randn, -seed |
operations; lx.fsl.add_noise(image, distribution="uniform", seed=None) |
uniform noise on [0, 1) or Gaussian noise added; without seed fslmaths’ fixed initial state (deterministic)FSL: “add uniform noise (range 0:1)”FSL: “add Gaussian noise (mean=0 sigma=1)”FSL: “seed random number generator with following number” |
|
-grid |
operations; lx.fsl.grid(image, value, spacing) |
the voxels on every spacing-th plane along x, y or z set to valueFSL: “add a 3D grid of intensity <value> with grid spacing <spacing>” |
|
-dog_edge |
operations; lx.fsl.dog_edge(image, sigma1, sigma2) |
the zero crossings of a difference of Gaussians, sigmas in voxels in each slice’s planeFSL: “difference of gaussians edge filter. Typical sigma1 is 1.0 and sigma2 is 1.6” | |
-inm, -ing |
operations; lx.fsl.normalise_intensity(image, mean, per_volume=True) |
scaled to mean, each volume’s (-inm) or the whole image’s (-ing) mean of its positive voxelsFSL: “(-i i ip.c) intensity normalisation (per 3D volume mean)”FSL: “(-I i ip.c) intensity normalisation, global 4D mean)” |
|
-kernel |
operations; lx.fsl.spatial_filter(..., kernel=...) |
the kernel of the filters after it: 3D (the default 3 × 3 × 3 box), 2D, box, boxv, boxv3, gauss, sphere, fileFSL: “3D: 3x3x3 box centered on target voxel (set as default kernel); 2D: 3x3x1 box centered on target voxel; box <size>: all voxels in a cube of width <size> mm centered on target voxel; boxv <size>: all voxels in a cube of width <size> voxels centered on target voxel, CAUTION: size should be an odd number; boxv3 <X> <Y> <Z>: all voxels in a cuboid of dimensions X x Y x Z centered on target voxel, CAUTION: size should be an odd number; gauss <sigma>: gaussian kernel (sigma in mm, not voxels); sphere <size>: all voxels in a sphere of radius <size> mm centered on target voxel; file <filename>: use external file as kernel” |
|
-dilM, -dilD, -dilF, -dilall, -ero, -eroF, -fmedian, -fmean, -fmeanu |
operations; lx.fsl.spatial_filter(image, operation, kernel=None) |
mean, modal and maximum dilation, dilation until the field of view is filled, erosion, minimum, median and kernel-weighted mean filtering (-fmeanu un-normalised)FSL: “Mean Dilation of non-zero voxels”FSL: “Modal Dilation of non-zero voxels”FSL: “Maximum filtering of all voxels”FSL: “Apply -dilM repeatedly until the entire FOV is covered”FSL: “Erode by zeroing non-zero voxels when zero voxels found in kernel”FSL: “Minimum filtering of all voxels”FSL: “Median Filtering”FSL: “Mean filtering, kernel weighted (conventionally used with gauss kernel)”FSL: “Mean filtering, kernel weighted, un-normalised (gives edge effects)” |
|
-s |
operations; lx.fsl.smooth(image, sigma) |
Gaussian smoothing, sigma in mm, normalised at the image’s edgesFSL: “create a gauss kernel of sigma mm and perform mean filtering” | |
-subsamp2, -subsamp2offc |
operations; lx.fsl.subsample2(image, centred=True) |
halved along x, y, z (new voxels centred on old ones, or on 2 × 2 × 2 blocks)FSL: “downsamples image by a factor of 2 (keeping new voxels centred on old)”FSL: “downsamples image by a factor of 2 (non-centred)” | |
-Tmean, -Tstd, -Tmax, -Tmaxn, -Tmin, -Tmedian, -Tperc, -Tar1 |
operations; lx.fsl.collapse(image, statistic, axis="T", percentile=None) |
a statistic along one axis, the axis kept with size 1; X, Y or Z in place of T (-Xmean, …) collapse along x, y or zFSL: “mean across time”FSL: “standard deviation across time”FSL: “max across time”FSL: “time index of max across time”FSL: “min across time”FSL: “median across time”FSL: “nth percentile (0-100) of FULL RANGE across time”FSL: “temporal AR(1) coefficient (use -odt float and probably demean first)” |
|
-pval, -pval0, -cpval, -ztop, -ptoz, -rank, -ranknorm |
operations; lx.fsl.statistical(image, operation) |
permutation p-values (the first volume the actual statistic), z to p, p to z, ranks over time and their normal transformFSL: “Nonparametric uncorrected P-value, assuming timepoints are the permutations; first timepoint is actual (unpermuted) stats image”FSL: “Same as -pval, but treat zeros as missing data”FSL: “Same as -pval, but gives FWE corrected P-values”FSL: “Convert Z-stat to (uncorrected) P”FSL: “Convert (uncorrected) P to Z”FSL: “Convert data to ranks (over T dim)”FSL: “Transform to Normal dist via ranks” | |
-roi |
operations; lx.fsl.roi(image, x=(0, -1), y=(0, -1), z=(0, -1), t=(0, -1)) |
zero outside a box given per axis as (first voxel, size) in the file’s voxel coordinates (-1: to the end)FSL: “zero outside roi (using voxel coordinates). Inputting -1 for a size will set it to the full image extent for that dimension.” |
|
-bptf |
operations; lx.fsl.bandpass_temporal_filter(image, highpass_sigma, lowpass_sigma) |
temporal band-pass filtering, sigmas in volumes, a negative one skipping its filter (the high-pass removes the mean)FSL: “(-t in ip.c) Bandpass temporal filtering; nonlinear highpass and Gaussian linear lowpass (with sigmas in volumes, not seconds); set either sigma<0 to skip that filter” | |
-tfce, -tfce_minT, -tfce_delta |
operations; lx.fsl.tfce(image, h=2.0, e=0.5, connectivity=6, min_t=None, delta=None) |
threshold-free cluster enhancement (the sum over the thresholds, as FSL’s); -tfce_minT and -tfce_delta (hidden in FSL’s usage) set the first threshold and the step (specs/fslmaths.md §14)FSL: “enhance with TFCE, e.g. -tfce 2 0.5 6 (maybe change 6 to 26 for skeletons)” |
|
-tfceS |
operations; lx.fsl.tfce_support(image, voxel, tfce_threshold) |
TFCE’s support area at one voxelFSL: “show support area for voxel (X,Y,Z)” | |
-roc |
operations; lx.fsl.roc(image, truth, aroc_threshold=0.05, noise=None) |
the area under the ROC curve up to the false-positive limit (normalised by it), its quartiles over the volumes, the curve (false- and true-positive rates and thresholds)FSL: “take (normally binary) truth and test current image in ROC analysis against truth. <AROC-thresh> is usually 0.05 and is limit of Area-under-ROC measure FP axis. <outfile> is a text file of the ROC curve (triplets of values: FP TP threshold). If the truth image contains negative voxels these get excluded from all calculations. If <AROC-thresh> is positive then the [4Dnoiseonly] option needs to be set, and the FP rate is determined from this noise-only data, and is set to be the fraction of timepoints where any FP (anywhere) is seen, as found in the noise-only 4d-dataset. This is then controlling the FWE rate. If <AROC-thresh> is negative the FP rate is calculated from the zero-value parts of the <truth> image, this time averaging voxelwise FP rate over all timepoints. In both cases the TP rate is the average fraction of truth=positive voxels correctly found.” | |
-tensor_decomp |
operations; lx.fsl.tensor_decomp(image) |
eigenvalues, FA, MD, mode and eigenvectors of a 6-volume tensor imageFSL: “convert a 4D (6-timepoint )tensor image into L1,2,3,FA,MD,MO,V1,2,3 (remaining image in pipeline is FA)” | |
-save, -restart |
operations |
the current image written to the name that follows, or replaced by that imageFSL: “save the current working image to the input filename”FSL: “replace the current image with input for future processing operations” | |
-h, --help |
command line only | ||
FSLOUTPUTTYPE |
the result | the output’s format on the command line (NIFTI_GZ when it is unset: FSL-11); the Python functions write NIfTI-1 and read it back |
|
LARMORX_UPSTREAM_DEFECTS |
upstream_defects |
"fix" |
"reproduce": FSL’s defects as FSL has them |
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 fslmaths ...) and are arguments of lx.fsl.fslmaths. Each one given wins over its environment variable, which keeps working.
| Command line, then Python | What it does |
|---|---|
--n-threads Nn_threads=1 |
Threads (0 = all) for the in-memory images and the clean room’s operations; the replica runs on one thread; the same results at any count. 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 replica when larmorx-nc is installed, else the clean room; "replica" or "clean-room" ("original", 0.1.0rc1’s spelling, still works). The variable LARMORX_IMPLEMENTATION in 0.1.0rc1. |
--upstream-defects fix|reproduceupstream_defects="fix" |
"fix" (default) or "reproduce": FSL’s defects corrected, or FSL’s behaviour (docs/api/fsl-maths.md, “Defects of the original, corrected by default”). 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: t1w.nii.gz (a synthetic head of 40 × 48 × 40 voxels of 4 mm), bold.nii.gz (a synthetic series of 4 such heads). The command lines run as python -m larmorx.
import larmorx as lx
# fMRIPrep's goodvoxels mask, its first steps: -Tstd, -Tmean, then -div <image>
std = lx.fsl.collapse("bold.nii.gz", "std")
mean = lx.fsl.collapse("bold.nii.gz", "mean")
cov = lx.fsl.arithmetic(std, "divide", mean)
cov.shape # -> (40, 48, 40)
# Any chain in fslmaths' own words: 1 above 10 % of the robust range, stored as bytes.
binary = lx.fsl.fslmaths("t1w.nii.gz", "-thrp", 10, "-bin", odt="char")
binary.data.dtype # -> dtype('uint8')larmorx fsl fslmaths bold.nii.gz -Tstd stdev
larmorx fsl fslmaths t1w.nii.gz -thr 100 -bin mask -odt char
larmorx fsl fslmaths t1w.nii.gz -kernel sphere 8 -fmean smoothedPorts
fslmaths has two ports: a replica and a clean room.
| Port | Package | Licence | Status | Records |
|---|---|---|---|---|
| replica | larmorx-nc |
FSL Licence: non-commercial use only | experimental | fsl-maths-replica |
| clean room | larmorx |
Apache-2.0 | experimental | fsl-maths |
Both ports take every operation of the usage text and the hidden ones (-pow, -invbin,
-tfce_minT, -tfce_delta) in every data type, every message, exit status and failure case of
FSL’s, and correct FSL’s defects (Defects of the original).
The replica against FSL 6.0.7.23 itself (its record,
the standard comparison, 2026-11-04): 360 of 361 compared cases bit-identical, the other one,
fn/double-tan, differing in the last place in 3 of its 210 double-precision values as glibc’s
tan does (GLIBC-07); 61 more rejected by both alike. fMRIPrep’s mask combination (fslmaths <a> -mul <b>) bit-identical on three of fMRIPrep’s runs (ds000005, ds005040 in two kinds, ds003592),
fMRIPrep’s 14 goodvoxels calls bit-identical in their workflow’s order on ds005040’s BOLD series
(the ribbon a stand-in: the segmentation’s grey matter, as the no-reconall runs have no
FreeSurfer ribbon), and every operation of the usage text (and the hidden ones) in every data
type, 3D and 4D, odd sizes and voxel sizes, the FFT path of the convolutions, every message, exit
status and failure case, each output compared with FSL’s file by file (data and header).
The clean room against FSL 6.0.7.23 (its record, the standard
comparison, 2026-11-07, specs/fslmaths.md §21’s thresholds): 454 cases, 386 within the
thresholds, 63 rejected by both alike, 5 expected divergences, 0 failures. Of the 386, 370
identical to FSL’s outputs (data, header, messages, exit status): fMRIPrep’s mask combination on
its three runs and its 14 goodvoxels calls on ds005040 among them (the -s 5 at 3 × 3 × 3.3 mm
too; the ribbon a stand-in, as for the replica); 3 of -tensor_decomp identical but for the
eigenvectors’ signs (the clean room’s own convention, compared up to the sign); 13 within the
thresholds: 11 sums (FSL’s FFT path on four kernels, -subsamp2 under the floating types, the
double -ztop and -ranknorm) at most 2.0e-7 of FSL’s largest value, fn/double-tan one unit in
the last place in its double values (glibc’s tan, GLIBC-07), one -roc area within its
threshold. The 5 expected divergences (FSL’s single-precision FFT convolution against the clean
room’s double sums on 3 kernels, -subsamp2offc’s means on 2 cases) stay inside the sums’ bound
(at most 1.1e-7 of FSL’s largest value) and miss only its share of voxels within 4 units in the
last place (spec questions 13 and 14), each with its reason in the record; on the FFT cases the
clean room lies closer to the exact result than FSL’s FFT (findings 31). It is built for speed:
1.8 to 28 times faster than FSL on one thread, up to 268 times on 14
(the benchmarks).
FSL is distributed under the FSL Licence (non-commercial use only), so fslmaths has two ports,
a replica and a clean room, in different packages (licensing):
- The replica is bit-exact:
larmorx-nc fsl fslmaths, in the packagelarmorx-nc(crates-nc/larmorx-nc-avwutils), under the FSL Licence’s terms, translated from FSL’s source with the image library’s arithmetic, statistics, kernels, filters, FFT and probability functions inlarmorx-nc-core. - The clean room is in the main package (Apache-2.0, crate
larmorx-fsl, itsmaths), written fromspecs/fslmaths.md, FSL’s documentation and black-box runs of FSL’s program (PROVENANCE).
implementation="auto" (the default) runs the replica when larmorx-nc is installed, the clean
room otherwise; "replica" needs larmorx-nc (otherwise ReplicaNotFoundError); "clean-room"
("original", 0.1.0rc1’s spelling, still works) runs the clean room in this process on
n_threads threads (its results the same at any count). The command line chooses alike
(--implementation before the family, or LARMORX_IMPLEMENTATION).
Evidence
How each of fslmaths’s ports was measured against FSL, case by case: its evidence.
More in the repository
The API page docs/api/fsl-maths.md holds what fslmaths shares with the page’s other programs: