



"""simple docstring"""




import io
import json

import fsspec
import pytest

from datasets import Dataset, DatasetDict, Features, NamedSplit, Value
from datasets.io.json import JsonDatasetReader, JsonDatasetWriter

from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases


def      lowercase__   (	_UpperCAmelCase		,					_UpperCAmelCase )   ->	Optional[int]:






      '''simple docstring'''


      assert isinstance(__a		,					__a )
      assert dataset.num_rows == 4
      assert dataset.num_columns == 3
      assert dataset.column_names == ["col_1", "col_2", "col_3"]
      for feature, expected_dtype in expected_features.items():
            assert dataset.features[feature].dtype == expected_dtype


@pytest.mark.parametrize('keep_in_memory'		,					[False, True] )
def      lowercase__   (	_UpperCAmelCase		,					_UpperCAmelCase		,					_UpperCAmelCase )   ->	Optional[Any]:






      '''simple docstring'''


      lowercase     :					Union[str, Any] 		=      tmp_path / '''cache'''
      lowercase     :					Dict 		=      {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
      with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
            lowercase     :					Tuple 		=      JsonDatasetReader(__a		,					cache_dir=__a		,					keep_in_memory=__a ).read()
      _check_json_dataset(__a		,					__a )


@pytest.mark.parametrize(
    'features'		,					[
        None,
        {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'},
        {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'},
        {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'},
        {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'},
    ]		,					)
def      lowercase__   (	_UpperCAmelCase		,					_UpperCAmelCase		,					_UpperCAmelCase )   ->	Any:






      '''simple docstring'''


      lowercase     :					Union[str, Any] 		=      tmp_path / '''cache'''
      lowercase     :					Optional[Any] 		=      {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
      lowercase     :					Optional[Any] 		=      features.copy() if features else default_expected_features
      lowercase     :					Tuple 		=      (
          Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None
      )
      lowercase     :					int 		=      JsonDatasetReader(__a		,					features=__a		,					cache_dir=__a ).read()
      _check_json_dataset(__a		,					__a )


@pytest.mark.parametrize(
    'features'		,					[
        None,
        {'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'},
    ]		,					)
def      lowercase__   (	_UpperCAmelCase		,					_UpperCAmelCase		,					_UpperCAmelCase )   ->	Tuple:






      '''simple docstring'''


      lowercase     :					int 		=      tmp_path / '''cache'''
      lowercase     :					str 		=      {'''col_3''': '''float64''', '''col_1''': '''string''', '''col_2''': '''int64'''}
      lowercase     :					Any 		=      features.copy() if features else default_expected_features
      lowercase     :					Union[str, Any] 		=      (
          Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None
      )
      lowercase     :					Any 		=      JsonDatasetReader(__a		,					features=__a		,					cache_dir=__a ).read()
      assert isinstance(__a		,					__a )
      assert dataset.num_rows == 2
      assert dataset.num_columns == 3
      assert dataset.column_names == ["col_3", "col_1", "col_2"]
      for feature, expected_dtype in expected_features.items():
            assert dataset.features[feature].dtype == expected_dtype


def      lowercase__   (	_UpperCAmelCase		,					_UpperCAmelCase )   ->	List[Any]:






      '''simple docstring'''


      lowercase     :					Any 		=      {'''col_2''': '''int64''', '''col_3''': '''float64''', '''col_1''': '''string'''}
      lowercase     :					int 		=      features.copy()
      lowercase     :					List[Any] 		=      (
          Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None
      )
      lowercase     :					Optional[int] 		=      tmp_path / '''cache'''
      lowercase     :					Dict 		=      JsonDatasetReader(__a		,					features=__a		,					cache_dir=__a ).read()
      assert isinstance(__a		,					__a )
      assert dataset.num_rows == 2
      assert dataset.num_columns == 3
      assert dataset.column_names == ["col_2", "col_3", "col_1"]
      for feature, expected_dtype in expected_features.items():
            assert dataset.features[feature].dtype == expected_dtype


@pytest.mark.parametrize('split'		,					[None, NamedSplit('train' ), 'train', 'test'] )
def      lowercase__   (	_UpperCAmelCase		,					_UpperCAmelCase		,					_UpperCAmelCase )   ->	List[Any]:






      '''simple docstring'''


      lowercase     :					Union[str, Any] 		=      tmp_path / '''cache'''
      lowercase     :					Optional[Any] 		=      {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
      lowercase     :					List[Any] 		=      JsonDatasetReader(__a		,					cache_dir=__a		,					split=__a ).read()
      _check_json_dataset(__a		,					__a )
      assert dataset.split == split if split else "train"


@pytest.mark.parametrize('path_type'		,					[str, list] )
def      lowercase__   (	_UpperCAmelCase		,					_UpperCAmelCase		,					_UpperCAmelCase )   ->	Any:






      '''simple docstring'''


      if issubclass(__a		,					__a ):
            lowercase     :					Union[str, Any] 		=      jsonl_path
      elif issubclass(__a		,					__a ):
            lowercase     :					int 		=      [jsonl_path]
      lowercase     :					Dict 		=      tmp_path / '''cache'''
      lowercase     :					Any 		=      {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
      lowercase     :					List[str] 		=      JsonDatasetReader(__a		,					cache_dir=__a ).read()
      _check_json_dataset(__a		,					__a )


def      lowercase__   (	_UpperCAmelCase		,					_UpperCAmelCase		,					_UpperCAmelCase=("train",) )   ->	Optional[Any]:






      '''simple docstring'''


      assert isinstance(__a		,					__a )
      for split in splits:
            lowercase     :					Optional[int] 		=      dataset_dict[split]
            assert dataset.num_rows == 4
            assert dataset.num_columns == 3
            assert dataset.column_names == ["col_1", "col_2", "col_3"]
            for feature, expected_dtype in expected_features.items():
                  assert dataset.features[feature].dtype == expected_dtype


@pytest.mark.parametrize('keep_in_memory'		,					[False, True] )
def      lowercase__   (	_UpperCAmelCase		,					_UpperCAmelCase		,					_UpperCAmelCase )   ->	List[str]:






      '''simple docstring'''


      lowercase     :					List[str] 		=      tmp_path / '''cache'''
      lowercase     :					Dict 		=      {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
      with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
            lowercase     :					str 		=      JsonDatasetReader({'train': jsonl_path}		,					cache_dir=__a		,					keep_in_memory=__a ).read()
      _check_json_datasetdict(__a		,					__a )


@pytest.mark.parametrize(
    'features'		,					[
        None,
        {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'},
        {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'},
        {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'},
        {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'},
    ]		,					)
def      lowercase__   (	_UpperCAmelCase		,					_UpperCAmelCase		,					_UpperCAmelCase )   ->	int:






      '''simple docstring'''


      lowercase     :					Tuple 		=      tmp_path / '''cache'''
      lowercase     :					Any 		=      {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
      lowercase     :					Optional[int] 		=      features.copy() if features else default_expected_features
      lowercase     :					str 		=      (
          Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None
      )
      lowercase     :					Dict 		=      JsonDatasetReader({'train': jsonl_path}		,					features=__a		,					cache_dir=__a ).read()
      _check_json_datasetdict(__a		,					__a )


@pytest.mark.parametrize('split'		,					[None, NamedSplit('train' ), 'train', 'test'] )
def      lowercase__   (	_UpperCAmelCase		,					_UpperCAmelCase		,					_UpperCAmelCase )   ->	str:






      '''simple docstring'''


      if split:
            lowercase     :					List[str] 		=      {split: jsonl_path}
      else:
            lowercase     :					int 		=      '''train'''
            lowercase     :					int 		=      {'''train''': jsonl_path, '''test''': jsonl_path}
      lowercase     :					Any 		=      tmp_path / '''cache'''
      lowercase     :					Union[str, Any] 		=      {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
      lowercase     :					Any 		=      JsonDatasetReader(__a		,					cache_dir=__a ).read()
      _check_json_datasetdict(__a		,					__a		,					splits=list(path.keys() ) )
      assert all(dataset[split].split == split for split in path.keys() )


def      lowercase__   (	_UpperCAmelCase )   ->	Union[str, Any]:






      '''simple docstring'''


      return json.load(__a )


def      lowercase__   (	_UpperCAmelCase )   ->	int:






      '''simple docstring'''


      return [json.loads(__a ) for line in buffer]





class      a__						:


   @pytest.mark.parametrize('lines, load_json_function',   [(True, load_json_lines), (False, load_json)]	)
   def 				lowercase (							self					:							Optional[Any],   lowerCAmelCase					:							Optional[int],   lowerCAmelCase					:							Tuple,   lowerCAmelCase					:							Optional[Any]	)			->				List[str]:


         with io.BytesIO() as buffer:
               JsonDatasetWriter(UpperCamelCase_,   UpperCamelCase_,   lines=UpperCamelCase_	).write()
               buffer.seek(0	)
               lowercase     :					List[Any] 		=      load_json_function(UpperCamelCase_	)
         assert isinstance(UpperCamelCase_,   UpperCamelCase_	)
         assert isinstance(exported_content[0],   UpperCamelCase_	)
         assert len(UpperCamelCase_	) == 10


   @pytest.mark.parametrize(
       'orient, container, keys, len_at',   [
           ('records', list, {'tokens', 'labels', 'answers', 'id'}, None),
           ('split', dict, {'columns', 'data'}, 'data'),
           ('index', dict, set('0123456789'	), None),
           ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'),
           ('values', list, None, None),
           ('table', dict, {'schema', 'data'}, 'data'),
       ],   )
   def 				lowercase (							self					:							List[Any],   lowerCAmelCase					:							List[str],   lowerCAmelCase					:							Dict,   lowerCAmelCase					:							List[Any],   lowerCAmelCase					:							List[Any],   lowerCAmelCase					:							Optional[Any]	)			->				Optional[int]:


         with io.BytesIO() as buffer:
               JsonDatasetWriter(UpperCamelCase_,   UpperCamelCase_,   lines=UpperCamelCase_,   orient=UpperCamelCase_	).write()
               buffer.seek(0	)
               lowercase     :					Optional[int] 		=      load_json(UpperCamelCase_	)
         assert isinstance(UpperCamelCase_,   UpperCamelCase_	)
         if keys:
               if container is dict:
                     assert exported_content.keys() == keys
               else:
                     assert exported_content[0].keys() == keys
         else:
               assert not hasattr(UpperCamelCase_,   'keys'	) and not hasattr(exported_content[0],   'keys'	)
         if len_at:
               assert len(exported_content[len_at]	) == 10
         else:
               assert len(UpperCamelCase_	) == 10


   @pytest.mark.parametrize('lines, load_json_function',   [(True, load_json_lines), (False, load_json)]	)
   def 				lowercase (							self					:							Any,   lowerCAmelCase					:							Union[str, Any],   lowerCAmelCase					:							Union[str, Any],   lowerCAmelCase					:							str	)			->				Union[str, Any]:


         with io.BytesIO() as buffer:
               JsonDatasetWriter(UpperCamelCase_,   UpperCamelCase_,   lines=UpperCamelCase_,   num_proc=2	).write()
               buffer.seek(0	)
               lowercase     :					Union[str, Any] 		=      load_json_function(UpperCamelCase_	)
         assert isinstance(UpperCamelCase_,   UpperCamelCase_	)
         assert isinstance(exported_content[0],   UpperCamelCase_	)
         assert len(UpperCamelCase_	) == 10


   @pytest.mark.parametrize(
       'orient, container, keys, len_at',   [
           ('records', list, {'tokens', 'labels', 'answers', 'id'}, None),
           ('split', dict, {'columns', 'data'}, 'data'),
           ('index', dict, set('0123456789'	), None),
           ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'),
           ('values', list, None, None),
           ('table', dict, {'schema', 'data'}, 'data'),
       ],   )
   def 				lowercase (							self					:							Tuple,   lowerCAmelCase					:							List[str],   lowerCAmelCase					:							Dict,   lowerCAmelCase					:							int,   lowerCAmelCase					:							Tuple,   lowerCAmelCase					:							List[Any]	)			->				Dict:


         with io.BytesIO() as buffer:
               JsonDatasetWriter(UpperCamelCase_,   UpperCamelCase_,   lines=UpperCamelCase_,   orient=UpperCamelCase_,   num_proc=2	).write()
               buffer.seek(0	)
               lowercase     :					int 		=      load_json(UpperCamelCase_	)
         assert isinstance(UpperCamelCase_,   UpperCamelCase_	)
         if keys:
               if container is dict:
                     assert exported_content.keys() == keys
               else:
                     assert exported_content[0].keys() == keys
         else:
               assert not hasattr(UpperCamelCase_,   'keys'	) and not hasattr(exported_content[0],   'keys'	)
         if len_at:
               assert len(exported_content[len_at]	) == 10
         else:
               assert len(UpperCamelCase_	) == 10


   def 				lowercase (							self					:							List[Any],   lowerCAmelCase					:							Optional[Any]	)			->				Union[str, Any]:


         with pytest.raises(UpperCamelCase_	):
               with io.BytesIO() as buffer:
                     JsonDatasetWriter(UpperCamelCase_,   UpperCamelCase_,   num_proc=0	)






   @pytest.mark.parametrize('compression, extension',   [('gzip', 'gz'), ('bz2', 'bz2'), ('xz', 'xz')]	)
   def 				lowercase (							self					:							int,   lowerCAmelCase					:							Union[str, Any],   lowerCAmelCase					:							Union[str, Any],   lowerCAmelCase					:							Optional[int],   lowerCAmelCase					:							Optional[int],   lowerCAmelCase					:							Optional[int]	)			->				Tuple:
         lowercase     :					Tuple 		=      tmp_path_factory.mktemp('data'	) / f'''test.json.{extension}'''
         lowercase     :					Union[str, Any] 		=      str(shared_datadir / f'''test_file.json.{extension}'''	)
         JsonDatasetWriter(UpperCamelCase_,   UpperCamelCase_,   compression=UpperCamelCase_	).write()

         with fsspec.open(UpperCamelCase_,   'rb',   compression='infer'	) as f:
               lowercase     :					Dict 		=      f.read()
         with fsspec.open(UpperCamelCase_,   'rb',   compression='infer'	) as f:
               lowercase     :					int 		=      f.read()
         assert exported_content == original_content




'''simple docstring'''
from scipy.stats import pearsonr

import datasets


__snake_case							      =     '''
Pearson correlation coefficient and p-value for testing non-correlation.
The 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.
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.
'''


__snake_case							      =     '''
Args:
    predictions (`list` of `int`): Predicted class labels, as returned by a model.
    references (`list` of `int`): Ground truth labels.
    return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.

Returns:
    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.
    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.

Examples:

    Example 1-A simple example using only predictions and references.
        >>> pearsonr_metric = datasets.load_metric("pearsonr")
        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])
        >>> print(round(results[\'pearsonr\'], 2))
        -0.74

    Example 2-The same as Example 1, but that also returns the `p-value`.
        >>> pearsonr_metric = datasets.load_metric("pearsonr")
        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)
        >>> print(sorted(list(results.keys())))
        [\'p-value\', \'pearsonr\']
        >>> print(round(results[\'pearsonr\'], 2))
        -0.74
        >>> print(round(results[\'p-value\'], 2))
        0.15
'''


__snake_case							      =     '''
@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, Ilhan 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, Antonio 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    lowercase	(							datasets.Metric					):

		"""simple docstring"""

		def     lowerCAmelCase__				(		self							):

							'''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    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_=False							):

							'''simple docstring'''


							if return_pvalue:
												UpperCamelCase__   :Any												= pearsonr(UpperCamelCase_    ,   UpperCamelCase_							)
												return {"pearsonr": results[0], "p-value": results[1]}
							else:
												return {"pearsonr": float(pearsonr(UpperCamelCase_    ,   UpperCamelCase_							)[0]							)}