
    i)&                        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Z G d de      Zy)    )Sequence)AnyListOptionalUnionN)Tensor)_pearson_corrcoef_compute_pearson_corrcoef_update)Metric)_MATPLOTLIB_AVAILABLE)_AX_TYPE_PLOT_OUT_TYPEzPearsonCorrCoef.plotmeans_xmeans_y
maxs_abs_x
maxs_abs_yvars_xvars_ycorrs_xynbsepsreturnc	           	         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        j                  t        j                  ||      ||z   |      }||	z  ||z  z   |z  }||
z  ||z  z   |z  }||z  |z  }||	z
  }||
z
  }||z   ||dz  z  z   } ||z   ||dz  z  z   }!||z   ||z  |z  z   }"t        j
                  ||      }#t        j
                  ||      }$|}	|}
|#}|$}| }|!}|"}|} #$ !"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   mx1my1max1may1vx1vy1cxy1n1imx2my2max2may2vx2vy2cxy2n2nbmean_xmean_yn12_bdelta_xdelta_yvar_xvar_ycorr_xymax_abs_dev_xmax_abs_dev_ys%                                        t/Volumes/fast/ai/experiments/voice-extract-mac/.venv/lib/python3.12/site-packages/torchmetrics/regression/pearson.py_final_aggregationr?      s   , 7|qqz71:z!}jmVAYPVWXPY[cde[fhklmhnnn
!*C
!*Ca=Da=D
)C
)CA;D	QB1c'l#ajaj!}!}QiQi{V[[))"b127C@s(R#X%+s(R#X%+R"))c	EGQJ..c	EGQJ..+' 99dD1dD1G $H 6=-wPRRR    c                   F    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ZdededdfdZdefdZ	 ddeeeee   f      dee   defdZ x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targetr4   r5   r<   r=   r9   r:   r;   n_totalnum_outputskwargsr   c                    t        |   di | t        |t              s|dk  rt	        d      || _        | j                  dt        j                  | j
                        d        | j                  dt        j                  | j
                        d        | j                  dt        j                  | j
                        d        | j                  dt        j                  | j
                        d        | j                  dt        j                  | j
                        d        | j                  d	t        j                  | j
                        d        | j                  d
t        j                  | j
                        d        | j                  dt        j                  | j
                        d        y )Nr   zQExpected argument `num_outputs` to be an int larger than 0, but got {num_outputs}r4   )defaultdist_reduce_fxr5   r<   r=   r9   r:   r;   rJ    )	super__init__
isinstanceint
ValueErrorrK   	add_stater   zeros)selfrK   rL   	__class__s      r>   rR   zPearsonCorrCoef.__init__   sI   
 	"6"+s+apqq&xT5E5E)FW[\xT5E5E)FW[\D<L<L0M^bcD<L<L0M^bcwD4D4D(EVZ[wD4D4D(EVZ[y%++d6F6F*GX\]y%++d6F6F*GX\]r@   c                 F   t        ||| j                  | j                  | j                  | j                  | j
                  | j                  | j                  | j                  | j                        \  | _        | _        | _        | _        | _        | _        | _        | _        y)z*Update state with predictions and targets.)rH   rI   r4   r5   r<   r=   r9   r:   r;   	num_priorrK   N)
r
   r4   r5   r<   r=   r9   r:   r;   rJ   rK   )rX   rH   rI   s      r>   updatezPearsonCorrCoef.update   s     %;;;;,,,,****LLll((
		
KKJJLLr@   c           
      4   | j                   dk(  r| j                  j                         dkD  s(| j                   dkD  r| j                  j                  dkD  rmt	        | j                  | j
                  | j                  | j                  | j                  | j                  | j                  | j                        \  }}}}}}}}nH| j                  }| j                  }| j                  }| j                  }| j                  }| j                  }t        ||||||      S )z3Compute pearson correlation coefficient over state.r   )r   r   r   r   r   r   r   r   )rK   r4   numelndimr?   r5   r<   r=   r9   r:   r;   rJ   r	   )rX   _r<   r=   r9   r:   r;   rJ   s           r>   computezPearsonCorrCoef.compute   s    !dkk&7&7&9A&=4CSCSVWCW\`\g\g\l\lop\pQc----zzzzLL	RNAq-ugw !..M ..MJJEJJEllGllG(ueU\^effr@   valaxc                 &    | j                  ||      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)rX   rb   rc   s      r>   plotzPearsonCorrCoef.plot   s    P zz#r""r@   )r   )NN)__name__
__module____qualname____doc__rC   bool__annotations__rD   r   rE   rF   floatrG   r   r   rT   r   rR   r\   ra   r   r   r   r   rf   __classcell__)rY   s   @r>   rB   rB   d   s   &P #t"'+htn+"t""e"!e!<LNNMMOO ^^ ^ 
	^&
F 
F 
t 
2g g0 _c(#E&(6*:":;<(#IQRZI[(#	(#r@   rB   )g|=)collections.abcr   typingr   r   r   r   r   r   *torchmetrics.functional.regression.pearsonr	   r
   torchmetrics.metricr   torchmetrics.utilities.importsr   torchmetrics.utilities.plotr   r   __doctest_skip__rm   tupler?   rB   rP   r@   r>   <module>rw      s   % - -   j & @ @./ DS\\DS\\DS DS 	DS
 LLDS LLDS llDS 
DS 
DS 	LL%,,ellELL%,,X]XdXdfkfrfrrDSNd#f d#r@   