ultrasound_metrics.metrics.coherence
====================================

.. py:module:: ultrasound_metrics.metrics.coherence

.. autoapi-nested-parse::

   Coherence-based image quality metrics for ultrasound.

   This module implements coherence factor calculations for beamformed ultrasound data.
   The coherence factor quantifies the degree of coherence between signals received
   from different elements.



Functions
---------

.. autoapisummary::

   ultrasound_metrics.metrics.coherence.coherence_factor
   ultrasound_metrics.metrics.coherence.generalized_coherence_factor
   ultrasound_metrics.metrics.coherence.phase_coherence_factor
   ultrasound_metrics.metrics.coherence.sign_coherence_factor


Module Contents
---------------

.. py:function:: coherence_factor(channel_images: jaxtyping.Num[ultrasound_metrics._utils.array_api.ArrayAPIObj, receive_elements *img_dims], power_based: bool = True) -> jaxtyping.Float[ultrasound_metrics._utils.array_api.ArrayAPIObj, *img_dims]

   Compute the coherence factor of beamformed ultrasound data.

   The coherence factor [1]_ [2]_ measures the degree of coherence between signals
   received from different elements. Two formulations are supported:

   **Power-based coherence (power_based=True, default) [1]_ [4]_:**

   .. math::

       C_R(r) = \frac{|\sum_{m} \hat{b}(r,m)|^2}{\sum_{m} |\hat{b}(r,m)|^2 \cdot M}

   **Amplitude-based coherence (power_based=False) [2]_ [3]_:**

   .. math::

       C_R(r) = \frac{|\sum_{m} \hat{b}(r,m)|}{\sum_{m} |\hat{b}(r,m)|}

   where:

   - :math:`\hat{b}(r,m)` is the complex beamsum for pixel r and receive element m
   - :math:`|\cdot|` denotes absolute value (magnitude)
   - :math:`|\cdot|^2` denotes power (magnitude squared)
   - :math:`M` is the number of receive elements
   - :math:`\sum_{m}` denotes summation over all receive elements

   The numerator represents the coherent sum (signals add constructively
   when in phase), while the denominator represents the incoherent sum.

   The coherence factor ranges from 0 to 1:

   - 1.0: Perfect coherence (all signals perfectly in phase)
   - 0.0: Complete incoherence (random phase relationships)

   High coherence typically indicates good focusing and strong scattering,
   while low coherence may indicate aberrations, noise, or weak scattering.

   For applications in aberration correction, see [3]_.

   :param channel_images: Complex-valued beamformed data before summation across receive elements.
                          The first dimension corresponds to individual receive elements (M),
                          and remaining dimensions represent the image coordinates.
                          Can be 2D (receive_elements, pixels) or higher dimensional
                          (receive_elements, height, width, ...).
   :param power_based: If False, uses amplitude-based coherence as in [2].
                       If True, uses power-based coherence with element normalization [5],
                       similar to vbeam implementation [4].

   :returns: Coherence factor values ranging from 0 to 1. Higher values indicate
             better coherence between receive elements. Shape matches the image
             dimensions of the input (all dimensions except the first).
   :rtype: ndarray

   .. rubric:: Notes

   For ultrasound applications, the coherence factor is useful for:

   - Assessing focusing quality and aberration detection
   - Adaptive beamforming weight calculation
   - Sound speed estimation and correction
   - Tissue characterization based on scattering properties

   .. rubric:: References

   .. [1] Hollman, K. W., Rigby, K. W., & O'Donnell, M. (1999). Coherence factor of speckle from a multi-row probe.
          IEEE Ultrasonics Symposium.
   .. [2] Rigby, K. W., et al. (1999). Method and apparatus for coherence filtering of ultrasound images
   .. [3] Vrålstad, A.E. et al. (2024). Coherence Based Sound Speed Aberration
          Correction — with clinical validation in fetal ultrasound. arXiv:2411.16551


.. py:function:: generalized_coherence_factor(channel_images: jaxtyping.Num[ultrasound_metrics._utils.array_api.ArrayAPIObj, receive_elements *img_dims], m0: int = 1) -> jaxtyping.Float[ultrasound_metrics._utils.array_api.ArrayAPIObj, *img_dims]

   Compute the generalized coherence factor (GCF) of beamformed ultrasound data.

   The generalized coherence factor [4]_ is a more robust version of the standard
   coherence factor that uses spatial DFT across steering angles to reduce
   sensitivity to incoherent noise:

   .. math::

       \text{GCF} = \frac{\sum |X[k]|^2}{M \cdot \sum |x_{m}[n]|^2}

   where :math:`X[k] = \sum_{m} x_{m}[n] \cdot e^{-j2\pi km/M}` is the spatial DFT across elements,
   and the sum over k includes only the low-frequency region from -M0 to +M0.
   The low-frequency region can be viewed as the received signal from the angles
   around the transmit beam direction.

   :param channel_images: Complex-valued beamformed data before summation across receive elements.
   :param m0: Cutoff frequency for the low-frequency region. The GCF uses spatial
              frequencies from -m0 to +m0. Must be >= 0 and < num_elements/2.

              Selection guidelines [4]_:

              - m0=0: Point targets only (may introduce beam-splitting artifacts)
              - m0=1: Optimal for most diffuse scatterers and speckle patterns
              - m0=2-3: Alternative for diffuse scatterers, trades effectiveness for stability
              - Larger m0: Less effective but more stable

   :returns: Generalized coherence factor values ranging from 0 to 1.
   :rtype: ndarray

   .. rubric:: References

   .. [4] Li, P. C., & Li, M. L. (2003). Adaptive imaging using the
          generalized coherence factor. IEEE Transactions on Ultrasonics,
          Ferroelectrics, and Frequency Control, 50(2), 128-141.


.. py:function:: phase_coherence_factor(channel_images: jaxtyping.Num[ultrasound_metrics._utils.array_api.ArrayAPIObj, receive_elements *img_dims], power: float = 1.0) -> jaxtyping.Float[ultrasound_metrics._utils.array_api.ArrayAPIObj, *img_dims]

   Compute the phase coherence factor (PCF) of beamformed ultrasound data.

   The phase coherence factor [6]_ measures coherence based on phase alignment
   of aperture data. This implementation uses the magnitude of the mean unit
   phasor, which is equivalent to phase coherence:

   .. math::

       \text{PCF}^p[k] = \left|\text{mean}\left(\frac{x_{i}[k]}{|x_{i}[k]|}\right)\right|^p

   This is a simplified but mathematically equivalent implementation of the
   phase coherence factor that avoids issues with phase wrapping around ±π.
   The PCF is amplitude-independent and focuses purely on phase alignment.

   The PCF provides similar benefits to the standard coherence factor but is
   more robust in the presence of amplitude variations, making it particularly
   useful for suppressing side lobes and improving lateral resolution.

   :param channel_images: Complex-valued beamformed data before summation across receive elements.
   :param power: Exponential parameter p ≥ 0 to adjust sensitivity. Higher values provide
                 more aggressive suppression of phase-incoherent signals.

   :returns: Phase coherence factor values ranging from 0 to 1.
   :rtype: ndarray

   .. rubric:: Notes

   The PCF is maximum (1.0) when all signals have identical phases,
   and approaches 0 when phases are randomly distributed. Unlike amplitude-based
   coherence factors, PCF is insensitive to magnitude variations across elements.

   .. rubric:: References

   .. [6] Camacho, J., Parrilla, M., & Fritsch, C. (2009). Phase coherence
          imaging. IEEE Transactions on Ultrasonics, Ferroelectrics, and
          Frequency Control, 56(5), 958-974.


.. py:function:: sign_coherence_factor(channel_images: jaxtyping.Num[ultrasound_metrics._utils.array_api.ArrayAPIObj, receive_elements *img_dims], power: float = 1.0) -> jaxtyping.Float[ultrasound_metrics._utils.array_api.ArrayAPIObj, *img_dims]

   Compute the sign coherence factor (SCF) of beamformed ultrasound data.

   The sign coherence factor [5]_ uses only the polarity (sign) of signals,
   making it extremely efficient for hardware implementation:

   .. math::

       \text{SCF}^p[k] = |1 - \sigma|^p

   where :math:`\sigma = \sqrt{1 - |\frac{1}{M} \sum b_{i}[k]|^2}` and
   :math:`b_{i}[k] = \text{sign}(\text{real}(x_{i}[k]))`.

   The sign bit :math:`b_{i}[k]` is +1 if :math:`\text{real}(x_{i}[k]) \geq 0`
   and -1 if :math:`\text{real}(x_{i}[k]) < 0`.
   The SCF considers signals fully coherent when all have the same polarity
   (strict coherence criterion) and completely incoherent when half are
   positive and half are negative.

   This can be considered a particular case of the phase coherence factor (PCF)
   where phase is quantized to just 1 bit (sign), making it highly efficient
   for hardware implementation while maintaining good performance.

   :param channel_images: Complex-valued beamformed data before summation across receive elements.
                          Real part is used for sign computation.
   :param power: Exponential parameter p ≥ 0 to adjust sensitivity. Higher values provide
                 more aggressive suppression of incoherent signals.

   :returns: Sign coherence factor values ranging from 0 to 1.
   :rtype: ndarray

   .. rubric:: Notes

   The SCF is maximum (1.0) when all aperture data have the same polarity,
   and minimum (0.0) when half are positive and half are negative.

   .. rubric:: References

   .. [5] Camacho, J., Parrilla, M., & Fritsch, C. (2009). Phase coherence
          imaging. IEEE Transactions on Ultrasonics, Ferroelectrics, and
          Frequency Control, 56(5), 958-974.


