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


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

@dataclass
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->EulerAncestralDiscrete
class __lowerCAmelCase						( __SCREAMING_SNAKE_CASE     ):
     lowercase		  =		42
     lowercase		  =		None






def 				A		(							snake_case :int							,   snake_case :int=0.999							,   snake_case :List[str]="cosine"							,   ) ->      List[str]:
 if alpha_transform_type == "cosine":

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

 elif alpha_transform_type == "exp":

  def alpha_bar_fn(snake_case :List[str]						):
   return math.exp(t * -12.0						)

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

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





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





     @register_to_config
     def __init__(      self      ,	__UpperCAmelCase = 1000      ,	__UpperCAmelCase = 0.0_0_0_1      ,	__UpperCAmelCase = 0.0_2      ,	__UpperCAmelCase = "linear"      ,	__UpperCAmelCase = None      ,	__UpperCAmelCase = "epsilon"      ,	__UpperCAmelCase = "linspace"      ,	__UpperCAmelCase = 0      ,	):

      '''simple docstring'''




      if trained_betas is not None:
       __UpperCamelCase							    =			torch.tensor(__UpperCAmelCase      ,	dtype=torch.floataa )
      elif beta_schedule == "linear":
       __UpperCamelCase							    =			torch.linspace(__UpperCAmelCase      ,	__UpperCAmelCase      ,	__UpperCAmelCase      ,	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      ,	__UpperCAmelCase      ,	dtype=torch.floataa ) ** 2
       )
      elif beta_schedule == "squaredcos_cap_v2":
       # Glide cosine schedule
       __UpperCamelCase							    =			betas_for_alpha_bar(__UpperCAmelCase )
      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(__UpperCAmelCase )

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





     @property
     def 		UpperCAmelCase   (      self ):

      '''simple docstring'''




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

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





     def 		UpperCAmelCase   (      self      ,	__UpperCAmelCase      ,	__UpperCAmelCase ):

      '''simple docstring'''




      if isinstance(__UpperCAmelCase      ,	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 		UpperCAmelCase   (      self      ,	__UpperCAmelCase      ,	__UpperCAmelCase = None ):

      '''simple docstring'''




      __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      ,	__UpperCAmelCase      ,	dtype=__UpperCAmelCase )[
           ::-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      ,	__UpperCAmelCase ) * step_ratio).round()[::-1].copy().astype(__UpperCAmelCase )
       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(__UpperCAmelCase )
       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(__UpperCAmelCase      ,	np.arange(0      ,	len(__UpperCAmelCase ) )      ,	__UpperCAmelCase )
      __UpperCamelCase							    =			np.concatenate([sigmas, [0.0]] ).astype(np.floataa )
      __UpperCamelCase							    =			torch.from_numpy(__UpperCAmelCase ).to(device=__UpperCAmelCase )
      if str(__UpperCAmelCase ).startswith('mps' ):
       # mps does not support float64
       __UpperCamelCase							    =			torch.from_numpy(__UpperCAmelCase ).to(__UpperCAmelCase      ,	dtype=torch.floataa )
      else:
       __UpperCamelCase							    =			torch.from_numpy(__UpperCAmelCase ).to(device=__UpperCAmelCase )





     def 		UpperCAmelCase   (      self      ,	__UpperCAmelCase      ,	__UpperCAmelCase      ,	__UpperCAmelCase      ,	__UpperCAmelCase = None      ,	__UpperCAmelCase = True      ,	):

      '''simple docstring'''




      if (
          isinstance(__UpperCAmelCase      ,	__UpperCAmelCase )
          or isinstance(__UpperCAmelCase      ,	torch.IntTensor )
          or isinstance(__UpperCAmelCase      ,	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(__UpperCAmelCase      ,	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=__UpperCAmelCase      ,	generator=__UpperCAmelCase )

      __UpperCamelCase							    =			prev_sample + noise * sigma_up

      if not return_dict:
       return (prev_sample,)

      return EulerAncestralDiscreteSchedulerOutput(
          prev_sample=__UpperCAmelCase      ,	pred_original_sample=__UpperCAmelCase )





     def 		UpperCAmelCase   (      self      ,	__UpperCAmelCase      ,	__UpperCAmelCase      ,	__UpperCAmelCase      ,	):

      '''simple docstring'''




      __UpperCamelCase							    =			self.sigmas.to(device=original_samples.device      ,	dtype=original_samples.dtype )
      if original_samples.device.type == "mps" and torch.is_floating_point(__UpperCAmelCase ):
       # 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 ):

      '''simple docstring'''




      return self.config.num_train_timesteps





"""simple docstring"""

import math
from itertools import permutations






def 				A		(							snake_case :int						) ->      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(snake_case						) + 1						)							,   6						):
  if number % i == 0 or number % (i + 2) == 0:
   return False
 return True






def 				A		(							snake_case :int							,   snake_case :list						) ->      bool:
 __UpperCamelCase    ,      __UpperCamelCase							    =			0, len(snake_case						) - 1
 while left <= right:
  __UpperCamelCase							    =			(left + right) // 2
  if prime_list[middle] == target:
   return True
  elif prime_list[middle] < target:
   __UpperCamelCase							    =			middle + 1
  else:
   __UpperCamelCase							    =			middle - 1

 return False






def 				A		(							) ->      int:
 __UpperCamelCase							    =			[n for n in range(1_0_0_1							,   1_0_0_0_0							,   2						) if is_prime(snake_case						)]
 __UpperCamelCase							    =			[]

 for number in prime_list:
  __UpperCamelCase							    =			[]

  for prime_member in permutations(list(str(snake_case						)						)						):
   __UpperCamelCase							    =			int(''.join(snake_case						)						)

   if prime % 2 == 0:
    continue

   if search(snake_case							,   snake_case						):
    tmp_numbers.append(snake_case						)

  tmp_numbers.sort()
  if len(snake_case						) >= 3:
   candidates.append(snake_case						)

 __UpperCamelCase							    =			[]
 for candidate in candidates:
  __UpperCamelCase							    =			len(snake_case						)
  __UpperCamelCase							    =			False

  for i in range(snake_case						):
   for j in range(i + 1							,   snake_case						):
    for k in range(j + 1							,   snake_case						):
     if (
         abs(candidate[i] - candidate[j]						)
         == abs(candidate[j] - candidate[k]						)
         and len({candidate[i], candidate[j], candidate[k]}						) == 3
     ):
      passed.append(
          sorted([candidate[i], candidate[j], candidate[k]]						)						)
      __UpperCamelCase							    =			True

     if found:
      break
    if found:
     break
   if found:
    break

 __UpperCamelCase							    =			set()
 for seq in passed:
  answer.add(''.join([str(snake_case						) for i in seq]						)						)

 return max(int(snake_case						) for x in answer						)


if __name__ == "__main__":
      print(solution())



