
import math
from dataclasses import dataclass
from typing import List, Optional, Tuple, Union

import numpy as np
import torch

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, logging, randn_tensor
from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin


lowerCamelCase__        =						logging.get_logger(__name__)  # pylint: disable=invalid-name







@dataclass
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->EulerDiscrete
class 	A__				(	_snake_case      ):
				lowercase            =    42
				lowercase            =    None






def 					lowerCAmelCase__     (    SCREAMING_SNAKE_CASE_			,				SCREAMING_SNAKE_CASE_=0.999			,				SCREAMING_SNAKE_CASE_="cosine"			,				)							->						Tuple:
			if alpha_transform_type == "cosine":

						def alpha_bar_fn(SCREAMING_SNAKE_CASE_	):
									return math.cos((t + 0.008) / 1.008 * math.pi / 2	) ** 2

			elif alpha_transform_type == "exp":

						def alpha_bar_fn(SCREAMING_SNAKE_CASE_	):
									return math.exp(t * -12.0	)

			else:
						raise ValueError(F'''Unsupported alpha_tranform_type: {alpha_transform_type}'''	)

			lowerCAmelCase__ : Tuple   =						[]
			for i in range(UpperCAmelCase_	):
						lowerCAmelCase__ : List[Any]   =						i / num_diffusion_timesteps
						lowerCAmelCase__ : str   =						(i + 1) / num_diffusion_timesteps
						betas.append(min(1 - alpha_bar_fn(UpperCAmelCase_	) / alpha_bar_fn(UpperCAmelCase_	)			,				UpperCAmelCase_	)	)
			return torch.tensor(UpperCAmelCase_			,				dtype=torch.floataa	)







class 	A__				(	_snake_case		,  _snake_case      ):
				lowercase            =    [e.name for e in KarrasDiffusionSchedulers]
				lowercase            =    1






				@register_to_config
				def __init__(		self   : Union[str, Any]       ,	a   : int = 1_000       ,	a   : float = 0.0_0_0_1       ,	a   : float = 0.0_2       ,	a   : str = "linear"       ,	a   : Optional[Union[np.ndarray, List[float]]] = None       ,	a   : str = "epsilon"       ,	a   : str = "linear"       ,	a   : Optional[bool] = False       ,	a   : str = "linspace"       ,	a   : int = 0       ,	):






							'''simple docstring'''







							if trained_betas is not None:
										lowerCAmelCase__ : List[str]   =						torch.tensor(lowercase_       ,	dtype=torch.floataa  )
							elif beta_schedule == "linear":
										lowerCAmelCase__ : Tuple   =						torch.linspace(lowercase_       ,	lowercase_       ,	lowercase_       ,	dtype=torch.floataa  )
							elif beta_schedule == "scaled_linear":
										# this schedule is very specific to the latent diffusion model.
										lowerCAmelCase__ : int   =						(
										    torch.linspace(beta_start**0.5       ,	beta_end**0.5       ,	lowercase_       ,	dtype=torch.floataa  ) ** 2
										)
							elif beta_schedule == "squaredcos_cap_v2":
										# Glide cosine schedule
										lowerCAmelCase__ : Tuple   =						betas_for_alpha_bar(lowercase_  )
							else:
										raise NotImplementedError(f'''{beta_schedule} does is not implemented for {self.__class__}'''  )

							lowerCAmelCase__ : List[str]   =						1.0 - self.betas
							lowerCAmelCase__ : str   =						torch.cumprod(self.alphas       ,	dim=0  )

							lowerCAmelCase__ : Optional[Any]   =						np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5  )
							lowerCAmelCase__ : int   =						np.concatenate([sigmas[::-1], [0.0]]  ).astype(np.floataa  )
							lowerCAmelCase__ : Optional[Any]   =						torch.from_numpy(lowercase_  )

							# setable values
							lowerCAmelCase__ : str   =						None
							lowerCAmelCase__ : List[Any]   =						np.linspace(0       ,	num_train_timesteps - 1       ,	lowercase_       ,	dtype=lowercase_  )[::-1].copy()
							lowerCAmelCase__ : Optional[Any]   =						torch.from_numpy(lowercase_  )
							lowerCAmelCase__ : List[str]   =						False
							lowerCAmelCase__ : Dict   =						use_karras_sigmas






				@property
				def 				_lowerCamelCase						(		self   : Tuple  ):






							'''simple docstring'''







							if self.config.timestep_spacing in ["linspace", "trailing"]:
										return self.sigmas.max()

							return (self.sigmas.max() ** 2 + 1) ** 0.5






				def 				_lowerCamelCase						(		self   : Tuple       ,	a   : torch.FloatTensor       ,	a   : Union[float, torch.FloatTensor]  ):






							'''simple docstring'''







							if isinstance(lowercase_       ,	torch.Tensor  ):
										lowerCAmelCase__ : int   =						timestep.to(self.timesteps.device  )
							lowerCAmelCase__ : List[str]   =						(self.timesteps == timestep).nonzero().item()
							lowerCAmelCase__ : Dict   =						self.sigmas[step_index]

							lowerCAmelCase__ : Tuple   =						sample / ((sigma**2 + 1) ** 0.5)

							lowerCAmelCase__ : List[Any]   =						True
							return sample






				def 				_lowerCamelCase						(		self   : Optional[int]       ,	a   : int       ,	a   : Union[str, torch.device] = None  ):






							'''simple docstring'''







							lowerCAmelCase__ : Optional[Any]   =						num_inference_steps

							# "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
							if self.config.timestep_spacing == "linspace":
										lowerCAmelCase__ : str   =						np.linspace(0       ,	self.config.num_train_timesteps - 1       ,	lowercase_       ,	dtype=lowercase_  )[
										    ::-1
										].copy()
							elif self.config.timestep_spacing == "leading":
										lowerCAmelCase__ : str   =						self.config.num_train_timesteps // self.num_inference_steps
										# creates integer timesteps by multiplying by ratio
										# casting to int to avoid issues when num_inference_step is power of 3
										lowerCAmelCase__ : Optional[int]   =						(np.arange(0       ,	lowercase_  ) * step_ratio).round()[::-1].copy().astype(lowercase_  )
										timesteps += self.config.steps_offset
							elif self.config.timestep_spacing == "trailing":
										lowerCAmelCase__ : int   =						self.config.num_train_timesteps / self.num_inference_steps
										# creates integer timesteps by multiplying by ratio
										# casting to int to avoid issues when num_inference_step is power of 3
										lowerCAmelCase__ : Any   =						(np.arange(self.config.num_train_timesteps       ,	0       ,	-step_ratio  )).round().copy().astype(lowercase_  )
										timesteps -= 1
							else:
										raise ValueError(
										    f'''{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.'''  )

							lowerCAmelCase__ : Optional[int]   =						np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5  )
							lowerCAmelCase__ : int   =						np.log(lowercase_  )

							if self.config.interpolation_type == "linear":
										lowerCAmelCase__ : Tuple   =						np.interp(lowercase_       ,	np.arange(0       ,	len(lowercase_  )  )       ,	lowercase_  )
							elif self.config.interpolation_type == "log_linear":
										lowerCAmelCase__ : List[str]   =						torch.linspace(np.log(sigmas[-1]  )       ,	np.log(sigmas[0]  )       ,	num_inference_steps + 1  ).exp()
							else:
										raise ValueError(
										    f'''{self.config.interpolation_type} is not implemented. Please specify interpolation_type to either'''
										    ' \'linear\' or \'log_linear\''  )

							if self.use_karras_sigmas:
										lowerCAmelCase__ : List[str]   =						self._convert_to_karras(in_sigmas=lowercase_       ,	num_inference_steps=self.num_inference_steps  )
										lowerCAmelCase__ : Any   =						np.array([self._sigma_to_t(lowercase_       ,	lowercase_  ) for sigma in sigmas]  )

							lowerCAmelCase__ : Tuple   =						np.concatenate([sigmas, [0.0]]  ).astype(np.floataa  )
							lowerCAmelCase__ : Optional[Any]   =						torch.from_numpy(lowercase_  ).to(device=lowercase_  )
							if str(lowercase_  ).startswith('mps'  ):
										# mps does not support float64
										lowerCAmelCase__ : Union[str, Any]   =						torch.from_numpy(lowercase_  ).to(lowercase_       ,	dtype=torch.floataa  )
							else:
										lowerCAmelCase__ : Dict   =						torch.from_numpy(lowercase_  ).to(device=lowercase_  )






				def 				_lowerCamelCase						(		self   : Optional[int]       ,	a   : Tuple       ,	a   : int  ):






							'''simple docstring'''







							lowerCAmelCase__ : Any   =						np.log(lowercase_  )

							# get distribution
							lowerCAmelCase__ : Dict   =						log_sigma - log_sigmas[:, np.newaxis]

							# get sigmas range
							lowerCAmelCase__ : List[str]   =						np.cumsum((dists >= 0)       ,	axis=0  ).argmax(axis=0  ).clip(max=log_sigmas.shape[0] - 2  )
							lowerCAmelCase__ : List[str]   =						low_idx + 1

							lowerCAmelCase__ : Any   =						log_sigmas[low_idx]
							lowerCAmelCase__ : int   =						log_sigmas[high_idx]

							# interpolate sigmas
							lowerCAmelCase__ : Optional[Any]   =						(low - log_sigma) / (low - high)
							lowerCAmelCase__ : str   =						np.clip(lowercase_       ,	0       ,	1  )

							# transform interpolation to time range
							lowerCAmelCase__ : Optional[int]   =						(1 - w) * low_idx + w * high_idx
							lowerCAmelCase__ : Dict   =						t.reshape(sigma.shape  )
							return t






				def 				_lowerCamelCase						(		self   : Tuple       ,	a   : torch.FloatTensor       ,	a   : Union[str, Any]  ):






							'''simple docstring'''







							lowerCAmelCase__ : float   =						in_sigmas[-1].item()
							lowerCAmelCase__ : float   =						in_sigmas[0].item()

							lowerCAmelCase__ : Any   =						7.0  # 7.0 is the value used in the paper
							lowerCAmelCase__ : Any   =						np.linspace(0       ,	1       ,	lowercase_  )
							lowerCAmelCase__ : Dict   =						sigma_min ** (1 / rho)
							lowerCAmelCase__ : int   =						sigma_max ** (1 / rho)
							lowerCAmelCase__ : List[str]   =						(max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
							return sigmas






				def 				_lowerCamelCase						(		self   : Tuple       ,	a   : torch.FloatTensor       ,	a   : Union[float, torch.FloatTensor]       ,	a   : torch.FloatTensor       ,	a   : float = 0.0       ,	a   : float = 0.0       ,	a   : float = float('inf'  )       ,	a   : float = 1.0       ,	a   : Optional[torch.Generator] = None       ,	a   : bool = True       ,	):






							'''simple docstring'''







							if (
							    isinstance(lowercase_       ,	lowercase_  )
							    or isinstance(lowercase_       ,	torch.IntTensor  )
							    or isinstance(lowercase_       ,	torch.LongTensor  )
							):
										raise ValueError(
										    (
										        'Passing integer indices (e.g. from `enumerate(timesteps)`) as timesteps to'
										        ' `EulerDiscreteScheduler.step()` is not supported. Make sure to pass'
										        ' one of the `scheduler.timesteps` as a timestep.'
										    )       ,	)

							if not self.is_scale_input_called:
										logger.warning(
										    'The `scale_model_input` function should be called before `step` to ensure correct denoising. '
										    'See `StableDiffusionPipeline` for a usage example.'  )

							if isinstance(lowercase_       ,	torch.Tensor  ):
										lowerCAmelCase__ : Tuple   =						timestep.to(self.timesteps.device  )

							lowerCAmelCase__ : List[Any]   =						(self.timesteps == timestep).nonzero().item()
							lowerCAmelCase__ : int   =						self.sigmas[step_index]

							lowerCAmelCase__ : Dict   =						min(s_churn / (len(self.sigmas  ) - 1)       ,	2**0.5 - 1  ) if s_tmin <= sigma <= s_tmax else 0.0

							lowerCAmelCase__ : Union[str, Any]   =						randn_tensor(
							    model_output.shape       ,	dtype=model_output.dtype       ,	device=model_output.device       ,	generator=lowercase_  )

							lowerCAmelCase__ : Any   =						noise * s_noise
							lowerCAmelCase__ : List[Any]   =						sigma * (gamma + 1)

							if gamma > 0:
										lowerCAmelCase__ : Dict   =						sample + eps * (sigma_hat**2 - sigma**2) ** 0.5

							# 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
							# NOTE: "original_sample" should not be an expected prediction_type but is left in for
							# backwards compatibility
							if self.config.prediction_type == "original_sample" or self.config.prediction_type == "sample":
										lowerCAmelCase__ : int   =						model_output
							elif self.config.prediction_type == "epsilon":
										lowerCAmelCase__ : Union[str, Any]   =						sample - sigma_hat * model_output
							elif self.config.prediction_type == "v_prediction":
										# * c_out + input * c_skip
										lowerCAmelCase__ : Union[str, Any]   =						model_output * (-sigma / (sigma**2 + 1) ** 0.5) + (sample / (sigma**2 + 1))
							else:
										raise ValueError(
										    f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`'''  )

							# 2. Convert to an ODE derivative
							lowerCAmelCase__ : Tuple   =						(sample - pred_original_sample) / sigma_hat

							lowerCAmelCase__ : str   =						self.sigmas[step_index + 1] - sigma_hat

							lowerCAmelCase__ : str   =						sample + derivative * dt

							if not return_dict:
										return (prev_sample,)

							return EulerDiscreteSchedulerOutput(prev_sample=lowercase_       ,	pred_original_sample=lowercase_  )






				def 				_lowerCamelCase						(		self   : Dict       ,	a   : torch.FloatTensor       ,	a   : torch.FloatTensor       ,	a   : torch.FloatTensor       ,	):






							'''simple docstring'''







							lowerCAmelCase__ : Any   =						self.sigmas.to(device=original_samples.device       ,	dtype=original_samples.dtype  )
							if original_samples.device.type == "mps" and torch.is_floating_point(lowercase_  ):
										# mps does not support float64
										lowerCAmelCase__ : Optional[int]   =						self.timesteps.to(original_samples.device       ,	dtype=torch.floataa  )
										lowerCAmelCase__ : Dict   =						timesteps.to(original_samples.device       ,	dtype=torch.floataa  )
							else:
										lowerCAmelCase__ : Union[str, Any]   =						self.timesteps.to(original_samples.device  )
										lowerCAmelCase__ : Tuple   =						timesteps.to(original_samples.device  )

							lowerCAmelCase__ : Union[str, Any]   =						[(schedule_timesteps == t).nonzero().item() for t in timesteps]

							lowerCAmelCase__ : List[str]   =						sigmas[step_indices].flatten()
							while len(sigma.shape  ) < len(original_samples.shape  ):
										lowerCAmelCase__ : List[Any]   =						sigma.unsqueeze(-1  )

							lowerCAmelCase__ : Union[str, Any]   =						original_samples + noise * sigma
							return noisy_samples






				def __len__(		self   : Tuple  ):






							'''simple docstring'''







							return self.config.num_train_timesteps


'''simple docstring'''

from __future__ import annotations

from collections.abc import Callable




def  UpperCamelCase(	UpperCAmelCase_    ,			UpperCAmelCase_    ,			UpperCAmelCase_    ,			UpperCAmelCase_ = 1_00    ,			):
 UpperCAmelCase			:      Any		   =					x_start
 UpperCAmelCase			:      int		   =					fnc(UpperCAmelCase_      )
 UpperCAmelCase			:      str		   =					0.0

 for _ in range(UpperCAmelCase_      ):
  # Approximates small segments of curve as linear and solve
  # for trapezoidal area
  UpperCAmelCase			:      List[Any]		   =					(x_end - x_start) / steps + xa
  UpperCAmelCase			:      int		   =					fnc(UpperCAmelCase_      )
  area += abs(fxa + fxa      ) * (xa - xa) / 2

  # Increment step
  UpperCAmelCase			:      List[str]		   =					xa
  UpperCAmelCase			:      List[Any]		   =					fxa
 return area


if __name__ == "__main__":




 def  UpperCamelCase(	UpperCAmelCase_      ):
  return x**3

 print("f(x) = x^3")
 print("The area between the curve, x = -10, x = 10 and the x axis is:")
 lowercase__            =     10
 while i <= 100000:
  lowercase__            =     trapezoidal_area(f, -5, 5, i)
  print(f'''with {i} steps: {area}''')
  i *= 10




