



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

import numpy as np
import torch
from scipy import integrate

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





@dataclass
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->LMSDiscrete
class       __lowerCAmelCase				(  A__ ):
    __lowerCamelCase				=       42
    __lowerCamelCase				=       None


def 	_UpperCAmelCase       (   snake_case			,		snake_case=0.999			,		snake_case="cosine"			,		):





     """simple docstring"""

     if alpha_transform_type == "cosine":

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

     elif alpha_transform_type == "exp":

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

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

     _lowerCAmelCase      			=					[]
     for i in range(snake_case    ):
          _lowerCAmelCase      			=					i / num_diffusion_timesteps
          _lowerCAmelCase      			=					(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				(  A__ ,		A__ ):
    __lowerCamelCase				=       [e.name for e in KarrasDiffusionSchedulers]
    __lowerCamelCase				=       1




    @register_to_config
    def __init__(							self		,       _snake_case = 1000		,       _snake_case = 0.0001		,       _snake_case = 0.02		,       _snake_case = "linear"		,       _snake_case = None		,       _snake_case = False		,       _snake_case = "epsilon"		,       _snake_case = "linspace"		,       _snake_case = 0		,       ):



         """simple docstring"""





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

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

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

         # setable values
         _lowerCAmelCase      			=					None
         _lowerCAmelCase      			=					use_karras_sigmas
         self.set_timesteps(_lowerCAmelCase		,       _lowerCAmelCase	)
         _lowerCAmelCase      			=					[]
         _lowerCAmelCase      			=					False




    @property
    def 							snake_case     (							self	):



         """simple docstring"""





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

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




    def 							snake_case     (							self		,       _snake_case		,       _snake_case	):



         """simple docstring"""





         if isinstance(_lowerCAmelCase		,       torch.Tensor	):
              _lowerCAmelCase      			=					timestep.to(self.timesteps.device	)
         _lowerCAmelCase      			=					(self.timesteps == timestep).nonzero().item()
         _lowerCAmelCase      			=					self.sigmas[step_index]
         _lowerCAmelCase      			=					sample / ((sigma**2 + 1) ** 0.5)
         _lowerCAmelCase      			=					True
         return sample




    def 							snake_case     (							self		,       _snake_case		,       _snake_case		,       _snake_case	):



         """simple docstring"""





         def lms_derivative(_snake_case	):
              _lowerCAmelCase      			=					1.0
              for k in range(_lowerCAmelCase	):
                   if current_order == k:
                        continue
                   prod *= (tau - self.sigmas[t - k]) / (self.sigmas[t - current_order] - self.sigmas[t - k])
              return prod

         _lowerCAmelCase      			=					integrate.quad(_lowerCAmelCase		,       self.sigmas[t]		,       self.sigmas[t + 1]		,       epsrel=1e-4	)[0]

         return integrated_coeff




    def 							snake_case     (							self		,       _snake_case		,       _snake_case = None	):



         """simple docstring"""





         _lowerCAmelCase      			=					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      			=					np.linspace(0		,       self.config.num_train_timesteps - 1		,       _lowerCAmelCase		,       dtype=_lowerCAmelCase	)[
                  ::-1
              ].copy()
         elif self.config.timestep_spacing == "leading":
              _lowerCAmelCase      			=					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      			=					(np.arange(0		,       _lowerCAmelCase	) * step_ratio).round()[::-1].copy().astype(_lowerCAmelCase	)
              timesteps += self.config.steps_offset
         elif self.config.timestep_spacing == "trailing":
              _lowerCAmelCase      			=					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      			=					(np.arange(self.config.num_train_timesteps		,       0		,       -step_ratio	)).round().copy().astype(_lowerCAmelCase	)
              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      			=					np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5	)
         _lowerCAmelCase      			=					np.log(_lowerCAmelCase	)
         _lowerCAmelCase      			=					np.interp(_lowerCAmelCase		,       np.arange(0		,       len(_lowerCAmelCase	)	)		,       _lowerCAmelCase	)

         if self.use_karras_sigmas:
              _lowerCAmelCase      			=					self._convert_to_karras(in_sigmas=_lowerCAmelCase	)
              _lowerCAmelCase      			=					np.array([self._sigma_to_t(_lowerCAmelCase		,       _lowerCAmelCase	) for sigma in sigmas]	)

         _lowerCAmelCase      			=					np.concatenate([sigmas, [0.0]]	).astype(np.floataa	)

         _lowerCAmelCase      			=					torch.from_numpy(_lowerCAmelCase	).to(device=_lowerCAmelCase	)
         if str(_lowerCAmelCase	).startswith("""mps"""	):
              # mps does not support float64
              _lowerCAmelCase      			=					torch.from_numpy(_lowerCAmelCase	).to(_lowerCAmelCase		,       dtype=torch.floataa	)
         else:
              _lowerCAmelCase      			=					torch.from_numpy(_lowerCAmelCase	).to(device=_lowerCAmelCase	)

         _lowerCAmelCase      			=					[]




    def 							snake_case     (							self		,       _snake_case		,       _snake_case	):



         """simple docstring"""





         _lowerCAmelCase      			=					np.log(_lowerCAmelCase	)

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

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

         _lowerCAmelCase      			=					log_sigmas[low_idx]
         _lowerCAmelCase      			=					log_sigmas[high_idx]

         # interpolate sigmas
         _lowerCAmelCase      			=					(low - log_sigma) / (low - high)
         _lowerCAmelCase      			=					np.clip(_lowerCAmelCase		,       0		,       1	)

         # transform interpolation to time range
         _lowerCAmelCase      			=					(1 - w) * low_idx + w * high_idx
         _lowerCAmelCase      			=					t.reshape(sigma.shape	)
         return t




    def 							snake_case     (							self		,       _snake_case	):



         """simple docstring"""





         _lowerCAmelCase      			=					in_sigmas[-1].item()
         _lowerCAmelCase      			=					in_sigmas[0].item()

         _lowerCAmelCase      			=					7.0  # 7.0 is the value used in the paper
         _lowerCAmelCase      			=					np.linspace(0		,       1		,       self.num_inference_steps	)
         _lowerCAmelCase      			=					sigma_min ** (1 / rho)
         _lowerCAmelCase      			=					sigma_max ** (1 / rho)
         _lowerCAmelCase      			=					(max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
         return sigmas




    def 							snake_case     (							self		,       _snake_case		,       _snake_case		,       _snake_case		,       _snake_case = 4		,       _snake_case = True		,       ):



         """simple docstring"""





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

         if isinstance(_lowerCAmelCase		,       torch.Tensor	):
              _lowerCAmelCase      			=					timestep.to(self.timesteps.device	)
         _lowerCAmelCase      			=					(self.timesteps == timestep).nonzero().item()
         _lowerCAmelCase      			=					self.sigmas[step_index]

         # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
         if self.config.prediction_type == "epsilon":
              _lowerCAmelCase      			=					sample - sigma * model_output
         elif self.config.prediction_type == "v_prediction":
              # * c_out + input * c_skip
              _lowerCAmelCase      			=					model_output * (-sigma / (sigma**2 + 1) ** 0.5) + (sample / (sigma**2 + 1))
         elif self.config.prediction_type == "sample":
              _lowerCAmelCase      			=					model_output
         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      			=					(sample - pred_original_sample) / sigma
         self.derivatives.append(_lowerCAmelCase	)
         if len(self.derivatives	) > order:
              self.derivatives.pop(0	)

         # 3. Compute linear multistep coefficients
         _lowerCAmelCase      			=					min(step_index + 1		,       _lowerCAmelCase	)
         _lowerCAmelCase      			=					[self.get_lms_coefficient(_lowerCAmelCase		,       _lowerCAmelCase		,       _lowerCAmelCase	) for curr_order in range(_lowerCAmelCase	)]

         # 4. Compute previous sample based on the derivatives path
         _lowerCAmelCase      			=					sample + sum(
             coeff * derivative for coeff, derivative in zip(_lowerCAmelCase		,       reversed(self.derivatives	)	)	)

         if not return_dict:
              return (prev_sample,)

         return LMSDiscreteSchedulerOutput(prev_sample=_lowerCAmelCase		,       pred_original_sample=_lowerCAmelCase	)




    def 							snake_case     (							self		,       _snake_case		,       _snake_case		,       _snake_case		,       ):



         """simple docstring"""





         _lowerCAmelCase      			=					self.sigmas.to(device=original_samples.device		,       dtype=original_samples.dtype	)
         if original_samples.device.type == "mps" and torch.is_floating_point(_lowerCAmelCase	):
              # mps does not support float64
              _lowerCAmelCase      			=					self.timesteps.to(original_samples.device		,       dtype=torch.floataa	)
              _lowerCAmelCase      			=					timesteps.to(original_samples.device		,       dtype=torch.floataa	)
         else:
              _lowerCAmelCase      			=					self.timesteps.to(original_samples.device	)
              _lowerCAmelCase      			=					timesteps.to(original_samples.device	)

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

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

         _lowerCAmelCase      			=					original_samples + noise * sigma
         return noisy_samples




    def __len__(							self	):



         """simple docstring"""





         return self.config.num_train_timesteps








from __future__ import annotations

from PIL import Image

# Define the first generation of cells
# fmt: off
A__			   = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
          0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]


def 	_UpperCAmelCase       (   snake_case    ):





					"""simple docstring"""

					return [int(snake_case    ) for c in F'{ruleset:08}'[:8]]


def 	_UpperCAmelCase       (   snake_case			,		snake_case			,		snake_case    ):





					"""simple docstring"""

					_lowerCAmelCase      			=					len(cells[0]    )  # 31
					_lowerCAmelCase      			=					[]
					for i in range(snake_case    ):
										# Get the neighbors of each cell
										# Handle neighbours outside bounds by using 0 as their value
										_lowerCAmelCase      			=					0 if i == 0 else cells[time][i - 1]
										_lowerCAmelCase      			=					0 if i == population - 1 else cells[time][i + 1]
										# Define a new cell and add it to the new generation
										_lowerCAmelCase      			=					7 - int(F'{left_neighbor}{cells[time][i]}{right_neighbor}'			,		2    )
										next_generation.append(rule[situation]    )
					return next_generation


def 	_UpperCAmelCase       (   snake_case    ):





					"""simple docstring"""

					_lowerCAmelCase      			=					Image.new("""RGB"""			,		(len(cells[0]    ), len(snake_case    ))    )
					_lowerCAmelCase      			=					img.load()
					# Generates image
					for w in range(img.width    ):
										for h in range(img.height    ):
															_lowerCAmelCase      			=					2_55 - int(2_55 * cells[h][w]    )
															_lowerCAmelCase      			=					(color, color, color)
					return img


if __name__ == "__main__":
	A__			   = bin(int(input("""Rule:\n""").strip()))[2:]
	A__			   = format_ruleset(int(rule_num))
	for time in range(16):
		CELLS.append(new_generation(CELLS, rule, time))
	A__			   = generate_image(CELLS)
	# Uncomment to save the image
	# img.save(f"rule_{rule_num}.png")
	img.show()



