
    iv                         d dl mZ d dlmZmZmZ d dlZd dlmZ d dlm	Z	 d dl
mZ d dlmZmZ d dlmZ esd	gZ G d
 de      Zy)    )Sequence)AnyOptionalUnionN)Tensor)Metric)_MATPLOTLIB_AVAILABLE)_AX_TYPE_PLOT_OUT_TYPE)WrapperMetriczMinMaxMetric.plotc                        e Zd ZU dZdZee   ed<   eed<   eed<   de	de
dd	f fd
Zde
de
dd	fdZdeeef   fdZde
de
de
f fdZd fdZedeeef   defd       Z	 ddeeeee   f      dee   defdZ xZS )MinMaxMetricak  Wrapper metric that tracks both the minimum and maximum of a scalar/tensor across an experiment.

    The min/max value will be updated each time ``.compute`` is called.

    Args:
        base_metric:
            The metric of which you want to keep track of its maximum and minimum values.
        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Raises:
        ValueError
            If ``base_metric` argument is not a subclasses instance of ``torchmetrics.Metric``

    Example::
        >>> import torch
        >>> from torchmetrics.wrappers import MinMaxMetric
        >>> from torchmetrics.classification import BinaryAccuracy
        >>> from pprint import pprint
        >>> base_metric = BinaryAccuracy()
        >>> minmax_metric = MinMaxMetric(base_metric)
        >>> preds_1 = torch.Tensor([[0.1, 0.9], [0.2, 0.8]])
        >>> preds_2 = torch.Tensor([[0.9, 0.1], [0.2, 0.8]])
        >>> labels = torch.Tensor([[0, 1], [0, 1]]).long()
        >>> pprint(minmax_metric(preds_1, labels))
        {'max': tensor(1.), 'min': tensor(1.), 'raw': tensor(1.)}
        >>> pprint(minmax_metric.compute())
        {'max': tensor(1.), 'min': tensor(1.), 'raw': tensor(1.)}
        >>> minmax_metric.update(preds_2, labels)
        >>> pprint(minmax_metric.compute())
        {'max': tensor(1.), 'min': tensor(0.7500), 'raw': tensor(0.7500)}

    Tfull_state_updatemin_valmax_valbase_metrickwargsreturnNc                     t        |   di | t        |t              st	        d|       || _        t        j                  t        d            | _	        t        j                  t        d            | _
        y )NzMExpected base metric to be an instance of `torchmetrics.Metric` but received infz-inf )super__init__
isinstancer   
ValueError_base_metrictorchtensorfloatr   r   )selfr   r   	__class__s      q/Volumes/fast/ai/experiments/voice-extract-mac/.venv/lib/python3.12/site-packages/torchmetrics/wrappers/minmax.pyr   zMinMaxMetric.__init__D   sj    
 	"6"+v._`k_lm  (||E%L1||E&M2    argsc                 <     | j                   j                  |i | y)zUpdate the underlying metric.N)r   update)r    r$   r   s      r"   r&   zMinMaxMetric.updateR   s       $1&1r#   c                    | j                   j                         }| j                  |      st        d| d      | j                  j                  |j                        |k  r|n$| j                  j                  |j                        | _        | j                  j                  |j                        |kD  r|n$| j                  j                  |j                        | _        || j                  | j                  dS )zCompute the underlying metric as well as max and min values for this metric.

        Returns a dictionary that consists of the computed value (``raw``), as well as the minimum (``min``) and maximum
        (``max``) values.

        zLReturned value from base metric should be a float or scalar tensor, but got .)rawmaxmin)r   compute_is_suitable_valRuntimeErrorr   todevicer   )r    vals     r"   r,   zMinMaxMetric.computeV   s     '')$$S)!mnqmrrstuu"lloocjj9C?sT\\__UXU_U_E`"lloocjj9C?sT\\__UXU_U_E`4<<EEr#   c                 *    t        t        | 
  |i |S )z9Use the original forward method of the base metric class.)r   r   forward)r    r$   r   r!   s      r"   r3   zMinMaxMetric.forwardd   s    ]D14B6BBr#   c                 V    t         |           | j                  j                          y)zXSet ``max_val`` and ``min_val`` to the initialization bounds and resets the base metric.N)r   resetr   )r    r!   s    r"   r5   zMinMaxMetric.reseth   s    !r#   r1   c                 x    t        | t        t        f      ryt        | t              r| j	                         dk(  S y)z(Check whether min/max is a scalar value.T   F)r   intr   r   numel)r1   s    r"   r-   zMinMaxMetric._is_suitable_valm   s3     cC<(c6"99;!##r#   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
            >>> import torch
            >>> from torchmetrics.wrappers import MinMaxMetric
            >>> from torchmetrics.classification import BinaryAccuracy
            >>> metric = MinMaxMetric(BinaryAccuracy())
            >>> metric.update(torch.randint(2, (20,)), torch.randint(2, (20,)))
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

            >>> # Example plotting multiple values
            >>> import torch
            >>> from torchmetrics.wrappers import MinMaxMetric
            >>> from torchmetrics.classification import BinaryAccuracy
            >>> metric = MinMaxMetric(BinaryAccuracy())
            >>> values = [ ]
            >>> for _ in range(3):
            ...     values.append(metric(torch.randint(2, (20,)), torch.randint(2, (20,))))
            >>> fig_, ax_ = metric.plot(values)

        )_plot)r    r1   r:   s      r"   plotzMinMaxMetric.plotv   s    T zz#r""r#   )r   N)NN)__name__
__module____qualname____doc__r   r   bool__annotations__r   r   r   r   r&   dictstrr,   r3   r5   staticmethodr   r   r-   r   r
   r   r=   __classcell__)r!   s   @r"   r   r      s   B )-x~,OO33 3 
	32C 23 24 2Fc6k* FCS CC CC C"
 eE6M2 t   _c*#E&(6*:":;<*#IQRZI[*#	*#r#   r   )collections.abcr   typingr   r   r   r   r   torchmetrics.metricr   torchmetrics.utilities.importsr	   torchmetrics.utilities.plotr
   r   torchmetrics.wrappers.abstractr   __doctest_skip__r   r   r#   r"   <module>rO      s<    % ' '   & @ @ 8+,B#= B#r#   