
"""simple docstring"""

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


SCREAMING_SNAKE_CASE_			    =  logging.get_logger(__name__)  # pylint: disable=invalid-name
@dataclass
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->EulerAncestralDiscrete
class    _UpperCAmelCase							(						SCREAMING_SNAKE_CASE_							):
      __SCREAMING_SNAKE_CASE      :							torch.FloatTensor
      __SCREAMING_SNAKE_CASE      :							Optional[torch.FloatTensor]												=		None




def 			lowercase__  (    lowerCAmelCase :    List[str]       , lowerCAmelCase :    Union[str, Any]=0.999       , lowerCAmelCase :    Optional[Any]="cosine"       , )       ->					int:






    """simple docstring"""




    if alpha_transform_type == "cosine":

        def alpha_bar_fn(lowerCAmelCase :    List[Any]       ):
            return math.cos((t + 0.008) / 1.008 * math.pi / 2       ) ** 2

    elif alpha_transform_type == "exp":

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

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

    UpperCAmelCase  	=    []
    for i in range(lowerCAmelCase       ):
        UpperCAmelCase  	=    i / num_diffusion_timesteps
        UpperCAmelCase  	=    (i + 1) / num_diffusion_timesteps
        betas.append(min(1 - alpha_bar_fn(lowerCAmelCase       ) / alpha_bar_fn(lowerCAmelCase       )       , lowerCAmelCase       )       )
    return torch.tensor(lowerCAmelCase       , dtype=torch.floataa       )







class    _UpperCAmelCase							(						SCREAMING_SNAKE_CASE_   ,	SCREAMING_SNAKE_CASE_							):
      __SCREAMING_SNAKE_CASE      :							Optional[Any]												=		[e.name for e in KarrasDiffusionSchedulers]
      __SCREAMING_SNAKE_CASE      :							Dict												=		1




      @register_to_config
      def __init__(							self      ,				lowercase_ = 1_0_0_0      ,				lowercase_ = 0.0_0_0_1      ,				lowercase_ = 0.0_2      ,				lowercase_ = "linear"      ,				lowercase_ = None      ,				lowercase_ = "epsilon"      ,				lowercase_ = "linspace"      ,				lowercase_ = 0      ,				)  ->    Optional[Any]:
          if trained_betas is not None:
              UpperCAmelCase  	=    torch.tensor(lowercase_      ,				dtype=torch.floataa							)
          elif beta_schedule == "linear":
              UpperCAmelCase  	=    torch.linspace(lowercase_      ,				lowercase_      ,				lowercase_      ,				dtype=torch.floataa							)
          elif beta_schedule == "scaled_linear":
              # this schedule is very specific to the latent diffusion model.
              UpperCAmelCase  	=    (
                  torch.linspace(beta_start**0.5      ,				beta_end**0.5      ,				lowercase_      ,				dtype=torch.floataa							) ** 2
              )
          elif beta_schedule == "squaredcos_cap_v2":
              # Glide cosine schedule
              UpperCAmelCase  	=    betas_for_alpha_bar(lowercase_							)
          else:
              raise NotImplementedError(F"{beta_schedule} does is not implemented for {self.__class__}"							)

          UpperCAmelCase  	=    1.0 - self.betas
          UpperCAmelCase  	=    torch.cumprod(self.alphas      ,				dim=0							)

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

          # setable values
          UpperCAmelCase  	=    None
          UpperCAmelCase  	=    np.linspace(0      ,				num_train_timesteps - 1      ,				lowercase_      ,				dtype=lowercase_							)[::-1].copy()
          UpperCAmelCase  	=    torch.from_numpy(lowercase_							)
          UpperCAmelCase  	=    False




      @property
      def 			a_					(							self							)  ->    Tuple:
          # standard deviation of the initial noise distribution
          if self.config.timestep_spacing in ["linspace", "trailing"]:
              return self.sigmas.max()

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




      def 			a_					(							self      ,				lowercase_      ,				lowercase_							)  ->    torch.FloatTensor:
          if isinstance(lowercase_      ,				torch.Tensor							):
              UpperCAmelCase  	=    timestep.to(self.timesteps.device							)
          UpperCAmelCase  	=    (self.timesteps == timestep).nonzero().item()
          UpperCAmelCase  	=    self.sigmas[step_index]
          UpperCAmelCase  	=    sample / ((sigma**2 + 1) ** 0.5)
          UpperCAmelCase  	=    True
          return sample




      def 			a_					(							self      ,				lowercase_      ,				lowercase_ = None							)  ->    Optional[Any]:
          UpperCAmelCase  	=    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":
              UpperCAmelCase  	=    np.linspace(0      ,				self.config.num_train_timesteps - 1      ,				lowercase_      ,				dtype=lowercase_							)[
                  ::-1
              ].copy()
          elif self.config.timestep_spacing == "leading":
              UpperCAmelCase  	=    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
              UpperCAmelCase  	=    (np.arange(0      ,				lowercase_							) * step_ratio).round()[::-1].copy().astype(lowercase_							)
              timesteps += self.config.steps_offset
          elif self.config.timestep_spacing == "trailing":
              UpperCAmelCase  	=    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
              UpperCAmelCase  	=    (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'."							)

          UpperCAmelCase  	=    np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5							)
          UpperCAmelCase  	=    np.interp(lowercase_      ,				np.arange(0      ,				len(lowercase_							)							)      ,				lowercase_							)
          UpperCAmelCase  	=    np.concatenate([sigmas, [0.0]]							).astype(np.floataa							)
          UpperCAmelCase  	=    torch.from_numpy(lowercase_							).to(device=lowercase_							)
          if str(lowercase_							).startswith('mps'							):
              # mps does not support float64
              UpperCAmelCase  	=    torch.from_numpy(lowercase_							).to(lowercase_      ,				dtype=torch.floataa							)
          else:
              UpperCAmelCase  	=    torch.from_numpy(lowercase_							).to(device=lowercase_							)




      def 			a_					(							self      ,				lowercase_      ,				lowercase_      ,				lowercase_      ,				lowercase_ = None      ,				lowercase_ = True      ,				)  ->    Union[EulerAncestralDiscreteSchedulerOutput, Tuple]:

          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							):
              UpperCAmelCase  	=    timestep.to(self.timesteps.device							)

          UpperCAmelCase  	=    (self.timesteps == timestep).nonzero().item()
          UpperCAmelCase  	=    self.sigmas[step_index]

          # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
          if self.config.prediction_type == "epsilon":
              UpperCAmelCase  	=    sample - sigma * model_output
          elif self.config.prediction_type == "v_prediction":
              # * c_out + input * c_skip
              UpperCAmelCase  	=    model_output * (-sigma / (sigma**2 + 1) ** 0.5) + (sample / (sigma**2 + 1))
          elif self.config.prediction_type == "sample":
              raise NotImplementedError('prediction_type not implemented yet: sample'							)
          else:
              raise ValueError(
                  F"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`"							)

          UpperCAmelCase  	=    self.sigmas[step_index]
          UpperCAmelCase  	=    self.sigmas[step_index + 1]
          UpperCAmelCase  	=    (sigma_to**2 * (sigma_from**2 - sigma_to**2) / sigma_from**2) ** 0.5
          UpperCAmelCase  	=    (sigma_to**2 - sigma_up**2) ** 0.5

          # 2. Convert to an ODE derivative
          UpperCAmelCase  	=    (sample - pred_original_sample) / sigma

          UpperCAmelCase  	=    sigma_down - sigma

          UpperCAmelCase  	=    sample + derivative * dt

          UpperCAmelCase  	=    model_output.device
          UpperCAmelCase  	=    randn_tensor(model_output.shape      ,				dtype=model_output.dtype      ,				device=lowercase_      ,				generator=lowercase_							)

          UpperCAmelCase  	=    prev_sample + noise * sigma_up

          if not return_dict:
              return (prev_sample,)

          return EulerAncestralDiscreteSchedulerOutput(
              prev_sample=lowercase_      ,				pred_original_sample=lowercase_							)




      def 			a_					(							self      ,				lowercase_      ,				lowercase_      ,				lowercase_      ,				)  ->    torch.FloatTensor:
          # Make sure sigmas and timesteps have the same device and dtype as original_samples
          UpperCAmelCase  	=    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
              UpperCAmelCase  	=    self.timesteps.to(original_samples.device      ,				dtype=torch.floataa							)
              UpperCAmelCase  	=    timesteps.to(original_samples.device      ,				dtype=torch.floataa							)
          else:
              UpperCAmelCase  	=    self.timesteps.to(original_samples.device							)
              UpperCAmelCase  	=    timesteps.to(original_samples.device							)

          UpperCAmelCase  	=    [(schedule_timesteps == t).nonzero().item() for t in timesteps]

          UpperCAmelCase  	=    sigmas[step_indices].flatten()
          while len(sigma.shape							) < len(original_samples.shape							):
              UpperCAmelCase  	=    sigma.unsqueeze(-1							)

          UpperCAmelCase  	=    original_samples + noise * sigma
          return noisy_samples




      def __len__(							self							)  ->    Dict:
          return self.config.num_train_timesteps





"""simple docstring"""

import doctest

import projectq
from projectq.ops import H, Measure




def 			lowercase__  (    lowerCAmelCase :    projectq.cengines._main.MainEngine       )       ->					int:






    """simple docstring"""




    UpperCAmelCase  	=    quantum_engine.allocate_qubit()
    H | qubit
    Measure | qubit
    return int(lowerCAmelCase       )


if __name__ == "__main__":
   doctest.testmod()

   # initialises a new quantum backend
   SCREAMING_SNAKE_CASE_			    =  projectq.MainEngine()

   # Generate a list of 10 random numbers
   SCREAMING_SNAKE_CASE_			    =  [get_random_number(quantum_engine) for _ in range(10)]

   # Flushes the quantum engine from memory
   quantum_engine.flush()

   print('''Random numbers''', random_numbers_list)



