


"""simple docstring"""





import numpy as np

import datasets


snake_case__						:   Dict			 = '''
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/]
'''

snake_case__						:   Union[str, Any]			 = '''\
@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}
}
'''

snake_case__						:   Any			 = '''
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 						snake_case_(				datasets.Metric	):






     def    lowerCamelCase__   (		self     :    List[str] ):
           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    lowerCamelCase__   (		self     :    Optional[int]    , UpperCamelCase_     :    Optional[int]    , UpperCamelCase_     :    int ):
           # convert to numpy arrays
           lowerCAmelCase    :		List[str]				=      np.array(UpperCamelCase_ )
           lowerCAmelCase    :		Optional[Any]				=      np.array(UpperCamelCase_ )

           # 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
           lowerCAmelCase    :		List[Any]				=      X - np.mean(UpperCamelCase_ )
           lowerCAmelCase    :		Union[str, Any]				=      np.cov(reference_distribution.T )
           try:
                 lowerCAmelCase    :		Dict				=      np.linalg.inv(UpperCamelCase_ )
           except np.linalg.LinAlgError:
                 lowerCAmelCase    :		List[str]				=      np.linalg.pinv(UpperCamelCase_ )
           lowerCAmelCase    :		Optional[int]				=      np.dot(UpperCamelCase_    , UpperCamelCase_ )
           lowerCAmelCase    :		Optional[Any]				=      np.dot(UpperCamelCase_    , X_minus_mu.T ).diagonal()

           return {"mahalanobis": mahal_dist}









"""simple docstring"""
import json
import os
import tempfile

from transformers.testing_utils import check_json_file_has_correct_format






class 					_UpperCAmelCase   :
					UpperCamelCase      =							None


					def 	lowerCamelCase       (					self			:List[Any]		):
												A		=  self.feature_extraction_class(**self.feat_extract_dict		)
												A		=  json.loads(feat_extract.to_json_string()		)
												for key, value in self.feat_extract_dict.items():
																			self.assertEqual(obj[key]     ,       __UpperCamelCase		)


					def 	lowerCamelCase       (					self			:Dict		):
												A		=  self.feature_extraction_class(**self.feat_extract_dict		)

												with tempfile.TemporaryDirectory() as tmpdirname:
																			A		=  os.path.join(__UpperCamelCase     ,       "feat_extract.json"		)
																			feat_extract_first.to_json_file(__UpperCamelCase		)
																			A		=  self.feature_extraction_class.from_json_file(__UpperCamelCase		)

												self.assertEqual(feat_extract_second.to_dict()     ,       feat_extract_first.to_dict()		)


					def 	lowerCamelCase       (					self			:Dict		):
												A		=  self.feature_extraction_class(**self.feat_extract_dict		)

												with tempfile.TemporaryDirectory() as tmpdirname:
																			A		=  feat_extract_first.save_pretrained(__UpperCamelCase		)[0]
																			check_json_file_has_correct_format(__UpperCamelCase		)
																			A		=  self.feature_extraction_class.from_pretrained(__UpperCamelCase		)

												self.assertEqual(feat_extract_second.to_dict()     ,       feat_extract_first.to_dict()		)


					def 	lowerCamelCase       (					self			:Tuple		):
												A		=  self.feature_extraction_class()
												self.assertIsNotNone(__UpperCamelCase		)


