

from scipy.stats import spearmanr

import datasets


_SCREAMING_SNAKE_CASE  :						Any         =    '''
The Spearman rank-order correlation coefficient is a measure of the
relationship between two datasets. Like other correlation coefficients,
this one varies between -1 and +1 with 0 implying no correlation.
Positive correlations imply that as data in dataset x increases, so
does data in dataset y. Negative correlations imply that as x increases,
y decreases. Correlations of -1 or +1 imply an exact monotonic relationship.

Unlike the Pearson correlation, the Spearman correlation does not
assume that both datasets are normally distributed.

The p-value roughly indicates the probability of an uncorrelated system
producing datasets that have a Spearman correlation at least as extreme
as the one computed from these datasets. The p-values are not entirely
reliable but are probably reasonable for datasets larger than 500 or so.
'''

_SCREAMING_SNAKE_CASE  :						Tuple         =    '''
Args:
    predictions (`List[float]`): Predicted labels, as returned by a model.
    references (`List[float]`): Ground truth labels.
    return_pvalue (`bool`): If `True`, returns the p-value. If `False`, returns
            only the spearmanr score. Defaults to `False`.
Returns:
    spearmanr (`float`): Spearman correlation coefficient.
    p-value (`float`): p-value. **Note**: is only returned if `return_pvalue=True` is input.
Examples:
    Example 1:
        >>> spearmanr_metric = datasets.load_metric("spearmanr")
        >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5], predictions=[10, 9, 2.5, 6, 4])
        >>> print(results)
        {\'spearmanr\': -0.7}

    Example 2:
        >>> spearmanr_metric = datasets.load_metric("spearmanr")
        >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5],
        ...                                     predictions=[10, 9, 2.5, 6, 4],
        ...                                     return_pvalue=True)
        >>> print(results[\'spearmanr\'])
        -0.7
        >>> print(round(results[\'spearmanr_pvalue\'], 2))
        0.19
'''

_SCREAMING_SNAKE_CASE  :						str         =    r'''\
@book{kokoska2000crc,
  title={CRC standard probability and statistics tables and formulae},
  author={Kokoska, Stephen and Zwillinger, Daniel},
  year={2000},
  publisher={Crc Press}
}
@article{2020SciPy-NMeth,
  author  = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and
            Haberland, Matt and Reddy, Tyler and Cournapeau, David and
            Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and
            Bright, Jonathan and {van der Walt}, St{\'e}fan J. and
            Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and
            Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and
            Kern, Robert and Larson, Eric and Carey, C J and
            Polat, {\.I}lhan and Feng, Yu and Moore, Eric W. and
            {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and
            Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and
            Harris, Charles R. and Archibald, Anne M. and
            Ribeiro, Ant{\^o}nio H. and Pedregosa, Fabian and
            {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},
  title   = {{{SciPy} 1.0: Fundamental Algorithms for Scientific
            Computing in Python}},
  journal = {Nature Methods},
  year    = {2020},
  volume  = {17},
  pages   = {261--272},
  adsurl  = {https://rdcu.be/b08Wh},
  doi     = {10.1038/s41592-019-0686-2},
}
'''






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION		,  _KWARGS_DESCRIPTION )
class  UpperCAmelCase__	( datasets.Metric ):






  """simple docstring"""


  def    lowercase_	(							self		:	Dict      )	->							str:
       return datasets.MetricInfo(
           description=_DESCRIPTION			,     citation=_CITATION			,     inputs_description=_KWARGS_DESCRIPTION			,     features=datasets.Features(
               {
                   '''predictions''': datasets.Value('''float'''      ),
                   '''references''': datasets.Value('''float'''      ),
               }      )			,     reference_urls=['''https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.spearmanr.html''']			,     )







  def    lowercase_	(							self		:	Any			,     __lowerCamelCase		:	List[Any]			,     __lowerCamelCase		:	Optional[int]			,     __lowerCamelCase		:	str=False      )	->							Tuple:
       SCREAMING_SNAKE_CASE__					=					spearmanr(__lowerCamelCase			,     __lowerCamelCase      )
       if return_pvalue:
            return {"spearmanr": results[0], "spearmanr_pvalue": results[1]}
       else:
            return {"spearmanr": results[0]}





from importlib import import_module

from .logging import get_logger


_SCREAMING_SNAKE_CASE  :						Optional[int]         =    get_logger(__name__)






class  UpperCAmelCase__	:






  """simple docstring"""


  def __init__(							self		:	Optional[int]			,     __lowerCamelCase		:	Optional[Any]			,     __lowerCamelCase		:	Any=None      )	->							int:
       SCREAMING_SNAKE_CASE__					=					attrs or []
       if module is not None:
            for key in module.__dict__:
                 if key in attrs or not key.startswith('''__'''      ):
                      setattr(self			,     __lowerCamelCase			,     getattr(__lowerCamelCase			,     __lowerCamelCase      )      )
       SCREAMING_SNAKE_CASE__					=					module._original_module if isinstance(__lowerCamelCase			,     _PatchedModuleObj      ) else module






class  UpperCAmelCase__	:






  """simple docstring"""


  a     =      []






  def __init__(							self		:	int			,     __lowerCamelCase		:	Union[str, Any]			,     __lowerCamelCase		:	str			,     __lowerCamelCase		:	Optional[int]			,     __lowerCamelCase		:	List[Any]=None      )	->							Any:
       SCREAMING_SNAKE_CASE__					=					obj
       SCREAMING_SNAKE_CASE__					=					target
       SCREAMING_SNAKE_CASE__					=					new
       SCREAMING_SNAKE_CASE__					=					target.split('''.'''      )[0]
       SCREAMING_SNAKE_CASE__					=					{}
       SCREAMING_SNAKE_CASE__					=					attrs or []






  def __enter__(							self		:	int      )	->							Tuple:
       *SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__					=					self.target.split('''.'''      )

       # Patch modules:
       # it's used to patch attributes of submodules like "os.path.join";
       # in this case we need to patch "os" and "os.path"

       for i in range(len(__lowerCamelCase      )      ):
            try:
                 SCREAMING_SNAKE_CASE__					=					import_module('''.'''.join(submodules[: i + 1]      )      )
            except ModuleNotFoundError:
                 continue
            # We iterate over all the globals in self.obj in case we find "os" or "os.path"
            for attr in self.obj.__dir__():
                 SCREAMING_SNAKE_CASE__					=					getattr(self.obj			,     __lowerCamelCase      )
                 # We don't check for the name of the global, but rather if its value *is* "os" or "os.path".
                 # This allows to patch renamed modules like "from os import path as ospath".
                 if obj_attr is submodule or (
                     (isinstance(__lowerCamelCase			,     _PatchedModuleObj      ) and obj_attr._original_module is submodule)
                 ):
                      SCREAMING_SNAKE_CASE__					=					obj_attr
                      # patch at top level
                      setattr(self.obj			,     __lowerCamelCase			,     _PatchedModuleObj(__lowerCamelCase			,     attrs=self.attrs      )      )
                      SCREAMING_SNAKE_CASE__					=					getattr(self.obj			,     __lowerCamelCase      )
                      # construct lower levels patches
                      for key in submodules[i + 1 :]:
                           setattr(__lowerCamelCase			,     __lowerCamelCase			,     _PatchedModuleObj(getattr(__lowerCamelCase			,     __lowerCamelCase			,     __lowerCamelCase      )			,     attrs=self.attrs      )      )
                           SCREAMING_SNAKE_CASE__					=					getattr(__lowerCamelCase			,     __lowerCamelCase      )
                      # finally set the target attribute
                      setattr(__lowerCamelCase			,     __lowerCamelCase			,     self.new      )

        # Patch attribute itself:
        # it's used for builtins like "open",
        # and also to patch "os.path.join" we may also need to patch "join"
        # itself if it was imported as "from os.path import join".

       if submodules:  # if it's an attribute of a submodule like "os.path.join"
            try:
                 SCREAMING_SNAKE_CASE__					=					getattr(import_module('''.'''.join(__lowerCamelCase      )      )			,     __lowerCamelCase      )
            except (AttributeError, ModuleNotFoundError):
                 return
            # We iterate over all the globals in self.obj in case we find "os.path.join"
            for attr in self.obj.__dir__():
                 # We don't check for the name of the global, but rather if its value *is* "os.path.join".
                 # This allows to patch renamed attributes like "from os.path import join as pjoin".
                 if getattr(self.obj			,     __lowerCamelCase      ) is attr_value:
                      SCREAMING_SNAKE_CASE__					=					getattr(self.obj			,     __lowerCamelCase      )
                      setattr(self.obj			,     __lowerCamelCase			,     self.new      )
       elif target_attr in globals()["__builtins__"]:  # if it'a s builtin like "open"
            SCREAMING_SNAKE_CASE__					=					globals()['''__builtins__'''][target_attr]
            setattr(self.obj			,     __lowerCamelCase			,     self.new      )
       else:
            raise RuntimeError(f'''Tried to patch attribute {target_attr} instead of a submodule.'''      )






  def __exit__(							self		:	Optional[Any]			,     *__lowerCamelCase		:	Tuple      )	->							List[str]:
       for attr in list(self.original      ):
            setattr(self.obj			,     __lowerCamelCase			,     self.original.pop(__lowerCamelCase      )      )






  def    lowercase_	(							self		:	List[Any]      )	->							Optional[Any]:
       self.__enter__()
       self._active_patches.append(self      )







  def    lowercase_	(							self		:	int      )	->							int:
       try:
            self._active_patches.remove(self      )
       except ValueError:
            # If the patch hasn't been started this will fail
            return None

       return self.__exit__()


