Programs · FSL

topup

Original
FSL 6.0.7.23
Command line
larmorx fsl topup
Python
lx.fsl.topup
Ports
  • replica larmorx-nc FSL Licence: non-commercial use only experimental
  • clean room larmorx Apache-2.0 experimental
Evidence
every comparison with FSL
Source
made from docs/api/fsl-topup.md and the code

What it does

topup estimates the off-resonance field (Hz) that displaces echo-planar images along their phase encoding, from two or more images acquired with different phase encodings (typically “blip up” and “blip down”), with each image’s rigid-body movement if asked.

Command line

text
larmorx fsl topup --imain=<some 4D image> --datain=<text file> --config=<text file with parameters> --out=my_topup_results

Everything after larmorx fsl topup is the original’s command line: the arguments of FSL 6.0.7.23’s topup, as FSL takes them. LARMORX’s own options stand between larmorx and the family fsl, so they never meet the original’s (below):

text
larmorx
        [--n-threads N]
        [--implementation auto|replica|clean-room]
        [--upstream-defects fix|reproduce]
        fsl topup ...

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.

topup's usage text, as the clean room prints it
text
Part of FSL (ID: 2412.6-dirty)
topup

Usage: 
topup --imain=<some 4D image> --datain=<text file> --config=<text file with parameters> --out=my_topup_results


Compulsory arguments (You MUST set one or more of):
	--imain		name of 4D file with images

Optional arguments (You may optionally specify one or more of):
	--datain	name of text file with PE directions/times
	--acqp		alternative way to specify text file with PE directions/times
	--out		base-name of output files (spline coefficients (Hz) and movement parameters)
	--fout		name of image file with field (Hz)
	--iout		name of 4D image file with unwarped images
	--featout		base-name of output for export to FEAT
	--logout	Name of log-file
	--warpres	(approximate) resolution (in mm) of warp basis for the different sub-sampling levels, default 10
	--subsamp	sub-sampling scheme, default 1
	--fwhm		FWHM (in mm) of gaussian smoothing kernel, default 8
	--config	Name of config file specifying command line arguments
	--miter		Max # of non-linear iterations, default 5
	--lambda	Weight of regularisation, default depending on --ssqlambda and --regmod switches. See user documetation.
	--ssqlambda	If set (=1), lambda is weighted by current ssq, default 1
	--regmod	Model for regularisation of warp-field [membrane_energy bending_energy], default bending_energy
	--estmov	Estimate movements if set, default 1 (true)
	--minmet	Minimisation method 0=Levenberg-Marquardt, 1=Scaled Conjugate Gradient, default 0 (LM)
	--splineorder	Order of spline, 2->Qadratic spline, 3->Cubic spline. Default=3
	--numprec	Precision for representing Hessian, double or float. Default double
	--interp	Image interpolation model, linear or spline. Default spline
	--scale		If set (=1), the images are individually scaled to a common mean, default 0 (false)
	--regrid		If set (=1), the calculations are done in a different grid, default 1 (true)
	--nthr		Number of threads to use (cannot be greater than numbers of hardware cores), default 1
	-h,--help	display help info
	-v,--verbose	Print diagonostic information while running
	-h,--help	display help info

Python

python
lx.fsl.topup(
    images: Any,
    acquisition: Any,
    *,
    config: str | os.PathLike[str] | None = None,
    fsldir: str | os.PathLike[str] | None = None,
    warpres: float | Sequence[float] | None = None,
    subsamp: int | Sequence[int] | None = None,
    fwhm: float | Sequence[float] | None = None,
    miter: int | Sequence[int] | None = None,
    lambda_: float | Sequence[float] | None = None,
    ssqlambda: bool | None = None,
    regmod: Regularisation | None = None,
    estmov: bool | Sequence[bool] | None = None,
    minmet: Minimiser | Sequence[Minimiser] | None = None,
    splineorder: int | None = None,
    numprec: Literal["double", "float"] | None = None,
    interp: Literal["spline", "linear"] | None = None,
    scale: bool | None = None,
    regrid: bool | None = None,
    field: bool = True,
    corrected: bool = False,
    feat: bool = False,
    displacement_fields: bool = False,
    rigid_body_matrices: bool = False,
    jacobians: bool = False,
    verbose: bool = False,
    n_threads: int = 1,
    implementation: ImplementationName = "auto",
    upstream_defects: UpstreamDefectsName = "fix",
) -> TopupResult

Where Regularisation is one of "bending_energy", "membrane_energy"; Minimiser is one of "LM", "SCG"; ImplementationName is one of "auto", "replica", "clean-room", "original" (0.1.0rc1’s spelling of "clean-room"); UpstreamDefectsName is one of "fix", "reproduce".

Estimate the susceptibility-induced field of images (FSL’s topup).

None (the default of every estimation setting) leaves the option out, so the configuration file, or topup’s own default, sets it; a value given wins over the configuration, as on topup’s command line. FSL’s settings are the call’s (CLAUDE.md rule 6): the outputs are NIfTI-1 read back, and no FSL variable of the process reaches the program.

python
import larmorx as lx

# fMRIPrep's call (sdcflows' PEPOLAR estimation):
# topup --config=b02b0.cnf --datain=<encfile> --imain=<pair> --out=<base> --iout --fout
#       --jacout --logout --rbmout --dfout
acq = [[0, 1, 0, 0.0138], [0, -1, 0, 0.0138]]   # phase-encoding vector and read-out time (s)
r = lx.fsl.topup(
    "b0_pair.nii.gz", acq, config="sdcflows/data/flirtsch/b02b0.cnf",
    corrected=True, jacobians=True, rigid_body_matrices=True, displacement_fields=True,
)
field_hz = r.field                     # lx.Image on the input's grid
up_corrected = r.corrected.data[..., 0]

Its result, TopupResult, holds what topup wrote, read back.

Field Type What it holds
coefficients Image The field’s B-spline coefficients in Hz (--out‘s _fieldcoef: an image of the coefficients’ grid whose voxel sizes are the knot spacings in voxels, whose intent holds the spline order and the field’s voxel sizes, and whose translation the field’s size). applytopup reads it with movement_parameters.
movement_parameters np.ndarray Each image’s rigid-body movement relative to the first (_movpar.txt): one row per image, three translations (mm) then three rotations (radians) about the field of view’s centre.
field Image | None With field=True: the field in Hz on the input’s grid (--fout), else None.
corrected Image | None With corrected=True: the images corrected by Jacobian modulation (--iout, 4D) and their mean over the voxels every image sees (--iout's _mean), else None.
corrected_mean Image | None With corrected=True: the images corrected by Jacobian modulation (--iout, 4D) and their mean over the voxels every image sees (--iout's _mean), else None.
feat_fieldmap_rads Image | None With feat=True: the field in rad/s and the mean corrected image (--featout's _fieldmap_rads and _fieldmap_mag), else None.
feat_fieldmap_mag Image | None With feat=True: the field in rad/s and the mean corrected image (--featout's _fieldmap_rads and _fieldmap_mag), else None.
displacement_fields tuple[Image, ...] | None With displacement_fields=True: one 4D image per input image, its displacement in mm along x, y and z (--dfout), else None.
rigid_body_matrices tuple[np.ndarray, ...] | None With rigid_body_matrices=True: one 4 x 4 matrix per image (--rbmout), else None.
jacobians tuple[Image, ...] | None With jacobians=True: each image’s Jacobian determinant (--jacout), else None.
log str The log file’s text (--logout: the settings of every level).
stdout str topup’s standard output (its progress with verbose=True).

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 topup accepts (crates/larmorx-fsl/src/cli/topup.rs) and the arguments of lx.fsl.topup (python/larmorx/fsl/topup.py), whose defaults and descriptions are taken from it. Under each option, in grey, FSL’s own help for it.

topup option Python Default Notes
--imain images the 4D image of the volumes (path or lx.Image)FSL: “name of 4D file with images”
--datain, --acqp acquisition per volume the phase-encoding vector (3 numbers, voxel axes) and the read-out time (s): a file, or an array of shape (n, 4)FSL: “name of text file with PE directions/times”FSL: “alternative way to specify text file with PE directions/times”
--config config None a configuration file, or the name of one of FSL’s: the six FSL ships ("b02b0", "b02b0_1", "b02b0_2", "b02b0_4", "b02b0_7T", "test_acqp", with or without .cnf) need nothing more (LARMORX’s own settings); any other needs fsldirFSL: “Name of config file specifying command line arguments”
FSLDIR fsldir None the FSL installation whose etc/flirtsch holds FSL’s configurations (only for a config given by name; its file wins over LARMORX’s own settings of the same name)
--warpres warpres None knot spacing (mm), one value or one per level; 10FSL: “(approximate) resolution (in mm) of warp basis for the different sub-sampling levels, default 10”
--subsamp subsamp None subsampling factor per level; 1FSL: “sub-sampling scheme, default 1”
--fwhm fwhm None Gaussian smoothing (mm) per level; 8FSL: “FWHM (in mm) of gaussian smoothing kernel, default 8”
--miter miter None iterations per level; 5FSL: “Max # of non-linear iterations, default 5”
--lambda lambda_ None regularisation weight per level; 0FSL: “Weight of regularisation, default depending on --ssqlambda and --regmod switches. See user documetation.”
--ssqlambda ssqlambda None the weight times the current sum of squared differences; onFSL: “If set (=1), lambda is weighted by current ssq, default 1”
--regmod regmod None "bending_energy" (default) or "membrane_energy"FSL: “Model for regularisation of warp-field [membrane_energy bending_energy], default bending_energy”
--estmov estmov None estimate the movements, per level; onFSL: “Estimate movements if set, default 1 (true)”
--minmet minmet None "LM" (Levenberg-Marquardt, default) or "SCG" (scaled conjugate gradients), per levelFSL: “Minimisation method 0=Levenberg-Marquardt, 1=Scaled Conjugate Gradient, default 0 (LM)”
--splineorder splineorder None 2 (quadratic) or 3 (cubic, default)FSL: “Order of spline, 2->Qadratic spline, 3->Cubic spline. Default=3”
--numprec numprec None the Hessian’s precision: "double" (default) or "float"FSL: “Precision for representing Hessian, double or float. Default double”
--interp interp None "spline" (default) or "linear"FSL: “Image interpolation model, linear or spline. Default spline”
--scale scale None each volume scaled to a mean of 100 by itself; offFSL: “If set (=1), the images are individually scaled to a common mean, default 0 (false)”
--regrid regrid None work on a grid of n + s_max voxels per axis; onFSL: “If set (=1), the calculations are done in a different grid, default 1 (true)”
--out the result the base name of the coefficients (_fieldcoef) and the movements (_movpar.txt)FSL: “base-name of output files (spline coefficients (Hz) and movement parameters)”
--fout field True the field in HzFSL: “name of image file with field (Hz)”
--iout corrected False the corrected volumes and their mean (_mean)FSL: “name of 4D image file with unwarped images”
--featout feat False the field in rad/s and the corrected mean, for FEATFSL: “base-name of output for export to FEAT”
--dfout displacement_fields False each volume’s displacement field (mm)
--rbmout rigid_body_matrices False each volume’s rigid-body matrix
--jacout jacobians False each volume’s Jacobian determinant
--logout the result the log’s text: the result’s logFSL: “Name of log-file”
-v, --verbose verbose=True False the cost of every evaluation, in the result’s stdoutFSL: “Print diagonostic information while running”
--nthr n_threads 1 threads; the results are FSL’s one-thread results at any count (FSL-116). On the command line without --nthr (nor in the configuration), the replica takes LARMORX’s own --n-threads (else OMP_NUM_THREADS, else every logical CPU)FSL: “Number of threads to use (cannot be greater than numbers of hardware cores), default 1”
--debug, --trace, --profile command line only the hidden debugging options
-h, --help command line only FSL: “display help info”
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 topup ...) and are arguments of lx.fsl.topup. Each one given wins over its environment variable, which keeps working.

Command line, then Python What it does
--n-threads N
n_threads=1
Threads (0 = all); the results do 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-room
implementation="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|reproduce
upstream_defects="fix"
"fix" (default) or "reproduce": FSL’s defects corrected, or FSL’s behaviour (docs/api/fsl-topup.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: b0.nii.gz (a synthetic series of 4 such heads), acqp.txt (the phase encodings of four volumes, two along +y and two along −y, read out in 0.05 s). The command lines run as python -m larmorx.

python
import larmorx as lx

# One level of a coarse field, without movements: a quick estimate.
r = lx.fsl.topup("b0.nii.gz", "acqp.txt", warpres=20, subsamp=2, miter=2, estmov=False)
r.field.shape  # -> (40, 48, 40)
bash
larmorx fsl topup --imain=b0 --datain=acqp.txt --warpres=20 --subsamp=2 --miter=2 --estmov=0 --out=tu --fout=field

Ports

topup 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-topup-replica
clean room larmorx Apache-2.0 experimental fsl-topup

Both ports are complete (specs/topup.md §2 to §10): every option of topup (precision, interpolation, both regularisers, spline orders, scaling, regridding, the minimisers per level, the movements, FSL’s shipped configurations, x and y and oblique phase encodings, four volumes, a zero read-out time, --debug, --trace, --profile), every message, exit status and failure case, each compared file by file with FSL’s. fMRIPrep’s topup call: bit-identical in the replica in two of fMRIPrep’s runs (ds005040 and ds001600: every file topup writes); in the clean room, ds001600 within the thresholds, ds005040 within FSL’s own band of a last-bit change (the field’s p99 0.61 Hz against FSL at --nthr=4’s 0.64).

The replica’s record holds 102 cases of topup: 59 identical to FSL, 42 where both refuse alike, 1 refused in both modes. The clean room’s holds 112: 62 within its thresholds, 42 refused alike, 8 expected divergences (the records say why). The clean room is built for speed: fMRIPrep’s call on ds005040 takes 2.8 s on one thread and 0.8 s on 14 (FSL 32.6 s, the replica 29.7 s), on ds001600 7.7 s and 2.0 s (FSL 77.4 s, the replica 71.4 s).

FSL is distributed under the FSL Licence (non-commercial use only), so each program has two ports, a replica and a clean room, in different packages (licensing):

  • The replica is bit-exact: larmorx-nc fsl topup and fsl applytopup, in the package larmorx-nc (crates-nc/larmorx-nc-topup), under the FSL Licence’s terms, translated from FSL’s source with the B-spline fields, sparse matrices, non-linear optimisers and warps of FSL’s libraries.
  • The clean room is in the main package (Apache-2.0, crate larmorx-fsl, module topup), written from specs/topup.md without FSL’s source.

implementation="auto" (the default) runs the replica when larmorx-nc is installed (pip install larmorx-nc) and the clean room otherwise; "replica" needs larmorx-nc (otherwise ReplicaNotFoundError); "clean-room" ("original", 0.1.0rc1’s spelling, still works) always runs the clean room. The command line chooses alike (--implementation before the family, or LARMORX_IMPLEMENTATION).

Evidence

How each of topup’s ports was measured against FSL, case by case: its evidence.

More in the repository

The API page docs/api/fsl-topup.md holds what topup shares with the page’s other programs: