
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   :     Any      =						logging.get_logger(__name__)  # pylint: disable=invalid-name


@dataclass
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->EulerDiscrete
class   __lowerCAmelCase		(		lowerCAmelCase_ ):



      """simple docstring"""







      A__		:     torch.FloatTensor
      A__		:     Optional[torch.FloatTensor]       				=      None






def       UpperCAmelCase_					(  __lowerCAmelCase		,   __lowerCAmelCase=0.999		,   __lowerCAmelCase="cosine"		,   )	->  List[str]:
    if alpha_transform_type == "cosine":

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

    elif alpha_transform_type == "exp":

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

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

    __lowercase						:     Union[str, Any]		      =    []
    for i in range(__lowerCAmelCase		):
        __lowercase						:     Union[str, Any]		      =    i / num_diffusion_timesteps
        __lowercase						:     Tuple		      =    (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   __lowerCAmelCase		(		lowerCAmelCase_	,	lowerCAmelCase_ ):



      """simple docstring"""







      A__		:     List[Any]       				=      [e.name for e in KarrasDiffusionSchedulers]
      A__		:     Union[str, Any]       				=      1




      @register_to_config
      def __init__( self						:    int			,    _snake_case						:    int = 1000			,    _snake_case						:    float = 0.00_01			,    _snake_case						:    float = 0.02			,    _snake_case						:    str = "linear"			,    _snake_case						:    Optional[Union[np.ndarray, List[float]]] = None			,    _snake_case						:    str = "epsilon"			,    _snake_case						:    str = "linear"			,    _snake_case						:    Optional[bool] = False			,    _snake_case						:    str = "linspace"			,    _snake_case						:    int = 0			,    ):
          if trained_betas is not None:
              __lowercase						:     Dict		      =    torch.tensor(_snake_case			,    dtype=torch.floataa			)
          elif beta_schedule == "linear":
              __lowercase						:     Optional[Any]		      =    torch.linspace(_snake_case			,    _snake_case			,    _snake_case			,    dtype=torch.floataa			)
          elif beta_schedule == "scaled_linear":
              # this schedule is very specific to the latent diffusion model.
              __lowercase						:     Union[str, Any]		      =    (
                  torch.linspace(beta_start**0.5			,    beta_end**0.5			,    _snake_case			,    dtype=torch.floataa			) ** 2
              )
          elif beta_schedule == "squaredcos_cap_v2":
              # Glide cosine schedule
              __lowercase						:     List[Any]		      =    betas_for_alpha_bar(_snake_case			)
          else:
              raise NotImplementedError(F'{beta_schedule} does is not implemented for {self.__class__}'			)

          __lowercase						:     Tuple		      =    1.0 - self.betas
          __lowercase						:     Optional[int]		      =    torch.cumprod(self.alphas			,    dim=0			)

          __lowercase						:     Union[str, Any]		      =    np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5			)
          __lowercase						:     str		      =    np.concatenate([sigmas[::-1], [0.0]]			).astype(np.floataa			)
          __lowercase						:     Dict		      =    torch.from_numpy(_snake_case			)

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




      @property
      def 						snake_case_     ( self						:    List[str]			):
          # 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 						snake_case_     ( self						:    int			,    _snake_case						:    torch.FloatTensor			,    _snake_case						:    Union[float, torch.FloatTensor]			):
          if isinstance(_snake_case			,    torch.Tensor			):
              __lowercase						:     Dict		      =    timestep.to(self.timesteps.device			)
          __lowercase						:     Union[str, Any]		      =    (self.timesteps == timestep).nonzero().item()
          __lowercase						:     Optional[int]		      =    self.sigmas[step_index]

          __lowercase						:     Union[str, Any]		      =    sample / ((sigma**2 + 1) ** 0.5)

          __lowercase						:     Union[str, Any]		      =    True
          return sample




      def 						snake_case_     ( self						:    Dict			,    _snake_case						:    int			,    _snake_case						:    Union[str, torch.device] = None			):
          __lowercase						:     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":
              __lowercase						:     Optional[Any]		      =    np.linspace(0			,    self.config.num_train_timesteps - 1			,    _snake_case			,    dtype=_snake_case			)[
                  ::-1
              ].copy()
          elif self.config.timestep_spacing == "leading":
              __lowercase						:     Tuple		      =    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
              __lowercase						:     Dict		      =    (np.arange(0			,    _snake_case			) * step_ratio).round()[::-1].copy().astype(_snake_case			)
              timesteps += self.config.steps_offset
          elif self.config.timestep_spacing == "trailing":
              __lowercase						:     Any		      =    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
              __lowercase						:     Optional[int]		      =    (np.arange(self.config.num_train_timesteps			,    0			,    -step_ratio			)).round().copy().astype(_snake_case			)
              timesteps -= 1
          else:
              raise ValueError(
                  F'{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.'			)

          __lowercase						:     List[Any]		      =    np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5			)
          __lowercase						:     Any		      =    np.log(_snake_case			)

          if self.config.interpolation_type == "linear":
              __lowercase						:     Dict		      =    np.interp(_snake_case			,    np.arange(0			,    len(_snake_case			)			)			,    _snake_case			)
          elif self.config.interpolation_type == "log_linear":
              __lowercase						:     List[Any]		      =    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:
              __lowercase						:     Tuple		      =    self._convert_to_karras(in_sigmas=_snake_case			,    num_inference_steps=self.num_inference_steps			)
              __lowercase						:     List[str]		      =    np.array([self._sigma_to_t(_snake_case			,    _snake_case			) for sigma in sigmas]			)

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




      def 						snake_case_     ( self						:    str			,    _snake_case						:    Dict			,    _snake_case						:    int			):
          # get log sigma
          __lowercase						:     Dict		      =    np.log(_snake_case			)

          # get distribution
          __lowercase						:     Tuple		      =    log_sigma - log_sigmas[:, np.newaxis]

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

          __lowercase						:     str		      =    log_sigmas[low_idx]
          __lowercase						:     Dict		      =    log_sigmas[high_idx]

          # interpolate sigmas
          __lowercase						:     str		      =    (low - log_sigma) / (low - high)
          __lowercase						:     List[Any]		      =    np.clip(_snake_case			,    0			,    1			)

          # transform interpolation to time range
          __lowercase						:     Union[str, Any]		      =    (1 - w) * low_idx + w * high_idx
          __lowercase						:     Optional[Any]		      =    t.reshape(sigma.shape			)
          return t




      def 						snake_case_     ( self						:    str			,    _snake_case						:    torch.FloatTensor			,    _snake_case						:    Union[str, Any]			):
          __lowercase						:     float		      =    in_sigmas[-1].item()
          __lowercase						:     float		      =    in_sigmas[0].item()

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




      def 						snake_case_     ( self						:    Dict			,    _snake_case						:    torch.FloatTensor			,    _snake_case						:    Union[float, torch.FloatTensor]			,    _snake_case						:    torch.FloatTensor			,    _snake_case						:    float = 0.0			,    _snake_case						:    float = 0.0			,    _snake_case						:    float = float('''inf'''			)			,    _snake_case						:    float = 1.0			,    _snake_case						:    Optional[torch.Generator] = None			,    _snake_case						:    bool = True			,    ):

          if (
              isinstance(_snake_case			,    _snake_case			)
              or isinstance(_snake_case			,    torch.IntTensor			)
              or isinstance(_snake_case			,    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(_snake_case			,    torch.Tensor			):
              __lowercase						:     Any		      =    timestep.to(self.timesteps.device			)

          __lowercase						:     int		      =    (self.timesteps == timestep).nonzero().item()
          __lowercase						:     Optional[int]		      =    self.sigmas[step_index]

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

          __lowercase						:     str		      =    randn_tensor(
              model_output.shape			,    dtype=model_output.dtype			,    device=model_output.device			,    generator=_snake_case			)

          __lowercase						:     List[str]		      =    noise * s_noise
          __lowercase						:     Optional[int]		      =    sigma * (gamma + 1)

          if gamma > 0:
              __lowercase						:     Optional[Any]		      =    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":
              __lowercase						:     List[Any]		      =    model_output
          elif self.config.prediction_type == "epsilon":
              __lowercase						:     Any		      =    sample - sigma_hat * model_output
          elif self.config.prediction_type == "v_prediction":
              # * c_out + input * c_skip
              __lowercase						:     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
          __lowercase						:     List[Any]		      =    (sample - pred_original_sample) / sigma_hat

          __lowercase						:     Union[str, Any]		      =    self.sigmas[step_index + 1] - sigma_hat

          __lowercase						:     List[str]		      =    sample + derivative * dt

          if not return_dict:
              return (prev_sample,)

          return EulerDiscreteSchedulerOutput(prev_sample=_snake_case			,    pred_original_sample=_snake_case			)




      def 						snake_case_     ( self						:    Optional[int]			,    _snake_case						:    torch.FloatTensor			,    _snake_case						:    torch.FloatTensor			,    _snake_case						:    torch.FloatTensor			,    ):
          # Make sure sigmas and timesteps have the same device and dtype as original_samples
          __lowercase						:     Tuple		      =    self.sigmas.to(device=original_samples.device			,    dtype=original_samples.dtype			)
          if original_samples.device.type == "mps" and torch.is_floating_point(_snake_case			):
              # mps does not support float64
              __lowercase						:     Dict		      =    self.timesteps.to(original_samples.device			,    dtype=torch.floataa			)
              __lowercase						:     Union[str, Any]		      =    timesteps.to(original_samples.device			,    dtype=torch.floataa			)
          else:
              __lowercase						:     Any		      =    self.timesteps.to(original_samples.device			)
              __lowercase						:     Optional[Any]		      =    timesteps.to(original_samples.device			)

          __lowercase						:     Optional[Any]		      =    [(schedule_timesteps == t).nonzero().item() for t in timesteps]

          __lowercase						:     Optional[int]		      =    sigmas[step_indices].flatten()
          while len(sigma.shape			) < len(original_samples.shape			):
              __lowercase						:     Dict		      =    sigma.unsqueeze(-1			)

          __lowercase						:     Optional[int]		      =    original_samples + noise * sigma
          return noisy_samples




      def __len__( self						:    Any			):
          return self.config.num_train_timesteps




from __future__ import annotations

import math
from itertools import permutations


def       UpperCAmelCase_					(  __lowerCAmelCase		)	->  bool:

    if 1 < number < 4:
        # 2 and 3 are primes
        return True
    elif number < 2 or number % 2 == 0 or number % 3 == 0:
        # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
        return False

    # All primes number are in format of 6k +/- 1
    for i in range(5		,   int(math.sqrt(__lowerCAmelCase		) + 1		)		,   6		):
        if number % i == 0 or number % (i + 2) == 0:
            return False
    return True


def       UpperCAmelCase_					(  __lowerCAmelCase = 7		)	->  int:
    __lowercase						:     Union[str, Any]		      =    ''''''.join(str(__lowerCAmelCase		) for i in range(1		,   n + 1		)		)
    __lowercase						:     Dict		      =    [int(''''''.join(__lowerCAmelCase		)		) for i in permutations(__lowerCAmelCase		,   __lowerCAmelCase		)]
    __lowercase						:     int		      =    [num for num in perm_list if is_prime(__lowerCAmelCase		)]
    return max(__lowerCAmelCase		) if pandigitals else 0


if __name__ == "__main__":
 print(F'{solution() = }')


