
'''simple docstring'''




# Lint as: python3
import sys
from collections.abc import Mapping
from typing import TYPE_CHECKING, Dict, Optional

import numpy as np
import pyarrow as pa

from .. import config
from ..utils.logging import get_logger
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter


if TYPE_CHECKING:
      import jax
      import jaxlib

lowercase			:				List[str]    		=			get_logger()

lowercase			:				Optional[dict]    		=			None





class  A				(							TensorFormatter[Mapping, '''jax.Array''', Mapping]						):





     def __init__(							self						,			SCREAMING_SNAKE_CASE=None						,			SCREAMING_SNAKE_CASE=None						,			**SCREAMING_SNAKE_CASE	) ->				int:






         """simple docstring"""






         super().__init__(features=SCREAMING_SNAKE_CASE	)
         import jax
         from jaxlib.xla_client import Device

         if isinstance(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	):
             raise ValueError(
                 F'Expected {device} to be a `str` not {type(SCREAMING_SNAKE_CASE	)}, as `jaxlib.xla_extension.Device` '
                 '''is not serializable neither with `pickle` nor with `dill`. Instead you can surround '''
                 '''the device with `str()` to get its string identifier that will be internally mapped '''
                 '''to the actual `jaxlib.xla_extension.Device`.'''	)
         A       :   int					=						device if isinstance(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	) else str(jax.devices()[0]	)
         # using global variable since `jaxlib.xla_extension.Device` is not serializable neither
         # with `pickle` nor with `dill`, so we need to use a global variable instead
         global DEVICE_MAPPING
         if DEVICE_MAPPING is None:
             A       :   Tuple					=						self._map_devices_to_str()
         if self.device not in list(DEVICE_MAPPING.keys()	):
             logger.warning(
                 F'Device with string identifier {self.device} not listed among the available '
                 F'devices: {list(DEVICE_MAPPING.keys()	)}, so falling back to the default '
                 F'device: {str(jax.devices()[0]	)}.'	)
             A       :   Optional[Any]					=						str(jax.devices()[0]	)
         A       :   Dict					=						jnp_array_kwargs





     @staticmethod
     def 				__lowerCAmelCase							(							) ->				Dict[str, "jaxlib.xla_extension.Device"]:






         """simple docstring"""






         import jax

         return {str(SCREAMING_SNAKE_CASE	): device for device in jax.devices()}





     def 				__lowerCAmelCase							(							self						,			SCREAMING_SNAKE_CASE	) ->				Optional[Any]:






         """simple docstring"""






         import jax
         import jax.numpy as jnp

         if isinstance(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	) and column:
             if all(
                 isinstance(SCREAMING_SNAKE_CASE						,			jax.Array	) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column	):
                 return jnp.stack(SCREAMING_SNAKE_CASE						,			axis=0	)
         return column





     def 				__lowerCAmelCase							(							self						,			SCREAMING_SNAKE_CASE	) ->				Dict:






         """simple docstring"""






         import jax
         import jax.numpy as jnp

         if isinstance(SCREAMING_SNAKE_CASE						,			(str, bytes, type(SCREAMING_SNAKE_CASE	))	):
             return value
         elif isinstance(SCREAMING_SNAKE_CASE						,			(np.character, np.ndarray)	) and np.issubdtype(value.dtype						,			np.character	):
             return value.tolist()

         A       :   int					=						{}

         if isinstance(SCREAMING_SNAKE_CASE						,			(np.number, np.ndarray)	) and np.issubdtype(value.dtype						,			np.integer	):
             # the default int precision depends on the jax config
             # see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision
             if jax.config.jax_enable_xaa:
                 A       :   List[Any]					=						{'''dtype''': jnp.intaa}
             else:
                 A       :   Tuple					=						{'''dtype''': jnp.intaa}
         elif isinstance(SCREAMING_SNAKE_CASE						,			(np.number, np.ndarray)	) and np.issubdtype(value.dtype						,			np.floating	):
             A       :   Union[str, Any]					=						{'''dtype''': jnp.floataa}
         elif config.PIL_AVAILABLE and "PIL" in sys.modules:
             import PIL.Image

             if isinstance(SCREAMING_SNAKE_CASE						,			PIL.Image.Image	):
                 A       :   List[str]					=						np.asarray(SCREAMING_SNAKE_CASE	)

        # using global variable since `jaxlib.xla_extension.Device` is not serializable neither
        # with `pickle` nor with `dill`, so we need to use a global variable instead
         global DEVICE_MAPPING
         if DEVICE_MAPPING is None:
             A       :   int					=						self._map_devices_to_str()

         with jax.default_device(DEVICE_MAPPING[self.device]	):
             # calling jnp.array on a np.ndarray does copy the data
             # see https://github.com/google/jax/issues/4486
             return jnp.array(SCREAMING_SNAKE_CASE						,			**{**default_dtype, **self.jnp_array_kwargs}	)





     def 				__lowerCAmelCase							(							self						,			SCREAMING_SNAKE_CASE	) ->				Union[str, Any]:






         """simple docstring"""






         import jax

         # support for torch, tf, jax etc.
         if config.TORCH_AVAILABLE and "torch" in sys.modules:
             import torch

             if isinstance(SCREAMING_SNAKE_CASE						,			torch.Tensor	):
                 return self._tensorize(data_struct.detach().cpu().numpy()[()]	)
         if hasattr(SCREAMING_SNAKE_CASE						,			'''__array__'''	) and not isinstance(SCREAMING_SNAKE_CASE						,			jax.Array	):
             A       :   Any					=						data_struct.__array__()
         # support for nested types like struct of list of struct
         if isinstance(SCREAMING_SNAKE_CASE						,			np.ndarray	):
             if data_struct.dtype == object:  # jax arrays cannot be instantied from an array of objects
                 return self._consolidate([self.recursive_tensorize(SCREAMING_SNAKE_CASE	) for substruct in data_struct]	)
         elif isinstance(SCREAMING_SNAKE_CASE						,			(list, tuple)	):
             return self._consolidate([self.recursive_tensorize(SCREAMING_SNAKE_CASE	) for substruct in data_struct]	)
         return self._tensorize(SCREAMING_SNAKE_CASE	)





     def 				__lowerCAmelCase							(							self						,			SCREAMING_SNAKE_CASE	) ->				Optional[Any]:






         """simple docstring"""






         return map_nested(self._recursive_tensorize						,			SCREAMING_SNAKE_CASE						,			map_list=SCREAMING_SNAKE_CASE	)





     def 				__lowerCAmelCase							(							self						,			SCREAMING_SNAKE_CASE	) ->				Mapping:






         """simple docstring"""






         A       :   List[str]					=						self.numpy_arrow_extractor().extract_row(SCREAMING_SNAKE_CASE	)
         A       :   Any					=						self.python_features_decoder.decode_row(SCREAMING_SNAKE_CASE	)
         return self.recursive_tensorize(SCREAMING_SNAKE_CASE	)





     def 				__lowerCAmelCase							(							self						,			SCREAMING_SNAKE_CASE	) ->				"jax.Array":






         """simple docstring"""






         A       :   Union[str, Any]					=						self.numpy_arrow_extractor().extract_column(SCREAMING_SNAKE_CASE	)
         A       :   Tuple					=						self.python_features_decoder.decode_column(SCREAMING_SNAKE_CASE						,			pa_table.column_names[0]	)
         A       :   Optional[int]					=						self.recursive_tensorize(SCREAMING_SNAKE_CASE	)
         A       :   List[Any]					=						self._consolidate(SCREAMING_SNAKE_CASE	)
         return column





     def 				__lowerCAmelCase							(							self						,			SCREAMING_SNAKE_CASE	) ->				Mapping:






         """simple docstring"""






         A       :   Optional[Any]					=						self.numpy_arrow_extractor().extract_batch(SCREAMING_SNAKE_CASE	)
         A       :   Any					=						self.python_features_decoder.decode_batch(SCREAMING_SNAKE_CASE	)
         A       :   Any					=						self.recursive_tensorize(SCREAMING_SNAKE_CASE	)
         for column_name in batch:
             A       :   Optional[Any]					=						self._consolidate(batch[column_name]	)
         return batch






'''simple docstring'''




from scipy.stats import pearsonr

import datasets


lowercase			:				Optional[int]    		=			'\nPearson correlation coefficient and p-value for testing non-correlation.\nThe Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.\nThe p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.\n'


lowercase			:				Optional[Any]    		=			'\nArgs:\n    predictions (`list` of `int`): Predicted class labels, as returned by a model.\n    references (`list` of `int`): Ground truth labels.\n    return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.\n\nReturns:\n    pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation.\n    p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities.\n\nExamples:\n\n    Example 1-A simple example using only predictions and references.\n        >>> pearsonr_metric = datasets.load_metric("pearsonr")\n        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])\n        >>> print(round(results[\'pearsonr\'], 2))\n        -0.74\n\n    Example 2-The same as Example 1, but that also returns the `p-value`.\n        >>> pearsonr_metric = datasets.load_metric("pearsonr")\n        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)\n        >>> print(sorted(list(results.keys())))\n        [\'p-value\', \'pearsonr\']\n        >>> print(round(results[\'pearsonr\'], 2))\n        -0.74\n        >>> print(round(results[\'p-value\'], 2))\n        0.15\n'


lowercase			:				str    		=			'\n@article{2020SciPy-NMeth,\nauthor  = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and\n      Haberland, Matt and Reddy, Tyler and Cournapeau, David and\n      Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and\n      Bright, Jonathan and {van der Walt}, St{\'e}fan J. and\n      Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and\n      Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and\n      Kern, Robert and Larson, Eric and Carey, C J and\n      Polat, Ilhan and Feng, Yu and Moore, Eric W. and\n      {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and\n      Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and\n      Harris, Charles R. and Archibald, Anne M. and\n      Ribeiro, Antonio H. and Pedregosa, Fabian and\n      {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},\ntitle   = {{{SciPy} 1.0: Fundamental Algorithms for Scientific\n      Computing in Python}},\njournal = {Nature Methods},\nyear    = {2020},\nvolume  = {17},\npages   = {261--272},\nadsurl  = {https://rdcu.be/b08Wh},\ndoi = {10.1038/s41592-019-0686-2},\n}\n'





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





     def 				__lowerCAmelCase							(							self	) ->				List[str]:






         """simple docstring"""






         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.pearsonr.html''']						,			)





     def 				__lowerCAmelCase							(							self						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE=False	) ->				Union[str, Any]:






         """simple docstring"""






         if return_pvalue:
             A       :   Union[str, Any]					=						pearsonr(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)
             return {"pearsonr": results[0], "p-value": results[1]}
         else:
             return {"pearsonr": float(pearsonr(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)[0]	)}




