diff --git a/docs/api/apps.md b/docs/api/apps.md index d23282df..ca78ea31 100644 --- a/docs/api/apps.md +++ b/docs/api/apps.md @@ -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 | diff --git a/docs/api/tools.md b/docs/api/tools.md index 9f77acd9..14de768c 100644 --- a/docs/api/tools.md +++ b/docs/api/tools.md @@ -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 diff --git a/src/bartorch/apps/__init__.py b/src/bartorch/apps/__init__.py index 1599ac9c..94dc1482 100644 --- a/src/bartorch/apps/__init__.py +++ b/src/bartorch/apps/__init__.py @@ -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 @@ -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", +] diff --git a/src/bartorch/apps/_buda.py b/src/bartorch/apps/_buda.py new file mode 100644 index 00000000..faafd3ea --- /dev/null +++ b/src/bartorch/apps/_buda.py @@ -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:])) diff --git a/src/bartorch/tools/_correct/__init__.py b/src/bartorch/tools/_correct/__init__.py index 4c0cb51c..b15b9253 100644 --- a/src/bartorch/tools/_correct/__init__.py +++ b/src/bartorch/tools/_correct/__init__.py @@ -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", @@ -31,6 +35,7 @@ "bias_field_correct", "correct_lines", "correct_susceptibility", + "displacement_off_resonance", "deblur", "epi_ramp_operator", "estimate_epi_phase", diff --git a/src/bartorch/tools/_correct/_susceptibility.py b/src/bartorch/tools/_correct/_susceptibility.py index efeb9b00..0e0c0308 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", "correct_susceptibility", "displacement_off_resonance"] Optimizer = Literal["gauss-newton", "lbfgs", "admm"] @@ -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) diff --git a/tests/_epi_pair.py b/tests/_epi_pair.py new file mode 100644 index 00000000..9e5541e7 --- /dev/null +++ b/tests/_epi_pair.py @@ -0,0 +1,58 @@ +"""A multi-coil EPI pair of opposite phase-encode polarity, encoded line by line off resonance.""" + +from __future__ import annotations + +import math + +import torch + +from bartorch import linop + + +def coil_maps(n: int, coils: int) -> torch.Tensor: + """Smooth sensitivities of coils around the field of view, unit root sum of squares.""" + rows, columns = torch.meshgrid( + torch.linspace(-1, 1, n), torch.linspace(-1, 1, n), indexing="ij" + ) + maps = [] + for coil in range(coils): + angle = 2 * math.pi * coil / coils + centre = (1.2 * math.sin(angle), 1.2 * math.cos(angle)) + magnitude = torch.exp(-((rows - centre[0]) ** 2 + (columns - centre[1]) ** 2) / 0.8) + maps.append(magnitude * torch.exp(1j * (0.7 * coil + 0.5 * columns))) + maps = torch.stack(maps).to(torch.complex64) + return maps / maps.abs().pow(2).sum(0, keepdim=True).sqrt() + + +def disc(n: int) -> torch.Tensor: + """An ellipse with structure inside it, and a smooth phase.""" + rows, columns = torch.meshgrid( + torch.linspace(-1, 1, n), torch.linspace(-1, 1, n), indexing="ij" + ) + inside = ((rows / 0.75) ** 2 + (columns / 0.6) ** 2) < 1 + image = inside * (1 + 0.5 * torch.sin(6 * rows) * torch.cos(5 * columns)) + return (image * torch.exp(0.5j * columns)).to(torch.complex64) + + +def field(n: int, peak: float) -> torch.Tensor: + """A smooth off-resonance in Hz, peaking off centre.""" + rows, columns = torch.meshgrid( + torch.linspace(-1, 1, n), torch.linspace(-1, 1, n), indexing="ij" + ) + return (peak * torch.exp(-((rows + 0.3) ** 2 + columns**2) / 0.15)).float() + + +def times(n: int, line_time: float, polarity: int, echo_time: float = 0.03) -> torch.Tensor: + """Sample time of every line, the centre line at ``echo_time``.""" + return echo_time + polarity * line_time * (torch.arange(n, dtype=torch.float32) - n // 2) + + +def acquire(image, maps, off_resonance, line_times, lines) -> torch.Tensor: + """``(coils, y, x)`` k-space of ``lines``, each from the image at that line's time.""" + n = image.shape[-1] + encode = linop.CartesianSense(maps, (n, n)) + kspace = torch.zeros((maps.shape[0], n, n), dtype=torch.complex64) + for line in lines: + phase = torch.exp(2j * math.pi * off_resonance * float(line_times[line])) + kspace[:, line] = encode(image * phase).reshape(maps.shape[0], n, n)[:, line] + return kspace diff --git a/tests/test_apps_buda.py b/tests/test_apps_buda.py new file mode 100644 index 00000000..ae0472ff --- /dev/null +++ b/tests/test_apps_buda.py @@ -0,0 +1,68 @@ +"""BUDA: one image from EPI shots of opposite phase-encode polarity.""" + +from __future__ import annotations + +import pytest +import torch + +from bartorch import apps, linop, optim +from tests._epi_pair import acquire, coil_maps, disc, field, times + +N, COILS, LINE_TIME = 48, 6, 1e-3 + + +def nrmse(image, truth, support): + image, truth = image.abs()[support], truth.abs()[support] + scale = float((image * truth).sum() / (image * image).sum()) + return float((scale * image - truth).norm() / truth.norm()) + + +@pytest.fixture(scope="module") +def pair(): + image, maps, off_resonance = disc(N), coil_maps(N, COILS), field(N, 60.0) + support = image.abs() > 0 + off_resonance = off_resonance * support + lines = range(0, N, 2) + up, down = times(N, LINE_TIME, +1), times(N, LINE_TIME, -1) + kspace = torch.stack( + [ + acquire(image, maps, off_resonance, up, lines), + acquire(image, maps, off_resonance, down, lines), + ] + ) + readout_time = torch.stack([up, down])[:, :, None].expand(2, N, N) + return image, maps, off_resonance, support, kspace, readout_time + + +def test_the_joint_image_is_undistorted_where_each_shot_alone_is_not(pair): + image, maps, off_resonance, support, kspace, readout_time = pair + sense = linop.CartesianSense( + maps, (N, N), pattern=(kspace[0].abs().sum(0) > 0).to(torch.complex64) + ) + alone = optim.CG(1e-3, maxiter=30)(kspace[0].reshape(sense.oshape), sense).reshape(N, N) + + joint = apps.buda(kspace, maps, off_resonance, readout_time, l2=1e-3, mask=support) + + assert nrmse(alone, image, support) > 0.1 + assert nrmse(joint, image, support) < 0.03 + + +def test_each_shot_has_its_own_phase(pair): + image, maps, off_resonance, support, kspace, readout_time = pair + drift = torch.linspace(-0.5, 0.5, N)[None, :].expand(N, N) + shifted = kspace.clone() + shifted[1] = acquire( + image * torch.exp(1j * drift), maps, off_resonance, readout_time[1, :, 0], range(0, N, 2) + ) + + phase = apps.shot_phase(shifted, maps, off_resonance, readout_time, mask=support) + difference = torch.angle(torch.exp(1j * (phase[1] - phase[0]))) + + assert phase.shape == (2, N, N) + assert float((difference - drift)[support].abs().mean()) < 0.1 + + +def test_a_phase_named_otherwise_is_refused(pair): + _, maps, off_resonance, _, kspace, readout_time = pair + with pytest.raises(ValueError, match="estimate"): + apps.buda(kspace, maps, off_resonance, readout_time, phase="guess") diff --git a/tests/test_correct_susceptibility.py b/tests/test_correct_susceptibility.py index 44e272ff..a0db9b61 100644 --- a/tests/test_correct_susceptibility.py +++ b/tests/test_correct_susceptibility.py @@ -7,7 +7,7 @@ import pytest import torch -from bartorch.tools import correct_susceptibility +from bartorch.tools import correct_susceptibility, displacement_off_resonance needs_pyhysco = pytest.mark.skipif( importlib.util.find_spec("EPI_MRI") is None, @@ -136,3 +136,38 @@ def test_two_dimensional_pair_reports_the_upstream_limit() -> None: voxel_size=(1.0, 1.0), max_iter=6, ) + + +def test_off_resonance_is_minus_the_displacement_over_the_phase_encode_time() -> None: + edges = torch.zeros(17, 8) + edges[:, :4] = 3.0 # mm, on the 17 edges of 16 cells + hz = displacement_off_resonance(edges, (1.5, 1.0), 2e-3, phase_encoding_axis=0) + assert hz.shape == (16, 8) + assert hz[:, :4] == pytest.approx(torch.full((16, 4), -2.0 / (16 * 2e-3))) + assert hz[:, 4:] == pytest.approx(torch.zeros(16, 4)) + across = displacement_off_resonance(edges.T, (1.0, 1.5), 2e-3, phase_encoding_axis=1) + assert across == pytest.approx(hz.T) + + +@needs_pyhysco +def test_the_off_resonance_of_a_corrected_epi_pair_is_the_one_that_displaced_it() -> None: + """Sign, centring and units, against the field an EPI pair was encoded at.""" + from bartorch import linop + from tests._epi_pair import acquire, coil_maps, disc, field, times + + n, line_time = 64, 1e-3 + image, maps = disc(n), coil_maps(n, 4) + support = image.abs() > 0 + truth = field(n, 80.0) * support + pair = [] + for polarity in (+1, -1): + kspace = acquire(image, maps, truth, times(n, line_time, polarity), range(n)) + coils = linop.CartesianSense(maps, (n, n)) + pair.append(coils.H(kspace.reshape(coils.oshape)).reshape(n, n).abs().double()) + stack = [part[:, :, None].repeat(1, 1, 3) for part in pair] + result = correct_susceptibility(*stack, voxel_size=(1.0, 1.0, 1.0), alpha=30.0, max_iter=20) + hz = displacement_off_resonance(result.field_map.float(), (1.0, 1.0, 1.0), line_time)[:, :, 1] + inside = support & (truth.abs() > 10.0) + correlation = torch.corrcoef(torch.stack([hz[inside], truth[inside]]))[0, 1] + assert float(correlation) > 0.9 + assert float((hz - truth)[inside].abs().mean()) < 0.25 * float(truth[inside].abs().mean())