o
    .wiv                     @   s   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s9d	gZG d
d deZdS )    )Sequence)AnyOptional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< de	de
dd	f fd
dZde
de
dd	fddZdeeef fddZde
de
de
f fddZd fddZedeeef defddZ		ddeeeee f  dee def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_valbase_metrickwargsreturnNc                    sT   t  jd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torchtensorfloatr   r   )selfr   r   	__class__r   Y/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/torchmetrics/wrappers/minmax.pyr   D   s   
zMinMaxMetric.__init__argsc                 O   s   | j j|i | dS )zUpdate the underlying metric.N)r   updater   r"   r   r   r   r!   r#   R      zMinMaxMetric.updatec                 C   s   | j  }| |std| d| j|j|k r|n| j|j| _| j|j|kr0|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.

        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   valr   r   r!   r*   V   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!   r0   d   r%   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!   r1   h   s   
zMinMaxMetric.resetr/   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   numel)r/   r   r   r!   r+   m   s
   
zMinMaxMetric._is_suitable_valaxc                 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)

        )_plot)r   r/   r5   r   r   r!   plotv   s   *r   )r   N)NN)__name__
__module____qualname____doc__r   r   bool__annotations__r   r   r   r   r#   dictstrr*   r0   r1   staticmethodr   r   r+   r   r	   r
   r7   __classcell__r   r   r   r!   r      s4   
 !	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   r!   <module>   s   