nifreeze.registration.gem module

A global, physics-based model of the eddy-current fields of a DWI (nipreps/nifreeze#745).

A field of eddy currents linear in position moves points only along the phase-encoding direction \(u\): \(E = I - u s^T\), with three slopes \(s\) (see split_phase_encoding()). The field comes from the diffusion gradient, so its slopes follow it. In volume \(v\), with the unit b-vector \(g_v\) and the b-value \(b_v\),

\[s_v = \left(\frac{b_v}{b_\text{ref}}\right)^p C g_v,\]

where the tensor \(C\), which maps the gradient’s direction to the field’s slopes, and the exponent \(p\) are the same for every volume (EddyTensor). The exponent is 1/2 when the field follows the gradient’s strength at a fixed timing, and 1 when it follows the b-value, as in the phantoms that TRXScan makes (PennLINC/TRXScan#27). Alternatively, each segment of b-values has its own tensor, with the exponent held (SegmentedEddyTensor). The model can also be fitted on the volumes of a range of b-values only, and give every volume its field (fit_range of GEM). A stretch that every volume shares has no parameter to go into, as long as the b-vectors average out; fitted on images, where volumes weigh a little differently in the metric, a small part of it still reaches the fields.

The fields are zero at one point, by default the centre of the field of view (field_of_view_centre()). Only the tensor and the exponent are estimated: each volume’s slopes follow from them, and so does its shift along phase encoding, the field’s displacement away from that point. The shift is head motion by the convention of split_phase_encoding(); each volume keeps the rest of the head motion it is given.

Estimating the model is one registration of all the volumes at once, with one set of parameters, in which each volume moves by its own field. ITK’s transforms map a point without knowing which volume it belongs to, so GEM has ITK’s metric evaluate each volume’s similarity and its derivative, and scipy estimates the parameters.

FSL eddy’s second-level model (--slm linear) is the antecedent: it replaces each volume’s estimated field coefficients by their least-squares fit on \((b_v / 1000)\, g_v\), which is this model with \(p = 1\), fitted to the estimates of the volumes registered one by one (EddyTensor.from_slopes() does the same, with the exponent free). Here, the model is fitted on the images; the zero point is given, whereas eddy regresses the field’s offset on the gradients; and each segment of b-values may have its own tensor.

nifreeze.registration.gem.BVALUE_ERROR_MSG = 'Every b-value must be positive: the field of a b=0 volume is not modelled.'

A b-value that is not positive error message.

nifreeze.registration.gem.B_REF_ERROR_MSG = 'The reference b-value must be positive.'

A reference b-value that is not positive error message.

nifreeze.registration.gem.DEFAULT_EXPONENT = 0.5

The exponent of a field that follows the gradient’s strength at a fixed timing.

nifreeze.registration.gem.EDGES_B_REF_ERROR_MSG = "b_ref applies to one model for all volumes: with edges, each segment's reference is the geometric mean of its b-values."

A reference b-value given with segments error message.

nifreeze.registration.gem.EDGES_ERROR_MSG = 'The b-values that split the segments must be positive and increasing.'

Malformed segment edges error message.

nifreeze.registration.gem.EMPTY_RANGE_ERROR_MSG = 'No volume added has a b-value in the fit range [{low:g}, {high:g}).'

A range of b-values without volumes error message.

nifreeze.registration.gem.EMPTY_SEGMENT_ERROR_MSG = 'No volume has a b-value in segment {segment} of the edges {edges}.'

A segment without volumes error message.

nifreeze.registration.gem.EXPONENT_BOUNDS = (0.0, 2.0)

The range the exponent is estimated in.

class nifreeze.registration.gem.EddyTensor(self, matrix: 'Any', exponent=0.5, b_ref=1000.0) → None[source]

Bases: object

The eddy-current tensor, which gives every volume its field from its b-vector and b-value.

The tensor \(C\) maps the unit b-vector to the field’s slopes at the reference b-value; with the scanner’s frame rotated by \(R\), it becomes \(R C R^T\). In volume \(v\), the field’s slopes are \(s_v = (b_v / b_\text{ref})^p C g_v\), with \(g_v\) the b-vector as acquired (see The b-vectors), and the field is \(E_v = I - u s_v^T\).

Examples

>>> tensor = EddyTensor(0.02 * np.eye(3), exponent=0.5, b_ref=1000.0)
>>> gradients = [[1.0, 0.0, 0.0, 1000.0], [0.0, -1.0, 0.0, 4000.0]]
>>> tensor.slopes(gradients).round(6).tolist()
[[0.02, 0.0, 0.0], [0.0, -0.04, 0.0]]
>>> tensor.fields(gradients, [0.0, 1.0, 0.0])[1, :3, :3].round(6).tolist()
[[1.0, 0.0, 0.0], [0.0, 1.04, 0.0], [0.0, 0.0, 1.0]]

Method generated by attrs for class EddyTensor.

b_ref: float

The reference b-value \(b_\text{ref}\) (s/mm²).

exponent: float

the slopes scale with the b-value to this power.

Type:

\(p\)

fields(gradients: Any, direction: Any) → ndarray[source]

Each volume’s field \(E_v = I - u s_v^T\), (N, 4, 4) RAS+ matrices.

This is how split_phase_encoding() gives a field: without a translation, which belongs to the head motion.

classmethod from_slopes(slopes: Any, gradients: Any, weights: Any = None, exponent: float | None = None, b_ref: float | None = None) → EddyTensor[source]

Fit \(C\) and \(p\) to each volume’s slopes, by least squares.

For a fixed exponent, \(C\) is linear least squares; the exponent is the one, within EXPONENT_BOUNDS, that leaves the least residual. With the exponent held at 1, this is FSL eddy’s linear second-level model.

Parameters:
  • slopes (ndarray) – The slopes of each volume’s field, (N, 3) (see field_slopes()).

  • gradients (ndarray) – The gradient table, (N, 4) (see slopes()).

  • weights (ndarray, optional) – A weight for each volume.

  • exponent (float, optional) – Hold the exponent at this value. With a single b-value, it is held at DEFAULT_EXPONENT, with a warning.

  • b_ref (float, optional) – The reference b-value (default: the b-values’ geometric_mean()).

Raises:

ValueError – If the shapes do not match, a b-value is not positive, or the b-vectors do not span three dimensions.

Examples

>>> rng = np.random.default_rng(0)
>>> b_vectors = rng.normal(size=(30, 3))
>>> b_vectors /= np.linalg.norm(b_vectors, axis=1, keepdims=True)
>>> gradients = np.column_stack([b_vectors, np.repeat([1000.0, 2000.0, 3000.0], 10)])
>>> truth = EddyTensor(rng.normal(scale=0.02, size=(3, 3)), exponent=1.0, b_ref=1000.0)
>>> found = EddyTensor.from_slopes(truth.slopes(gradients), gradients, b_ref=1000.0)
>>> round(found.exponent, 6), np.allclose(found.matrix, truth.matrix)
(1.0, True)
matrix: ndarray

the slopes of a unit b-vector at the reference b-value.

Type:

\(C\)

rescaled(b_ref: float) → EddyTensor[source]

The same fields, with \(C\) given at another reference b-value.

scales(bvals: Any) → ndarray[source]

How much each b-value scales the slopes: \((b / b_\text{ref})^p\).

slopes(gradients: Any) → ndarray[source]

The slopes of each volume’s field, (N, 3).

Parameters:

gradients (ndarray) – The gradient table, (N, 4): a unit b-vector in world RAS+ coordinates, as the scanner applied it (eddy currents do not turn with the head), then the b-value.

nifreeze.registration.gem.FIT_RANGE_EDGES_ERROR_MSG = 'fit_range fits one model on some of the volumes, and edges one model for each segment: give one of them.'

A range of b-values given with segments error message.

nifreeze.registration.gem.FIT_RANGE_ERROR_MSG = 'fit_range must be two b-values, low then high, with 0 <= low < high.'

Malformed range of b-values error message.

class nifreeze.registration.gem.GEM(self, align_config: 'Mapping[str, Any] | str | PathLike | None' = None, *, phase_encoding: 'str | None' = None, exponent: 'float | None' = None, b_ref: 'float | None' = None, edges: 'Sequence[float] | None' = None, fit_range: 'Sequence[float] | None' = None, zero_point: 'Sequence[float] | np.ndarray | None' = None, seed: 'int | None' = 12345, num_threads: 'int | None' = None, clip: 'str | bool | None' = 'both', margin: 'float' = 15.0) → 'None'[source]

Bases: object

The global eddy model (GEM): the eddy-current field of every volume, from their images, with one tensor.

Each volume is added (add()) with its target (the image it should match once its field is undone), its sample, the head motion it is given and any field an earlier pass estimated; fit() then estimates the model, and mappings() gives each volume’s head motion and field. Without edges, the model is one EddyTensor (\(C\) and \(p\)); with them, a SegmentedEddyTensor, one \(C\) for each segment of b-values, with the exponent held. The segments share no parameter, so each is fitted on its own. With fit_range, the model is fitted on the volumes of a range of b-values only, and every volume added gets its field from it. Each volume’s shift along phase encoding is derived from its slopes and the fields’ zero point.

The cost is the sum over volumes of ITK’s metric between the target and the sample, run in the stages of the settings (the itk section of AFFINE by default), and minimized by L-BFGS-B. A stage takes its metric, histogram bins, sampling, smoothing (in voxels), shrink factor and iterations from the settings; their step settings (learning_rate and the like) belong to ITK’s optimizer and do not apply. Both images of a stage are smoothed and then shrunk, and its points, drawn once, are the same for every volume. The images are prepared as ITK prepares them (clipped to the sample’s window, winsorized, histogram-matched as the settings ask), in their voxel frame, and kept within the mask’s box and margin; a point mapped beyond it does not count.

Parameters:
  • align_config (Mapping or os.pathlike, optional) – ITK’s settings, or a file with an itk section (see get_settings()).

  • phase_encoding (str, optional) – The phase-encoding direction, as BIDS writes it.

  • exponent (float, optional) – Hold the exponent \(p\) at this value. Without edges, it is estimated by default; with them, it is held at DEFAULT_EXPONENT by default.

  • b_ref (float, optional) – The reference b-value, without edges (default: the geometric_mean() of the b-values). With them, each segment’s is the geometric mean of its b-values.

  • edges (Sequence of float, optional) – The b-values that split the segments, each with its own matrix \(C\) (see SegmentedEddyTensor); one model for all volumes if None.

  • fit_range (Sequence of float, optional) – Fit the model on the volumes whose b-value is in [low, high) only, and give every volume added its field from it (default: fit on all of them). With a single b-value in the range, the exponent is held: at exponent, or at DEFAULT_EXPONENT with a warning. Not with edges.

  • zero_point (ndarray, optional) – Where the fields are zero (RAS+, mm; default: the field_of_view_centre() of the volumes’ grid).

  • seed (int, optional) – Seed of the points drawn in each stage.

  • num_threads (int, optional) – ITK’s threads.

  • clip (str, optional) – Clip "sample", "predicted" (the target), "both" (default) or "none" of the images to the sample’s intensity window.

  • margin (float, optional) – How far (mm) beyond the mask’s box each volume’s images are kept.

add(index: int, fixed: ndarray, moving: ndarray, affine: ndarray, mask: ndarray | None = None, motion: ndarray | None = None, field: ndarray | None = None) → None[source]

Add one volume.

Parameters:
  • index (int) – The volume’s index, its row in the gradient table.

  • fixed, moving (ndarray) – The volume’s target and its sample.

  • affine (ndarray) – The voxel-to-RAS+ affine of their grid, the same for every volume.

  • mask (ndarray, optional) – The mask of the target, the same for every volume.

  • motion (ndarray, optional) – The head motion the volume is given (a RAS+ matrix that maps the reference into it; default: none).

  • field (ndarray, optional) – The volume’s eddy-current field already estimated, by an earlier pass (a RAS+ matrix that applies after motion, as mappings() gives it; default: none). The fit takes it as a field zero at the zero point, and factors it out of the volume’s mapping: the fit starts from the head motion that remains, so the earlier field’s shift along phase encoding is not counted twice.

evaluations: list[list[int]]

How many times each stage evaluated the cost, for each segment (one list without edges).

fit(gradients: Any) → EddyTensor | SegmentedEddyTensor[source]

Estimate the tensor, and with it the field of every volume added.

The estimation starts from no field, with the exponent at DEFAULT_EXPONENT unless it is held.

Parameters:

gradients (ndarray) – The dataset’s gradient table, (N, 4), with a row for each volume index (see EddyTensor.slopes()): the b-vectors as acquired, never rotated by the head motion, since the field follows the gradient the scanner plays (see The b-vectors).

Returns:

The estimate (segmented with edges), also kept as tensor. The images are released.

Return type:

EddyTensor or SegmentedEddyTensor

property indices: list[int]

The volumes added, in order.

mappings() → dict[int, tuple[ndarray, ndarray]][source]

Each volume’s head motion and field, as the dataset stores them.

Returns:

By volume index, the head motion (with the shift along phase encoding derived from the field) and the field \(E_v = I - u s_v^T\), both RAS+ matrices; the field applies after the motion.

Return type:

dict

messages: list[list[str]]

How each stage’s minimization stopped, for each segment.

tensor: EddyTensor | SegmentedEddyTensor | None

The estimated tensor, once fitted.

zero_point

Where the fields are zero (RAS+, mm); once fitted, the one used.

nifreeze.registration.gem.GRID_ERROR_MSG = 'Volume {index} is not on the grid and mask of the volumes added before it.'

A volume on another grid error message.

nifreeze.registration.gem.MATRIX_ERROR_MSG = 'The matrix C must be 3 x 3.'

Malformed matrix error message.

nifreeze.registration.gem.NOTHING_ADDED_ERROR_MSG = 'No volume was added to the fit.'

A fit without volumes error message.

nifreeze.registration.gem.NOT_FITTED_ERROR_MSG = 'The tensor is not fitted yet: call fit() first.'

Mappings before the fit error message.

nifreeze.registration.gem.NO_PHASE_ENCODING_ERROR_MSG = "The eddy-current field moves points along phase encoding, whose direction is unknown: give the fit phase_encoding (the dataset's, as BIDS writes it)."

Unknown phase-encoding direction error message.

nifreeze.registration.gem.ONE_BVALUE_WARN_MSG = 'Every volume has the same b-value, so the exponent is not determined: it is held at {exponent:g}.'

A single b-value warning message.

nifreeze.registration.gem.PARTS_ERROR_MSG = 'A segmented tensor needs one tensor for each segment: {parts} for {edges} edges.'

A segmented tensor with the wrong number of tensors error message.

nifreeze.registration.gem.SLOPES_ERROR_MSG = 'The slopes must be (N, 3), one row per volume of the gradient table.'

Malformed slopes error message.

nifreeze.registration.gem.SPAN_ERROR_MSG = 'The b-vectors do not span three dimensions, so the matrix C is not determined.'

B-vectors in a plane error message.

class nifreeze.registration.gem.SegmentedEddyTensor(self, edges: 'Any', parts: 'Any') → None[source]

Bases: object

Eddy-current tensors, one \(C\) for each segment of b-values, which give every volume its field.

edges split the b-values into segments: segment \(k\) holds the b-values from edges[k - 1] up to, not including, edges[k] (the first, those below edges[0]; the last, those from edges[-1] on). Each segment has its own EddyTensor, so the slopes need not follow one power of the b-value: within a single shell, its tensor takes up the shell’s scale.

Examples

>>> tensor = SegmentedEddyTensor(
...     [1500.0],
...     [
...         EddyTensor(0.02 * np.eye(3), b_ref=1000.0),
...         EddyTensor(0.05 * np.eye(3), b_ref=2000.0),
...     ],
... )
>>> gradients = [[1.0, 0.0, 0.0, 1000.0], [1.0, 0.0, 0.0, 2000.0]]
>>> tensor.slopes(gradients).round(6).tolist()
[[0.02, 0.0, 0.0], [0.05, 0.0, 0.0]]
>>> tensor.segments([1000.0, 1500.0, 3000.0]).tolist()
[0, 1, 1]

Method generated by attrs for class SegmentedEddyTensor.

edges: tuple[float, ...]

The b-values that split the segments, increasing.

fields(gradients: Any, direction: Any) → ndarray[source]

Each volume’s field, (N, 4, 4) RAS+ matrices (see EddyTensor.fields()).

parts: tuple[EddyTensor, ...]

The tensor of each segment, one more than edges.

segments(bvals: Any) → ndarray[source]

The segment of each b-value.

slopes(gradients: Any) → ndarray[source]

The slopes of each volume’s field, (N, 3) (see EddyTensor.slopes()).

nifreeze.registration.gem.TABLE_ERROR_MSG = 'The gradient table must be (N, 4): a b-vector, then the b-value.'

Malformed gradient table error message.

nifreeze.registration.gem.TABLE_LENGTH_ERROR_MSG = 'The gradient table has {rows} rows, but volume {index} was added.'

A gradient table without a row for every volume error message.

nifreeze.registration.gem.field_of_view_centre(affine: Any, shape: Sequence[int]) → ndarray[source]

The centre of a grid’s field of view: the middle of its physical extent (RAS+, mm).

Samples lie at the centres of the voxels, so the extent runs from index -0.5 to n - 0.5 along each axis, and its middle is index (n - 1) / 2, whether n is odd or even.

>>> field_of_view_centre(np.diag([2.0, 2.0, 2.0, 1.0]), (4, 5, 6)).tolist()
[3.0, 4.0, 5.0]
nifreeze.registration.gem.field_slopes(fields: Any, direction: Any) → ndarray[source]

The slopes \(s\) of fields \(E = I - u s^T\) along direction.

For a mapping outside that family, they are those of its row along \(u\).

Parameters:
  • fields (ndarray) – The fields, (N, 4, 4) RAS+ matrices (eddy).

  • direction (ndarray) – The phase-encoding direction \(u\) in world coordinates.

Returns:

The slopes, (N, 3).

Return type:

ndarray

Examples

>>> field = np.eye(4)
>>> field[1, :3] = [0.02, 0.97, -0.01]
>>> field_slopes(field[np.newaxis], [0.0, 1.0, 0.0]).round(6).tolist()
[[-0.02, 0.03, 0.01]]
nifreeze.registration.gem.geometric_mean(bvals: Any) → float[source]

The geometric mean of the b-values, the default reference.

>>> round(geometric_mean([1000.0, 4000.0]), 6)
2000.0