



'''simple docstring'''






import numpy as np

import datasets


A_							: str						 =	"\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_							: Dict						 =	"\\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_							: List[str]						 =	"\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 							lowercase       (  datasets.Metric				):


 """simple docstring"""


 def _snake_case (							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 _snake_case (							self  ,a_  ,a_							)		->   int:
        _UpperCAmelCase  :						Union[str, Any]			     = np.array(a_							)
        _UpperCAmelCase  :						Optional[Any]			     = np.array(a_							)

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

        return {"mahalanobis": mahal_dist}









import importlib
import sys
from argparse import REMAINDER, ArgumentParser
from pathlib import Path

import torch_xla.distributed.xla_multiprocessing as xmp





def 		__A		(	)      ->       Any:
	a										=							ArgumentParser(
	    description=(
	        """PyTorch TPU distributed training launch """
	        """helper utility that will spawn up """
	        """multiple distributed processes"""
	    )    )

	# Optional arguments for the launch helper
	parser.add_argument("""--num_cores"""							,			type=__lowerCamelCase							,			default=1							,			help="""Number of TPU cores to use (1 or 8)."""    )

	# positional
	parser.add_argument(
	    """training_script"""							,			type=__lowerCamelCase							,			help=(
	        """The full path to the single TPU training """
	        """program/script to be launched in parallel, """
	        """followed by all the arguments for the """
	        """training script"""
	    )							,			)

	# rest from the training program
	parser.add_argument("""training_script_args"""							,			nargs=__lowerCamelCase    )

	return parser.parse_args()





def 		__A		(	)      ->       Union[str, Any]:
	a										=							parse_args()

	# Import training_script as a module.
	a										=							Path(args.training_script    )
	sys.path.append(str(script_fpath.parent.resolve()    )    )
	a										=							script_fpath.stem
	a										=							importlib.import_module(__lowerCamelCase    )

	# Patch sys.argv
	a										=							[args.training_script] + args.training_script_args + ["""--tpu_num_cores""", str(args.num_cores    )]
	xmp.spawn(mod._mp_fn							,			args=()							,			nprocs=args.num_cores    )


if __name__ == "__main__":
		main()

