Skip to content
Draft
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/apps.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,6 @@ interface they are assembled from.
| {obj}`~bartorch.apps.partial_fourier` | `homodyne` | `homodyne -I -C` along each axis acquired on one side of k-space only, the side and the acquired fraction read from the sampling mask |
| {obj}`~bartorch.apps.pocsense` | none | The POCSENSE projections swept by BART's `pocs` iteration |
| {obj}`~bartorch.apps.mobafit` | `mobafit` | Per-voxel Levenberg-Marquardt over a BlochSim model; returns named parameter maps in physical units |
| {obj}`~bartorch.apps.buda` | none | Blip-up/blip-down EPI: one image from shots of opposite phase-encode polarity, each encoded by {obj}`~bartorch.linop.CartesianSense` under {obj}`~bartorch.linop.FieldCorrected` at its own sample times, solved jointly with an iteration {obj}`~bartorch.apps.pics` would choose |
| {obj}`~bartorch.apps.shot_phase` | none | Each shot's low-resolution image phase, from its own field-corrected SENSE image, for {obj}`~bartorch.apps.buda` |
| {obj}`~bartorch.apps.moba` | `moba` | Same Gauss-Newton method over a BlochSim model inside the encoding, with the coils known or estimated jointly under Sobolev weighting; returns named parameter maps in physical units, not held to the command's output |
1 change: 1 addition & 0 deletions docs/api/tools.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ when {obj}`~bartorch.tools.correct_susceptibility` is called
| {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.SusceptibilityCorrection` | Corrected pair and displacement field from {obj}`~bartorch.tools.correct_susceptibility` |
| {obj}`~bartorch.tools.displacement_off_resonance` | Off-resonance in Hz from the displacement of a {obj}`~bartorch.tools.SusceptibilityCorrection`, at the cell centres |

## Rigid motion from navigators

Expand Down
13 changes: 12 additions & 1 deletion src/bartorch/apps/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

from __future__ import annotations

from bartorch.apps._buda import buda, shot_phase
from bartorch.apps._calibration import nlinv_maps
from bartorch.apps._moba import moba
from bartorch.apps._mobafit import mobafit
Expand All @@ -21,4 +22,14 @@
from bartorch.apps._pics import pics
from bartorch.apps._pocsense import pocsense

__all__ = ["moba", "mobafit", "nlinv_maps", "nlinv_pics", "partial_fourier", "pics", "pocsense"]
__all__ = [
"buda",
"moba",
"mobafit",
"nlinv_maps",
"nlinv_pics",
"partial_fourier",
"pics",
"pocsense",
"shot_phase",
]
245 changes: 245 additions & 0 deletions src/bartorch/apps/_buda.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,245 @@
"""BUDA: one image from EPI shots of opposite phase-encode polarity, solved jointly.

Not a BART command. Each shot is encoded by :func:`~bartorch.linop.CartesianSense`
under :func:`~bartorch.linop.FieldCorrected` at its own sample times, so the
off-resonance that displaces a blip-up image one way and a blip-down image the
other is part of the encoding, and one image serves both shots' data.
"""

from __future__ import annotations

from collections.abc import Iterable

import torch

import bartorch
from bartorch import linop, optim
from bartorch.apps._pics import _MAXITER, _SOLVERS, _chosen, _terms
from bartorch.priors import Regularizer

__all__ = ["buda", "shot_phase"]


def _per_shot(values: torch.Tensor | None, shots: int, name: str) -> list:
if values is None:
return [None] * shots
if values.shape[0] != shots:
raise ValueError(f"{name} has {values.shape[0]} shots, the k-space {shots}")
return list(values)


def _on_codomain(times: torch.Tensor, oshape: tuple[int, ...]) -> torch.Tensor:
"""Sample times ``([z,] y, x)``, or broadcastable to it, reshaped to broadcast to ``oshape``."""
times = torch.as_tensor(times, dtype=torch.float32)
return times.reshape((1,) * (len(oshape) - times.ndim) + tuple(times.shape))


def _encodings(
kspace: torch.Tensor,
sensitivities: torch.Tensor,
field_map: torch.Tensor,
readout_time: torch.Tensor,
phase: torch.Tensor | None,
segments: int,
mask: torch.Tensor | None,
device,
) -> list[linop.LinearOperator]:
"""One field-corrected SENSE encoding per shot, each on that shot's sampling pattern."""
shots = kspace.shape[0]
grid = tuple(kspace.shape[2:])
times = _per_shot(torch.as_tensor(readout_time), shots, "readout_time")
phases = _per_shot(phase, shots, "phase")
encodings = []
for shot in range(shots):
pattern = (kspace[shot].abs().sum(dim=0) > 0).to(torch.complex64)
maps = sensitivities
if phases[shot] is not None:
maps = maps * torch.exp(1j * phases[shot].to(torch.float32))
sense = linop.CartesianSense(maps, grid, pattern=pattern, device=device)
encodings.append(
linop.FieldCorrected(
sense,
field_map.to(torch.float32),
_on_codomain(times[shot], tuple(sense.oshape)),
mask=mask,
segments=segments,
)
)
return encodings


def shot_phase(
kspace: torch.Tensor,
sensitivities: torch.Tensor,
field_map: torch.Tensor,
readout_time: torch.Tensor,
*,
fraction: float = 0.25,
l2: float = 1e-3,
maxiter: int = 20,
segments: int = -1,
mask: torch.Tensor | None = None,
device=None,
) -> torch.Tensor:
"""Return each shot's low-resolution image phase, from its own field-corrected SENSE image.

Each shot is solved alone, by conjugate gradients with Tikhonov weight
``l2`` relative to its data scaling, under the encoding :func:`buda`
builds, and its image is low-pass filtered by a Hann window spanning
``fraction`` of k-space along each axis. The phase that remains is what
differs between shots acquired at different times, such as a drift of the
field or of the receiver, which a joint image cannot carry.

Parameters
----------
kspace, sensitivities, field_map, readout_time
As :func:`buda`.
fraction : float, default=0.25
Width of the Hann window, as a fraction of each axis of k-space.
l2 : float, default=0.001
Tikhonov weight of each shot's solve.
maxiter : int, default=20
Conjugate-gradient iterations of each shot's solve.
segments : int, default=-1
As :func:`buda`.
mask : torch.Tensor, default=None
As :func:`buda`.
device : torch.device or str, default=None
As :func:`buda`.

Returns
-------
torch.Tensor
``(shots, [z,] y, x)`` phase in radians.
"""
grid = tuple(kspace.shape[2:])
phases = []
for shot, encoding in enumerate(
_encodings(kspace, sensitivities, field_map, readout_time, None, segments, mask, device)
):
data = (kspace[shot] * (kspace[shot].abs().sum(dim=0) > 0)).reshape(encoding.oshape)
scale = optim.data_scaling(data, A=encoding) or 1.0
image = optim.CG(l2, maxiter=maxiter)(data * (1.0 / scale), encoding).reshape(grid)
axes = tuple(range(-len(grid), 0))
spectrum = bartorch.fft(image.to(torch.complex64), axes, unitary=True).reshape(grid)
window = torch.ones(grid)
for axis, n in zip(axes, grid, strict=True):
width = max(int(round(fraction * n)), 1)
hann = torch.zeros(n)
start = n // 2 - width // 2
hann[start : start + width] = torch.hann_window(width, periodic=False)
shape = [1] * len(grid)
shape[axis] = n
window = window * hann.reshape(shape)
low = bartorch.fft(spectrum * window, axes, inverse=True, unitary=True).reshape(grid)
phases.append(torch.angle(low))
return torch.stack(phases)


def buda(
kspace: torch.Tensor,
sensitivities: torch.Tensor,
field_map: torch.Tensor,
readout_time: torch.Tensor,
*,
phase: torch.Tensor | str | None = None,
regularizers: Regularizer | Iterable[Regularizer] | None = None,
l2: float | None = None,
maxiter: int | None = None,
segments: int = -1,
mask: torch.Tensor | None = None,
device=None,
scaling: float | None = None,
) -> torch.Tensor:
r"""Reconstruct one image from EPI shots of opposite phase-encode polarity (BUDA).

Blip-up/blip-down acquisition (BUDA; Liao et al., Magn Reson Med 2021):
the shots are encoded together,

.. math::

y_s = P_s F \, S \, e^{i \phi_s} e^{i 2 \pi f t_s} x ,

with :math:`P_s` the sampling of shot :math:`s`, :math:`S` the coil
sensitivities, :math:`\phi_s` the shot's image phase, :math:`f` the
off-resonance and :math:`t_s` the time each k-space sample was acquired, by
time segmentation (:func:`~bartorch.linop.FieldCorrected`). The image
solves the stacked data consistency over every shot, under ``regularizers``
as :func:`~bartorch.apps.pics` chooses its iteration from them, after
dividing the data by the scaling estimated from the adjoint image. The
off-resonance displaces the shots in opposite directions along the phase
encode, so the joint image is undistorted, and the shots' samples sum
where a lattice is shared, or fill each other's gaps where it is not.

Parameters
----------
kspace : torch.Tensor
``(shots, coils, [z,] y, x)`` k-space on the reconstruction grid, centred,
zero where a shot has no sample.
sensitivities : torch.Tensor
``(coils, [z,] y, x)`` coil sensitivities, undistorted, such as those of
a gradient-echo calibration.
field_map : torch.Tensor
``([z,] y, x)`` off-resonance in Hz.
readout_time : torch.Tensor
``(shots, [z,] y, x)``, or broadcastable to it, the time of each
k-space sample from the excitation, in s; an EPI line's samples share
its echo time to within a readout.
phase : torch.Tensor or "estimate" or None, default=None
``(shots, [z,] y, x)`` image phase of each shot in radians;
``"estimate"`` takes :func:`shot_phase`; ``None`` is a phase shared by
every shot.
regularizers : Regularizer or iterable of Regularizer, default=None
Terms from :mod:`bartorch.priors`, relative to the scaled data.
l2 : float, default=None
Tikhonov weight, with conjugate gradients.
maxiter : int, default=None
Iterations; ``None`` is BART's 30.
segments : int, default=-1
Time segments of :func:`~bartorch.linop.FieldCorrected`; -1 lets it
choose.
mask : torch.Tensor, default=None
Support of the field map, which its fit weights.
device : torch.device or str, default=None
Where the encodings compute; the data and the image stay where they are.
scaling : float, default=None
Data scaling; ``None`` estimates it from the adjoint image.

Returns
-------
torch.Tensor
``([z,] y, x)`` complex image in the units of ``kspace``.

Raises
------
ValueError
If ``readout_time`` or ``phase`` does not hold one entry per shot.
"""
if isinstance(phase, str):
if phase != "estimate":
raise ValueError(f"phase is a tensor, 'estimate' or None, not {phase!r}")
phase = shot_phase(
kspace,
sensitivities,
field_map,
readout_time,
segments=segments,
mask=mask,
device=device,
)
encodings = _encodings(
kspace, sensitivities, field_map, readout_time, phase, segments, mask, device
)
A = linop.stack(encodings)
patterns = (kspace.abs().sum(dim=1, keepdim=True) > 0).to(kspace.dtype)
data = (kspace * patterns).reshape(A.oshape)
scale = scaling or optim.data_scaling(data, A=A) or 1.0

terms = _terms(regularizers)
solver = _chosen(terms)
if solver == "cg":
arguments = [] if l2 is None else [l2]
else:
arguments = [terms]
iterate = _SOLVERS[solver](*arguments, maxiter=_MAXITER if maxiter is None else maxiter)
return (iterate(data * (1.0 / scale), A) * scale).reshape(tuple(kspace.shape[2:]))
7 changes: 6 additions & 1 deletion src/bartorch/tools/_correct/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,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,
correct_susceptibility,
displacement_off_resonance,
)

__all__ = [
"CoefficientAccessor",
Expand All @@ -31,6 +35,7 @@
"bias_field_correct",
"correct_lines",
"correct_susceptibility",
"displacement_off_resonance",
"deblur",
"epi_ramp_operator",
"estimate_epi_phase",
Expand Down
64 changes: 63 additions & 1 deletion 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", "correct_susceptibility", "displacement_off_resonance"]

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

Expand Down Expand Up @@ -268,3 +268,65 @@ 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 displacement_off_resonance(
field_map: torch.Tensor,
voxel_size: tuple[float, ...],
line_time: float,
*,
phase_encoding_axis: int = 0,
) -> torch.Tensor:
r"""Return the off-resonance in Hz that displaces an EPI image as a correction's field does.

The displacement :math:`b` of :class:`SusceptibilityCorrection` is defined
on the cell edges along the phase-encoding axis, in the units of
``voxel_size``; it is averaged onto the cell centres and divided by the
voxel size there. A voxel off resonance by :math:`f` accrues
:math:`e^{i 2 \pi f t}`, and a blip-up shot reads the :math:`n` lines of
the grid :math:`\Delta t` apart, so its image is displaced by
:math:`f n \Delta t` voxels; the correction samples it at :math:`x + b`,
hence

.. math::

f = -\frac{b}{n \, \Delta t}

for k-space centred with its first line at :math:`-n/2`, as
:func:`~bartorch.linop.CartesianSense` encodes it.

Parameters
----------
field_map : torch.Tensor
A correction's displacement: one sample longer than the images along
``phase_encoding_axis``.
voxel_size : tuple of float
Voxel size per axis, as given to :func:`correct_susceptibility`.
line_time : float
Time between consecutive lines of the grid in the blip-up shot, in s:
the echo spacing over the lines one blip steps; positive where the
shot's sample time grows with the line index.
phase_encoding_axis : int, default=0
As given to :func:`correct_susceptibility`.

Returns
-------
torch.Tensor
Off-resonance in Hz on the image grid.

Raises
------
ValueError
If ``line_time`` is zero or ``voxel_size`` does not give one value per
axis.
"""
if line_time == 0:
raise ValueError("line_time must not be zero")
if len(voxel_size) != field_map.ndim:
raise ValueError(f"voxel_size has {len(voxel_size)} entries for a {field_map.ndim}D field")
axis = phase_encoding_axis % field_map.ndim
edges = field_map.movedim(axis, 0)
centres = 0.5 * (edges[:-1] + edges[1:])
lines = centres.shape[0]
voxels = centres / voxel_size[axis]
return (-voxels / (lines * line_time)).movedim(0, axis)
Loading
Loading