Source code for medaugmentx.transforms.intensity.noise

"""Noise models: additive Gaussian and MRI-style Rician."""

from __future__ import annotations

from typing import Any, Union

import numpy as np

from medaugmentx.core.base import Transform
from medaugmentx.core.parameters import validate_parameters
from medaugmentx.core.utils import SeedLike, as_float32
from medaugmentx.core.volume import MedVolume

Range = Union[float, tuple[float, float]]


def _as_std_range(x: Range) -> tuple[float, float]:
    if isinstance(x, (int, float, np.integer, np.floating)):
        v = float(x)
        if v < 0:
            raise ValueError(f"std must be >= 0, got {v}")
        return (v, v)
    lo, hi = float(x[0]), float(x[1])
    if lo < 0 or hi < lo:
        raise ValueError(f"std range invalid: {x}")
    return lo, hi


[docs] class GaussianNoise(Transform): """Additive zero-mean Gaussian noise. The standard deviation is interpreted in the **intensity units of the image**. For images normalised to ``[0, 1]`` typical values are ``0.005–0.05``. For raw HU CT images you'd pass tens to hundreds. Args: std: Either a fixed value or a ``(low, high)`` range to sample from. relative: If True, ``std`` is interpreted as a fraction of the current image standard deviation (per-call). clip: Optional ``(min, max)`` to clip the output. ``None`` skips clipping. p: Probability of applying. seed: RNG seed. """ def __init__( self, std: Range = 0.01, relative: bool = False, clip: tuple[float, float] | None = None, p: float = 1.0, seed: SeedLike = None, ) -> None: super().__init__(p=p, seed=seed) validate_parameters(std=std, relative=relative, clip=clip) self.std_range = _as_std_range(std) self.relative = bool(relative) self.clip = clip def apply(self, volume: MedVolume) -> MedVolume: image = as_float32(volume.image) std = float(self.rng.uniform(*self.std_range)) if self.relative: std = std * float(image.std() + 1e-8) noise = self.rng.normal(loc=0.0, scale=std, size=image.shape).astype(np.float32) out = image + noise if self.clip is not None: out = np.clip(out, self.clip[0], self.clip[1]) return volume.replace(image=out) def to_dict(self) -> dict[str, Any]: sr = self.std_range std: Any = sr[0] if sr[0] == sr[1] else list(sr) return { "name": self.__class__.__name__, "params": { "std": std, "relative": self.relative, "clip": list(self.clip) if self.clip is not None else None, "p": self.p, "seed": self._seed, }, }
[docs] class RicianNoise(Transform): """Rician magnitude noise under a single-complex-signal model. Rician noise arises naturally because the magnitude of complex Gaussian noise (which corrupts both real and imaginary k-space channels) is no longer Gaussian: ``|N(s, σ) + j·N(0, σ)|`` follows a Rice distribution. For high SNR it approaches Gaussian behaviour; for low-signal regions (e.g. CSF or air outside the head) it produces the characteristic elevated noise floor seen on real MRI. Treats the input as a non-negative signal amplitude. Applying this to an already noisy reconstruction adds another perturbation; it does not infer or replace its existing noise. Multi-coil combination, parallel imaging, and reconstruction processing can require different noise models. Args: std: Per-channel sigma — the standard deviation of the underlying real/imaginary Gaussians. Either a scalar or ``(low, high)``. clip: Optional ``(min, max)`` to clip the result. p: Probability of applying. seed: RNG seed. """ def __init__( self, std: Range = 0.01, clip: tuple[float, float] | None = None, p: float = 1.0, seed: SeedLike = None, ) -> None: super().__init__(p=p, seed=seed) validate_parameters(std=std, clip=clip) self.std_range = _as_std_range(std) self.clip = clip def apply(self, volume: MedVolume) -> MedVolume: image = as_float32(volume.image) std = float(self.rng.uniform(*self.std_range)) real = image + self.rng.normal(0.0, std, size=image.shape).astype(np.float32) imag = self.rng.normal(0.0, std, size=image.shape).astype(np.float32) out = np.hypot(real, imag).astype(np.float32) if self.clip is not None: out = np.clip(out, self.clip[0], self.clip[1]) return volume.replace(image=out) def to_dict(self) -> dict[str, Any]: sr = self.std_range std: Any = sr[0] if sr[0] == sr[1] else list(sr) return { "name": self.__class__.__name__, "params": { "std": std, "clip": list(self.clip) if self.clip is not None else None, "p": self.p, "seed": self._seed, }, }