o
    yi,                     @   s   d dl mZ 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 d dlmZ G d	d
 d
eZdS )    )deepcopy)AnyDictListTupleUnionN)Tensor)
ModuleList)MetricCollection)Metric)rank_zero_warnc                       s0  e Zd ZdZd!deeef deeee f ddf fddZ	e
defd	d
Zd"ddZd"ddZd"ddZdefddZdeeeeef f fddZd"ddZd"ddZ	d#dededeeeef ed eeeedf f eeeeedf f eeeedf f f f fddZdeddfdd Z  ZS )$MetricTrackeraH  A wrapper class that can help keeping track of a metric or metric collection over time and implement useful
    methods. The wrapper implements the standard ``.update()``, ``.compute()``, ``.reset()`` methods that just
    calls corresponding method of the currently tracked metric. However, the following additional methods are
    provided:

        -``MetricTracker.n_steps``: number of metrics being tracked
        -``MetricTracker.increment()``: initialize a new metric for being tracked
        -``MetricTracker.compute_all()``: get the metric value for all steps
        -``MetricTracker.best_metric()``: returns the best value

    Args:
        metric: instance of a ``torchmetrics.Metric`` or ``torchmetrics.MetricCollection``
            to keep track of at each timestep.
        maximize: either single bool or list of bool indicating if higher metric values are
            better (``True``) or lower is better (``False``).

    Example (single metric):
        >>> from torchmetrics import MetricTracker
        >>> from torchmetrics.classification import MulticlassAccuracy
        >>> _ = torch.manual_seed(42)
        >>> tracker = MetricTracker(MulticlassAccuracy(num_classes=10, average='micro'))
        >>> for epoch in range(5):
        ...     tracker.increment()
        ...     for batch_idx in range(5):
        ...         preds, target = torch.randint(10, (100,)), torch.randint(10, (100,))
        ...         tracker.update(preds, target)
        ...     print(f"current acc={tracker.compute()}")
        current acc=0.1120000034570694
        current acc=0.08799999952316284
        current acc=0.12600000202655792
        current acc=0.07999999821186066
        current acc=0.10199999809265137
        >>> best_acc, which_epoch = tracker.best_metric(return_step=True)
        >>> best_acc  # doctest: +ELLIPSIS
        0.1260...
        >>> which_epoch
        2
        >>> tracker.compute_all()
        tensor([0.1120, 0.0880, 0.1260, 0.0800, 0.1020])

    Example (multiple metrics using MetricCollection):
        >>> from torchmetrics import MetricTracker, MetricCollection, MeanSquaredError, ExplainedVariance
        >>> _ = torch.manual_seed(42)
        >>> tracker = MetricTracker(MetricCollection([MeanSquaredError(), ExplainedVariance()]), maximize=[False, True])
        >>> for epoch in range(5):
        ...     tracker.increment()
        ...     for batch_idx in range(5):
        ...         preds, target = torch.randn(100), torch.randn(100)
        ...         tracker.update(preds, target)
        ...     print(f"current stats={tracker.compute()}")  # doctest: +NORMALIZE_WHITESPACE
        current stats={'MeanSquaredError': tensor(1.8218), 'ExplainedVariance': tensor(-0.8969)}
        current stats={'MeanSquaredError': tensor(2.0268), 'ExplainedVariance': tensor(-1.0206)}
        current stats={'MeanSquaredError': tensor(1.9491), 'ExplainedVariance': tensor(-0.8298)}
        current stats={'MeanSquaredError': tensor(1.9800), 'ExplainedVariance': tensor(-0.9199)}
        current stats={'MeanSquaredError': tensor(2.2481), 'ExplainedVariance': tensor(-1.1622)}
        >>> from pprint import pprint
        >>> best_res, which_epoch = tracker.best_metric(return_step=True)
        >>> pprint(best_res)  # doctest: +ELLIPSIS
        {'ExplainedVariance': -0.829...,
         'MeanSquaredError': 1.821...}
        >>> which_epoch
        {'MeanSquaredError': 0, 'ExplainedVariance': 2}
        >>> pprint(tracker.compute_all())
        {'ExplainedVariance': tensor([-0.8969, -1.0206, -0.8298, -0.9199, -1.1622]),
         'MeanSquaredError': tensor([1.8218, 2.0268, 1.9491, 1.9800, 2.2481])}
    TmetricmaximizereturnNc                    s   t    t|ttfstd| || _t|ttfs!t	dt|tr7t|tr7t
|t
|kr7t	dt|trEt|tsEt	d|| _d| _d S )Nz[Metric arg need to be an instance of a torchmetrics `Metric` or `MetricCollection` but got zBArgument `maximize` should either be a single bool or list of boolzOThe len of argument `maximize` should match the length of the metric collectionzLArgument `maximize` should be a single bool when `metric` is a single MetricF)super__init__
isinstancer   r
   	TypeError_base_metricboollist
ValueErrorlenr   _increment_called)selfr   r   	__class__ Q/home/ubuntu/.local/lib/python3.10/site-packages/torchmetrics/wrappers/tracker.pyr   ^   s    
$
zMetricTracker.__init__c                 C   s   t | d S )z=Returns the number of times the tracker has been incremented.   )r   r   r   r   r   n_stepsp   s   zMetricTracker.n_stepsc                 C   s   d| _ | t| j dS )zECreates a new instance of the input metric that will be updated next.TN)r   appendr   r   r!   r   r   r   	incrementu   s   zMetricTracker.incrementc                 O   s   |  d | d |i |S )z2Calls forward of the current metric being tracked.forward)_check_for_incrementr   argskwargsr   r   r   r%   z   s   
zMetricTracker.forwardc                 O   s"   |  d | d j|i | dS )z)Updates the current metric being tracked.updater&   N)r'   r+   r(   r   r   r   r+      s   
zMetricTracker.updatec                 C   s   |  d | d  S )z1Call compute of the current metric being tracked.computer&   )r'   r,   r!   r   r   r   r,      s   
zMetricTracker.computec                    sT   |  d dd t| D  t| jtr# d  } fdd|D S tj ddS )as  Compute the metric value for all tracked metrics.

        Return:
            Either a single tensor if the tracked base object is a single metric, else if a metric collection is
            provide a dict of tensors will be returned

        Raises:
            ValueError:
                If `self.increment` have not been called before this method is called.
        compute_allc                 S   s    g | ]\}}|d kr|  qS )r   )r,   ).0ir   r   r   r   
<listcomp>   s     z-MetricTracker.compute_all.<locals>.<listcomp>r   c                    s*   i | ]  t j fd dD ddqS )c                    s   g | ]}|  qS r   r   )r.   rkr   r   r0      s    z8MetricTracker.compute_all.<locals>.<dictcomp>.<listcomp>r   dim)torchstack)r.   resr2   r   
<dictcomp>   s   * z-MetricTracker.compute_all.<locals>.<dictcomp>r4   )r'   	enumerater   r   r
   keysr6   r7   )r   r<   r   r8   r   r-      s   
zMetricTracker.compute_allc                 C   s   | d    dS )z(Resets the current metric being tracked.r&   Nresetr!   r   r   r   r>      s   zMetricTracker.resetc                 C   s   | D ]}|   qdS )z!Resets all metrics being tracked.Nr=   )r   r   r   r   r   	reset_all   s   
zMetricTracker.reset_allFreturn_stepNNc                 C   s  t | jtrN| jrtjntj}z||  d\}}|r$| | fW S | W S  t	yM } zt
d| dt |rBW Y d}~dS W Y d}~dS d}~ww |  }t | jtr[| jnt|| jg }i i }}t| D ]N\}\}	}
z"|| r|tjntj}||
d}|d  |d  ||	< ||	< W qn t	y } zt
d|	 d| d	t d\||	< ||	< W Y d}~qnd}~ww |r||fS |S )
ai  Returns the highest metric out of all tracked.

        Args:
            return_step: If ``True`` will also return the step with the highest metric value.

        Returns:
            Either a single value or a tuple, depends on the value of ``return_step`` and the object being tracked.


            - If a single metric is being tracked and ``return_step=False`` then a single tensor will be returned
            - If a single metric is being tracked and ``return_step=True`` then a 2-element tuple will be returned,
              where the first value is optimal value and second value is the corresponding optimal step
            - If a metric collection is being tracked and ``return_step=False`` then a single dict will be returned,
              where keys correspond to the different values of the collection and the values are the optimal metric
              value
            - If a metric collection is being bracked and ``return_step=True`` then a 2-element tuple will be returned
              where each is a dict, with keys corresponding to the different values of th collection and the values
              of the first dict being the optimal values and the values of the second dict being the optimal step

            In addtion the value in all cases may be ``None`` if the underlying metric does have a proper defined way
            of being optimal.
        r   zDEncountered the following error when trying to get the best metric: z^this is probably due to the 'best' not being defined for this metric.Returning `None` instead.NrA   r    zNEncountered the following error when trying to get the best metric for metric :z_ this is probably due to the 'best' not being defined for this metric.Returning `None` instead.)r   r   r   r   r6   maxminr-   itemr   r   UserWarningr   r   r;   items)r   r@   fnvalueidxerrorr9   r   r/   r3   voutr   r   r   best_metric   sL    

"

&	zMetricTracker.best_metricmethodc                 C   s   | j std| ddS )z`Method for checking that a metric that can be updated/used for computations has been intialized.`z8` cannot be called before `.increment()` has been calledN)r   r   )r   rO   r   r   r   r'      s   z"MetricTracker._check_for_increment)T)r   N)F)__name__
__module____qualname____doc__r   r   r
   r   r   r   propertyintr"   r$   r%   r+   r   r,   r   r   strr-   r>   r?   floatr   rN   r'   __classcell__r   r   r   r   r      s6    0C





*
Hr   )copyr   typingr   r   r   r   r   r6   r   torch.nnr	   torchmetrics.collectionsr
   torchmetrics.metricr   torchmetrics.utilities.printsr   r   r   r   r   r   <module>   s   