o
    ´ôj)&  ã                   @   sø   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
mZ d dlmZ d dlmZ d dlmZmZ es=d	gZ	
ddejdejdejdejdejdejdejdejdedeejejejejejejejejf fdd„ZG dd„ deƒZdS )é    )ÚSequence)ÚAnyÚListÚOptionalÚUnionN)ÚTensor)Ú_pearson_corrcoef_computeÚ_pearson_corrcoef_update)ÚMetric)Ú_MATPLOTLIB_AVAILABLE)Ú_AX_TYPEÚ_PLOT_OUT_TYPEúPearsonCorrCoef.plotç»½×Ùß|Û=Úmeans_xÚmeans_yÚ
maxs_abs_xÚ
maxs_abs_yÚvars_xÚvars_yÚcorrs_xyÚnbsÚepsÚreturnc	           %   	   C   sº  t | ƒdkr | d |d |d |d |d |d |d |d fS | d }	|d }
|d }|d }|d }|d }|d }|d }tdt | ƒƒD ]‹}| | }|| }|| }|| }|| }|| }|| }|| }t t ||¡|| |¡}||	 ||  | }||
 ||  | }|| | }||	 }||
 }|| ||d   } || ||d   }!|| || |  }"t ||¡}#t ||¡}$|}	|}
|#}|$}| }|!}|"}|}qG|||#|$| |!|"|fS )a¥  Aggregate the statistics from multiple devices.

    Formula taken from here: `Parallel algorithm for calculating variance
    <https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Parallel_algorithm>`_

    We use `eps` to avoid division by zero when `n1` and `n2` are both zero. Generally, the value of `eps` should not
    matter, as if `n1` and `n2` are both zero, all the states will also be zero.

    é   r   é   )ÚlenÚrangeÚtorchÚwhereÚ
logical_orÚmaximum)%r   r   r   r   r   r   r   r   r   Zmx1Zmy1Zmax1Zmay1Zvx1Zvy1Zcxy1Ún1ÚiZmx2Zmy2Zmax2Zmay2Zvx2Zvy2Zcxy2Ún2ÚnbÚmean_xÚmean_yZn12_bÚdelta_xÚdelta_yÚvar_xÚvar_yÚcorr_xyÚmax_abs_dev_xÚmax_abs_dev_y© r/   úr/var/www/html/academy/tools/voices/clone/cosy-venv/lib/python3.10/site-packages/torchmetrics/regression/pearson.pyÚ_final_aggregation   sN   4r1   c                       s  e Zd ZU dZdZeed< dZee ed< dZ	eed< dZ
eed< d	Zeed
< ee ed< ee ed< eed< eed< eed< eed< eed< eed< eed< eed< 	d#dededdf‡ fdd„Zdededdfdd„Zdefdd„Z	d$deeeee f  d ee defd!d"„Z‡  ZS )%ÚPearsonCorrCoefa  Compute `Pearson Correlation Coefficient`_.

    .. math::
        P_{corr}(x,y) = \frac{cov(x,y)}{\sigma_x \sigma_y}

    Where :math:`y` is a tensor of target values, and :math:`x` is a tensor of predictions.

    As input to ``forward`` and ``update`` the metric accepts the following input:

    - ``preds`` (:class:`~torch.Tensor`): either single output float tensor with shape ``(N,)``
      or multioutput float tensor of shape ``(N,d)``
    - ``target`` (:class:`~torch.Tensor`): either single output tensor with shape ``(N,)``
      or multioutput tensor of shape ``(N,d)``

    As output of ``forward`` and ``compute`` the metric returns the following output:

    - ``pearson`` (:class:`~torch.Tensor`): A tensor with the Pearson Correlation Coefficient

    Args:
        num_outputs: Number of outputs in multioutput setting
        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Example (single output regression):
        >>> from torchmetrics.regression import PearsonCorrCoef
        >>> target = torch.tensor([3, -0.5, 2, 7])
        >>> preds = torch.tensor([2.5, 0.0, 2, 8])
        >>> pearson = PearsonCorrCoef()
        >>> pearson(preds, target)
        tensor(0.9849)

    Example (multi output regression):
        >>> from torchmetrics.regression import PearsonCorrCoef
        >>> target = torch.tensor([[3, -0.5], [2, 7]])
        >>> preds = torch.tensor([[2.5, 0.0], [2, 8]])
        >>> pearson = PearsonCorrCoef(num_outputs=2)
        >>> pearson(preds, target)
        tensor([1., 1.])

    TÚis_differentiableNÚhigher_is_betterÚfull_state_updateg      ð¿Úplot_lower_boundg      ð?Úplot_upper_boundÚpredsÚtargetr&   r'   r-   r.   r*   r+   r,   Ún_totalr   Únum_outputsÚkwargsr   c                    sö   t ƒ jdi |¤Ž t|tƒs|dk rtdƒ‚|| _| jdt | j¡d d� | jdt | j¡d d� | jdt | j¡d d� | jdt | j¡d d� | jdt | j¡d d� | jd	t | j¡d d� | jd
t | j¡d d� | jdt | j¡d d� d S )Nr   zQExpected argument `num_outputs` to be an int larger than 0, but got {num_outputs}r&   )ÚdefaultÚdist_reduce_fxr'   r-   r.   r*   r+   r,   r:   r/   )	ÚsuperÚ__init__Ú
isinstanceÚintÚ
ValueErrorr;   Ú	add_stater   Úzeros)Úselfr;   r<   ©Ú	__class__r/   r0   r@   �   s   zPearsonCorrCoef.__init__c                 C   sT   t ||| j| j| j| j| j| j| j| j| j	d�\| _| _| _| _| _| _| _| _dS )z*Update state with predictions and targets.)r8   r9   r&   r'   r-   r.   r*   r+   r,   Ú	num_priorr;   N)
r	   r&   r'   r-   r.   r*   r+   r,   r:   r;   )rF   r8   r9   r/   r/   r0   Úupdate°   s,   õ÷zPearsonCorrCoef.updatec              
   C   sž   | j dkr| j ¡ dks| j dkr4| jjdkr4t| j| j| j| j| j| j	| j
| jd�\}}}}}}}}n| j}| j}| j}| j	}| j
}| j}t||||||ƒS )z3Compute pearson correlation coefficient over state.r   )r   r   r   r   r   r   r   r   )r;   r&   ÚnumelÚndimr1   r'   r-   r.   r*   r+   r,   r:   r   )rF   Ú_r-   r.   r*   r+   r,   r:   r/   r/   r0   ÚcomputeÉ   s$   .øzPearsonCorrCoef.computeÚ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

            >>> from torch import randn
            >>> # Example plotting a single value
            >>> from torchmetrics.regression import PearsonCorrCoef
            >>> metric = PearsonCorrCoef()
            >>> metric.update(randn(10,), randn(10,))
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

            >>> from torch import randn
            >>> # Example plotting multiple values
            >>> from torchmetrics.regression import PearsonCorrCoef
            >>> metric = PearsonCorrCoef()
            >>> values = []
            >>> for _ in range(10):
            ...     values.append(metric(randn(10,), randn(10,)))
            >>> fig, ax = metric.plot(values)

        )Ú_plot)rF   rO   rP   r/   r/   r0   Úplotà   s   (r   )r   )NN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r3   ÚboolÚ__annotations__r4   r   r5   r6   Úfloatr7   r   r   rB   r   r@   rJ   rN   r   r   r   r   rR   Ú__classcell__r/   r/   rG   r0   r2   d   sF   
 (þþýüÿÿÿþr2   )r   )Úcollections.abcr   Útypingr   r   r   r   r   r   Ú*torchmetrics.functional.regression.pearsonr   r	   Útorchmetrics.metricr
   Útorchmetrics.utilities.importsr   Útorchmetrics.utilities.plotr   r   Ú__doctest_skip__rY   Útupler1   r2   r/   r/   r/   r0   Ú<module>   sF   ÷ÿþýüûúùø	÷
"ÿ
öG