a
    d                     @   s   d dl mZ d dlZd dlmZ d dlmZ d dlmZ eedddZeedd	d
Z	eee
eeef dddZdeeeedddZeeedddZdS )    )TupleN)Tensor) _check_data_shape_to_num_outputs)_check_same_shape)datareturnc                 C   s   |    }| d }ttjdg|jd|dd |dd kg}|| }tt|tj| gg|jdg	 }|dd |dd  }|dk}|| S )z_Find and return values which have repeats i.e. the same value are more than once in the tensor.r   T)device   N)
detachclonesorttorchcatZtensorr   Znonzeronumelflatten)r   tempZchangeuniqueZ
change_idxfreqZatleast2 r   t/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/torchmetrics/functional/regression/spearman.py_find_repeats   s    0,r   c                 C   sn   |   }t| }|  }tjd|d | j| jd||d| < t| }|D ]}| |k}||  ||< qL|S )a  Calculate the rank for each element of a tensor.

    The rank refers to the indices of an element in the corresponding sorted tensor (starting from 1). Duplicates of the
    same value will be assigned the mean of their rank.

    Adopted from `Rank of element tensor`_

    r	   )dtyper   N)	r   r   Z
empty_likeZargsortZaranger   r   r   mean)r   nZrankidxZrepeatsr	conditionr   r   r   
_rank_data$   s    	
&r   )predstargetnum_outputsr   c                 C   s6   |   r|  stdt| | t| || | |fS )a  Update and returns variables required to compute Spearman Correlation Coefficient.

    Check for same shape and type of input tensors.

    Args:
        preds: Predicted tensor
        target: Ground truth tensor
        num_outputs: Number of outputs in multioutput setting

    zhExpected `preds` and `target` both to be floating point tensors, but got {pred.dtype} and {target.dtype})Zis_floating_point	TypeErrorr   r   )r   r    r!   r   r   r   _spearman_corrcoef_update9   s    
r#   ư>)r   r    epsr   c           	      C   s   | j dkrt| } t|}n0tdd | jD j} tdd |jD j}| | d }||d }|| d}t|| d}t|| d}||| |  }t|ddS )a  Compute Spearman Correlation Coefficient.

    Args:
        preds: Predicted tensor
        target: Ground truth tensor
        eps: Avoids ``ZeroDivisionError``.

    Example:
        >>> target = torch.tensor([3, -0.5, 2, 7])
        >>> preds = torch.tensor([2.5, 0.0, 2, 8])
        >>> preds, target = _spearman_corrcoef_update(preds, target, num_outputs=1)
        >>> _spearman_corrcoef_compute(preds, target)
        tensor(1.0000)

    r	   c                 S   s   g | ]}t |qS r   r   ).0pr   r   r   
<listcomp>b       z._spearman_corrcoef_compute.<locals>.<listcomp>c                 S   s   g | ]}t |qS r   r&   )r'   tr   r   r   r)   c   r*   r   g      g      ?)ndimr   r   stackTr   sqrtclamp)	r   r    r%   Z
preds_diffZtarget_diffZcovZ	preds_stdZ
target_stdZcorrcoefr   r   r   _spearman_corrcoef_computeN   s    

r1   )r   r    r   c                 C   s0   t | || jdkrdn| jd d\} }t| |S )a  Compute `spearmans rank correlation coefficient`_.

    .. math:
        r_s = = \frac{cov(rg_x, rg_y)}{\sigma_{rg_x} * \sigma_{rg_y}}

    where :math:`rg_x` and :math:`rg_y` are the rank associated to the variables x and y. Spearmans correlations
    coefficient corresponds to the standard pearsons correlation coefficient calculated on the rank variables.

    Args:
        preds: estimated scores
        target: ground truth scores

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

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

    r	   r
   )r!   )r#   r,   shaper1   )r   r    r   r   r   spearman_corrcoefp   s    &r3   )r$   )typingr   r   r   Z(torchmetrics.functional.regression.utilsr   Ztorchmetrics.utilities.checksr   r   r   intr#   floatr1   r3   r   r   r   r   <module>   s   "