





from scipy.stats import pearsonr

import datasets


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


lowercase      :       Any									=  """
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
"""


lowercase      :       Optional[int]									=  """
@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  A__    (							datasets.Metric	):




   """simple docstring"""



   def 							__lowercase		(					self)			->						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 							__lowercase		(					self					,  lowercase					,  lowercase					,  lowercase=False)			->						Tuple:







          '''simple docstring'''

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






'''simple docstring'''

from __future__ import annotations

import unittest

from transformers import EsmConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
     import numpy
     import tensorflow as tf

     from transformers.models.esm.modeling_tf_esm import (
         TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST,
         TFEsmForMaskedLM,
         TFEsmForSequenceClassification,
         TFEsmForTokenClassification,
         TFEsmModel,
     )





class      snake_case    :





  """simple docstring"""




  def __init__(    self			,  UpperCamelCase			,  ):







   """simple docstring"""
   lowerCamelCase_      =  parent
   lowerCamelCase_      =  13
   lowerCamelCase_      =  7
   lowerCamelCase_      =  True
   lowerCamelCase_      =  True
   lowerCamelCase_      =  True
   lowerCamelCase_      =  99
   lowerCamelCase_      =  32
   lowerCamelCase_      =  2
   lowerCamelCase_      =  4
   lowerCamelCase_      =  37
   lowerCamelCase_      =  "gelu"
   lowerCamelCase_      =  0.1
   lowerCamelCase_      =  0.1
   lowerCamelCase_      =  512
   lowerCamelCase_      =  16
   lowerCamelCase_      =  2
   lowerCamelCase_      =  0.02
   lowerCamelCase_      =  3
   lowerCamelCase_      =  4
   lowerCamelCase_      =  None






  def   snake_case		(    self     ):







   """simple docstring"""
   lowerCamelCase_      =  ids_tensor([self.batch_size, self.seq_length]			,  self.vocab_size     )

   lowerCamelCase_      =  None
   if self.use_input_mask:
    lowerCamelCase_      =  random_attention_mask([self.batch_size, self.seq_length]     )

   lowerCamelCase_      =  None
   lowerCamelCase_      =  None
   lowerCamelCase_      =  None
   if self.use_labels:
    lowerCamelCase_      =  ids_tensor([self.batch_size]			,  self.type_sequence_label_size     )
    lowerCamelCase_      =  ids_tensor([self.batch_size, self.seq_length]			,  self.num_labels     )
    lowerCamelCase_      =  ids_tensor([self.batch_size]			,  self.num_choices     )

   lowerCamelCase_      =  EsmConfig(
       vocab_size=self.vocab_size			,  hidden_size=self.hidden_size			,  num_hidden_layers=self.num_hidden_layers			,  pad_token_id=1			,  num_attention_heads=self.num_attention_heads			,  intermediate_size=self.intermediate_size			,  hidden_act=self.hidden_act			,  hidden_dropout_prob=self.hidden_dropout_prob			,  attention_probs_dropout_prob=self.attention_probs_dropout_prob			,  max_position_embeddings=self.max_position_embeddings			,  type_vocab_size=self.type_vocab_size			,  initializer_range=self.initializer_range			,  )

   return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels






  def   snake_case		(    self     ):







   """simple docstring"""
   (
       (
       lowerCamelCase_
   ) ,(
       lowerCamelCase_
   ) ,(
       lowerCamelCase_
   ) ,(
       lowerCamelCase_
   ) ,(
       lowerCamelCase_
   ) ,(
       lowerCamelCase_
   ) ,
   )      =  self.prepare_config_and_inputs()

   lowerCamelCase_      =  True
   lowerCamelCase_      =  floats_tensor([self.batch_size, self.seq_length, self.hidden_size]     )
   lowerCamelCase_      =  ids_tensor([self.batch_size, self.seq_length]			,  vocab_size=2     )

   return (
       config,
       input_ids,
       input_mask,
       sequence_labels,
       token_labels,
       choice_labels,
       encoder_hidden_states,
       encoder_attention_mask,
   )






  def   snake_case		(    self			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase     ):







   """simple docstring"""
   lowerCamelCase_      =  TFEsmModel(config=UpperCamelCase     )
   lowerCamelCase_      =  {"input_ids": input_ids, "attention_mask": input_mask}
   lowerCamelCase_      =  model(UpperCamelCase     )

   lowerCamelCase_      =  [input_ids, input_mask]
   lowerCamelCase_      =  model(UpperCamelCase     )

   lowerCamelCase_      =  model(UpperCamelCase     )

   self.parent.assertEqual(result.last_hidden_state.shape			,  (self.batch_size, self.seq_length, self.hidden_size)     )






  def   snake_case		(    self			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  ):







   """simple docstring"""
   lowerCamelCase_      =  True

   lowerCamelCase_      =  TFEsmModel(config=UpperCamelCase     )
   lowerCamelCase_      =  {
       "input_ids": input_ids,
       "attention_mask": input_mask,
       "encoder_hidden_states": encoder_hidden_states,
       "encoder_attention_mask": encoder_attention_mask,
   }
   lowerCamelCase_      =  model(UpperCamelCase     )

   lowerCamelCase_      =  [input_ids, input_mask]
   lowerCamelCase_      =  model(UpperCamelCase			,  encoder_hidden_states=UpperCamelCase     )

   # Also check the case where encoder outputs are not passed
   lowerCamelCase_      =  model(UpperCamelCase			,  attention_mask=UpperCamelCase     )

   self.parent.assertEqual(result.last_hidden_state.shape			,  (self.batch_size, self.seq_length, self.hidden_size)     )






  def   snake_case		(    self			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase     ):







   """simple docstring"""
   lowerCamelCase_      =  TFEsmForMaskedLM(config=UpperCamelCase     )
   lowerCamelCase_      =  model([input_ids, input_mask]     )
   self.parent.assertEqual(result.logits.shape			,  (self.batch_size, self.seq_length, self.vocab_size)     )






  def   snake_case		(    self			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase			,  UpperCamelCase     ):







   """simple docstring"""
   lowerCamelCase_      =  self.num_labels
   lowerCamelCase_      =  TFEsmForTokenClassification(config=UpperCamelCase     )
   lowerCamelCase_      =  {"input_ids": input_ids, "attention_mask": input_mask}
   lowerCamelCase_      =  model(UpperCamelCase     )
   self.parent.assertEqual(result.logits.shape			,  (self.batch_size, self.seq_length, self.num_labels)     )







  def   snake_case		(    self     ):







   """simple docstring"""
   lowerCamelCase_      =  self.prepare_config_and_inputs()
   (
       (
       lowerCamelCase_
   ) ,(
       lowerCamelCase_
   ) ,(
       lowerCamelCase_
   ) ,(
       lowerCamelCase_
   ) ,(
       lowerCamelCase_
   ) ,(
       lowerCamelCase_
   ) ,
   )      =  config_and_inputs
   lowerCamelCase_      =  {"input_ids": input_ids, "attention_mask": input_mask}
   return config, inputs_dict





@require_tf
class      snake_case    (    lowercase			,						lowercase			,						unittest.TestCase			):





  """simple docstring"""




  _lowerCamelCase		    =  (
      (
          TFEsmModel,
          TFEsmForMaskedLM,
          TFEsmForSequenceClassification,
          TFEsmForTokenClassification,
      )
      if is_tf_available()
      else ()
  )
  _lowerCamelCase		    =  (
      {
          "feature-extraction": TFEsmModel,
          "fill-mask": TFEsmForMaskedLM,
          "text-classification": TFEsmForSequenceClassification,
          "token-classification": TFEsmForTokenClassification,
          "zero-shot": TFEsmForSequenceClassification,
      }
      if is_tf_available()
      else {}
  )
  _lowerCamelCase		    =  False
  _lowerCamelCase		    =  False






  def   snake_case		(    self     ):







   """simple docstring"""
   lowerCamelCase_      =  TFEsmModelTester(self     )
   lowerCamelCase_      =  ConfigTester(self			,  config_class=UpperCamelCase			,  hidden_size=37     )






  def   snake_case		(    self     ):







   """simple docstring"""
   self.config_tester.run_common_tests()






  def   snake_case		(    self     ):







   """simple docstring"""
   lowerCamelCase_      =  self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*UpperCamelCase     )






  def   snake_case		(    self     ):







   """simple docstring"""
   lowerCamelCase_      =  self.model_tester.prepare_config_and_inputs_for_decoder()
   self.model_tester.create_and_check_model_as_decoder(*UpperCamelCase     )






  def   snake_case		(    self     ):







   """simple docstring"""
   lowerCamelCase_      =  self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_masked_lm(*UpperCamelCase     )






  def   snake_case		(    self     ):







   """simple docstring"""
   lowerCamelCase_      =  self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_token_classification(*UpperCamelCase     )






  @slow
  def   snake_case		(    self     ):







   """simple docstring"""
   for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
    lowerCamelCase_      =  TFEsmModel.from_pretrained(UpperCamelCase     )
    self.assertIsNotNone(UpperCamelCase     )






  @unittest.skip("Protein models do not support embedding resizing."     )
  def   snake_case		(    self     ):







   """simple docstring"""
   pass






  @unittest.skip("Protein models do not support embedding resizing."     )
  def   snake_case		(    self     ):







   """simple docstring"""
   pass







  def   snake_case		(    self     ):







   """simple docstring"""
   lowerCamelCase_ ,lowerCamelCase_      =  self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
    lowerCamelCase_      =  model_class(UpperCamelCase     )
    assert isinstance(model.get_input_embeddings()			,  tf.keras.layers.Layer     )
    if model_class is TFEsmForMaskedLM:
     # Output embedding test differs from the main test because they're a matrix, not a layer
     lowerCamelCase_      =  model.get_bias()
     assert isinstance(UpperCamelCase			,  UpperCamelCase     )
     for k, v in name.items():
      assert isinstance(UpperCamelCase			,  tf.Variable     )
    else:
     lowerCamelCase_      =  model.get_output_embeddings()
     assert x is None
     lowerCamelCase_      =  model.get_bias()
     assert name is None





@require_tf
class      snake_case    (    unittest.TestCase			):





  """simple docstring"""




  @slow
  def   snake_case		(    self     ):







   """simple docstring"""
   lowerCamelCase_      =  TFEsmForMaskedLM.from_pretrained("facebook/esm2_t6_8M_UR50D"     )

   lowerCamelCase_      =  tf.constant([[0, 1, 2, 3, 4, 5]]     )
   lowerCamelCase_      =  model(UpperCamelCase     )[0]
   lowerCamelCase_      =  [1, 6, 33]
   self.assertEqual(list(output.numpy().shape     )			,  UpperCamelCase     )
   # compare the actual values for a slice.
   lowerCamelCase_      =  tf.constant(
       [
           [
               [8.921_518, -10.589_814, -6.4_671_307],
               [-6.3_967_156, -13.911_377, -1.1_211_915],
               [-7.781_247, -13.951_557, -3.740_592],
           ]
       ]     )
   self.assertTrue(numpy.allclose(output[:, :3, :3].numpy()			,  expected_slice.numpy()			,  atol=1e-2     )     )







  @slow
  def   snake_case		(    self     ):







   """simple docstring"""
   lowerCamelCase_      =  TFEsmModel.from_pretrained("facebook/esm2_t6_8M_UR50D"     )

   lowerCamelCase_      =  tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]]     )
   lowerCamelCase_      =  model(UpperCamelCase     )[0]
   # compare the actual values for a slice.
   lowerCamelCase_      =  tf.constant(
       [
           [
               [0.14_443_092, 0.54_125_327, 0.3_247_739],
               [0.30_340_484, 0.00_526_676, 0.31_077_722],
               [0.32_278_043, -0.24_987_096, 0.3_414_628],
           ]
       ]     )
   self.assertTrue(numpy.allclose(output[:, :3, :3].numpy()			,  expected_slice.numpy()			,  atol=1e-4     )     )



