import numpy as np

import datasets


lowerCamelCase__  =					'''
Compute the Mahalanobis Distance

Mahalonobis distance is the distance between a point and a distribution.
And not between two distinct points. It is effectively a multivariate equivalent of the Euclidean distance.
It was introduced by Prof. P. C. Mahalanobis in 1936
and has been used in various statistical applications ever since
[source: https://www.machinelearningplus.com/statistics/mahalanobis-distance/]
'''

lowerCamelCase__  =					'''\
@article{de2000mahalanobis,
  title={The mahalanobis distance},
  author={De Maesschalck, Roy and Jouan-Rimbaud, Delphine and Massart, D{\'e}sir{\'e} L},
  journal={Chemometrics and intelligent laboratory systems},
  volume={50},
  number={1},
  pages={1--18},
  year={2000},
  publisher={Elsevier}
}
'''

lowerCamelCase__  =					'''
Args:
    X: List of datapoints to be compared with the `reference_distribution`.
    reference_distribution: List of datapoints from the reference distribution we want to compare to.
Returns:
    mahalanobis: The Mahalonobis distance for each datapoint in `X`.
Examples:

    >>> mahalanobis_metric = datasets.load_metric("mahalanobis")
    >>> results = mahalanobis_metric.compute(reference_distribution=[[0, 1], [1, 0]], X=[[0, 1]])
    >>> print(results)
    {\'mahalanobis\': array([0.5])}
'''




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



 '''simple docstring'''




 def 		__UpperCAmelCase				(		self				:   str)						->	List[Any]:


   """simple docstring"""







   return datasets.MetricInfo(
       description=_DESCRIPTION							, citation=_CITATION							, inputs_description=_KWARGS_DESCRIPTION							, features=datasets.Features(
           {
               "X": datasets.Sequence(datasets.Value("float"							, id="sequence")							, id="X"),
           })							, )







 def 		__UpperCAmelCase				(		self				:   str							, lowercase_				:   Dict							, lowercase_				:   Optional[Any])						->	Optional[Any]:


   """simple docstring"""







   _UpperCamelCase           =    np.array(lowercase_)
   _UpperCamelCase           =    np.array(lowercase_)

   # Assert that arrays are 2D
   if len(X.shape) != 2:
     raise ValueError("Expected `X` to be a 2D vector")
   if len(reference_distribution.shape) != 2:
     raise ValueError("Expected `reference_distribution` to be a 2D vector")
   if reference_distribution.shape[0] < 2:
     raise ValueError(
         "Expected `reference_distribution` to be a 2D vector with more than one element in the first dimension")

   # Get mahalanobis distance for each prediction
   _UpperCamelCase           =    X - np.mean(lowercase_)
   _UpperCamelCase           =    np.cov(reference_distribution.T)
   try:
     _UpperCamelCase           =    np.linalg.inv(lowercase_)
   except np.linalg.LinAlgError:
     _UpperCamelCase           =    np.linalg.pinv(lowercase_)
   _UpperCamelCase           =    np.dot(lowercase_							, lowercase_)
   _UpperCamelCase           =    np.dot(lowercase_							, X_minus_mu.T).diagonal()

   return {"mahalanobis": mahal_dist}





import time
import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_torch, torch_device

from ..test_modeling_common import ids_tensor


if is_torch_available():
   import torch

   from transformers.generation import (
       MaxLengthCriteria,
       MaxNewTokensCriteria,
       MaxTimeCriteria,
       StoppingCriteriaList,
       validate_stopping_criteria,
   )




@require_torch
class 					_UpperCAmelCase			(     unittest.TestCase  ):



 '''simple docstring'''




 def 		__UpperCAmelCase				(		self				:   List[Any]							, lowercase_				:   Dict)						->	Optional[Any]:


   """simple docstring"""







   _UpperCamelCase           =    3
   _UpperCamelCase           =    250

   _UpperCamelCase           =    ids_tensor((batch_size, length)							, lowercase_)
   _UpperCamelCase           =    torch.ones((batch_size, length)							, device=lowercase_							, dtype=torch.float) / length
   return input_ids, scores







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


   """simple docstring"""







   _UpperCamelCase      ,						_UpperCamelCase           =    self._get_tensors(5)

   _UpperCamelCase           =    StoppingCriteriaList(
       [
           MaxLengthCriteria(max_length=10),
           MaxTimeCriteria(max_time=0.1),
       ])

   self.assertFalse(criteria(lowercase_							, lowercase_))

   _UpperCamelCase      ,						_UpperCamelCase           =    self._get_tensors(9)
   self.assertFalse(criteria(lowercase_							, lowercase_))

   _UpperCamelCase      ,						_UpperCamelCase           =    self._get_tensors(10)
   self.assertTrue(criteria(lowercase_							, lowercase_))







 def 		__UpperCAmelCase				(		self				:   Tuple)						->	int:


   """simple docstring"""







   _UpperCamelCase           =    MaxLengthCriteria(max_length=10)

   _UpperCamelCase      ,						_UpperCamelCase           =    self._get_tensors(5)
   self.assertFalse(criteria(lowercase_							, lowercase_))

   _UpperCamelCase      ,						_UpperCamelCase           =    self._get_tensors(9)
   self.assertFalse(criteria(lowercase_							, lowercase_))

   _UpperCamelCase      ,						_UpperCamelCase           =    self._get_tensors(10)
   self.assertTrue(criteria(lowercase_							, lowercase_))







 def 		__UpperCAmelCase				(		self				:   Optional[int])						->	int:


   """simple docstring"""







   _UpperCamelCase           =    MaxNewTokensCriteria(start_length=5							, max_new_tokens=5)

   _UpperCamelCase      ,						_UpperCamelCase           =    self._get_tensors(5)
   self.assertFalse(criteria(lowercase_							, lowercase_))

   _UpperCamelCase      ,						_UpperCamelCase           =    self._get_tensors(9)
   self.assertFalse(criteria(lowercase_							, lowercase_))

   _UpperCamelCase      ,						_UpperCamelCase           =    self._get_tensors(10)
   self.assertTrue(criteria(lowercase_							, lowercase_))

   _UpperCamelCase           =    StoppingCriteriaList([criteria])
   self.assertEqual(criteria_list.max_length							, 10)







 def 		__UpperCAmelCase				(		self				:   int)						->	str:


   """simple docstring"""







   _UpperCamelCase      ,						_UpperCamelCase           =    self._get_tensors(5)

   _UpperCamelCase           =    MaxTimeCriteria(max_time=0.1)
   self.assertFalse(criteria(lowercase_							, lowercase_))

   _UpperCamelCase           =    MaxTimeCriteria(max_time=0.1							, initial_timestamp=time.time() - 0.2)
   self.assertTrue(criteria(lowercase_							, lowercase_))







 def 		__UpperCAmelCase				(		self				:   Optional[int])						->	Tuple:


   """simple docstring"""







   validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(10)])							, 10)

   with self.assertWarns(lowercase_):
     validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(10)])							, 11)

   _UpperCamelCase           =    validate_stopping_criteria(StoppingCriteriaList()							, 11)

   self.assertEqual(len(lowercase_)							, 1)




