





import time
from dataclasses import dataclass
from multiprocessing import Pool
from unittest import TestCase
from unittest.mock import patch

import multiprocess
import numpy as np
import pytest

from datasets.utils.py_utils import (
    NestedDataStructure,
    asdict,
    iflatmap_unordered,
    map_nested,
    temp_seed,
    temporary_assignment,
    zip_dict,
)

from .utils import require_tf, require_torch




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	)       ->     Any:  # picklable for multiprocessing
  return x.sum()




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	)       ->     str:  # picklable for multiprocessing
  return i + 1
@dataclass
class        SCREAMING_SNAKE_CASE     :
   _UpperCamelCase					:	int
   _UpperCamelCase					:	str






class        SCREAMING_SNAKE_CASE     (UpperCAmelCase   ):


   def  SCREAMING_SNAKE_CASE_							(					self    :       int )->     Optional[Any]:





     """simple docstring"""







     lowercase__			    =						{}
     lowercase__			    =						[]
     lowercase__			    =						1
     lowercase__			    =						[1, 2]
     lowercase__			    =						{'a': 1, 'b': 2}
     lowercase__			    =						{'a': [1, 2], 'b': [3, 4]}
     lowercase__			    =						{'a': {'1': 1}, 'b': 2}
     lowercase__			    =						{'a': 1, 'b': 2, 'c': 3, 'd': 4}
     lowercase__			    =						{}
     lowercase__			    =						[]
     lowercase__			    =						2
     lowercase__			    =						[2, 3]
     lowercase__			    =						{'a': 2, 'b': 3}
     lowercase__			    =						{'a': [2, 3], 'b': [4, 5]}
     lowercase__			    =						{'a': {'1': 2}, 'b': 3}
     lowercase__			    =						{'a': 2, 'b': 3, 'c': 4, 'd': 5}
     self.assertEqual(map_nested(a    ,  a )    ,  a )
     self.assertEqual(map_nested(a    ,  a )    ,  a )
     self.assertEqual(map_nested(a    ,  a )    ,  a )
     self.assertEqual(map_nested(a    ,  a )    ,  a )
     self.assertEqual(map_nested(a    ,  a )    ,  a )
     self.assertEqual(map_nested(a    ,  a )    ,  a )
     self.assertEqual(map_nested(a    ,  a )    ,  a )
     self.assertEqual(map_nested(a    ,  a )    ,  a )

     lowercase__			    =						2
     self.assertEqual(map_nested(a    ,  a    ,  num_proc=a )    ,  a )
     self.assertEqual(map_nested(a    ,  a    ,  num_proc=a )    ,  a )
     self.assertEqual(map_nested(a    ,  a    ,  num_proc=a )    ,  a )
     self.assertEqual(map_nested(a    ,  a    ,  num_proc=a )    ,  a )
     self.assertEqual(map_nested(a    ,  a    ,  num_proc=a )    ,  a )
     self.assertEqual(map_nested(a    ,  a    ,  num_proc=a )    ,  a )
     self.assertEqual(map_nested(a    ,  a    ,  num_proc=a )    ,  a )
     self.assertEqual(map_nested(a    ,  a    ,  num_proc=a )    ,  a )

     lowercase__			    =						{'a': np.eye(2 ), 'b': np.zeros(3 ), 'c': np.ones(2 )}
     lowercase__			    =						{'a': 2, 'b': 0, 'c': 2}
     lowercase__			    =						{
         'a': np.eye(2 ).astype(a ),
         'b': np.zeros(3 ).astype(a ),
         'c': np.ones(2 ).astype(a ),
     }
     self.assertEqual(map_nested(a    ,  a    ,  map_numpy=a )    ,  a )
     self.assertEqual(
         {k: v.tolist() for k, v in map_nested(a    ,  a    ,  map_numpy=a ).items()}    ,  {k: v.tolist() for k, v in expected_map_nested_sna_int.items()}    ,  )
     self.assertEqual(map_nested(a    ,  a    ,  map_numpy=a    ,  num_proc=a )    ,  a )
     self.assertEqual(
         {k: v.tolist() for k, v in map_nested(a    ,  a    ,  map_numpy=a    ,  num_proc=a ).items()}    ,  {k: v.tolist() for k, v in expected_map_nested_sna_int.items()}    ,  )
     with self.assertRaises(a ):  # can't pickle a local lambda
       map_nested(lambda a : x + 1    ,  a    ,  num_proc=a )


   def  SCREAMING_SNAKE_CASE_							(					self    :       List[Any] )->     Any:





     """simple docstring"""







     lowercase__			    =						{'a': 1, 'b': 2}
     lowercase__			    =						{'a': 3, 'b': 4}
     lowercase__			    =						{'a': 5, 'b': 6}
     lowercase__			    =						sorted([('a', (1, 3, 5)), ('b', (2, 4, 6))] )
     self.assertEqual(sorted(zip_dict(a    ,  a    ,  a ) )    ,  a )


   def  SCREAMING_SNAKE_CASE_							(					self    :       Optional[Any] )->     int:





     """simple docstring"""







     class        SCREAMING_SNAKE_CASE     :
        _UpperCamelCase					:	Any				      = 'bar'






     lowercase__			    =						Foo()
     self.assertEqual(foo.my_attr    ,  'bar' )
     with temporary_assignment(a    ,  'my_attr'    ,  'BAR' ):
       self.assertEqual(foo.my_attr    ,  'BAR' )
     self.assertEqual(foo.my_attr    ,  'bar' )






@pytest.mark.parametrize(
    'iterable_length, num_proc, expected_num_proc'	,		[
        (1, None, 1),
        (1, 1, 1),
        (2, None, 1),
        (2, 1, 1),
        (2, 2, 1),
        (2, 3, 1),
        (3, 2, 1),
        (16, 16, 16),
        (16, 17, 16),
        (17, 16, 16),
    ]	,		)
def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	)       ->     Any:
  with patch('datasets.utils.py_utils._single_map_nested'	) as mock_single_map_nested, patch(
      'datasets.parallel.parallel.Pool'	) as mock_multiprocessing_pool:
    lowercase__			    =						{F"""{i}""": i for i in range(_SCREAMING_SNAKE_CASE	)}
    lowercase__			    =						map_nested(lambda _SCREAMING_SNAKE_CASE	: x + 10	,		_SCREAMING_SNAKE_CASE	,		num_proc=_SCREAMING_SNAKE_CASE	,		parallel_min_length=16	)
    if expected_num_proc == 1:
      assert mock_single_map_nested.called
      assert not mock_multiprocessing_pool.called
    else:
      assert not mock_single_map_nested.called
      assert mock_multiprocessing_pool.called
      assert mock_multiprocessing_pool.call_args[0][0] == expected_num_proc
class        SCREAMING_SNAKE_CASE     (UpperCAmelCase   ):


   @require_tf
   def  SCREAMING_SNAKE_CASE_							(					self    :       Tuple )->     str:





     """simple docstring"""







     import tensorflow as tf
     from tensorflow.keras import layers

     lowercase__			    =						layers.Dense(2 )

     def gen_random_output():
       lowercase__			    =						tf.random.uniform((1, 3) )
       return model(a ).numpy()

     with temp_seed(42    ,  set_tensorflow=a ):
       lowercase__			    =						gen_random_output()
     with temp_seed(42    ,  set_tensorflow=a ):
       lowercase__			    =						gen_random_output()
     lowercase__			    =						gen_random_output()

     np.testing.assert_equal(a    ,  a )
     self.assertGreater(np.abs(outa - outa ).sum()    ,  0 )


   @require_torch
   def  SCREAMING_SNAKE_CASE_							(					self    :       Tuple )->     Any:





     """simple docstring"""







     import torch

     def gen_random_output():
       lowercase__			    =						torch.nn.Linear(3    ,  2 )
       lowercase__			    =						torch.rand(1    ,  3 )
       return model(a ).detach().numpy()

     with temp_seed(42    ,  set_pytorch=a ):
       lowercase__			    =						gen_random_output()
     with temp_seed(42    ,  set_pytorch=a ):
       lowercase__			    =						gen_random_output()
     lowercase__			    =						gen_random_output()

     np.testing.assert_equal(a    ,  a )
     self.assertGreater(np.abs(outa - outa ).sum()    ,  0 )


   def  SCREAMING_SNAKE_CASE_							(					self    :       List[str] )->     Tuple:





     """simple docstring"""







     def gen_random_output():
       return np.random.rand(1    ,  3 )

     with temp_seed(42 ):
       lowercase__			    =						gen_random_output()
     with temp_seed(42 ):
       lowercase__			    =						gen_random_output()
     lowercase__			    =						gen_random_output()

     np.testing.assert_equal(a    ,  a )
     self.assertGreater(np.abs(outa - outa ).sum()    ,  0 )






@pytest.mark.parametrize('input_data'	,		[{}]	)
def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	)       ->     Any:
  lowercase__			    =						NestedDataStructure(_SCREAMING_SNAKE_CASE	).data
  assert output_data == input_data




@pytest.mark.parametrize(
    'data, expected_output'	,		[
        ({}, []),
        ([], []),
        ('foo', ['foo']),
        (['foo', 'bar'], ['foo', 'bar']),
        ([['foo', 'bar']], ['foo', 'bar']),
        ([[['foo'], ['bar']]], ['foo', 'bar']),
        ([[['foo'], 'bar']], ['foo', 'bar']),
        ({'a': 1, 'b': 2}, [1, 2]),
        ({'a': [1, 2], 'b': [3, 4]}, [1, 2, 3, 4]),
        ({'a': [[1, 2]], 'b': [[3, 4]]}, [1, 2, 3, 4]),
        ({'a': [[1, 2]], 'b': [3, 4]}, [1, 2, 3, 4]),
        ({'a': [[[1], [2]]], 'b': [[[3], [4]]]}, [1, 2, 3, 4]),
        ({'a': [[[1], [2]]], 'b': [[3, 4]]}, [1, 2, 3, 4]),
        ({'a': [[[1], [2]]], 'b': [3, 4]}, [1, 2, 3, 4]),
        ({'a': [[[1], [2]]], 'b': [3, [4]]}, [1, 2, 3, 4]),
        ({'a': {'1': 1}, 'b': 2}, [1, 2]),
        ({'a': {'1': [1]}, 'b': 2}, [1, 2]),
        ({'a': {'1': [1]}, 'b': [2]}, [1, 2]),
    ]	,		)
def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	)       ->     Optional[int]:
  lowercase__			    =						NestedDataStructure(_SCREAMING_SNAKE_CASE	).flatten()
  assert output == expected_output




def     __UpperCamelCase						()       ->     int:
  lowercase__			    =						A(x=1	,		y='foobar'	)
  lowercase__			    =						{'x': 1, 'y': 'foobar'}
  assert asdict(_SCREAMING_SNAKE_CASE	) == expected_output

  lowercase__			    =						{'a': {'b': A(x=10	,		y='foo'	)}, 'c': [A(x=20	,		y='bar'	)]}
  lowercase__			    =						{'a': {'b': {'x': 10, 'y': 'foo'}}, 'c': [{'x': 20, 'y': 'bar'}]}
  assert asdict(_SCREAMING_SNAKE_CASE	) == expected_output

  with pytest.raises(_SCREAMING_SNAKE_CASE	):
    asdict([1, A(x=10	,		y='foo'	)]	)




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	)       ->     Any:
  return text.split()




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	)       ->     Union[str, Any]:
  yield (time.time(), content)
  time.sleep(2	)
  yield (time.time(), content)




def     __UpperCamelCase						()       ->     Any:
  with Pool(2	) as pool:
    lowercase__			    =						list(iflatmap_unordered(_SCREAMING_SNAKE_CASE	,		_split_text	,		kwargs_iterable=[{'text': 'hello there'}] * 10	)	)
    assert out.count('hello'	) == 10
    assert out.count('there'	) == 10
    assert len(_SCREAMING_SNAKE_CASE	) == 20

  # check multiprocess from pathos (uses dill for pickling)
  with multiprocess.Pool(2	) as pool:
    lowercase__			    =						list(iflatmap_unordered(_SCREAMING_SNAKE_CASE	,		_split_text	,		kwargs_iterable=[{'text': 'hello there'}] * 10	)	)
    assert out.count('hello'	) == 10
    assert out.count('there'	) == 10
    assert len(_SCREAMING_SNAKE_CASE	) == 20

  # check that we get items as fast as possible
  with Pool(2	) as pool:
    lowercase__			    =						[]
    for yield_time, content in iflatmap_unordered(
        _SCREAMING_SNAKE_CASE	,		_aseconds_generator_of_aitems_with_timing	,		kwargs_iterable=[{'content': 'a'}, {'content': 'b'}]	):
      assert yield_time < time.time() + 0.1, "we should each item directly after it was yielded"
      out.append(_SCREAMING_SNAKE_CASE	)
    assert out.count('a'	) == 2
    assert out.count('b'	) == 2
    assert len(_SCREAMING_SNAKE_CASE	) == 4









from scipy.stats import spearmanr

import datasets


lowercase_					     =	"""
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.
"""

lowercase_					     =	"""
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
"""

lowercase_					     =	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        SCREAMING_SNAKE_CASE     (datasets.Metric   ):


   def  SCREAMING_SNAKE_CASE_							(					self    :       Union[str, Any] )->     Tuple:





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


   def  SCREAMING_SNAKE_CASE_							(					self    :       int    ,  a    :       str    ,  a    :       Any    ,  a    :       str=False )->     Optional[int]:





     """simple docstring"""







     lowercase__			    =						spearmanr(a    ,  a )
     if return_pvalue:
       return {"spearmanr": results[0], "spearmanr_pvalue": results[1]}
     else:
       return {"spearmanr": results[0]}


