
    i`                         d dl mZ d dlmZmZmZmZ d dlmZ d dl	m
Z
 d dlmZmZ d dlmZ d dlmZ d dlmZ d d	lmZ d d
lmZmZ esdgZ G d de      Zy)    )Sequence)AnyListOptionalUnion)Tensor)Literal)_ergas_compute_ergas_update)Metric)rank_zero_warn)dim_zero_cat)_MATPLOTLIB_AVAILABLE)_AX_TYPE_PLOT_OUT_TYPEz.ErrorRelativeGlobalDimensionlessSynthesis.plotc            	            e Zd ZU dZdZeed<   dZeed<   dZeed<   dZ	e
ed<   ee   ed	<   ee   ed
<   	 	 dde
ded   deddf fdZd	ed
eddfdZdefdZ	 ddeeeee   f      dee   defdZ xZS ))ErrorRelativeGlobalDimensionlessSynthesisa  Calculate the `Error relative global dimensionless synthesis`_  (ERGAS) metric.

    This metric is used to calculate the accuracy of Pan sharpened image considering normalized average error of each
    band of the result image. It is defined as:

    .. math::
        ERGAS = \frac{100}{r} \cdot \sqrt{\frac{1}{N} \sum_{k=1}^{N} \frac{RMSE(B_k)^2}{\mu_k^2}}

    where :math:`r=h/l` denote the ratio in spatial resolution (pixel size) between the high and low resolution images.
    :math:`N` is the number of spectral bands, :math:`RMSE(B_k)` is the root mean square error of the k-th band between
    low and high resolution images, and :math:`\\mu_k` is the mean value of the k-th band of the reference image.

    As input to ``forward`` and ``update`` the metric accepts the following input

    - ``preds`` (:class:`~torch.Tensor`): Predictions from model
    - ``target`` (:class:`~torch.Tensor`): Ground truth values

    As output of `forward` and `compute` the metric returns the following output

    - ``ergas`` (:class:`~torch.Tensor`): if ``reduction!='none'`` returns float scalar tensor with average ERGAS
      value over sample else returns tensor of shape ``(N,)`` with ERGAS values per sample

    Args:
        ratio: ratio of high resolution to low resolution.
        reduction: a method to reduce metric score over labels.

            - ``'elementwise_mean'``: takes the mean (default)
            - ``'sum'``: takes the sum
            - ``'none'`` or ``None``: no reduction will be applied

        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Example:
        >>> from torch import rand
        >>> from torchmetrics.image import ErrorRelativeGlobalDimensionlessSynthesis
        >>> preds = rand([16, 1, 16, 16])
        >>> target = preds * 0.75
        >>> ergas = ErrorRelativeGlobalDimensionlessSynthesis()
        >>> ergas(preds, target).round()
        tensor(10.)

    Fhigher_is_betterTis_differentiablefull_state_updateg        plot_lower_boundpredstargetratio	reduction)elementwise_meansumnoneNkwargsreturnNc                     t        |   di | t        d       | j                  dg d       | j                  dg d       || _        || _        y )NzMetric `UniversalImageQualityIndex` will save all targets and predictions in buffer. For large datasets this may lead to large memory footprint.r   cat)defaultdist_reduce_fxr    )super__init__r   	add_stater   r   )selfr   r   r   	__class__s       m/Volumes/fast/ai/experiments/voice-extract-mac/.venv/lib/python3.12/site-packages/torchmetrics/image/ergas.pyr'   z2ErrorRelativeGlobalDimensionlessSynthesis.__init__T   sV     	"6"*	
 	w5AxEB
"    c                     t        ||      \  }}| j                  j                  |       | j                  j                  |       y)z*Update state with predictions and targets.N)r   r   appendr   r)   r   r   s      r+   updatez0ErrorRelativeGlobalDimensionlessSynthesis.updatef   s6    %eV4v

% 6"r,   c                     t        | j                        }t        | j                        }t        ||| j                  | j
                        S )z&Compute explained variance over state.)r   r   r   r
   r   r   r/   s      r+   computez1ErrorRelativeGlobalDimensionlessSynthesis.computel   s7    TZZ(dkk*eVTZZHHr,   valaxc                 &    | j                  ||      S )a   Plot a single or multiple values from the metric.

        Args:
            val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
                If no value is provided, will automatically call `metric.compute` and plot that result.
            ax: An matplotlib axis object. If provided will add plot to that axis

        Returns:
            Figure and Axes object

        Raises:
            ModuleNotFoundError:
                If `matplotlib` is not installed

        .. plot::
            :scale: 75

            >>> # Example plotting a single value
            >>> from torch import rand
            >>> from torchmetrics.image import ErrorRelativeGlobalDimensionlessSynthesis
            >>> preds = rand([16, 1, 16, 16])
            >>> target = preds * 0.75
            >>> metric = ErrorRelativeGlobalDimensionlessSynthesis()
            >>> metric.update(preds, target)
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

            >>> # Example plotting multiple values
            >>> from torch import rand
            >>> from torchmetrics.image import ErrorRelativeGlobalDimensionlessSynthesis
            >>> preds = rand([16, 1, 16, 16])
            >>> target = preds * 0.75
            >>> metric = ErrorRelativeGlobalDimensionlessSynthesis()
            >>> values = [ ]
            >>> for _ in range(10):
            ...     values.append(metric(preds, target))
            >>> fig_, ax_ = metric.plot(values)

        )_plot)r)   r3   r4   s      r+   plotz.ErrorRelativeGlobalDimensionlessSynthesis.plotr   s    X zz#r""r,   )   r   )NN)__name__
__module____qualname____doc__r   bool__annotations__r   r   r   floatr   r   r	   r   r'   r0   r2   r   r   r   r   r   r7   __classcell__)r*   s   @r+   r   r       s    )V #d""t"#t#!e!<L FX## BC# 	#
 
#$#F #F #t #I I _c,#E&(6*:":;<,#IQRZI[,#	,#r,   r   N)collections.abcr   typingr   r   r   r   torchr   typing_extensionsr	   #torchmetrics.functional.image.ergasr
   r   torchmetrics.metricr   torchmetrics.utilitiesr   torchmetrics.utilities.datar   torchmetrics.utilities.importsr   torchmetrics.utilities.plotr   r   __doctest_skip__r   r%   r,   r+   <module>rL      sB    % - -  % M & 1 4 @ @HI~# ~#r,   