nifreeze.registration.eddy_field 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 matrix \(C\) and the exponent \(p\) are the same for every volume (EddyField). 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 matrix, with the exponent held (SegmentedEddyField). 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 model is estimated: each volume’s slopes follow from it, 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 EddyFieldFit 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 (EddyField.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 matrix.

nifreeze.registration.eddy_field.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.eddy_field.B_REF_ERROR_MSG = 'The reference b-value must be positive.'

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

nifreeze.registration.eddy_field.DEFAULT_EXPONENT = 0.5

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

nifreeze.registration.eddy_field.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.eddy_field.EDGES_ERROR_MSG = 'The b-values that split the segments must be positive and increasing.'

Malformed segment edges error message.

nifreeze.registration.eddy_field.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.eddy_field.EXPONENT_BOUNDS = (0.0, 2.0)

The range the exponent is estimated in.

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

Bases: object

The eddy-current field of every volume, from its b-vector and b-value.

In volume \(v\), the field’s slopes are \(s_v = (b_v / b_\text{ref})^p C g_v\), and the field is \(E_v = I - u s_v^T\).

Examples

>>> field = EddyField(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]]
>>> field.slopes(gradients).round(6).tolist()
[[0.02, 0.0, 0.0], [0.0, -0.04, 0.0]]
>>> field.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 EddyField.

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) → EddyField[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 = EddyField(rng.normal(scale=0.02, size=(3, 3)), exponent=1.0, b_ref=1000.0)
>>> found = EddyField.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) → EddyField[source]

The same field, 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.

class nifreeze.registration.eddy_field.EddyFieldFit(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, 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

Estimate the eddy-current field of all volumes, from their images, with one model.

Each volume is added (add()) with its target (the image it should match once its field is undone), its sample and the head motion it is given; fit() then estimates the model, and mappings() gives each volume’s head motion and field. Without edges, the model is one EddyField (\(C\) and \(p\)); with them, a SegmentedEddyField, one \(C\) for each segment of b-values, with the exponent held. The segments share no parameter, so each is fitted on its own. 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 SegmentedEddyField); one model for all volumes if None.

  • 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) → 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).

evaluations: list[list[int]]

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

field: EddyField | SegmentedEddyField | None

The estimated field, once fitted.

fit(gradients: Any) → EddyField | SegmentedEddyField[source]

Estimate 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 EddyField.slopes()).

Returns:

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

Return type:

EddyField or SegmentedEddyField

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.

zero_point

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

nifreeze.registration.eddy_field.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.eddy_field.MATRIX_ERROR_MSG = 'The matrix C must be 3 x 3.'

Malformed matrix error message.

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

A fit without volumes error message.

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

Mappings before the fit error message.

nifreeze.registration.eddy_field.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.eddy_field.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.eddy_field.PARTS_ERROR_MSG = 'A segmented field needs one field for each segment: {parts} for {edges} edges.'

A segmented field with the wrong number of fields error message.

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

Malformed slopes error message.

nifreeze.registration.eddy_field.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.eddy_field.SegmentedEddyField(self, edges: 'Any', parts: 'Any') → None[source]

Bases: object

The eddy-current field of every volume, with a matrix \(C\) for each segment of b-values.

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 EddyField, so the slopes need not follow one power of the b-value: within a single shell, its matrix takes up the shell’s scale.

Examples

>>> field = SegmentedEddyField(
...     [1500.0],
...     [EddyField(0.02 * np.eye(3), b_ref=1000.0), EddyField(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]]
>>> field.slopes(gradients).round(6).tolist()
[[0.02, 0.0, 0.0], [0.05, 0.0, 0.0]]
>>> field.segments([1000.0, 1500.0, 3000.0]).tolist()
[0, 1, 1]

Method generated by attrs for class SegmentedEddyField.

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 EddyField.fields()).

parts: tuple[EddyField, ...]

The field 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 EddyField.slopes()).

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

Malformed gradient table error message.

nifreeze.registration.eddy_field.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.eddy_field.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.eddy_field.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.eddy_field.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