
import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
     import torch

if is_vision_available():
     from PIL import Image

     from transformers import PoolFormerImageProcessor



class       _snake_case   (	unittest.TestCase							):


 def __init__(					self					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_=7					,  SCREAMING_SNAKE_CASE_=3					,  SCREAMING_SNAKE_CASE_=30					,  SCREAMING_SNAKE_CASE_=4_00					,  SCREAMING_SNAKE_CASE_=True					,  SCREAMING_SNAKE_CASE_=None					,  SCREAMING_SNAKE_CASE_=0.9					,  SCREAMING_SNAKE_CASE_=None					,  SCREAMING_SNAKE_CASE_=True					,  SCREAMING_SNAKE_CASE_=[0.5, 0.5, 0.5]					,  SCREAMING_SNAKE_CASE_=[0.5, 0.5, 0.5]					,  ):


   '''simple docstring'''




   lowercase__  :   Dict    		=      size if size is not None else {"""shortest_edge""": 30}
   lowercase__  :   List[Any]    		=      crop_size if crop_size is not None else {"""height""": 30, """width""": 30}
   lowercase__  :   List[str]    		=      parent
   lowercase__  :   Tuple    		=      batch_size
   lowercase__  :   List[str]    		=      num_channels
   lowercase__  :   Optional[Any]    		=      min_resolution
   lowercase__  :   Tuple    		=      max_resolution
   lowercase__  :   str    		=      do_resize_and_center_crop
   lowercase__  :   Union[str, Any]    		=      size
   lowercase__  :   Tuple    		=      crop_pct
   lowercase__  :   List[str]    		=      crop_size
   lowercase__  :   Union[str, Any]    		=      do_normalize
   lowercase__  :   Optional[Any]    		=      image_mean
   lowercase__  :   int    		=      image_std



 def      lowercase__     (					self):


   '''simple docstring'''




   return {
       "size": self.size,
       "do_resize_and_center_crop": self.do_resize_and_center_crop,
       "crop_pct": self.crop_pct,
       "crop_size": self.crop_size,
       "do_normalize": self.do_normalize,
       "image_mean": self.image_mean,
       "image_std": self.image_std,
   }



@require_torch
@require_vision
class       _snake_case   (	UpperCAmelCase_  ,						unittest.TestCase							):
 __lowerCAmelCase  :     Any        =			PoolFormerImageProcessor if is_vision_available() else None


 def      lowercase__     (					self):


   '''simple docstring'''




   lowercase__  :   Union[str, Any]    		=      PoolFormerImageProcessingTester(self)


 @property
 def      lowercase__     (					self):


   '''simple docstring'''




   return self.image_processor_tester.prepare_image_processor_dict()


 def      lowercase__     (					self):


   '''simple docstring'''




   lowercase__  :   Dict    		=      self.image_processing_class(**self.image_processor_dict)
   self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_					,  """do_resize_and_center_crop"""))
   self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_					,  """size"""))
   self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_					,  """crop_pct"""))
   self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_					,  """do_normalize"""))
   self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_					,  """image_mean"""))
   self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_					,  """image_std"""))


 def      lowercase__     (					self):


   '''simple docstring'''




   lowercase__  :   Optional[int]    		=      self.image_processing_class.from_dict(self.image_processor_dict)
   self.assertEqual(image_processor.size					,  {"""shortest_edge""": 30})
   self.assertEqual(image_processor.crop_size					,  {"""height""": 30, """width""": 30})

   lowercase__  :   Optional[Any]    		=      self.image_processing_class.from_dict(self.image_processor_dict					,  size=42					,  crop_size=84)
   self.assertEqual(image_processor.size					,  {"""shortest_edge""": 42})
   self.assertEqual(image_processor.crop_size					,  {"""height""": 84, """width""": 84})


 def      lowercase__     (					self):


   '''simple docstring'''




   pass


 def      lowercase__     (					self):


   '''simple docstring'''




   lowercase__  :   List[str]    		=      self.image_processing_class(**self.image_processor_dict)
   # create random PIL images
   lowercase__  :   int    		=      prepare_image_inputs(self.image_processor_tester					,  equal_resolution=SCREAMING_SNAKE_CASE_)
   for image in image_inputs:
     self.assertIsInstance(SCREAMING_SNAKE_CASE_					,  Image.Image)

   # Test not batched input
   lowercase__  :   Tuple    		=      image_processing(image_inputs[0]					,  return_tensors="""pt""").pixel_values

   self.assertEqual(
       encoded_images.shape					,  (
           1,
           self.image_processor_tester.num_channels,
           self.image_processor_tester.crop_size["""height"""],
           self.image_processor_tester.crop_size["""width"""],
       )					,  )

   # Test batched
   lowercase__  :   str    		=      image_processing(SCREAMING_SNAKE_CASE_					,  return_tensors="""pt""").pixel_values
   self.assertEqual(
       encoded_images.shape					,  (
           self.image_processor_tester.batch_size,
           self.image_processor_tester.num_channels,
           self.image_processor_tester.crop_size["""height"""],
           self.image_processor_tester.crop_size["""width"""],
       )					,  )


 def      lowercase__     (					self):


   '''simple docstring'''




   lowercase__  :   List[Any]    		=      self.image_processing_class(**self.image_processor_dict)
   # create random numpy tensors
   lowercase__  :   Optional[int]    		=      prepare_image_inputs(self.image_processor_tester					,  equal_resolution=SCREAMING_SNAKE_CASE_					,  numpify=SCREAMING_SNAKE_CASE_)
   for image in image_inputs:
     self.assertIsInstance(SCREAMING_SNAKE_CASE_					,  np.ndarray)

   # Test not batched input
   lowercase__  :   Optional[int]    		=      image_processing(image_inputs[0]					,  return_tensors="""pt""").pixel_values
   self.assertEqual(
       encoded_images.shape					,  (
           1,
           self.image_processor_tester.num_channels,
           self.image_processor_tester.crop_size["""height"""],
           self.image_processor_tester.crop_size["""width"""],
       )					,  )

   # Test batched
   lowercase__  :   str    		=      image_processing(SCREAMING_SNAKE_CASE_					,  return_tensors="""pt""").pixel_values
   self.assertEqual(
       encoded_images.shape					,  (
           self.image_processor_tester.batch_size,
           self.image_processor_tester.num_channels,
           self.image_processor_tester.crop_size["""height"""],
           self.image_processor_tester.crop_size["""width"""],
       )					,  )



 def      lowercase__     (					self):


   '''simple docstring'''




   lowercase__  :   List[Any]    		=      self.image_processing_class(**self.image_processor_dict)
   # create random PyTorch tensors
   lowercase__  :   Optional[Any]    		=      prepare_image_inputs(self.image_processor_tester					,  equal_resolution=SCREAMING_SNAKE_CASE_					,  torchify=SCREAMING_SNAKE_CASE_)
   for image in image_inputs:
     self.assertIsInstance(SCREAMING_SNAKE_CASE_					,  torch.Tensor)

   # Test not batched input
   lowercase__  :   List[str]    		=      image_processing(image_inputs[0]					,  return_tensors="""pt""").pixel_values
   self.assertEqual(
       encoded_images.shape					,  (
           1,
           self.image_processor_tester.num_channels,
           self.image_processor_tester.crop_size["""height"""],
           self.image_processor_tester.crop_size["""width"""],
       )					,  )

   # Test batched
   lowercase__  :   str    		=      image_processing(SCREAMING_SNAKE_CASE_					,  return_tensors="""pt""").pixel_values
   self.assertEqual(
       encoded_images.shape					,  (
           self.image_processor_tester.batch_size,
           self.image_processor_tester.num_channels,
           self.image_processor_tester.crop_size["""height"""],
           self.image_processor_tester.crop_size["""width"""],
       )					,  )








from scipy.stats import spearmanr

import datasets


lowerCamelCase__    :		Union[str, 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.
"""

lowerCamelCase__    :		int          =   """
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
"""

lowerCamelCase__    :		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       _snake_case   (	datasets.Metric							):


 def      lowercase__     (					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.spearmanr.html"""]					,  )



 def      lowercase__     (					self					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_=False):


   '''simple docstring'''




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






