o
    Òôjs#  ã                   @   sÊ   d dl mZ d dlmZ d dl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 d d
lmZmZ d dlmZ esMdgZ	ddedede	jfdd„ZG dd„ deƒZdS )é    )ÚSequence©Údeepcopy)ÚAnyÚOptionalÚUnionÚcastN)Úapply_to_collection)ÚTensor)Ú
ModuleList)ÚMetric)Ú_MATPLOTLIB_AVAILABLE)Ú_AX_TYPEÚ_PLOT_OUT_TYPE)ÚWrapperMetricúBootStrapper.plotÚpoissonÚsizeÚsampling_strategyÚreturnc                 C   s^   |dkrt j d¡}| | f¡}t  | ¡j| ¡ dd�S |dkr+t jt  | ¡| dd�S t	dƒ‚)	züResample a tensor along its first dimension with replacement.

    Args:
        size: number of samples
        sampling_strategy: the strategy to use for sampling, either ``'poisson'`` or ``'multinomial'``

    Returns:
        resampled tensor

    r   é   r   ©ÚdimÚmultinomialT)Únum_samplesÚreplacementzUnknown sampling strategy)
ÚtorchÚdistributionsÚPoissonÚsampleÚarangeÚrepeat_interleaveÚlongr   ÚonesÚ
ValueError)r   r   ÚpÚn© r'   úv/var/www/html/academy/tools/voices/clone/cosy-venv/lib/python3.10/site-packages/torchmetrics/wrappers/bootstrapping.pyÚ_bootstrap_sampler    s   r)   c                       sô   e Zd ZU dZdZee ed< 						d ded	e	d
ededee
eef  de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	d"dee
eee f  dee defdd„Z‡  ZS )#ÚBootStrapperaÑ  Using `Turn a Metric into a Bootstrapped`_.

    That can automate the process of getting confidence intervals for metric values. This wrapper
    class basically keeps multiple copies of the same base metric in memory and whenever ``update`` or
    ``forward`` is called, all input tensors are resampled (with replacement) along the first dimension.

    Args:
        base_metric: base metric class to wrap
        num_bootstraps: number of copies to make of the base metric for bootstrapping
        mean: if ``True`` return the mean of the bootstraps
        std: if ``True`` return the standard deviation of the bootstraps
        quantile: if given, returns the quantile of the bootstraps. Can only be used with pytorch version 1.6 or higher
        raw: if ``True``, return all bootstrapped values
        sampling_strategy:
            Determines how to produce bootstrapped samplings. Either ``'poisson'`` or ``multinomial``.
            If ``'possion'`` is chosen, the number of times each sample will be included in the bootstrap
            will be given by :math:`n\sim Poisson(\lambda=1)`, which approximates the true bootstrap distribution
            when the number of samples is large. If ``'multinomial'`` is chosen, we will apply true bootstrapping
            at the batch level to approximate bootstrapping over the hole dataset.
        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Example::
        >>> from pprint import pprint
        >>> from torch import randint
        >>> from torchmetrics.wrappers import BootStrapper
        >>> from torchmetrics.classification import MulticlassAccuracy
        >>> base_metric = MulticlassAccuracy(num_classes=5, average='micro')
        >>> bootstrap = BootStrapper(base_metric, num_bootstraps=20)
        >>> bootstrap.update(randint(5, (20,)), randint(5, (20,)))
        >>> output = bootstrap.compute()
        >>> pprint(output)
        {'mean': tensor(0.2089), 'std': tensor(0.0772)}

    TÚfull_state_updateé
   NFr   Úbase_metricÚnum_bootstrapsÚmeanÚstdÚquantileÚrawr   Úkwargsr   c           
         sŽ   t ƒ jdi |¤Ž tˆ tƒstdˆ › �ƒ‚t‡ fdd„t|ƒD ƒƒ| _|| _|| _	|| _
|| _|| _d}	||	vrBtd|	› d|› �ƒ‚|| _d S )NzKExpected base metric to be an instance of torchmetrics.Metric but received c                    s   g | ]}t ˆ ƒ‘qS r'   r   )Ú.0Ú_©r-   r'   r(   Ú
<listcomp>n   s    z)BootStrapper.__init__.<locals>.<listcomp>)r   r   z5Expected argument ``sampling_strategy`` to be one of z but received r'   )ÚsuperÚ__init__Ú
isinstancer   r$   r   ÚrangeÚmetricsr.   r/   r0   r1   r2   r   )
Úselfr-   r.   r/   r0   r1   r2   r   r3   Zallowed_sampling©Ú	__class__r6   r(   r9   ]   s&   
ÿÿÿ
zBootStrapper.__init__Úargsc           
      O   sÒ   t |tjtƒ}t |tjtƒ}t|ƒdkr|d }nt|ƒdkr(tt| ¡ ƒƒ}ntdƒ‚t| j	ƒD ]5}t
|| jd� | j¡}| ¡ dkrEq1t |tjtjd|d�}t |tjtjd|d�}	| j| j|i |	¤Ž q1dS )ztUpdate the state of the base metric.

        Any tensor passed in will be bootstrapped along dimension 0.

        r   zMNone of the input contained tensors, so could not determine the sampling size)r   )r   ÚindexN)r	   r   r
   ÚlenÚnextÚiterÚvaluesr$   r;   r.   r)   r   ÚtoÚdeviceÚnumelÚindex_selectr<   Úupdate)
r=   r@   r3   Z
args_sizesZkwargs_sizesr   ÚidxÚ
sample_idxÚnew_argsÚ
new_kwargsr'   r'   r(   rJ   ~   s   
úzBootStrapper.updatec                 C   sx   t jdd„ | jD ƒdd�}i }| jr|jdd�|d< | jr%|jdd�|d< | jdur3t  || j¡|d< | jr:||d	< |S )
zâCompute the bootstrapped metric values.

        Always returns a dict of tensors, which can contain the following keys: ``mean``, ``std``, ``quantile`` and
        ``raw`` depending on how the class was initialized.

        c                 S   s   g | ]	}t t|ƒ ¡ ‘qS r'   )r   r   Úcompute)r4   Úmr'   r'   r(   r7   œ   s    z(BootStrapper.compute.<locals>.<listcomp>r   r   r/   r0   Nr1   r2   )r   Ústackr<   r/   r0   r1   r2   )r=   Zcomputed_valsÚoutput_dictr'   r'   r(   rO   •   s   
zBootStrapper.computec                    s   t t| ƒj|i |¤ŽS )z9Use the original forward method of the base metric class.)r8   r   Úforward)r=   r@   r3   r>   r'   r(   rS   ¨   s   zBootStrapper.forwardc                    s,   | j D ]}tt|ƒ}| ¡  qtƒ  ¡  dS )z#Reset the state of the base metric.N)r<   r   r   Úresetr8   )r=   rP   r>   r'   r(   rT   ¬   s   


zBootStrapper.resetÚ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 BootStrapper
            >>> from torchmetrics.regression import MeanSquaredError
            >>> metric = BootStrapper(MeanSquaredError(), num_bootstraps=20)
            >>> metric.update(torch.randn(100,), torch.randn(100,))
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

            >>> # Example plotting multiple values
            >>> import torch
            >>> from torchmetrics.wrappers import BootStrapper
            >>> from torchmetrics.regression import MeanSquaredError
            >>> metric = BootStrapper(MeanSquaredError(), num_bootstraps=20)
            >>> values = [ ]
            >>> for _ in range(3):
            ...     values.append(metric(torch.randn(100,), torch.randn(100,)))
            >>> fig_, ax_ = metric.plot(values)

        )Ú_plot)r=   rU   rV   r'   r'   r(   Úplot³   s   *r   )r,   TTNFr   )r   N)NN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r+   r   ÚboolÚ__annotations__r   Úintr   Úfloatr
   Ústrr   r9   rJ   ÚdictrO   rS   rT   r   r   r   rX   Ú__classcell__r'   r'   r>   r(   r*   7   sP   
 #øþýüûúùø	÷
ö!ÿÿÿþr*   )r   )Úcollections.abcr   Úcopyr   Útypingr   r   r   r   r   Úlightning_utilitiesr	   r
   Útorch.nnr   Útorchmetrics.metricr   Útorchmetrics.utilities.importsr   Útorchmetrics.utilities.plotr   r   Ztorchmetrics.wrappers.abstractr   Ú__doctest_skip__r_   ra   r)   r*   r'   r'   r'   r(   Ú<module>   s,   þÿþ
ý