
    j                    ^    d 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  G d de      Zy	)
zCSpearman rank correlation between reference and predicted rankings.    )annotations)AnySequence)
BaseMetric)ScoreResult)MetricComputationErrorc                  R     e Zd ZdZ	 	 	 d	 	 	 	 	 	 	 d fdZ	 	 	 	 	 	 	 	 ddZ xZS )SpearmanRankingaw  
    Compute Spearman's rank correlation for two rankings of the same items.

    Scores are normalised to ``[0.0, 1.0]`` where `1.0` indicates perfect rank
    agreement and `0.0` indicates complete disagreement (``rho = -1``).

    References:
      - Spearman's rank correlation coefficient (Wikipedia overview)
        https://en.wikipedia.org/wiki/Spearman%27s_rank_correlation_coefficient
      - SciPy documentation: ``scipy.stats.spearmanr``
        https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.spearmanr.html

    Args:
        name: Display name for the metric result. Defaults to
            ``"spearman_ranking_metric"``.
        track: Whether to automatically track metric results. Defaults to ``True``.
        project_name: Optional tracking project name. Defaults to ``None``.

    Example:
        >>> from opik.evaluation.metrics import SpearmanRanking
        >>> metric = SpearmanRanking()
        >>> result = metric.score(
        ...     output=["b", "a", "c"],
        ...     reference=["a", "b", "c"],
        ... )
        >>> round(result.metadata["rho"], 2)  # doctest: +SKIP
        -0.5
    c                *    t         |   |||       y )N)nametrackproject_name)super__init__)selfr   r   r   	__class__s       /Users/manta/Documents/Projects/TheRoad-I1/backend/.venv/lib/python3.12/site-packages/opik/evaluation/metrics/heuristics/spearman.pyr   zSpearmanRanking.__init__*   s     	d%lK    c                   t        |      t        |      k7  rt        d      t        |      dk(  rt        d      t        |      D ci c]  \  }}||
 }}}t        |      t        |      k7  rt        d      d}t        |      D ]  \  }}||   }|||z
  dz  z  } t        |      }	|	dk(  rd}
ndd|z  |	|	|	z  dz
  z  z  z
  }
|
dz   dz  }t	        || j
                  d	|d
d|
i      S c c}}w )Nz8output and reference rankings must have the same length.r   z2Rankings cannot be empty for Spearman correlation.z%Rankings must contain the same items.      g      ?   z#Spearman correlation (normalized): z.4frho)valuer   reasonmetadata)lenr   	enumeratesetr   r   )r   output	referenceignored_kwargsidxitem	ref_ranksdiffs_sqref_idxnr   
normalizeds               r   scorezSpearmanRanking.score2   s-    v;#i.((J  v;!(D  1:)0DE0D93T3Y0D	Ev;#i.(()PQQ"6*ICoGw1,,H + K6Cq8|QUQY88C Ag]
8C8HIS\	
 	
% Fs   
C/)spearman_ranking_metricTN)r   strr   boolr   z
str | NonereturnNone)r    Sequence[Any]r!   r0   r"   r   r.   r   )__name__
__module____qualname____doc__r   r*   __classcell__)r   s   @r   r
   r
      sn    > .#'	LL L !	L
 
L&
&
 !&
 	&

 
&
r   r
   N)r4   
__future__r   typingr   r   #opik.evaluation.metrics.base_metricr   $opik.evaluation.metrics.score_resultr   opik.exceptionsr   r
    r   r   <module>r<      s%    I "   : < 2L
j L
r   