Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/api/tools.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ when {obj}`~bartorch.tools.correct_susceptibility` is called
| --- | --- |
| {obj}`~bartorch.tools.epi_ramp_operator` | Band-limited resampling of a ramp-sampled EPI readout onto a uniform grid |
| {obj}`~bartorch.tools.estimate_epi_phase` | Odd/even phase of an EPI readout, fitted to a three-line navigator |
| {obj}`~bartorch.tools.estimate_epi_echo_phase` | Odd/even phase of every echo of an EPI train, fitted to a blip-free reference train |
| {obj}`~bartorch.tools.correct_lines` | Reversal of EPI lines into forward readout order, with the odd/even phase removed |
| {obj}`~bartorch.tools.bias_field_correct` | Receive-field (bias) correction by N4 |
| {obj}`~bartorch.tools.reslice` | Resampling of an image onto another prescription's grid from header geometry |
Expand All @@ -115,6 +116,7 @@ when {obj}`~bartorch.tools.correct_susceptibility` is called
| {obj}`~bartorch.tools.fit_transfer` | Fit of a {obj}`~bartorch.tools.SpiralTransfer` to a readout's time map |
| {obj}`~bartorch.tools.deblur` | Off-resonance deblurring of a spiral image |
| {obj}`~bartorch.tools.correct_susceptibility` | Susceptibility distortion correction from a reversed phase-encoding pair, by PyHySCO |
| {obj}`~bartorch.tools.apply_susceptibility` | An image corrected with a known displacement field, by PyHySCO's model, so one field estimated per slice serves every image of it |
| {obj}`~bartorch.tools.SusceptibilityCorrection` | Corrected pair and displacement field from {obj}`~bartorch.tools.correct_susceptibility` |

## Rigid motion from navigators
Expand Down
15 changes: 13 additions & 2 deletions src/bartorch/tools/_correct/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,12 @@
from __future__ import annotations

from bartorch.tools._correct._bias import bias_field_correct
from bartorch.tools._correct._epi import correct_lines, epi_ramp_operator, estimate_epi_phase
from bartorch.tools._correct._epi import (
correct_lines,
epi_ramp_operator,
estimate_epi_echo_phase,
estimate_epi_phase,
)
from bartorch.tools._correct._fieldmap import field_map_from_phase
from bartorch.tools._correct._gradunwarp import (
CoefficientAccessor,
Expand All @@ -19,7 +24,11 @@
)
from bartorch.tools._correct._reslice import reslice
from bartorch.tools._correct._spiral import ReadoutTiming, SpiralTransfer, deblur, fit_transfer
from bartorch.tools._correct._susceptibility import SusceptibilityCorrection, correct_susceptibility
from bartorch.tools._correct._susceptibility import (
SusceptibilityCorrection,
apply_susceptibility,
correct_susceptibility,
)

__all__ = [
"CoefficientAccessor",
Expand All @@ -28,11 +37,13 @@
"ReadoutTiming",
"SpiralTransfer",
"SusceptibilityCorrection",
"apply_susceptibility",
"bias_field_correct",
"correct_lines",
"correct_susceptibility",
"deblur",
"epi_ramp_operator",
"estimate_epi_echo_phase",
"estimate_epi_phase",
"field_map_from_phase",
"fit_transfer",
Expand Down
97 changes: 91 additions & 6 deletions src/bartorch/tools/_correct/_epi.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,12 @@

import torch

__all__ = ["correct_lines", "epi_ramp_operator", "estimate_epi_phase"]
__all__ = [
"correct_lines",
"epi_ramp_operator",
"estimate_epi_echo_phase",
"estimate_epi_phase",
]


def _hybrid(rows: torch.Tensor, *, inverse: bool = True) -> torch.Tensor:
Expand Down Expand Up @@ -129,8 +134,6 @@ def estimate_epi_phase(
ValueError
If fewer than three lines are given, or the order is negative.
"""
from bartorch._util import unwrap

if len(navigator_lines) < 3:
raise ValueError(
f"the navigator is three lines of alternating polarity, got {len(navigator_lines)}"
Expand All @@ -139,18 +142,100 @@ def estimate_epi_phase(
raise ValueError("polynomial_order must be non-negative")

forward = 0.5 * (_hybrid(navigator_lines[0]) + _hybrid(navigator_lines[2]))
backward = _hybrid(navigator_lines[1])
cross = (forward * backward.conj()).sum(0)
return _fit_odd_even(forward, _hybrid(navigator_lines[1]), polynomial_order)


def _fit_odd_even(forward: torch.Tensor, backward: torch.Tensor, order: int) -> torch.Tensor:
"""Weighted polynomial fit of the phase of ``forward * conj(backward)``, in hybrid space."""
from bartorch._util import unwrap

cross = (forward * backward.conj()).sum(0)
weights = cross.abs().to(torch.float64)
phase = unwrap(torch.angle(cross).to(torch.complex64), -1).real.to(torch.float64)
coordinate = _readout_coordinate(phase.shape[0], phase.device)
keep = weights > 0.1 * weights.max()
design = torch.stack([coordinate[keep] ** p for p in range(polynomial_order + 1)], dim=-1)
design = torch.stack([coordinate[keep] ** p for p in range(order + 1)], dim=-1)
scaled = design * weights[keep, None]
return torch.linalg.lstsq(scaled, (phase[keep] * weights[keep])[:, None]).solution[:, 0]


def estimate_epi_echo_phase(
reference_lines: list[torch.Tensor],
reversed_lines: list[bool],
*,
polynomial_order: int = 1,
) -> torch.Tensor:
r"""Odd/even phase of every echo of an EPI train, fitted to a blip-free reference train.

The reference is the imaging train played with every phase-encode
gradient at zero, so echo :math:`k` sees the read gradient, eddy currents
and timing of echo :math:`k` of every imaging train. For each reversed
echo, the forward echoes either side of it stand in for the line it would
have been read forward, their mean cancelling the off-resonance phase that
grows linearly along the train, and the phase of the reversed echo
against them is fitted as :func:`estimate_epi_phase` fits a navigator's.
A reversed echo with a forward echo on one side only (the first or last
of the train) takes the fit of the nearest reversed echo that has both,
or, in a train too short to have one, the one-sided fit. Forward echoes
define the grid and take no correction.

Parameters
----------
reference_lines : list of torch.Tensor
The reference train's ``(coils, samples)`` lines in echo order,
reversed lines already flipped into forward readout order.
reversed_lines : list of bool
Whether each echo was read with the negative read gradient.
polynomial_order : int, default=1
Polynomial order; one is a constant and a linear term.

Returns
-------
torch.Tensor
Float64 ``(echoes, polynomial_order + 1)`` coefficients, lowest order
first, on the reference's device, in the coordinate of
:func:`estimate_epi_phase`: row :math:`k` is what
:func:`correct_lines` applies to a reversed line of echo :math:`k`,
zeros for a forward echo.

Raises
------
ValueError
If the two lists differ in length, the train has no forward echo next
to a reversed one, or the order is negative.
"""
if len(reference_lines) != len(reversed_lines):
raise ValueError(
f"{len(reference_lines)} reference lines but {len(reversed_lines)} polarities"
)
if polynomial_order < 0:
raise ValueError("polynomial_order must be non-negative")
count = len(reference_lines)
flags = [bool(flag) for flag in reversed_lines]
hybrid = [_hybrid(line) for line in reference_lines]
device = hybrid[0].device if hybrid else None
coefficients = torch.zeros(count, polynomial_order + 1, dtype=torch.float64, device=device)

interior, edges = [], []
for echo in range(count):
if not flags[echo]:
continue
sides = [j for j in (echo - 1, echo + 1) if 0 <= j < count and not flags[j]]
if not sides:
continue
forward = sum(hybrid[j] for j in sides) / len(sides)
fit = _fit_odd_even(forward, hybrid[echo], polynomial_order)
coefficients[echo] = fit
(interior if len(sides) == 2 else edges).append(echo)
if not interior and not edges:
raise ValueError("the reference train has no forward echo next to a reversed one")
if interior:
for echo in edges:
nearest = min(interior, key=lambda other: abs(other - echo))
coefficients[echo] = coefficients[nearest]
return coefficients


def correct_lines(
lines: list[tuple[torch.Tensor, bool]], phase: torch.Tensor | None = None
) -> list[torch.Tensor]:
Expand Down
141 changes: 139 additions & 2 deletions src/bartorch/tools/_correct/_susceptibility.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

import torch

__all__ = ["SusceptibilityCorrection", "correct_susceptibility"]
__all__ = ["SusceptibilityCorrection", "apply_susceptibility", "correct_susceptibility"]

Optimizer = Literal["gauss-newton", "lbfgs", "admm"]

Expand Down Expand Up @@ -147,6 +147,7 @@ def correct_susceptibility(
optimizer: Optimizer = "gauss-newton",
max_iter: int = 10,
device: torch.device | str | None = None,
prealign: bool = True,
) -> SusceptibilityCorrection:
"""Correct susceptibility distortion from a pair with reversed phase encoding.

Expand Down Expand Up @@ -177,6 +178,16 @@ def correct_susceptibility(
Device of the computation, which runs in float64; that of ``blip_up``
if ``None``.

prealign : bool, default=True
Remove the uniform displacement first: the pair's profiles along the
phase-encoding axis are cross-correlated, each image is moved half
of the lag, in whole voxels, towards the other, and PyHySCO estimates the remaining
field. A uniform off-resonance, such as a centre frequency off the
sample's resonance, displaces the pair in opposite directions by
many voxels when the phase-encode bandwidth per voxel is low, more
than the field PyHySCO estimates from zero can recover. The removed
displacement is part of the returned ``field_map``.

Returns
-------
SusceptibilityCorrection
Expand Down Expand Up @@ -216,6 +227,18 @@ def correct_susceptibility(
parts = _require_pyhysco()
resolved = torch.device(device) if device is not None else blip_up.device

axis = phase_encoding_axis % blip_up.ndim
offset = 0.0
if prealign:
# The blip-down image is the blip-up one moved by ``lag`` voxels; the
# undistorted object lies half-way, at x + offset in the blip-up
# image and x - offset in the blip-down one.
# Whole voxels only: a roll does not blur, and PyHySCO takes the
# remaining half voxel at most.
offset = -float(round(0.5 * _profile_lag(blip_up, blip_down, axis)))
blip_up = _sampled(blip_up, offset, axis)
blip_down = _sampled(blip_down, -offset, axis)

holder = _data_object(
blip_up,
blip_down,
Expand Down Expand Up @@ -248,12 +271,95 @@ def correct_susceptibility(
shape = list(holder.m)
up, down = _in_input_units(objective, holder, field)
return SusceptibilityCorrection(
field_map=field.reshape(list(parts["m_plus"](holder.m))).permute(holder.p),
field_map=field.reshape(list(parts["m_plus"](holder.m))).permute(holder.p)
+ offset * float(voxel_size[axis]),
blip_up=up.reshape(shape).permute(holder.p),
blip_down=down.reshape(shape).permute(holder.p),
)


def apply_susceptibility(
image: torch.Tensor,
field_map: torch.Tensor,
*,
voxel_size: tuple[float, ...],
phase_encoding_axis: int = 0,
blip: Literal["up", "down"] = "up",
) -> torch.Tensor:
"""Correct an image for susceptibility distortion with a known displacement field.

The model is that of :func:`correct_susceptibility`: the blip-up image is
sampled at :math:`x + b(x)` and its intensity multiplied by
:math:`1 + \\partial b / \\partial x`, the blip-down image at
:math:`x - b(x)` with :math:`1 - \\partial b / \\partial x`. The field,
estimated once from a pair, so corrects every later image acquired with
the same phase encoding and field, as FSL's ``applytopup --method=jac``
does. The image is interpolated linearly along the phase-encoding axis,
wrapping around the field of view as the phase encoding does. Nothing
but torch is needed.

Parameters
----------
image : torch.Tensor
Real or complex image, 2D or 3D.
field_map : torch.Tensor
Displacement along the phase-encoding axis in the units of
``voxel_size``, on cell edges: one sample longer than ``image`` along
that axis and of its size along the others, as
:attr:`SusceptibilityCorrection.field_map`.
voxel_size : tuple of float
Voxel size per axis of the image, in the units of ``field_map``.
phase_encoding_axis : int, default=0
Phase-encoding axis of ``image`` and ``field_map``.
blip : {"up", "down"}, default='up'
Phase-encoding polarity of ``image``: ``"up"`` for the image passed as
``blip_up`` to :func:`correct_susceptibility`.

Returns
-------
torch.Tensor
The corrected image, of the shape of ``image``.

Raises
------
ValueError
If ``field_map`` is not one sample longer than ``image`` along the
phase-encoding axis and of its size along the others, ``voxel_size``
does not give one value per axis, or ``blip`` is unknown.
"""
if blip not in ("up", "down"):
raise ValueError(f"blip is 'up' or 'down', got {blip!r}")
if len(voxel_size) != image.ndim:
raise ValueError(f"voxel_size has {len(voxel_size)} entries for a {image.ndim}D image")
axis = phase_encoding_axis % image.ndim
expected = list(image.shape)
expected[axis] += 1
if list(field_map.shape) != expected:
raise ValueError(
f"the field of a {tuple(image.shape)} image along axis {axis} is "
f"{tuple(expected)}, got {tuple(field_map.shape)}"
)
sign = 1.0 if blip == "up" else -1.0
dtype = torch.promote_types(field_map.dtype, torch.float32)
edges = field_map.to(device=image.device, dtype=dtype).movedim(axis, -1) / float(
voxel_size[axis]
)
moved = image.movedim(axis, -1)
count = moved.shape[-1]
# Cell-centred displacement and its derivative, in voxels.
position = torch.arange(count, device=image.device, dtype=dtype) + sign * 0.5 * (
edges[..., :-1] + edges[..., 1:]
)
jacobian = 1.0 + sign * (edges[..., 1:] - edges[..., :-1])
left = torch.floor(position)
weight = position - left
left = left.to(torch.long)
sampled = (1.0 - weight) * moved.gather(-1, left % count) + weight * moved.gather(
-1, (left + 1) % count
)
return (sampled * jacobian).movedim(-1, axis)


def _in_input_units(objective, holder, field: torch.Tensor):
"""The corrected pair at ``field``, in the intensity units of the input pair.

Expand All @@ -268,3 +374,34 @@ def _in_input_units(objective, holder, field: torch.Tensor):
objective.corr1 * holder.intensity_scale + holder.intensity_offset * (1 + jacobian),
objective.corr2 * holder.intensity_scale + holder.intensity_offset * (1 - jacobian),
)


def _profile_lag(blip_up: torch.Tensor, blip_down: torch.Tensor, axis: int) -> float:
"""Return the lag, in voxels, by which ``blip_down`` is ``blip_up`` moved along ``axis``.

The magnitude profiles along ``axis`` (summed over the other axes) are
cross-correlated circularly, and the peak is refined to a fraction of a
voxel by a parabola through it and its neighbours.
"""
others = [d for d in range(blip_up.ndim) if d != axis]
up = blip_up.abs().to(torch.float64)
down = blip_down.abs().to(torch.float64)
a = up.sum(dim=others) if others else up
b = down.sum(dim=others) if others else down
a, b = a - a.mean(), b - b.mean()
n = a.numel()
xc = torch.fft.irfft(torch.conj(torch.fft.rfft(a)) * torch.fft.rfft(b), n=n)
k = int(torch.argmax(xc))
before, peak, after = float(xc[(k - 1) % n]), float(xc[k]), float(xc[(k + 1) % n])
curvature = before - 2.0 * peak + after
lag = k + (0.5 * (before - after) / curvature if curvature < 0 else 0.0)
return lag - n if lag > n / 2 else lag


def _sampled(image: torch.Tensor, offset: float, axis: int) -> torch.Tensor:
"""Return ``image`` sampled at ``x + offset`` voxels along ``axis``: linear, circular."""
whole = int(torch.floor(torch.tensor(offset)))
fraction = offset - whole
return (1.0 - fraction) * torch.roll(image, -whole, dims=axis) + fraction * torch.roll(
image, -(whole + 1), dims=axis
)
Loading
Loading