a
    d                     @   s   d dl mZmZ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sndgZG d	d
 d
eZdS )    )AnyDictOptionalSequenceUnionN)Tensor)Metric)_MATPLOTLIB_AVAILABLE)_AX_TYPE_PLOT_OUT_TYPE)WrapperMetricMinMaxMetric.plotc                       s   e Zd ZU dZdZee ed< eed< eed< e	e
dd fdd	Ze
e
dd
ddZeeef dddZe
e
e
d
 fddZdd fddZeeeeef edddZdeeeee f  ee edddZ  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_valN)base_metrickwargsreturnc                    sT   t  jf i | t|ts*td| || _ttd| _	ttd| _
d S )NzMExpected base metric to be an instance of `torchmetrics.Metric` but received infz-inf)super__init__
isinstancer   
ValueError_base_metrictorchZtensorfloatr   r   )selfr   r   	__class__ e/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/torchmetrics/wrappers/minmax.pyr   C   s    
zMinMaxMetric.__init__)argsr   r   c                 O   s   | j j|i | dS )zUpdate the underlying metric.N)r   updater   r"   r   r    r    r!   r#   Q   s    zMinMaxMetric.update)r   c                 C   s~   | j  }| |s"td| | j|j|k r8|n| j|j| _| j|j|kr^|n| 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.

        z\Returned value from base metric should be a scalar (int, float or tensor of size 1, but got )rawmaxmin)r   compute_is_suitable_valRuntimeErrorr   toZdevicer   )r   valr    r    r!   r(   U   s    

&&zMinMaxMetric.computec                    s   t t| j|i |S )z9Use the original forward method of the base metric class.)r   r   forwardr$   r   r    r!   r-   e   s    zMinMaxMetric.forwardc                    s   t    | j  dS )zXSet ``max_val`` and ``min_val`` to the initialization bounds and resets the base metric.N)r   resetr   )r   r   r    r!   r.   i   s    
zMinMaxMetric.reset)r,   r   c                 C   s,   t | ttfrdS t | tr(|  dkS dS )z(Check whether min/max is a scalar value.T   F)r   intr   r   Znumel)r,   r    r    r!   r)   n   s
    
zMinMaxMetric._is_suitable_val)r,   axr   c                 C   s   |  ||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)

        )Z_plot)r   r,   r1   r    r    r!   plotw   s    *r   )NN)__name__
__module____qualname____doc__r   r   bool__annotations__r   r   r   r   r#   r   strr(   r-   r.   staticmethodr   r0   r   r)   r   r
   r   r2   __classcell__r    r    r   r!   r      s&   
!	 r   )typingr   r   r   r   r   r   r   Ztorchmetrics.metricr   Ztorchmetrics.utilities.importsr	   Ztorchmetrics.utilities.plotr
   r   Ztorchmetrics.wrappers.abstractr   Z__doctest_skip__r   r    r    r    r!   <module>   s   