



'''simple docstring'''





import numpy as np

import datasets


snake_case__					:     Union[str, Any]    		=   """
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__					:     List[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   _A   ( datasets.Metric	):


						'''simple docstring'''





						def     _snake_case	(	self	:							Optional[int]	):






							'''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     _snake_case	(	self	:							List[Any]							,      lowerCamelCase	:							Any							,      lowerCamelCase	:							Tuple	):






							'''simple docstring'''



							__lowercase		       =			np.array(lowerCamelCase	)
							__lowercase		       =			np.array(lowerCamelCase	)

							# 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
							__lowercase		       =			X - np.mean(lowerCamelCase	)
							__lowercase		       =			np.cov(reference_distribution.T	)
							try:
								__lowercase		       =			np.linalg.inv(lowerCamelCase	)
							except np.linalg.LinAlgError:
								__lowercase		       =			np.linalg.pinv(lowerCamelCase	)
							__lowercase		       =			np.dot(lowerCamelCase							,      lowerCamelCase	)
							__lowercase		       =			np.dot(lowerCamelCase							,      X_minus_mu.T	).diagonal()

							return {"mahalanobis": mahal_dist}








# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


snake_case__					:     List[str]    		=   {
    """configuration_mgp_str""": ["""MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MgpstrConfig"""],
    """processing_mgp_str""": ["""MgpstrProcessor"""],
    """tokenization_mgp_str""": ["""MgpstrTokenizer"""],
}

try:
	if not is_torch_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	snake_case__					:     Dict    		=   [
	    """MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST""",
	    """MgpstrModel""",
	    """MgpstrPreTrainedModel""",
	    """MgpstrForSceneTextRecognition""",
	]

if TYPE_CHECKING:
	from .configuration_mgp_str import MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP, MgpstrConfig
	from .processing_mgp_str import MgpstrProcessor
	from .tokenization_mgp_str import MgpstrTokenizer

	try:
		if not is_torch_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_mgp_str import (
		    MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST,
		    MgpstrForSceneTextRecognition,
		    MgpstrModel,
		    MgpstrPreTrainedModel,
		)
else:
	import sys

	snake_case__					:     Union[str, Any]    		=   _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)



