a
    d                      @   s   d dl 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 esvdgZeeeeeeeeeeeeef d	d
dZG dd deZdS )    )AnyListOptionalSequenceTupleUnionN)Tensor)_pearson_corrcoef_compute_pearson_corrcoef_update)Metric)_MATPLOTLIB_AVAILABLE)_AX_TYPE_PLOT_OUT_TYPEPearsonCorrCoef.plot)means_xmeans_yvars_xvars_ycorrs_xynbsreturnc                 C   s>  t | dkr4| d |d |d |d |d |d fS | d |d |d |d |d |d f\}}}}	}
}tdt | D ]}| | || || || || || f\}}}}}}|| }|| ||  | }|| ||  | }|d | ||  }||| ||  || d  7 }|d | ||  }||| ||  || d  7 }|| }|d | ||  }|	|| ||  || d  7 }	|d | ||  }||| ||  || d  7 }|	| }|
|| ||  || ||   7 }
||| ||  || ||   7 }|
| }||||||f\}}}}	}
}qv||||||fS )zAggregate the statistics from multiple devices.

    Formula taken from here: `Aggregate the statistics from multiple devices`_

       r      )lenrange)r   r   r   r   r   r   Zmx1Zmy1Zvx1Zvy1Zcxy1Zn1iZmx2Zmy2Zvx2Zvy2Zcxy2Zn2nbmean_xmean_yZ
element_x1Z
element_x2var_xZ
element_y1Z
element_y2var_ycorr_xy r"   h/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/torchmetrics/regression/pearson.py_final_aggregation   s.    (44    $$r$   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< d eedd fddZeeddddZedddZd!eeeee f  ee ed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!   n_totalr   )num_outputskwargsr   c                    s   t  jf 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 d S )
Nr   zQExpected argument `num_outputs` to be an int larger than 0, but got {num_outputs}r   )defaultZdist_reduce_fxr   r   r    r!   r-   )	super__init__
isinstanceint
ValueErrorr.   Z	add_statetorchzeros)selfr.   r/   	__class__r"   r#   r2      s    zPearsonCorrCoef.__init__)r+   r,   r   c              
   C   sB   t ||| j| j| j| j| j| j| j	\| _| _| _| _| _| _dS )z*Update state with predictions and targets.N)r
   r   r   r   r    r!   r-   r.   )r8   r+   r,   r"   r"   r#   update   s    zPearsonCorrCoef.update)r   c                 C   s   | j dkr| j dks.| j dkrZ| jjdkrZt| j| j| j| j| j| j	\}}}}}}n| j}| j}| j}| j	}t
||||S )z3Compute pearson correlation coefficient over state.r   )r.   r   Znumelndimr$   r   r   r    r!   r-   r	   )r8   _r   r    r!   r-   r"   r"   r#   compute   s    .zPearsonCorrCoef.compute)valaxr   c                 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)

        )Z_plot)r8   r?   r@   r"   r"   r#   plot   s    (r   )r   )NN)__name__
__module____qualname____doc__r&   bool__annotations__r'   r   r(   r)   floatr*   r   r   r4   r   r2   r;   r>   r   r   r   r   rA   __classcell__r"   r"   r9   r#   r%   I   s6   
'  r%   )typingr   r   r   r   r   r   r6   r   Z*torchmetrics.functional.regression.pearsonr	   r
   Ztorchmetrics.metricr   Ztorchmetrics.utilities.importsr   Ztorchmetrics.utilities.plotr   r   Z__doctest_skip__r$   r%   r"   r"   r"   r#   <module>   s"    -