§
    ’©ºjs#  ã                   óÞ   — 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sdgZ	 ddedede	j        fd„Z G 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)ÚWrapperMetriczBootStrapper.plotÚpoissonÚsizeÚsampling_strategyÚreturnc                 ój  — |dk    rpt           j                             d¦  «        }|                     | f¦  «        }t          j        | ¦  «                             |                     ¦   «         d¬¦  «        S |dk    r)t          j        t          j        | ¦  «        | 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Úns       ús/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/torchmetrics/wrappers/bootstrapping.pyÚ_bootstrap_samplerr)       s    € ð ˜IÒ%Ð%ÝÔ×'Ò'¨Ñ*Ô*ˆØ�HŠH�d�WÑÔˆÝŒ|˜DÑ!Ô!×3Ò3°A·F²F±H´HÀ!Ð3ÑDÔDÐDØ˜MÒ)Ð)ÝÔ ¥¤¨DÑ!1Ô!1¸tÐQUÐVÑVÔVÐVÝ
Ð0Ñ
1Ô
1Ð1ó    c                   ó.  ‡ — 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„Zdededdfd„Zdeeef         fd„Zdededefˆ fd„Zdˆ fd„Z	 ddee
eee         f                  dee         defd„Zˆ x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                 ón  •‡—  t          ¦   «         j        di |¤Ž t          ‰t          ¦  «        st	          d‰› �¦  «        ‚t          ˆfd„t          |¦  «        D ¦   «         ¦  «        | _        || _        || _	        || _
        || _        || _        d}	||	vrt	          d|	› d|› �¦  «        ‚|| _        d S )NzKExpected base metric to be an instance of torchmetrics.Metric but received c                 ó.   •— g | ]}t          ‰¦  «        ‘ŒS © r   )Ú.0Ú_r/   s     €r(   ú
<listcomp>z)BootStrapper.__init__.<locals>.<listcomp>n   s!   ø€ Ð"XÐ"XÐ"X¸Q¥8¨KÑ#8Ô#8Ð"XÐ"XÐ"Xr*   )r   r   z5Expected argument ``sampling_strategy`` to be one of z but received r8   )ÚsuperÚ__init__Ú
isinstancer   r%   r   ÚrangeÚmetricsr0   r1   r2   r3   r4   r   )Úselfr/   r0   r1   r2   r3   r4   r   r5   Úallowed_samplingÚ	__class__s    `        €r(   r=   zBootStrapper.__init__]   sø   øø€ ð 	�‰ŒÔÐ"Ð"˜6Ð"Ð"Ð"Ý˜+¥vÑ.Ô.ð 	ÝØkÐ^iÐkÐkñô ð õ "Ð"XÐ"XÐ"XÐ"XÅ%ÈÑBWÔBWÐ"XÑ"XÔ"XÑYÔYˆŒØ,ˆÔàˆŒ	ØˆŒØ ˆŒØˆŒà5ÐØÐ$4Ð4Ð4Ýð5ÐHXð 5ð 5Ø!2ð5ð 5ñô ð ð "3ˆÔÐÐr*   Úargsc                 óì  — t          |t          j        t          ¦  «        }t          |t          j        t          ¦  «        }t          |¦  «        dk    r	|d         }nQt          |¦  «        dk    r/t	          t          |                     ¦   «         ¦  «        ¦  «        }nt          d¦  «        ‚t          | j	        ¦  «        D ]±}t          || j        ¬¦  «                             | j        ¦  «        }|                     ¦   «         dk    rŒIt          |t          j        t          j        d|¬¦  «        }t          |t          j        t          j        d|¬¦  «        }	 | j        |         j        |i |	¤Ž Œ²d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?   r0   r)   r   ÚtoÚdeviceÚnumelÚindex_selectr@   Úupdate)
rA   rD   r5   Ú
args_sizesÚkwargs_sizesr   ÚidxÚ
sample_idxÚnew_argsÚ
new_kwargss
             r(   rO   zBootStrapper.update~   sP  € õ )¨­u¬|½SÑAÔAˆ
Ý*¨6µ5´<ÅÑEÔEˆÝˆz‰?Œ?˜QÒÐØ˜a”=ˆDˆDÝ�ÑÔ Ò"Ð"Ý�˜\×0Ò0Ñ2Ô2Ñ3Ô3Ñ4Ô4ˆDˆDåÐlÑmÔmÐmå˜Ô,Ñ-Ô-ð 	>ð 	>ˆCÝ+¨DÀDÔDZÐ[Ñ[Ô[×^Ò^Ð_cÔ_jÑkÔkˆJØ×ÒÑ!Ô! QÒ&Ð&ØÝ*¨4µ´½uÔ?QÐWXÐ`jÐkÑkÔkˆHÝ,¨VµU´\Å5ÔCUÐ[\ÐdnÐoÑoÔoˆJØ$ˆDŒL˜ÔÔ$ hÐ=°*Ð=Ð=Ð=Ð=ð	>ð 	>r*   c                 ó4  — t          j        d„ | j        D ¦   «         d¬¦  «        }i }| j        r|                     d¬¦  «        |d<   | j        r|                     d¬¦  «        |d<   | j        �t          j        || 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                 ó\   — g | ])}t          t          |¦  «                             ¦   «         ‘Œ*S r8   )r	   r   Úcompute)r9   Úms     r(   r;   z(BootStrapper.compute.<locals>.<listcomp>œ   s,   € Ð$UÐ$UÐ$UÀ1¥T­&°!¡_¤_×%<Ò%<Ñ%>Ô%>Ð$UÐ$UÐ$Ur*   r   r   r1   r2   Nr3   r4   )r   Ústackr@   r1   r2   r3   r4   )rA   Úcomputed_valsÚoutput_dicts      r(   rX   zBootStrapper.compute•   s³   € õ œÐ$UÐ$UÈÌÐ$UÑ$UÔ$UÐ[\Ð]Ñ]Ô]ˆØˆØŒ9ð 	<Ø"/×"4Ò"4¸Ð"4Ñ";Ô";ˆK˜ÑØŒ8ð 	:Ø!.×!2Ò!2°qÐ!2Ñ!9Ô!9ˆK˜ÑØŒ=Ð$Ý&+¤n°]ÀDÄMÑ&RÔ&RˆK˜
Ñ#ØŒ8ð 	/Ø!.ˆK˜ÑØÐr*   c                 óD   •—  t          t          | ¦  «        j        |i |¤ŽS )z9Use the original forward method of the base metric class.)r<   r   Úforward)rA   rD   r5   rC   s      €r(   r^   zBootStrapper.forward¨   s%   ø€ à1�u•] DÑ)Ô)Ô1°4ÐB¸6ÐBÐBÐBr*   c                 ó®   •— | j         D ]+}t          t          |¦  «        }|                     ¦   «          Œ,t	          ¦   «                              ¦   «          dS )z#Reset the state of the base metric.N)r@   r	   r   Úresetr<   )rA   rY   rC   s     €r(   r`   zBootStrapper.reset¬   sE   ø€ à”ð 	ð 	ˆAÝ•V˜Q‘”ˆAØ�GŠG‰IŒIˆIˆIÝ‰Œ�Š‰Œˆˆˆr*   ÚvalÚaxc                 ó.   — |                       ||¦  «        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)rA   ra   rb   s      r(   ÚplotzBootStrapper.plot³   s   € ðT �zŠz˜#˜rÑ"Ô"Ð"r*   )r.   TTNFr   )r   N)NN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r-   r   ÚboolÚ__annotations__r   Úintr   Úfloatr   Ústrr   r=   rO   ÚdictrX   r^   r`   r   r   r   re   Ú__classcell__)rC   s   @r(   r,   r,   7   sÚ  ø€ € € € € € ð!ð !ðF )-Ð�x ”~Ð,Ð,Ñ,ð
 !ØØØ37ØØ!*ð3ð 3àð3ð ð3ð ð	3ð
 ð3ð ˜5 ¨ Ô/Ô0ð3ð ð3ð ð3ð ð3ð 
ð3ð 3ð 3ð 3ð 3ð 3ðB>˜Cð >¨3ð >°4ð >ð >ð >ð >ð.˜˜c 6˜kÔ*ð ð ð ð ð&C˜Sð C¨Cð C°Cð Cð Cð Cð Cð Cð Cðð ð ð ð ð ð _cð*#ð *#Ø˜E &¨(°6Ô*:Ð":Ô;Ô<ð*#ØIQÐRZÔI[ð*#à	ð*#ð *#ð *#ð *#ð *#ð *#ð *#ð *#r*   r,   )r   )Úcollections.abcr   Úcopyr   Útypingr   r   r   r	   r   Úlightning_utilitiesr
   r   Útorch.nnr   Útorchmetrics.metricr   Útorchmetrics.utilities.importsr   Útorchmetrics.utilities.plotr   r   Útorchmetrics.wrappers.abstractr   Ú__doctest_skip__rl   rn   r)   r,   r8   r*   r(   ú<module>r{      se  ðð %Ð $Ð $Ð $Ð $Ð $Ø Ð Ð Ð Ð Ð Ø -Ð -Ð -Ð -Ð -Ð -Ð -Ð -Ð -Ð -Ð -Ð -à €€€Ø 3Ð 3Ð 3Ð 3Ð 3Ð 3Ø Ð Ð Ð Ð Ð Ø Ð Ð Ð Ð Ð à &Ð &Ð &Ð &Ð &Ð &Ø @Ð @Ð @Ð @Ð @Ð @Ø @Ð @Ð @Ð @Ð @Ð @Ð @Ð @Ø 8Ð 8Ð 8Ð 8Ð 8Ð 8àð -Ø+Ð,Ðð
 'ð2ð 2Ø
ð2àð2ð „\ð2ð 2ð 2ð 2ð.f#ð f#ð f#ð f#ð f#�=ñ f#ô f#ð f#ð f#ð f#r*   