o
    yiV                     @   s   d dl mZ d dlmZ d dlmZmZmZmZm	Z	m
Z
mZmZmZ d dlZd dlmZ d dlmZmZ d dlmZ d dlmZ d d	lmZmZ G d
d deZdS )    )OrderedDict)deepcopy)	AnyDictHashableIterableListOptionalSequenceTupleUnionN)Tensor)Module
ModuleDict)Metric)rank_zero_warn)_flatten_dictallclosec                       s  e Zd ZU dZeeee f ed< ddddde	e
ee
 eee
f f de
dee d	ee d
e	eeee  f ddf fddZejjdededeeef fddZdededdfddZdFddZede
de
defddZdGdeddfddZdeeef fddZdFd d!ZdHdee d	ee dd fd"d#ZdId$eddfd%d&Zde	e
ee
 eee
f f de
ddfd'd(ZdFd)d*Zedeeee f fd+d,Z d-edefd.d/Z!de"fd0d1Z#dGd2ede$e% fd3d4Z&dJd2ed5ede$e'ee(f  fd6d7Z)dId5ede$e( fd8d9Z*dId:ed5ede(fd;d<Z+ed=ee d>edee fd?d@Z,def fdAdBZ-dCe	eej.f dd fdDdEZ/  Z0S )KMetricCollectiona  MetricCollection class can be used to chain metrics that have the same call pattern into one single class.

    Args:
        metrics: One of the following

            * list or tuple (sequence): if metrics are passed in as a list or tuple, will use the metrics class name
              as key for output dict. Therefore, two metrics of the same class cannot be chained this way.

            * arguments: similar to passing in as a list, metrics passed in as arguments will use their metric
              class name as key for the output dict.

            * dict: if metrics are passed in as a dict, will use each key in the dict as key for output dict.
              Use this format if you want to chain together multiple of the same metric with different parameters.
              Note that the keys in the output dict will be sorted alphabetically.

        prefix: a string to append in front of the keys of the output dict

        postfix: a string to append after the keys of the output dict

        compute_groups:
            By default the MetricCollection will try to reduce the computations needed for the metrics in the collection
            by checking if they belong to the same **compute group**. All metrics in a compute group share the same
            metric state and are therefore only different in their compute step e.g. accuracy, precision and recall
            can all be computed from the true positives/negatives and false positives/negatives. By default,
            this argument is ``True`` which enables this feature. Set this argument to `False` for disabling
            this behaviour. Can also be set to a list of lists of metrics for setting the compute groups yourself.

    .. note::
        The compute groups feature can significatly speedup the calculation of metrics under the right conditions.
        First, the feature is only available when calling the ``update`` method and not when calling ``forward`` method
        due to the internal logic of ``forward`` preventing this. Secondly, since we compute groups share metric
        states by reference, calling ``.items()``, ``.values()`` etc. on the metric collection will break this
        reference and a copy of states are instead returned in this case (reference will be reestablished on the next
        call to ``update``).

    .. note::
        Metric collections can be nested at initilization (see last example) but the output of the collection will
        still be a single flatten dictionary combining the prefix and postfix arguments from the nested collection.

    Raises:
        ValueError:
            If one of the elements of ``metrics`` is not an instance of ``pl.metrics.Metric``.
        ValueError:
            If two elements in ``metrics`` have the same ``name``.
        ValueError:
            If ``metrics`` is not a ``list``, ``tuple`` or a ``dict``.
        ValueError:
            If ``metrics`` is ``dict`` and additional_metrics are passed in.
        ValueError:
            If ``prefix`` is set and it is not a string.
        ValueError:
            If ``postfix`` is set and it is not a string.

    Example (input as list):
        >>> import torch
        >>> from pprint import pprint
        >>> from torchmetrics import MetricCollection, MeanSquaredError
        >>> from torchmetrics.classification import MulticlassAccuracy, MulticlassPrecision, MulticlassRecall
        >>> target = torch.tensor([0, 2, 0, 2, 0, 1, 0, 2])
        >>> preds = torch.tensor([2, 1, 2, 0, 1, 2, 2, 2])
        >>> metrics = MetricCollection([MulticlassAccuracy(num_classes=3, average='micro'),
        ...                             MulticlassPrecision(num_classes=3, average='macro'),
        ...                             MulticlassRecall(num_classes=3, average='macro')])
        >>> metrics(preds, target)  # doctest: +NORMALIZE_WHITESPACE
        {'MulticlassAccuracy': tensor(0.1250),
         'MulticlassPrecision': tensor(0.0667),
         'MulticlassRecall': tensor(0.1111)}

    Example (input as arguments):
        >>> metrics = MetricCollection(MulticlassAccuracy(num_classes=3, average='micro'),
        ...                            MulticlassPrecision(num_classes=3, average='macro'),
        ...                            MulticlassRecall(num_classes=3, average='macro'))
        >>> metrics(preds, target)  # doctest: +NORMALIZE_WHITESPACE
        {'MulticlassAccuracy': tensor(0.1250),
         'MulticlassPrecision': tensor(0.0667),
         'MulticlassRecall': tensor(0.1111)}

    Example (input as dict):
        >>> metrics = MetricCollection({'micro_recall': MulticlassRecall(num_classes=3, average='micro'),
        ...                             'macro_recall': MulticlassRecall(num_classes=3, average='macro')})
        >>> same_metric = metrics.clone()
        >>> pprint(metrics(preds, target))
        {'macro_recall': tensor(0.1111), 'micro_recall': tensor(0.1250)}
        >>> pprint(same_metric(preds, target))
        {'macro_recall': tensor(0.1111), 'micro_recall': tensor(0.1250)}

    Example (specification of compute groups):
        >>> metrics = MetricCollection(
        ...     MulticlassRecall(num_classes=3, average='macro'),
        ...     MulticlassPrecision(num_classes=3, average='macro'),
        ...     MeanSquaredError(),
        ...     compute_groups=[['MulticlassRecall', 'MulticlassPrecision'], ['MeanSquaredError']]
        ... )
        >>> metrics.update(preds, target)
        >>> pprint(metrics.compute())
        {'MeanSquaredError': tensor(2.3750), 'MulticlassPrecision': tensor(0.0667), 'MulticlassRecall': tensor(0.1111)}
        >>> pprint(metrics.compute_groups)
        {0: ['MulticlassRecall', 'MulticlassPrecision'], 1: ['MeanSquaredError']}

    Example (nested metric collections):
        >>> metrics = MetricCollection([
        ...     MetricCollection([
        ...         MulticlassAccuracy(num_classes=3, average='macro'),
        ...         MulticlassPrecision(num_classes=3, average='macro')
        ...     ], postfix='_macro'),
        ...     MetricCollection([
        ...         MulticlassAccuracy(num_classes=3, average='micro'),
        ...         MulticlassPrecision(num_classes=3, average='micro')
        ...     ], postfix='_micro'),
        ... ], prefix='valmetrics/')
        >>> pprint(metrics(preds, target))  # doctest: +NORMALIZE_WHITESPACE
        {'valmetrics/MulticlassAccuracy_macro': tensor(0.1111),
         'valmetrics/MulticlassAccuracy_micro': tensor(0.1250),
         'valmetrics/MulticlassPrecision_macro': tensor(0.0667),
         'valmetrics/MulticlassPrecision_micro': tensor(0.1250)}
    _groupsNT)prefixpostfixcompute_groupsmetricsadditional_metricsr   r   r   returnc                   sN   t    | |d| _| |d| _|| _d| _d| _| j|g|R   d S )Nr   r   F)	super__init__
_check_argr   r   _enable_compute_groups_groups_checked_state_is_copyadd_metrics)selfr   r   r   r   r   	__class__ L/home/ubuntu/.local/lib/python3.10/site-packages/torchmetrics/collections.pyr      s   
zMetricCollection.__init__argskwargsc                    s<    fddj dddD }t|}fdd|  D S )zIteratively call forward for each metric.

        Positional arguments (args) will be passed to every metric in the collection, while keyword arguments (kwargs)
        will be filtered based on the signature of the individual metric.
        c              
      s,   i | ]\}}|| i |j d i qS )r&   )_filter_kwargs.0km)r(   r)   r&   r'   
<dictcomp>   s   , z,MetricCollection.forward.<locals>.<dictcomp>TF	keep_base
copy_statec                       i | ]
\}}  ||qS r&   	_set_namer,   r-   vr#   r&   r'   r/          itemsr   )r#   r(   r)   resr&   )r(   r)   r#   r'   forward   s   zMetricCollection.forwardc                 O   s   | j r0| j D ]\}}t| |d }|j|i |jdi | q| jr.|   d| _dS dS | jdddD ]\}}|jdi |}|j|i | q7| jr\| 	  |   d| _ dS dS )zIteratively call update for each metric.

        Positional arguments (args) will be passed to every metric in the collection, while keyword arguments (kwargs)
        will be filtered based on the signature of the individual metric.
        r   FTr0   Nr&   )
r    r   r;   getattrupdater*   r!    _compute_groups_create_state_refr   _merge_compute_groups)r#   r(   r)   _cgm0r.   m_kwargsr&   r&   r'   r?      s    

zMetricCollection.updatec                 C   s   t | j}	 t| j D ]@\}}t| j D ]+\}}||kr!qt| |d }t| |d }| ||rC| j| | j|  nqt | j|krM nqt | j|krVnt | j}qt| j}i | _t|	 D ]	\}	}
|
| j|	< qjdS )aA  Iterates over the collection of metrics, checking if the state of each metric matches another.

        If so, their compute groups will be merged into one. The complexity of the method is approximately
        ``O(number_of_metrics_in_collection ** 2)``, as all metrics need to be compared to all other metrics.
        Tr   N)
lenr   r   r;   r>   _equal_metric_statesextendpop	enumeratevalues)r#   n_groupscg_idx1cg_members1cg_idx2cg_members2metric1metric2tempidxrK   r&   r&   r'   rA      s0   


z&MetricCollection._merge_compute_groupsrQ   rR   c                 C   s   t | jdkst |jdkrdS | j |j krdS | j D ]F}t| |}t||}t|t|kr8 dS t|trOt|trO|j|jkoLt||  S t|t	rgt|t	rgt
dd t||D   S q!dS )z6Check if the metric state of two metrics are the same.r   Fc                 s   s*    | ]\}}|j |j kot||V  qd S N)shaper   )r,   s1s2r&   r&   r'   	<genexpr>  s   ( z8MetricCollection._equal_metric_states.<locals>.<genexpr>T)rF   	_defaultskeysr>   type
isinstancer   rV   r   listallzip)rQ   rR   keystate1state2r&   r&   r'   rG      s   

z%MetricCollection._equal_metric_statesFcopyc           	      C   s   | j sJ| j D ]A\}}t| |d }tdt|D ].}t| || }|jD ]}t||}t|||r6t|n| q&t|d|rDt|j	n|j	 qq|| _ dS )zCreate reference between metrics in the same compute group.

        Args:
            copy: If `True` the metric state will between members will be copied instead
                of just passed by reference
        r      _update_countN)
r!   r   r;   r>   rangerF   rZ   setattrr   rf   )	r#   rd   rB   rC   rD   imistatem0_stater&   r&   r'   r@   	  s   


z1MetricCollection._compute_groups_create_state_refc                    s6   dd  j dddD }t|} fdd|  D S )z5Compute the result for each metric in the collection.c                 S   s   i | ]	\}}||  qS r&   )computer+   r&   r&   r'   r/     s    z,MetricCollection.compute.<locals>.<dictcomp>TFr0   c                    r3   r&   r4   r6   r8   r&   r'   r/      r9   r:   )r#   r<   r&   r8   r'   rm     s   zMetricCollection.computec                 C   s@   | j dddD ]\}}|  q| jr| jr|   dS dS dS )z'Iteratively call reset for each metric.TFr0   N)r;   resetr   r    r@   )r#   rB   r.   r&   r&   r'   rn   "  s
   
zMetricCollection.resetc                 C   s0   t | }|r| |d|_|r| |d|_|S )zMake a copy of the metric collection
        Args:
            prefix: a string to append in front of the metric keys
            postfix: a string to append after the keys of the output dict

        r   r   )r   r   r   r   )r#   r   r   mcr&   r&   r'   clone*  s   zMetricCollection.clonemodec                 C   s&   | j dddD ]	\}}|| qdS )zRMethod for post-init to change if metric states should be saved to its state_dict.TFr0   N)r;   
persistent)r#   rq   rB   r.   r&   r&   r'   rr   8  s   zMetricCollection.persistentc           	      G   s  t |tr|g}t |tr/t|}g }|D ]}t |tr|n|| q|r.td| d n|r<td| d| dt |trt|	 D ]6}|| }t |tt
fs_td| d| dt |tri|| |< qG|jdd	D ]\}}|| | d
| < qoqGnFt |tr|D ]9}t |tt
fstd| dt |tr|jj}|| v rtd| || |< q|jdd	D ]\}}|| |< qqntdd| _| jr|   dS i | _dS )z%Add new metrics to Metric Collection.z You have passes extra arguments z0 which are not `Metric` so they will be ignored.z7 which are not compatible with first passed dictionary z so they will be ignored.zValue z belonging to key zO is not an instance of `torchmetrics.Metric` or `torchmetrics.MetricCollection`Fr1   rB   Input zd to `MetricCollection` is not a instance of `torchmetrics.Metric` or `torchmetrics.MetricCollection`z#Encountered two metrics both named z"Unknown input to MetricCollection.N)r]   r   r
   r^   appendr   
ValueErrordictsortedr[   r   r;   r%   __name__r    r   _init_compute_groupsr   )	r#   r   r   remainr.   namemetricr-   r7   r&   r&   r'   r"   =  sf   











zMetricCollection.add_metricsc                 C   s   t | jtr9dd t| jD | _| j D ]}|D ]}|| vr2td| d| j d| jdd qqd| _d	S dd t| jddD | _d	S )
zInitialize compute groups.

        If user provided a list, we check that all metrics in the list are also in the collection. If set to `True` we
        simply initialize each metric in the collection as its own group
        c                 S   s   i | ]\}}||qS r&   r&   r,   ri   r-   r&   r&   r'   r/     s    z9MetricCollection._init_compute_groups.<locals>.<dictcomp>rt   z_ in `compute_groups` argument does not match a metric in the collection. Please make sure that z	 matches Trs   c                 S   s   i | ]
\}}|t |gqS r&   )strr~   r&   r&   r'   r/     r9   N)	r]   r   r^   rJ   r   rK   rv   r[   r    )r#   r7   r}   r&   r&   r'   rz   |  s    

 z%MetricCollection._init_compute_groupsc                 C   s   | j S )z@Return a dict with the current compute groups in the collection.)r   r8   r&   r&   r'   r     s   zMetricCollection.compute_groupsbasec                 C   s8   | j du r|n| j | }| jdu r|}|S || j }|S )z3Adjust name of metric with both prefix and postfix.N)r   r   )r#   r   r|   r&   r&   r'   r5     s
   
zMetricCollection._set_namec                 C   s,   t  }| j D ]\}}||| |< q|S rU   )r   _modulesr;   r5   )r#   odr-   r7   r&   r&   r'   _to_renamed_ordered_dict  s   z)MetricCollection._to_renamed_ordered_dictr1   c                 C   s   |r| j  S |   S )zReturn an iterable of the ModuleDict key.

        Args:
            keep_base: Whether to add prefix/postfix on the items collection.
        )r   r[   r   )r#   r1   r&   r&   r'   r[     s   
zMetricCollection.keysr2   c                 C   s$   |  | |r| j S |   S )a%  Return an iterable of the ModuleDict key/value pairs.

        Args:
            keep_base: Whether to add prefix/postfix on the collection.
            copy_state:
                If metric states should be copied between metrics in the same compute group or just passed by reference
        )r@   r   r;   r   )r#   r1   r2   r&   r&   r'   r;     s   

zMetricCollection.itemsc                 C   s   |  | | j S )zReturn an iterable of the ModuleDict values.

        Args:
            copy_state:
                If metric states should be copied between metrics in the same compute group or just passed by reference
        )r@   r   rK   )r#   r2   r&   r&   r'   rK     s   

zMetricCollection.valuesra   c                 C   s   |  | | j| S )a  Retrieve a single metric from the collection.

        Args:
            key: name of metric to retrieve
            copy_state:
                If metric states should be copied between metrics in the same compute group or just passed by reference
        )r@   r   )r#   ra   r2   r&   r&   r'   __getitem__  s   

zMetricCollection.__getitem__argr|   c                 C   s.   | d u s	t | tr| S td| dt|  )NzExpected input `z` to be a string, but got )r]   r   rv   r\   )r   r|   r&   r&   r'   r     s   zMetricCollection._check_argc                    sb   t   d d }| jr|d| j | jrdnd 7 }| jr-|| js$dnd d| j 7 }|d S )Nz,
  prefix=, z
  postfix=z
))r   __repr__r   r   )r#   repr_strr$   r&   r'   r     s   zMetricCollection.__repr__dst_typec                 C   s&   | j dddD ]	\}}|| q| S )zTransfer all metric state to specific dtype. Special version of standard `type` method.

        Arguments:
            dst_type (type or string): the desired type.
        TFr0   )r;   	set_dtype)r#   r   rB   r.   r&   r&   r'   r     s   zMetricCollection.set_dtype)r   N)F)NN)T)FT)1ry   
__module____qualname____doc__r   intr   r   __annotations__r   r   r
   r	   boolr   torchjitunusedr   r=   r?   rA   staticmethodrG   r@   rm   rn   rp   rr   r"   rz   propertyr   r5   r   r   r   r   r[   r   r   r;   rK   r   r   r   dtyper   __classcell__r&   r&   r$   r'   r      sd   
 u 

$
 

?$

 $r   )collectionsr   rd   r   typingr   r   r   r   r   r	   r
   r   r   r   r   torch.nnr   r   torchmetrics.metricr   torchmetrics.utilitiesr   torchmetrics.utilities.datar   r   r   r&   r&   r&   r'   <module>   s   ,