import collections
import inspect
import unittest

from transformers import FocalNetConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
	import torch
	from torch import nn

	from transformers import (
	    FocalNetBackbone,
	    FocalNetForImageClassification,
	    FocalNetForMaskedImageModeling,
	    FocalNetModel,
	)
	from transformers.models.focalnet.modeling_focalnet import FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
	from PIL import Image

	from transformers import AutoImageProcessor

class        UpperCamelCase						:





						def __init__(self			,     __UpperCamelCase			,     __UpperCamelCase=13			,     __UpperCamelCase=32			,     __UpperCamelCase=2			,     __UpperCamelCase=3			,     __UpperCamelCase=16			,     __UpperCamelCase=[32, 64, 128]			,     __UpperCamelCase=[1, 2, 1]			,     __UpperCamelCase=[2, 2, 4]			,     __UpperCamelCase=2			,     __UpperCamelCase=2.0			,     __UpperCamelCase=True			,     __UpperCamelCase=0.0			,     __UpperCamelCase=0.0			,     __UpperCamelCase=0.1			,     __UpperCamelCase="gelu"			,     __UpperCamelCase=False			,     __UpperCamelCase=True			,     __UpperCamelCase=0.02			,     __UpperCamelCase=1E-5			,     __UpperCamelCase=True			,     __UpperCamelCase=None			,     __UpperCamelCase=True			,     __UpperCamelCase=10			,     __UpperCamelCase=8			,     __UpperCamelCase=["stage1", "stage2"]			,     __UpperCamelCase=[1, 2]			,     )				->				Union[str, Any]:
												UpperCamelCase_		:							Union[str, Any]  =		parent
												UpperCamelCase_		:							Tuple  =		batch_size
												UpperCamelCase_		:							Optional[int]  =		image_size
												UpperCamelCase_		:							Union[str, Any]  =		patch_size
												UpperCamelCase_		:							str  =		num_channels
												UpperCamelCase_		:							Tuple  =		embed_dim
												UpperCamelCase_		:							int  =		hidden_sizes
												UpperCamelCase_		:							Dict  =		depths
												UpperCamelCase_		:							Tuple  =		num_heads
												UpperCamelCase_		:							int  =		window_size
												UpperCamelCase_		:							List[str]  =		mlp_ratio
												UpperCamelCase_		:							List[str]  =		qkv_bias
												UpperCamelCase_		:							Optional[Any]  =		hidden_dropout_prob
												UpperCamelCase_		:							Union[str, Any]  =		attention_probs_dropout_prob
												UpperCamelCase_		:							str  =		drop_path_rate
												UpperCamelCase_		:							List[Any]  =		hidden_act
												UpperCamelCase_		:							List[Any]  =		use_absolute_embeddings
												UpperCamelCase_		:							List[Any]  =		patch_norm
												UpperCamelCase_		:							str  =		layer_norm_eps
												UpperCamelCase_		:							Tuple  =		initializer_range
												UpperCamelCase_		:							Any  =		is_training
												UpperCamelCase_		:							Any  =		scope
												UpperCamelCase_		:							Dict  =		use_labels
												UpperCamelCase_		:							Tuple  =		type_sequence_label_size
												UpperCamelCase_		:							Dict  =		encoder_stride
												UpperCamelCase_		:							int  =		out_features
												UpperCamelCase_		:							str  =		out_indices





						def        A_							(self						)				->				str:
												UpperCamelCase_		:							int  =		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

												UpperCamelCase_		:							List[Any]  =		None
												if self.use_labels:
																		UpperCamelCase_		:							int  =		ids_tensor([self.batch_size]			,     self.type_sequence_label_size						)

												UpperCamelCase_		:							str  =		self.get_config()

												return config, pixel_values, labels





						def        A_							(self						)				->				Optional[int]:
												return FocalNetConfig(
												    image_size=self.image_size			,     patch_size=self.patch_size			,     num_channels=self.num_channels			,     embed_dim=self.embed_dim			,     hidden_sizes=self.hidden_sizes			,     depths=self.depths			,     num_heads=self.num_heads			,     window_size=self.window_size			,     mlp_ratio=self.mlp_ratio			,     qkv_bias=self.qkv_bias			,     hidden_dropout_prob=self.hidden_dropout_prob			,     attention_probs_dropout_prob=self.attention_probs_dropout_prob			,     drop_path_rate=self.drop_path_rate			,     hidden_act=self.hidden_act			,     use_absolute_embeddings=self.use_absolute_embeddings			,     path_norm=self.patch_norm			,     layer_norm_eps=self.layer_norm_eps			,     initializer_range=self.initializer_range			,     encoder_stride=self.encoder_stride			,     out_features=self.out_features			,     out_indices=self.out_indices			,     )





						def        A_							(self			,     __UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase						)				->				Dict:
												UpperCamelCase_		:							Tuple  =		FocalNetModel(config=__UpperCamelCase						)
												model.to(__UpperCamelCase						)
												model.eval()
												UpperCamelCase_		:							int  =		model(__UpperCamelCase						)

												UpperCamelCase_		:							Union[str, Any]  =		((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths						) - 1))
												UpperCamelCase_		:							List[str]  =		int(config.embed_dim * 2 ** (len(config.depths						) - 1)						)

												self.parent.assertEqual(result.last_hidden_state.shape			,     (self.batch_size, expected_seq_len, expected_dim)						)





						def        A_							(self			,     __UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase						)				->				Union[str, Any]:
												UpperCamelCase_		:							Optional[Any]  =		FocalNetBackbone(config=__UpperCamelCase						)
												model.to(__UpperCamelCase						)
												model.eval()
												UpperCamelCase_		:							Tuple  =		model(__UpperCamelCase						)

												# verify feature maps
												self.parent.assertEqual(len(result.feature_maps						)			,     len(config.out_features						)						)
												self.parent.assertListEqual(list(result.feature_maps[0].shape						)			,     [self.batch_size, self.image_size, 8, 8]						)

												# verify channels
												self.parent.assertEqual(len(model.channels						)			,     len(config.out_features						)						)
												self.parent.assertListEqual(model.channels			,     config.hidden_sizes[:-1]						)

												# verify backbone works with out_features=None
												UpperCamelCase_		:							Tuple  =		None
												UpperCamelCase_		:							List[str]  =		FocalNetBackbone(config=__UpperCamelCase						)
												model.to(__UpperCamelCase						)
												model.eval()
												UpperCamelCase_		:							str  =		model(__UpperCamelCase						)

												# verify feature maps
												self.parent.assertEqual(len(result.feature_maps						)			,     1						)
												self.parent.assertListEqual(list(result.feature_maps[0].shape						)			,     [self.batch_size, self.image_size * 2, 4, 4]						)

												# verify channels
												self.parent.assertEqual(len(model.channels						)			,     1						)
												self.parent.assertListEqual(model.channels			,     [config.hidden_sizes[-1]]						)





						def        A_							(self			,     __UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase						)				->				Tuple:
												UpperCamelCase_		:							Any  =		FocalNetForMaskedImageModeling(config=__UpperCamelCase						)
												model.to(__UpperCamelCase						)
												model.eval()
												UpperCamelCase_		:							Optional[int]  =		model(__UpperCamelCase						)
												self.parent.assertEqual(
												    result.reconstruction.shape			,     (self.batch_size, self.num_channels, self.image_size, self.image_size)						)

												# test greyscale images
												UpperCamelCase_		:							List[Any]  =		1
												UpperCamelCase_		:							List[Any]  =		FocalNetForMaskedImageModeling(__UpperCamelCase						)
												model.to(__UpperCamelCase						)
												model.eval()

												UpperCamelCase_		:							Any  =		floats_tensor([self.batch_size, 1, self.image_size, self.image_size]						)
												UpperCamelCase_		:							Optional[int]  =		model(__UpperCamelCase						)
												self.parent.assertEqual(result.reconstruction.shape			,     (self.batch_size, 1, self.image_size, self.image_size)						)





						def        A_							(self			,     __UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase						)				->				Union[str, Any]:
												UpperCamelCase_		:							Tuple  =		self.type_sequence_label_size
												UpperCamelCase_		:							Dict  =		FocalNetForImageClassification(__UpperCamelCase						)
												model.to(__UpperCamelCase						)
												model.eval()
												UpperCamelCase_		:							Optional[Any]  =		model(__UpperCamelCase			,     labels=__UpperCamelCase						)
												self.parent.assertEqual(result.logits.shape			,     (self.batch_size, self.type_sequence_label_size)						)

												# test greyscale images
												UpperCamelCase_		:							Dict  =		1
												UpperCamelCase_		:							Union[str, Any]  =		FocalNetForImageClassification(__UpperCamelCase						)
												model.to(__UpperCamelCase						)
												model.eval()

												UpperCamelCase_		:							List[Any]  =		floats_tensor([self.batch_size, 1, self.image_size, self.image_size]						)
												UpperCamelCase_		:							List[Any]  =		model(__UpperCamelCase						)
												self.parent.assertEqual(result.logits.shape			,     (self.batch_size, self.type_sequence_label_size)						)





						def        A_							(self						)				->				List[Any]:
												UpperCamelCase_		:							Dict  =		self.prepare_config_and_inputs()

												UpperCamelCase_,UpperCamelCase_,UpperCamelCase_		:							int  =		config_and_inputs
												UpperCamelCase_		:							List[str]  =		{"""pixel_values""": pixel_values}
												return config, inputs_dict


@require_torch
class        UpperCamelCase						(				__a	,	__a	,	unittest.TestCase				):
						a__		:Any      =			(
						    (
						        FocalNetModel,
						        FocalNetForImageClassification,
						        FocalNetForMaskedImageModeling,
						        FocalNetBackbone,
						    )
						    if is_torch_available()
						    else ()
						)
						a__		:Dict      =			(
						    {'''feature-extraction''': FocalNetModel, '''image-classification''': FocalNetForImageClassification}
						    if is_torch_available()
						    else {}
						)
						a__		:Optional[Any]      =			False

						a__		:Optional[Any]      =			False
						a__		:Dict      =			False
						a__		:int      =			False
						a__		:Union[str, Any]      =			False





						def        A_							(self						)				->				Any:
												UpperCamelCase_		:							Tuple  =		FocalNetModelTester(self						)
												UpperCamelCase_		:							Optional[int]  =		ConfigTester(self			,     config_class=__UpperCamelCase			,     embed_dim=37			,     has_text_modality=__UpperCamelCase						)





						def        A_							(self						)				->				Optional[Any]:
												self.create_and_test_config_common_properties()
												self.config_tester.create_and_test_config_to_json_string()
												self.config_tester.create_and_test_config_to_json_file()
												self.config_tester.create_and_test_config_from_and_save_pretrained()
												self.config_tester.create_and_test_config_with_num_labels()
												self.config_tester.check_config_can_be_init_without_params()
												self.config_tester.check_config_arguments_init()





						def        A_							(self						)				->				Union[str, Any]:
												return





						def        A_							(self						)				->				List[str]:
												UpperCamelCase_		:							Union[str, Any]  =		self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*__UpperCamelCase						)





						def        A_							(self						)				->				str:
												UpperCamelCase_		:							Optional[Any]  =		self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_backbone(*__UpperCamelCase						)





						def        A_							(self						)				->				Any:
												UpperCamelCase_		:							List[str]  =		self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_masked_image_modeling(*__UpperCamelCase						)





						def        A_							(self						)				->				int:
												UpperCamelCase_		:							Dict  =		self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_image_classification(*__UpperCamelCase						)





						@unittest.skip(reason="""FocalNet does not use inputs_embeds"""						)
						def        A_							(self						)				->				Optional[int]:
												pass





						@unittest.skip(reason="""FocalNet does not use feedforward chunking"""						)
						def        A_							(self						)				->				Dict:
												pass





						def        A_							(self						)				->				int:
												UpperCamelCase_,UpperCamelCase_		:							List[str]  =		self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes[:-1]:
																		UpperCamelCase_		:							Dict  =		model_class(__UpperCamelCase						)
																		self.assertIsInstance(model.get_input_embeddings()			,     (nn.Module)						)
																		UpperCamelCase_		:							Union[str, Any]  =		model.get_output_embeddings()
																		self.assertTrue(x is None or isinstance(__UpperCamelCase			,     nn.Linear						)						)





						def        A_							(self						)				->				List[Any]:
												UpperCamelCase_,UpperCamelCase_		:							Optional[int]  =		self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes[:-1]:
																		UpperCamelCase_		:							Optional[Any]  =		model_class(__UpperCamelCase						)
																		UpperCamelCase_		:							Any  =		inspect.signature(model.forward						)
																		# signature.parameters is an OrderedDict => so arg_names order is deterministic
																		UpperCamelCase_		:							Dict  =		[*signature.parameters.keys()]

																		UpperCamelCase_		:							Dict  =		["""pixel_values"""]
																		self.assertListEqual(arg_names[:1]			,     __UpperCamelCase						)





						def        A_							(self			,     __UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase						)				->				Optional[Any]:
												UpperCamelCase_		:							Optional[Any]  =		model_class(__UpperCamelCase						)
												model.to(__UpperCamelCase						)
												model.eval()

												with torch.no_grad():
																		UpperCamelCase_		:							List[Any]  =		model(**self._prepare_for_class(__UpperCamelCase			,     __UpperCamelCase						)						)

												UpperCamelCase_		:							List[Any]  =		outputs.hidden_states

												UpperCamelCase_		:							str  =		getattr(
												    self.model_tester			,     """expected_num_hidden_layers"""			,     len(self.model_tester.depths						) + 1						)
												self.assertEqual(len(__UpperCamelCase						)			,     __UpperCamelCase						)

												# FocalNet has a different seq_length
												UpperCamelCase_		:							Optional[int]  =		(
												    config.patch_size
												    if isinstance(config.patch_size			,     collections.abc.Iterable						)
												    else (config.patch_size, config.patch_size)
												)

												UpperCamelCase_		:							Any  =		(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

												self.assertListEqual(
												    list(hidden_states[0].shape[-2:]						)			,     [num_patches, self.model_tester.embed_dim]			,     )

												UpperCamelCase_		:							Dict  =		outputs.reshaped_hidden_states
												self.assertEqual(len(__UpperCamelCase						)			,     __UpperCamelCase						)

												UpperCamelCase_,UpperCamelCase_,UpperCamelCase_,UpperCamelCase_		:							Optional[int]  =		reshaped_hidden_states[0].shape
												UpperCamelCase_		:							int  =		(
												    reshaped_hidden_states[0].view(__UpperCamelCase			,     __UpperCamelCase			,     height * width						).permute(0			,     2			,     1						)
												)
												self.assertListEqual(
												    list(reshaped_hidden_states.shape[-2:]						)			,     [num_patches, self.model_tester.embed_dim]			,     )





						def        A_							(self						)				->				str:
												UpperCamelCase_,UpperCamelCase_		:							int  =		self.model_tester.prepare_config_and_inputs_for_common()

												UpperCamelCase_		:							Dict  =		(
												    self.model_tester.image_size
												    if isinstance(self.model_tester.image_size			,     collections.abc.Iterable						)
												    else (self.model_tester.image_size, self.model_tester.image_size)
												)

												for model_class in self.all_model_classes[:-1]:
																		UpperCamelCase_		:							Optional[int]  =		True
																		self.check_hidden_states_output(__UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase						)

																		# check that output_hidden_states also work using config
																		del inputs_dict["output_hidden_states"]
																		UpperCamelCase_		:							Tuple  =		True

																		self.check_hidden_states_output(__UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase						)





						def        A_							(self						)				->				Any:
												UpperCamelCase_,UpperCamelCase_		:							str  =		self.model_tester.prepare_config_and_inputs_for_common()
												UpperCamelCase_		:							Optional[int]  =		3

												UpperCamelCase_		:							Union[str, Any]  =		(
												    self.model_tester.image_size
												    if isinstance(self.model_tester.image_size			,     collections.abc.Iterable						)
												    else (self.model_tester.image_size, self.model_tester.image_size)
												)
												UpperCamelCase_		:							int  =		(
												    config.patch_size
												    if isinstance(config.patch_size			,     collections.abc.Iterable						)
												    else (config.patch_size, config.patch_size)
												)

												UpperCamelCase_		:							List[Any]  =		image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
												UpperCamelCase_		:							Optional[Any]  =		image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

												for model_class in self.all_model_classes[:-1]:
																		UpperCamelCase_		:							int  =		True
																		self.check_hidden_states_output(__UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase			,     (padded_height, padded_width)						)

																		# check that output_hidden_states also work using config
																		del inputs_dict["output_hidden_states"]
																		UpperCamelCase_		:							List[str]  =		True
																		self.check_hidden_states_output(__UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase			,     (padded_height, padded_width)						)





						@slow
						def        A_							(self						)				->				List[str]:
												for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																		UpperCamelCase_		:							Optional[int]  =		FocalNetModel.from_pretrained(__UpperCamelCase						)
																		self.assertIsNotNone(__UpperCamelCase						)





						def        A_							(self						)				->				Dict:
												UpperCamelCase_,UpperCamelCase_		:							Optional[Any]  =		self.model_tester.prepare_config_and_inputs_for_common()

												UpperCamelCase_		:							Dict  =		_config_zero_init(__UpperCamelCase						)
												for model_class in self.all_model_classes:
																		UpperCamelCase_		:							Any  =		model_class(config=__UpperCamelCase						)
																		for name, param in model.named_parameters():
																								if "embeddings" not in name and param.requires_grad:
																														self.assertIn(
																														    ((param.data.mean() * 1E9).round() / 1E9).item()			,     [0.0, 1.0]			,     msg=f'''Parameter {name} of model {model_class} seems not properly initialized'''			,     )


@require_vision
@require_torch
class        UpperCamelCase						(				unittest.TestCase				):





						@cached_property
						def        A_							(self						)				->				Optional[int]:
												# TODO update organization
												return AutoImageProcessor.from_pretrained("""microsoft/focalnet-tiny"""						) if is_vision_available() else None





						@slow
						def        A_							(self						)				->				Optional[int]:
												UpperCamelCase_		:							Tuple  =		FocalNetForImageClassification.from_pretrained("""microsoft/focalnet-tiny"""						).to(__UpperCamelCase						)
												UpperCamelCase_		:							Dict  =		self.default_image_processor

												UpperCamelCase_		:							Optional[int]  =		Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""						)
												UpperCamelCase_		:							str  =		image_processor(images=__UpperCamelCase			,     return_tensors="""pt"""						).to(__UpperCamelCase						)

												# forward pass
												with torch.no_grad():
																		UpperCamelCase_		:							Any  =		model(**__UpperCamelCase						)

												# verify the logits
												UpperCamelCase_		:							Any  =		torch.Size((1, 1_000)						)
												self.assertEqual(outputs.logits.shape			,     __UpperCamelCase						)
												UpperCamelCase_		:							Optional[Any]  =		torch.tensor([0.2_166, -0.4_368, 0.2_191]						).to(__UpperCamelCase						)
												self.assertTrue(torch.allclose(outputs.logits[0, :3]			,     __UpperCamelCase			,     atol=1E-4						)						)
												self.assertTrue(outputs.logits.argmax(dim=-1						).item()			,     281						)


@require_torch
class        UpperCamelCase						(				__a	,	unittest.TestCase				):
						a__		:Tuple      =			(FocalNetBackbone,) if is_torch_available() else ()
						a__		:Tuple      =			FocalNetConfig

						a__		:Dict      =			False





						def        A_							(self						)				->				List[str]:
												UpperCamelCase_		:							Dict  =		FocalNetModelTester(self						)







import numpy as np

import datasets


SCREAMING_SNAKE_CASE		:     Optional[int]         =	"\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"

SCREAMING_SNAKE_CASE		:     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"

SCREAMING_SNAKE_CASE		:     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        UpperCamelCase						(				datasets.Metric				):





						def        A_							(self						)				->				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        A_							(self			,     __UpperCamelCase			,     __UpperCamelCase						)				->				int:
												# convert to numpy arrays
												UpperCamelCase_		:							int  =		np.array(__UpperCamelCase						)
												UpperCamelCase_		:							Union[str, 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
												UpperCamelCase_		:							str  =		X - np.mean(__UpperCamelCase						)
												UpperCamelCase_		:							Dict  =		np.cov(reference_distribution.T						)
												try:
																		UpperCamelCase_		:							str  =		np.linalg.inv(__UpperCamelCase						)
												except np.linalg.LinAlgError:
																		UpperCamelCase_		:							List[Any]  =		np.linalg.pinv(__UpperCamelCase						)
												UpperCamelCase_		:							Tuple  =		np.dot(__UpperCamelCase			,     __UpperCamelCase						)
												UpperCamelCase_		:							Tuple  =		np.dot(__UpperCamelCase			,     X_minus_mu.T						).diagonal()

												return {"mahalanobis": mahal_dist}






