


import numpy as np

import datasets


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

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

a					  =     '\nArgs:\n    X: List of datapoints to be compared with the `reference_distribution`.\n    reference_distribution: List of datapoints from the reference distribution we want to compare to.\nReturns:\n    mahalanobis: The Mahalonobis distance for each datapoint in `X`.\nExamples:\n\n    >>> mahalanobis_metric = datasets.load_metric("mahalanobis")\n    >>> results = mahalanobis_metric.compute(reference_distribution=[[0, 1], [1, 0]], X=[[0, 1]])\n    >>> print(results)\n    {\'mahalanobis\': array([0.5])}\n'







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

					def   UpperCAmelCase__       (     self       :   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   UpperCAmelCase__       (     self       :   Any							,					UpperCamelCase__       :   Any							,					UpperCamelCase__       :   Union[str, Any]       ):






										'''simple docstring'''






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

										return {"mahalanobis": mahal_dist}






# Copyright 2022 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.

import argparse
import os
import platform

import numpy as np
import psutil
import torch

from accelerate import __version__ as version
from accelerate.commands.config import default_config_file, load_config_from_file

from ..utils import is_npu_available, is_xpu_available


def 			UpperCAmelCase_				(      UpperCAmelCase__=None  ):
					if subparsers is not None:
										lowercase_  							=			subparsers.add_parser("""env"""  )
					else:
										lowercase_  							=			argparse.ArgumentParser("""Accelerate env command"""  )

					parser.add_argument(
					    """--config_file"""						,							default=UpperCAmelCase__						,							help="""The config file to use for the default values in the launching script."""  )

					if subparsers is not None:
										parser.set_defaults(func=UpperCAmelCase__  )
					return parser


def 			UpperCAmelCase_				(      UpperCAmelCase__  ):
					lowercase_  							=			torch.__version__
					lowercase_  							=			torch.cuda.is_available()
					lowercase_  							=			is_xpu_available()
					lowercase_  							=			is_npu_available()

					lowercase_  							=			"""Not found"""
					# Get the default from the config file.
					if args.config_file is not None or os.path.isfile(UpperCAmelCase__  ):
										lowercase_  							=			load_config_from_file(args.config_file  ).to_dict()

					lowercase_  							=			{
					    """`Accelerate` version""": version,
					    """Platform""": platform.platform(),
					    """Python version""": platform.python_version(),
					    """Numpy version""": np.__version__,
					    """PyTorch version (GPU?)""": F'''{pt_version} ({pt_cuda_available})''',
					    """PyTorch XPU available""": str(UpperCAmelCase__  ),
					    """PyTorch NPU available""": str(UpperCAmelCase__  ),
					    """System RAM""": F'''{psutil.virtual_memory().total / 1_0_2_4 ** 3:.2f} GB''',
					}
					if pt_cuda_available:
										lowercase_  							=			torch.cuda.get_device_name()

					print("""\nCopy-and-paste the text below in your GitHub issue\n"""  )
					print("""\n""".join([F'''- {prop}: {val}''' for prop, val in info.items()]  )  )

					print("""- `Accelerate` default config:""" if args.config_file is None else """- `Accelerate` config passed:"""  )
					lowercase_  							=			(
					    """\n""".join([F'''\t- {prop}: {val}''' for prop, val in accelerate_config.items()]  )
					    if isinstance(UpperCAmelCase__						,							UpperCAmelCase__  )
					    else F'''\t{accelerate_config}'''
					)
					print(UpperCAmelCase__  )

					lowercase_  							=			accelerate_config

					return info


def 			UpperCAmelCase_				(      ):
					lowercase_  							=			env_command_parser()
					lowercase_  							=			parser.parse_args()
					env_command(UpperCAmelCase__  )
					return 0


if __name__ == "__main__":
							raise SystemExit(main())


