diff --git a/docs/api/tools.md b/docs/api/tools.md index 9f77acd9..a2089d6b 100644 --- a/docs/api/tools.md +++ b/docs/api/tools.md @@ -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 | @@ -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 diff --git a/src/bartorch/tools/_correct/__init__.py b/src/bartorch/tools/_correct/__init__.py index 4c0cb51c..31963742 100644 --- a/src/bartorch/tools/_correct/__init__.py +++ b/src/bartorch/tools/_correct/__init__.py @@ -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, @@ -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", @@ -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", diff --git a/src/bartorch/tools/_correct/_epi.py b/src/bartorch/tools/_correct/_epi.py index 6a3d4635..a8948c7b 100644 --- a/src/bartorch/tools/_correct/_epi.py +++ b/src/bartorch/tools/_correct/_epi.py @@ -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: @@ -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)}" @@ -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]: diff --git a/src/bartorch/tools/_correct/_susceptibility.py b/src/bartorch/tools/_correct/_susceptibility.py index efeb9b00..fcf6c8ce 100644 --- a/src/bartorch/tools/_correct/_susceptibility.py +++ b/src/bartorch/tools/_correct/_susceptibility.py @@ -13,7 +13,7 @@ import torch -__all__ = ["SusceptibilityCorrection", "correct_susceptibility"] +__all__ = ["SusceptibilityCorrection", "apply_susceptibility", "correct_susceptibility"] Optimizer = Literal["gauss-newton", "lbfgs", "admm"] @@ -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. @@ -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 @@ -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, @@ -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. @@ -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 + ) diff --git a/tests/test_apply_susceptibility.py b/tests/test_apply_susceptibility.py new file mode 100644 index 00000000..6b380a7d --- /dev/null +++ b/tests/test_apply_susceptibility.py @@ -0,0 +1,102 @@ +"""A known displacement field applied to an image (no PyHySCO needed).""" + +import pytest +import torch + +from bartorch.tools import apply_susceptibility +from bartorch.tools._correct._susceptibility import _sampled + + +def _image(rows: int = 32, cols: int = 12) -> torch.Tensor: + return torch.rand(rows, cols, dtype=torch.float64, generator=torch.Generator().manual_seed(0)) + + +def _uniform(image: torch.Tensor, voxels: float, voxel: float) -> torch.Tensor: + return torch.full((image.shape[0] + 1, image.shape[1]), voxels * voxel, dtype=torch.float64) + + +def test_a_uniform_field_samples_blip_up_at_x_plus_b_and_blip_down_at_x_minus_b(): + image = _image() + field = _uniform(image, 3.0, 2.0) + + up = apply_susceptibility(image, field, voxel_size=(2.0, 1.0)) + down = apply_susceptibility(image, field, voxel_size=(2.0, 1.0), blip="down") + + torch.testing.assert_close(up, torch.roll(image, -3, dims=0)) + torch.testing.assert_close(down, torch.roll(image, 3, dims=0)) + + +def test_a_fractional_uniform_field_is_the_pre_alignment_shift(): + image = _image() + field = _uniform(image, -7.3, 1.5) + + torch.testing.assert_close( + apply_susceptibility(image, field, voxel_size=(1.5, 1.0)), _sampled(image, -7.3, 0) + ) + + +def test_the_intensity_is_modulated_by_the_field_derivative_and_mass_is_kept(): + rows = 128 + x = torch.arange(rows, dtype=torch.float64) + image = torch.exp(-(((x - 64) / 10) ** 2))[:, None].repeat(1, 4) + edges = torch.arange(rows + 1, dtype=torch.float64) - 0.5 + field = (3.0 * torch.sin(2 * torch.pi * edges / rows))[:, None].repeat(1, 4) + + up = apply_susceptibility(image, field, voxel_size=(1.0, 1.0)) + down = apply_susceptibility(image, field, voxel_size=(1.0, 1.0), blip="down") + + # At the bump's centre the field is zero and its derivative -0.15 per voxel. + slope = float(field[65, 0] - field[64, 0]) + assert slope == pytest.approx(-0.147, abs=1e-3) + assert float(up[64, 0]) == pytest.approx(1 + slope) + assert float(down[64, 0]) == pytest.approx(1 - slope) + torch.testing.assert_close(up.sum(0), image.sum(0), rtol=1e-3, atol=0) + torch.testing.assert_close(down.sum(0), image.sum(0), rtol=1e-3, atol=0) + + +def test_blip_down_with_a_field_is_blip_up_with_its_negative(): + image = _image() + field = torch.randn(33, 12, dtype=torch.float64, generator=torch.Generator().manual_seed(1)) + + torch.testing.assert_close( + apply_susceptibility(image, field, voxel_size=(1.2, 1.0), blip="down"), + apply_susceptibility(image, -field, voxel_size=(1.2, 1.0)), + ) + + +def test_a_volume_is_corrected_slice_by_slice_along_its_phase_encoding_axis(): + volume = torch.rand(5, 16, 9, dtype=torch.float64, generator=torch.Generator().manual_seed(2)) + field = torch.randn(5, 17, 9, dtype=torch.float64, generator=torch.Generator().manual_seed(3)) + + corrected = apply_susceptibility( + volume, field, voxel_size=(4.0, 1.1, 1.0), phase_encoding_axis=1 + ) + + for k in range(5): + torch.testing.assert_close( + corrected[k], apply_susceptibility(volume[k], field[k], voxel_size=(1.1, 1.0)) + ) + + +def test_a_complex_image_is_corrected_as_its_real_and_imaginary_parts(): + image = torch.complex(_image(), _image().flip(0)) + field = torch.randn(33, 12, dtype=torch.float64, generator=torch.Generator().manual_seed(4)) + + corrected = apply_susceptibility(image, field, voxel_size=(1.0, 1.0)) + + torch.testing.assert_close( + corrected.real, apply_susceptibility(image.real, field, voxel_size=(1.0, 1.0)) + ) + torch.testing.assert_close( + corrected.imag, apply_susceptibility(image.imag, field, voxel_size=(1.0, 1.0)) + ) + + +def test_a_field_not_on_the_cell_edges_of_the_image_is_refused(): + image = _image() + with pytest.raises(ValueError, match="field"): + apply_susceptibility(image, torch.zeros(32, 12, dtype=torch.float64), voxel_size=(1.0, 1.0)) + with pytest.raises(ValueError, match="blip"): + apply_susceptibility( + image, torch.zeros(33, 12, dtype=torch.float64), voxel_size=(1.0, 1.0), blip="left" + ) diff --git a/tests/test_correct_epi.py b/tests/test_correct_epi.py index ca5e83ad..29cf3e23 100644 --- a/tests/test_correct_epi.py +++ b/tests/test_correct_epi.py @@ -242,3 +242,52 @@ def test_correcting_a_train_leaves_no_signal_outside_the_object(device): estimate = _ifftc(np.concatenate([_numpy(line) for line in corrected], axis=0)) background = np.abs(image) < 1e-6 assert np.abs(estimate)[background].max() / np.abs(estimate).max() < 1e-3 + + +def _reference_train(per_echo, *, drift=0.2, echoes=8): + """A blip-free train: reversed echo k carries ``per_echo[k]``. + + Every echo also carries an off-resonance phase growing ``drift`` rad per echo. + """ + line = _navigator_line(coils=2) + lines, flags = [], [] + for echo in range(echoes): + drifted = line * np.exp(1j * drift * echo) + backwards = echo % 2 == 1 + stored = _delayed(drifted, per_echo[echo])[..., ::-1] if backwards else drifted + lines.append(stored) + flags.append(backwards) + flipped = bt.correct_lines([(t, f) for t, f in zip(_tensors(lines), flags, strict=True)]) + return flipped, flags + + +def test_the_reference_fit_is_the_correction_of_each_reversed_echo(device): + """Each reversed echo gets minus its own phase, forward echoes nothing, the drift cancels.""" + per_echo = {k: [0.1 * k, 0.5 + 0.05 * k] for k in range(8)} + lines, flags = _reference_train(per_echo) + fit = bt.estimate_epi_echo_phase([line.to(device) for line in lines], flags) + assert fit.shape == (8, 2) and fit.device.type == device + fit = _numpy(fit) + np.testing.assert_array_equal(fit[0::2], 0.0) + for echo in (1, 3, 5): + np.testing.assert_allclose(fit[echo], [-v for v in per_echo[echo]], atol=0.05) + # The last echo has a forward echo on one side only: it takes echo 5's fit. + np.testing.assert_allclose(fit[7], fit[5]) + + +def test_the_reference_fit_undoes_the_phase_of_a_reversed_imaging_line(): + impressed = [0.3, 0.8] + lines, flags = _reference_train(dict.fromkeys(range(8), impressed), drift=0.0) + fit = bt.estimate_epi_echo_phase(lines, flags) + line = _navigator_line(coils=2) + stored = _delayed(line, impressed)[..., ::-1] + corrected = bt.correct_lines([(_tensors([stored])[0], True)], fit[3])[0] + np.testing.assert_allclose(_numpy(corrected), line, atol=1e-2) + + +def test_a_reference_without_both_polarities_is_refused(): + line = torch.ones(2, 16, dtype=torch.complex64) + with pytest.raises(ValueError, match="no forward echo"): + bt.estimate_epi_echo_phase([line] * 3, [False] * 3) + with pytest.raises(ValueError, match="polarities"): + bt.estimate_epi_echo_phase([line] * 3, [False] * 2) diff --git a/tests/test_correct_susceptibility_prealign.py b/tests/test_correct_susceptibility_prealign.py new file mode 100644 index 00000000..fcbb1bbc --- /dev/null +++ b/tests/test_correct_susceptibility_prealign.py @@ -0,0 +1,27 @@ +"""The uniform displacement removed before PyHySCO (no PyHySCO needed).""" + +import torch + +from bartorch.tools._correct._susceptibility import _profile_lag, _sampled + + +def _disk(centre_row: float) -> torch.Tensor: + rows = torch.arange(96, dtype=torch.float64)[:, None, None] + cols = torch.arange(64, dtype=torch.float64)[None, :, None] + return ( + (((rows - centre_row) ** 2 + (cols - 32) ** 2) < 15**2).to(torch.float64).expand(96, 64, 3) + ) + + +def test_the_lag_of_a_pair_moved_apart_is_found_to_a_fraction_of_a_voxel(): + up, down = _disk(30.0), _disk(63.5) + assert abs(_profile_lag(up, down, 0) - 33.5) < 0.6 + assert abs(_profile_lag(down, up, 0) + 33.5) < 0.6 + + +def test_sampling_half_the_lag_brings_the_pair_together(): + up, down = _disk(30.0), _disk(64.0) + offset = -0.5 * _profile_lag(up, down, 0) + moved_up, moved_down = _sampled(up, offset, 0), _sampled(down, -offset, 0) + assert torch.allclose(moved_up, moved_down, atol=1e-6) + assert torch.allclose(moved_up, _disk(47.0), atol=1e-6)