






"""simple docstring"""



import numpy as np

import datasets


A_    =							'''
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/]
'''

A_    =							'''\
@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}
}
'''

A_    =							'''
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 							__SCREAMING_SNAKE_CASE						(				datasets.Metric		):


							def 						_UpperCamelCase       (			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 						_UpperCamelCase       (			self      :						int			,    snake_case      :						int			,    snake_case      :						List[Any]							):
													'''simple docstring'''





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

													return {"mahalanobis": mahal_dist}







"""simple docstring"""



from typing import List, Optional, Tuple, Union

import torch

from ...models import UNetaDModel
from ...schedulers import KarrasVeScheduler
from ...utils import randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput






class 							__SCREAMING_SNAKE_CASE						(				UpperCamelCase		):
							snake_case_     =							42
							snake_case_     =							42


							def __init__(			self      :						Union[str, Any]			,    snake_case      :						UNetaDModel			,    snake_case      :						KarrasVeScheduler							):
													'''simple docstring'''





													super().__init__()
													self.register_modules(unet=snake_case			,    scheduler=snake_case							)


							@torch.no_grad()
							def __call__(			self      :						Any			,    snake_case      :						int = 1			,    snake_case      :						int = 50			,    snake_case      :						Optional[Union[torch.Generator, List[torch.Generator]]] = None			,    snake_case      :						Optional[str] = "pil"			,    snake_case      :						bool = True			,    **snake_case      :						Dict			,    ):
													'''simple docstring'''





													A__						:  Optional[int]		  =  self.unet.config.sample_size
													A__						:  Dict		  =  (batch_size, 3, img_size, img_size)

													A__						:  Tuple		  =  self.unet

													# sample x_0 ~ N(0, sigma_0^2 * I)
													A__						:  Union[str, Any]		  =  randn_tensor(snake_case			,    generator=snake_case			,    device=self.device							) * self.scheduler.init_noise_sigma

													self.scheduler.set_timesteps(snake_case							)

													for t in self.progress_bar(self.scheduler.timesteps							):
																			# here sigma_t == t_i from the paper
																			A__						:  Optional[Any]		  =  self.scheduler.schedule[t]
																			A__						:  Union[str, Any]		  =  self.scheduler.schedule[t - 1] if t > 0 else 0

																			# 1. Select temporarily increased noise level sigma_hat
																			# 2. Add new noise to move from sample_i to sample_hat
																			A__  ,  A__						:  Dict		  =  self.scheduler.add_noise_to_input(snake_case			,    snake_case			,    generator=snake_case							)

																			# 3. Predict the noise residual given the noise magnitude `sigma_hat`
																			# The model inputs and output are adjusted by following eq. (213) in [1].
																			A__						:  int		  =  (sigma_hat / 2) * model((sample_hat + 1) / 2			,    sigma_hat / 2							).sample

																			# 4. Evaluate dx/dt at sigma_hat
																			# 5. Take Euler step from sigma to sigma_prev
																			A__						:  Tuple		  =  self.scheduler.step(snake_case			,    snake_case			,    snake_case			,    snake_case							)

																			if sigma_prev != 0:
																									# 6. Apply 2nd order correction
																									# The model inputs and output are adjusted by following eq. (213) in [1].
																									A__						:  Dict		  =  (sigma_prev / 2) * model((step_output.prev_sample + 1) / 2			,    sigma_prev / 2							).sample
																									A__						:  Tuple		  =  self.scheduler.step_correct(
																									    snake_case			,    snake_case			,    snake_case			,    snake_case			,    step_output.prev_sample			,    step_output["""derivative"""]			,    )
																			A__						:  Tuple		  =  step_output.prev_sample

													A__						:  Dict		  =  (sample / 2 + 0.5).clamp(0			,    1							)
													A__						:  Dict		  =  sample.cpu().permute(0			,    2			,    3			,    1							).numpy()
													if output_type == "pil":
																			A__						:  Optional[Any]		  =  self.numpy_to_pil(snake_case							)

													if not return_dict:
																			return (image,)

													return ImagePipelineOutput(images=snake_case							)






