o
    .wi                      @   s~   d dl mZ d dlmZmZm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s5dgZG d	d
 d
eZdS )    )Sequence)AnyOptionalUnion)Tensor)Metric)_MATPLOTLIB_AVAILABLE)_AX_TYPE_PLOT_OUT_TYPE)WrapperMetricRunning.plotc                       s   e Zd ZdZddededdf fddZd	ed
eddfddZd	ed
edefddZ	defddZ
d fddZ	ddeeeee f  dee defddZ  ZS )Runninga  Running wrapper for metrics.

    Using this wrapper allows for calculating metrics over a running window of values, instead of the whole history of
    values. This is beneficial when you want to get a better estimate of the metric during training and don't want to
    wait for the whole training to finish to get epoch level estimates.

    The running window is defined by the `window` argument. The window is a fixed size and this wrapper will store a
    duplicate of the underlying metric state for each value in the window. Thus memory usage will increase linearly
    with window size. Use accordingly. Also note that the running only works with metrics that have the
    `full_state_update` set to `False`.

    Importantly, the wrapper does not alter the value of the `forward` method of the underlying metric. Thus, forward
    will still return the value on the current batch. To get the running value call `compute` instead.

    Args:
        base_metric: The metric to wrap.
        window: The size of the running window.

    Example (single metric):
        >>> from torch import tensor
        >>> from torchmetrics.wrappers import Running
        >>> from torchmetrics.aggregation import SumMetric
        >>> metric = Running(SumMetric(), window=3)
        >>> for i in range(6):
        ...     current_val = metric(tensor([i]))
        ...     running_val = metric.compute()
        ...     total_val = tensor(sum(list(range(i+1))))  # value we would get from `compute` without running
        ...     print(f"{current_val=}, {running_val=}, {total_val=}")
        current_val=tensor(0.), running_val=tensor(0.), total_val=tensor(0)
        current_val=tensor(1.), running_val=tensor(1.), total_val=tensor(1)
        current_val=tensor(2.), running_val=tensor(3.), total_val=tensor(3)
        current_val=tensor(3.), running_val=tensor(6.), total_val=tensor(6)
        current_val=tensor(4.), running_val=tensor(9.), total_val=tensor(10)
        current_val=tensor(5.), running_val=tensor(12.), total_val=tensor(15)

    Example (metric collection):
        >>> from torch import tensor
        >>> from torchmetrics.wrappers import Running
        >>> from torchmetrics import MetricCollection
        >>> from torchmetrics.aggregation import SumMetric, MeanMetric
        >>> # note that running is input to collection, not the other way
        >>> metric = MetricCollection({"sum": Running(SumMetric(), 3), "mean": Running(MeanMetric(), 3)})
        >>> for i in range(6):
        ...     current_val = metric(tensor([i]))
        ...     running_val = metric.compute()
        ...     print(f"{current_val=}, {running_val=}")
        current_val={'mean': tensor(0.), 'sum': tensor(0.)}, running_val={'mean': tensor(0.), 'sum': tensor(0.)}
        current_val={'mean': tensor(1.), 'sum': tensor(1.)}, running_val={'mean': tensor(0.5000), 'sum': tensor(1.)}
        current_val={'mean': tensor(2.), 'sum': tensor(2.)}, running_val={'mean': tensor(1.), 'sum': tensor(3.)}
        current_val={'mean': tensor(3.), 'sum': tensor(3.)}, running_val={'mean': tensor(2.), 'sum': tensor(6.)}
        current_val={'mean': tensor(4.), 'sum': tensor(4.)}, running_val={'mean': tensor(3.), 'sum': tensor(9.)}
        current_val={'mean': tensor(5.), 'sum': tensor(5.)}, running_val={'mean': tensor(4.), 'sum': tensor(12.)}

       base_metricwindowreturnNc                    s   t    t|tstd| t|tr|dks!td| || _|| _|jdur4td|j d| _	|j
D ]}t|D ]}| j|d|  |j
| |j| d q@q:d S )NzNExpected argument `metric` to be an instance of `torchmetrics.Metric` but got r   z<Expected argument `window` to be a positive integer but got Fz>Expected attribute `full_state_update` set to `False` but got _)namedefaultdist_reduce_fx)super__init__
isinstancer   
ValueErrorintr   r   full_state_update_num_vals_seen	_defaultsrange	add_state_reductions)selfr   r   keyi	__class__ Z/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/torchmetrics/wrappers/running.pyr   T   s*   




zRunning.__init__argskwargsc                 O   sf   | j | j }| jj|i | | jjD ]}t| |d|  t| j| q| j  |  j d7  _ dS )z7Update the underlying metric and save state afterwards.r      N)r   r   r   updater   setattrgetattrreset)r!   r(   r)   valr"   r&   r&   r'   r+   k   s    
zRunning.updatec                 O   sl   | j | j }| jj|i |}| jjD ]}t| |d|  t| j| q| j  |  j d7  _ d| _|S )zAForward input to the underlying metric and save state afterwards.r   r*   N)	r   r   r   forwardr   r,   r-   r.   	_computed)r!   r(   r)   r/   resr"   r&   r&   r'   r0   t   s    
zRunning.forwardc                    sR   t jD ] j fddjjD  qjj_j }j  |S )z+Compute the metric over the running window.c                    s"   i | ]}|t |d    qS )r   )r-   ).0r"   r#   r!   r&   r'   
<dictcomp>   s   " z#Running.compute.<locals>.<dictcomp>)	r   r   r   _reduce_statesr   r   _update_countcomputer.   )r!   r/   r&   r4   r'   r8      s   "


zRunning.computec                    s   t    d| _dS )zReset metric.r   N)r   r.   r   )r!   r$   r&   r'   r.      s   

zRunning.resetr/   axc                 C   s   |  ||S )ae  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 Running
            >>> from torchmetrics.aggregation import SumMetric
            >>> metric = Running(SumMetric(), 2)
            >>> metric.update(torch.randn(20, 2))
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

            >>> # Example plotting multiple values
            >>> import torch
            >>> from torchmetrics.wrappers import Running
            >>> from torchmetrics.aggregation import SumMetric
            >>> metric = Running(SumMetric(), 2)
            >>> values = [ ]
            >>> for _ in range(3):
            ...     values.append(metric(torch.randn(20, 2)))
            >>> fig_, ax_ = metric.plot(values)

        )_plot)r!   r/   r9   r&   r&   r'   plot   s   *r   )r   )r   N)NN)__name__
__module____qualname____doc__r   r   r   r   r+   r0   r8   r.   r   r   r   r   r	   r
   r;   __classcell__r&   r&   r$   r'   r      s    7		r   N)collections.abcr   typingr   r   r   torchr   torchmetrics.metricr   torchmetrics.utilities.importsr   torchmetrics.utilities.plotr	   r
   torchmetrics.wrappers.abstractr   __doctest_skip__r   r&   r&   r&   r'   <module>   s   