# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
#
# Copyright The NiPreps Developers <nipreps@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# We support and encourage derived works from this project, please read
# about our expectations at
#
# https://www.nipreps.org/community/licensing/
#
"""Filtering data."""
from __future__ import annotations
import numpy as np
from scipy.ndimage import median_filter
from skimage.morphology import ball
DEFAULT_CLIP_PERCENTILE = 75
"""Upper percentile threshold for intensity clipping."""
DEFAULT_DTYPE = "int16"
"""The default image's data type."""
BVAL_ATOL = 100.0
"""b-value tolerance value."""
CLIPPING_EMPTY_SELECTION_ERROR_MSG = """\
Empty percentile selection after applying {constraints}finite filtering (p_min={p_min}, p_max={p_max}).
"""
"""Clipping empty selection error message."""
CLIPPING_NONFINITE_THRESHOLDS_ERROR_MSG = """\
Percentile thresholds are not finite (a_min={a_min}, a_max={a_max}, p_min={p_min}, p_max={p_max}, nonnegative={nonnegative}).
"""
"""Clipping non-finite thresholds error message."""
CLIPPING_INVALID_THRESHOLDS_ERROR_MSG = """\
Invalid percentile thresholds (a_max <= a_min) (a_min={a_min}, a_max={a_max}, p_min={p_min}, p_max={p_max}, nonnegative={nonnegative}).
"""
"""Clipping invalid percentile thresholds error message."""
CLIPPING_DEGENERATE_RANGE_ERROR_MSG = """\
Degenerate dynamic range after clipping/shift (den={den}, a_min={a_min}, a_max={a_max}, \
nonnegative={nonnegative}, data_finite={data_finite}, unique~={unique}).
"""
"""Clipping degenerate dynamic range error message."""
[docs]
class ClippingValueError(RuntimeError):
"""Raised when clipping cannot compute a valid clipping/scaling."""
[docs]
def robust_window(
data: np.ndarray,
mask: np.ndarray | None = None,
p_min: float | None = None,
p_max: float = 99.98,
nonnegative: bool = True,
) -> tuple[float, float]:
"""
Estimate an intensity window that isolated outliers cannot set.
The percentiles are computed on a median-filtered copy of ``data``. With a
``mask``, the filter runs only on the mask's bounding box (plus the
footprint's radius, so the values inside the mask are unchanged), and only
the voxels inside the mask are summarized.
Parameters
----------
data : :obj:`~numpy.ndarray`
The input n-dimensional data array.
mask : :obj:`~numpy.ndarray`, optional
Boolean mask of the voxels the window is estimated from.
p_min : :obj:`float`, optional
The lower percentile. Defaults to 35 without a mask (which flattens the
background) and to 1 with one.
p_max : :obj:`float`, optional
The upper percentile.
nonnegative : :obj:`bool`, optional
If True, only consider non-negative values when calculating thresholds.
Returns
-------
:obj:`tuple` of :obj:`float`
The lower and upper bounds of the window.
"""
if p_min is None:
p_min = 35.0 if mask is None else 1.0
footprint = ball(3)
data = np.asanyarray(data, dtype=np.float32)
if mask is None:
denoised = median_filter(data, footprint=footprint)
else:
mask = np.asanyarray(mask, dtype=bool)
if mask.any():
radius = footprint.shape[0] // 2
corners = np.argwhere(mask)
bbox = tuple(
slice(max(lo - radius, 0), hi + radius + 1)
for lo, hi in zip(corners.min(axis=0), corners.max(axis=0), strict=True)
)
denoised = median_filter(data[bbox], footprint=footprint)[mask[bbox]]
else:
denoised = data[mask]
# Select values for percentile computation.
# If nonnegative=True, we must have at least one finite >=0 value.
sel = denoised[denoised >= 0] if nonnegative else denoised
sel = sel[np.isfinite(sel)]
if sel.size == 0:
constraints = "nonnegative constraint and " if nonnegative else ""
raise ClippingValueError(
CLIPPING_EMPTY_SELECTION_ERROR_MSG.format(
constraints=constraints, p_min=p_min, p_max=p_max
)
)
a_min = float(np.percentile(sel, p_min))
a_max = float(np.percentile(sel, p_max))
if not np.isfinite(a_min) or not np.isfinite(a_max):
raise ClippingValueError(
CLIPPING_NONFINITE_THRESHOLDS_ERROR_MSG.format(
a_min=a_min, a_max=a_max, p_min=p_min, p_max=p_max, nonnegative=nonnegative
)
)
if a_max <= a_min:
raise ClippingValueError(
CLIPPING_INVALID_THRESHOLDS_ERROR_MSG.format(
a_min=a_min, a_max=a_max, p_min=p_min, p_max=p_max, nonnegative=nonnegative
)
)
return a_min, a_max
[docs]
def advanced_clip(
data: np.ndarray,
p_min: float = 35.0,
p_max: float = 99.98,
nonnegative: bool = True,
dtype: str | np.dtype = DEFAULT_DTYPE,
invert: bool = False,
inplace: bool = False,
) -> np.ndarray | None:
"""
Clips outliers from an n-dimensional array and scales/casts to a specified data type.
This function removes outliers from both ends of the intensity distribution
in an n-dimensional array using percentiles. It optionally enforces non-negative
values and scales the data to fit within a specified data type (e.g., uint8
for image registration). To remove outliers more robustly, the function
first applies a median filter to the data before calculating clipping thresholds.
Parameters
----------
data : :obj:`~numpy.ndarray`
The input n-dimensional data array.
p_min : :obj:`float`, optional
The lower percentile threshold for clipping. Values below this percentile
are set to the threshold value.
p_max : :obj:`float`, optional
The upper percentile threshold for clipping. Values above this percentile
are set to the threshold value.
nonnegative : :obj:`bool`, optional
If True, only consider non-negative values when calculating thresholds.
dtype : :obj:`str` or :obj:`~numpy.dtype`, optional
The desired data type for the output array. Supported types are "uint8"
and "int16".
invert : :obj:`bool`, optional
If :obj:`True`, inverts the intensity values after scaling (1.0 - ``data``).
inplace : :obj:`bool`, optional
If :obj:`True`, the normalization is performed on the original data.
Returns
-------
:obj:`~numpy.ndarray` or :obj:`None`
The clipped and scaled data array with the specified data type or
:obj:`None` if ``inplace`` is :obj:`True`.
"""
if not inplace:
data = data.copy()
# Cast to float32 before modifying in-place: clipping a float array and
# writing the result in-place to an integer array is disallowed by NumPy due
# to risk of data loss
if not inplace or not np.issubdtype(data.dtype, np.floating):
data = data.astype(np.float32, copy=not inplace)
# Calculate stats on denoised version to avoid outlier bias
a_min, a_max = robust_window(data, p_min=p_min, p_max=p_max, nonnegative=nonnegative)
# Clip and scale data
np.clip(data, a_min=a_min, a_max=a_max, out=data)
data -= data.min()
den = float(data.max()) # max-min because min is now 0
if not np.isfinite(den) or den == 0.0:
# Degenerate dynamic range after clipping
unique = len(np.unique(data)) if data.size < 1_000_000 else "too big"
raise ClippingValueError(
CLIPPING_DEGENERATE_RANGE_ERROR_MSG.format(
den=den,
a_min=a_min,
a_max=a_max,
nonnegative=nonnegative,
data_finite=bool(np.isfinite(data).all()),
unique=unique,
)
)
data /= den
if invert:
np.subtract(1.0, data, out=data)
if dtype in ("uint8", "int16"):
np.round(255 * data, out=data)
data = data.astype(dtype, copy=False)
if inplace:
return None
return data
[docs]
def robust_minmax_normalization(
data: np.ndarray,
mask: np.ndarray | None = None,
p_min: float = 5.0,
p_max: float = 95.0,
inplace: bool = False,
) -> np.ndarray | None:
r"""Normalize min-max percentiles of each volume to the grand min-max
percentiles.
Robust min/max normalization of the volumes in the dataset following:
.. math::
\text{data}_{\text{normalized}} = \frac{(\text{data} - p_{min}) \cdot p_{\text{mean}}}{p_{\text{range}}} + p_{min}^{\text{mean}}
where
.. math::
p_{\text{range}} = p_{max} - p_{min}, \quad p_{\text{mean}} = \frac{1}{N} \sum_{i=1}^N p_{\text{range}_i}, \quad p_{min}^{\text{mean}} = \frac{1}{N} \sum_{i=1}^N p_{5_i}
If a mask is provided, only the data within the mask are considered.
Parameters
----------
data : :obj:`~numpy.ndarray`
Data to be normalized, with volumes on the first axis.
mask : :obj:`~numpy.ndarray`, optional
Boolean mask of volumes. If provided, only those volumes are considered.
p_min : :obj:`float`, optional
The lower percentile value for normalization.
p_max : :obj:`float`, optional
The upper percentile value for normalization.
inplace : :obj:`bool`, optional
If :obj:`False`, the normalization is performed on the original data.
Returns
-------
data : :obj:`~numpy.ndarray` or :obj:`None`
Normalized data or :obj:`None` if ``inplace`` is :obj:`True`.
"""
normalized = data if inplace else data.copy()
mask = mask if mask is not None else np.ones(data.shape[0], dtype=bool)
volumes = data[mask]
reshaped_data = volumes.reshape(volumes.shape[0], -1)
p5 = np.percentile(reshaped_data, p_min, axis=1)
p95 = np.percentile(reshaped_data, p_max, axis=1) - p5
# Broadcast the per-volume values along the first axis
per_volume = (slice(None),) + (np.newaxis,) * (volumes.ndim - 1)
normalized[mask] = (volumes - p5[per_volume]) * p95.mean() / p95[per_volume] + p5.mean()
if inplace:
return None
return normalized
[docs]
def grand_mean_normalization(
data: np.ndarray,
mask: np.ndarray | None = None,
center: float = DEFAULT_CLIP_PERCENTILE,
inplace: bool = False,
) -> np.ndarray | None:
"""Robust grand mean normalization.
Regresses out global signal differences so that data are normalized and
centered around a given value.
If a mask is provided, only the data within the mask are considered.
Parameters
----------
data : :obj:`~numpy.ndarray`
Data to be normalized, with volumes on the first axis.
mask : :obj:`~numpy.ndarray`, optional
Boolean mask of volumes. If provided, only those volumes are considered.
center : float, optional
Central value around which to normalize the data.
inplace : :obj:`bool`, optional
If :obj:`False`, the normalization is performed on the original data.
Returns
-------
data : :obj:`~numpy.ndarray` or :obj:`None`
Normalized data or :obj:`None` if ``inplace`` is :obj:`True`.
"""
normalized = data if inplace else data.copy()
mask = mask if mask is not None else np.ones(data.shape[0], dtype=bool)
volumes = data[mask]
centers = np.median(volumes, axis=tuple(range(1, volumes.ndim)))
reference = np.percentile(centers[centers >= 1.0], center)
centers[centers < 1.0] = reference
drift = reference / centers
# Broadcast the per-volume values along the first axis
normalized[mask] = volumes * drift[(slice(None),) + (np.newaxis,) * (volumes.ndim - 1)]
if inplace:
return None
return normalized
[docs]
def dwi_select_shells(
gradients: np.ndarray,
index: int,
atol_low: float | None = None,
atol_high: float | None = None,
) -> np.ndarray:
"""Select DWI shells around the given index and lower and upper b-value
bounds.
Computes a boolean mask of the DWI shells around the given index with the
provided lower and upper bound b-values.
If ``atol_low`` and ``atol_high`` are both :obj:`None`, the returned shell mask
corresponds to the lengths of the diffusion-sensitizing gradients.
Parameters
----------
gradients : :obj:`~numpy.ndarray`
Gradients arranged as ``(N, C)`` with the last column storing b-values.
index : :obj:`int`
Index of the shell data.
atol_low : :obj:`float`, optional
A lower bound for the b-value.
atol_high : :obj:`float`, optional
An upper bound for the b-value.
Returns
-------
shellmask : :obj:`~numpy.ndarray`
Shell mask.
"""
bvals = gradients[:, -1]
bcenter = bvals[index]
shellmask = np.ones(len(bvals), dtype=bool)
shellmask[index] = False # Drop the held-out index
if atol_low is None and atol_high is None:
return shellmask
atol_low = 0 if atol_low is None else atol_low
atol_high = bvals.max() if atol_high is None else atol_high
# Keep only b-values within the range defined by atol_high and atol_low
shellmask[bvals > (bcenter + atol_high)] = False
shellmask[bvals < (bcenter - atol_low)] = False
if not shellmask.sum():
raise RuntimeError(f"Shell corresponding to index {index} (b={bcenter}) is empty.")
return shellmask