"""simple docstring"""
import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    EulerAncestralDiscreteScheduler,
    LMSDiscreteScheduler,
    PNDMScheduler,
    StableDiffusionInstructPixaPixPipeline,
    UNetaDConditionModel,
)
from diffusers.image_processor import VaeImageProcessor
from diffusers.utils import floats_tensor, load_image, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import (
    IMAGE_TO_IMAGE_IMAGE_PARAMS,
    TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()
class 					a	(  UpperCAmelCase__	,      UpperCAmelCase__	,      UpperCAmelCase__	,      unittest.TestCase       ):
  UpperCamelCase	:				Optional[Any]     						=					StableDiffusionInstructPixaPixPipeline
  UpperCamelCase	:				Union[str, Any]     						=					TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width', 'cross_attention_kwargs'}
  UpperCamelCase	:				List[str]     						=					TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
  UpperCamelCase	:				List[str]     						=					IMAGE_TO_IMAGE_IMAGE_PARAMS
  UpperCamelCase	:				Tuple     						=					IMAGE_TO_IMAGE_IMAGE_PARAMS



  def 	lowerCamelCase__       (						self :					Tuple		)     ->					List[Any]:


     '''simple docstring'''




     torch.manual_seed(0		)
     SCREAMING_SNAKE_CASE_: List[str]     			=UNetaDConditionModel(
         block_out_channels=(32, 64)       ,		layers_per_block=2       ,		sample_size=32       ,		in_channels=8       ,		out_channels=4       ,		down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")       ,		up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""")       ,		cross_attention_dim=32       ,		)
     SCREAMING_SNAKE_CASE_: Any     			=PNDMScheduler(skip_prk_steps=lowerCAmelCase		)
     torch.manual_seed(0		)
     SCREAMING_SNAKE_CASE_: Optional[Any]     			=AutoencoderKL(
         block_out_channels=[32, 64]       ,		in_channels=3       ,		out_channels=3       ,		down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]       ,		up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]       ,		latent_channels=4       ,		)
     torch.manual_seed(0		)
     SCREAMING_SNAKE_CASE_: Any     			=CLIPTextConfig(
         bos_token_id=0       ,		eos_token_id=2       ,		hidden_size=32       ,		intermediate_size=37       ,		layer_norm_eps=1E-05       ,		num_attention_heads=4       ,		num_hidden_layers=5       ,		pad_token_id=1       ,		vocab_size=1000       ,		)
     SCREAMING_SNAKE_CASE_: int     			=CLIPTextModel(lowerCAmelCase		)
     SCREAMING_SNAKE_CASE_: int     			=CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""		)

     SCREAMING_SNAKE_CASE_: List[str]     			={
         """unet""": unet,
         """scheduler""": scheduler,
         """vae""": vae,
         """text_encoder""": text_encoder,
         """tokenizer""": tokenizer,
         """safety_checker""": None,
         """feature_extractor""": None,
     }
     return components



  def 	lowerCamelCase__       (						self :					Optional[int]       ,		lowerCAmelCase :					int       ,		lowerCAmelCase :					List[Any]=0		)     ->					Any:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: Union[str, Any]     			=floats_tensor((1, 3, 32, 32)       ,		rng=random.Random(lowerCAmelCase		)		).to(lowerCAmelCase		)
     SCREAMING_SNAKE_CASE_: Dict     			=image.cpu().permute(0       ,		2       ,		3       ,		1		)[0]
     SCREAMING_SNAKE_CASE_: str     			=Image.fromarray(np.uinta(lowerCAmelCase		)		).convert("""RGB"""		)
     if str(lowerCAmelCase		).startswith("""mps"""		):
        SCREAMING_SNAKE_CASE_: List[str]     			=torch.manual_seed(lowerCAmelCase		)
     else:
        SCREAMING_SNAKE_CASE_: List[str]     			=torch.Generator(device=lowerCAmelCase		).manual_seed(lowerCAmelCase		)
     SCREAMING_SNAKE_CASE_: Optional[Any]     			={
         """prompt""": """A painting of a squirrel eating a burger""",
         """image""": image,
         """generator""": generator,
         """num_inference_steps""": 2,
         """guidance_scale""": 6.0,
         """image_guidance_scale""": 1,
         """output_type""": """numpy""",
     }
     return inputs



  def 	lowerCamelCase__       (						self :					List[Any]		)     ->					List[Any]:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: Optional[Any]     			="""cpu"""  # ensure determinism for the device-dependent torch.Generator
     SCREAMING_SNAKE_CASE_: Any     			=self.get_dummy_components()
     SCREAMING_SNAKE_CASE_: List[Any]     			=StableDiffusionInstructPixaPixPipeline(**lowerCAmelCase		)
     SCREAMING_SNAKE_CASE_: Optional[int]     			=sd_pipe.to(lowerCAmelCase		)
     sd_pipe.set_progress_bar_config(disable=lowerCAmelCase		)

     SCREAMING_SNAKE_CASE_: str     			=self.get_dummy_inputs(lowerCAmelCase		)
     SCREAMING_SNAKE_CASE_: List[str]     			=sd_pipe(**lowerCAmelCase		).images
     SCREAMING_SNAKE_CASE_: int     			=image[0, -3:, -3:, -1]
     assert image.shape == (1, 32, 32, 3)
     SCREAMING_SNAKE_CASE_: int     			=np.array([0.7_5_2_6, 0.3_7_5_0, 0.4_5_4_7, 0.6_1_1_7, 0.5_8_6_6, 0.5_0_1_6, 0.4_3_2_7, 0.5_6_4_2, 0.4_8_1_5]		)

     assert np.abs(image_slice.flatten() - expected_slice		).max() < 1E-3



  def 	lowerCamelCase__       (						self :					List[Any]		)     ->					Optional[int]:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: Dict     			="""cpu"""  # ensure determinism for the device-dependent torch.Generator
     SCREAMING_SNAKE_CASE_: Optional[Any]     			=self.get_dummy_components()
     SCREAMING_SNAKE_CASE_: List[Any]     			=StableDiffusionInstructPixaPixPipeline(**lowerCAmelCase		)
     SCREAMING_SNAKE_CASE_: Optional[int]     			=sd_pipe.to(lowerCAmelCase		)
     sd_pipe.set_progress_bar_config(disable=lowerCAmelCase		)

     SCREAMING_SNAKE_CASE_: List[str]     			=self.get_dummy_inputs(lowerCAmelCase		)
     SCREAMING_SNAKE_CASE_: Optional[Any]     			="""french fries"""
     SCREAMING_SNAKE_CASE_: List[Any]     			=sd_pipe(**lowerCAmelCase       ,		negative_prompt=lowerCAmelCase		)
     SCREAMING_SNAKE_CASE_: str     			=output.images
     SCREAMING_SNAKE_CASE_: int     			=image[0, -3:, -3:, -1]

     assert image.shape == (1, 32, 32, 3)
     SCREAMING_SNAKE_CASE_: List[Any]     			=np.array([0.7_5_1_1, 0.3_6_4_2, 0.4_5_5_3, 0.6_2_3_6, 0.5_7_9_7, 0.5_0_1_3, 0.4_3_4_3, 0.5_6_1_1, 0.4_8_3_1]		)

     assert np.abs(image_slice.flatten() - expected_slice		).max() < 1E-3



  def 	lowerCamelCase__       (						self :					int		)     ->					List[str]:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: Tuple     			="""cpu"""  # ensure determinism for the device-dependent torch.Generator
     SCREAMING_SNAKE_CASE_: int     			=self.get_dummy_components()
     SCREAMING_SNAKE_CASE_: Optional[int]     			=StableDiffusionInstructPixaPixPipeline(**lowerCAmelCase		)
     SCREAMING_SNAKE_CASE_: Optional[int]     			=sd_pipe.to(lowerCAmelCase		)
     sd_pipe.set_progress_bar_config(disable=lowerCAmelCase		)

     SCREAMING_SNAKE_CASE_: Optional[Any]     			=self.get_dummy_inputs(lowerCAmelCase		)
     SCREAMING_SNAKE_CASE_: Union[str, Any]     			=[inputs["""prompt"""]] * 2

     SCREAMING_SNAKE_CASE_: str     			=np.array(inputs["""image"""]		).astype(np.floataa		) / 255.0
     SCREAMING_SNAKE_CASE_: Dict     			=torch.from_numpy(lowerCAmelCase		).unsqueeze(0		).to(lowerCAmelCase		)
     SCREAMING_SNAKE_CASE_: Optional[int]     			=image / 2 + 0.5
     SCREAMING_SNAKE_CASE_: List[str]     			=image.permute(0       ,		3       ,		1       ,		2		)
     SCREAMING_SNAKE_CASE_: Optional[int]     			=image.repeat(2       ,		1       ,		1       ,		1		)

     SCREAMING_SNAKE_CASE_: int     			=sd_pipe(**lowerCAmelCase		).images
     SCREAMING_SNAKE_CASE_: Any     			=image[-1, -3:, -3:, -1]

     assert image.shape == (2, 32, 32, 3)
     SCREAMING_SNAKE_CASE_: Tuple     			=np.array([0.5_8_1_2, 0.5_7_4_8, 0.5_2_2_2, 0.5_9_0_8, 0.5_6_9_5, 0.7_1_7_4, 0.6_8_0_4, 0.5_5_2_3, 0.5_5_7_9]		)

     assert np.abs(image_slice.flatten() - expected_slice		).max() < 1E-3



  def 	lowerCamelCase__       (						self :					List[Any]		)     ->					Optional[int]:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: Dict     			="""cpu"""  # ensure determinism for the device-dependent torch.Generator
     SCREAMING_SNAKE_CASE_: List[str]     			=self.get_dummy_components()
     SCREAMING_SNAKE_CASE_: List[str]     			=EulerAncestralDiscreteScheduler(
         beta_start=0.0_0_0_8_5       ,		beta_end=0.0_1_2       ,		beta_schedule="""scaled_linear"""		)
     SCREAMING_SNAKE_CASE_: int     			=StableDiffusionInstructPixaPixPipeline(**lowerCAmelCase		)
     SCREAMING_SNAKE_CASE_: Tuple     			=sd_pipe.to(lowerCAmelCase		)
     sd_pipe.set_progress_bar_config(disable=lowerCAmelCase		)

     SCREAMING_SNAKE_CASE_: Dict     			=self.get_dummy_inputs(lowerCAmelCase		)
     SCREAMING_SNAKE_CASE_: Optional[int]     			=sd_pipe(**lowerCAmelCase		).images
     SCREAMING_SNAKE_CASE_: str     			=image[0, -3:, -3:, -1]

     SCREAMING_SNAKE_CASE_: List[Any]     			=[round(lowerCAmelCase       ,		4		) for x in image_slice.flatten().tolist()]
     print(""",""".join([str(lowerCAmelCase		) for x in slice]		)		)

     assert image.shape == (1, 32, 32, 3)
     SCREAMING_SNAKE_CASE_: Tuple     			=np.array([0.7_4_1_7, 0.3_8_4_2, 0.4_7_3_2, 0.5_7_7_6, 0.5_8_9_1, 0.5_1_3_9, 0.4_0_5_2, 0.5_6_7_3, 0.4_9_8_6]		)

     assert np.abs(image_slice.flatten() - expected_slice		).max() < 1E-3



  def 	lowerCamelCase__       (						self :					str		)     ->					Tuple:


     '''simple docstring'''




     super().test_inference_batch_single_identical(expected_max_diff=3E-3		)





  def 	lowerCamelCase__       (						self :					Tuple		)     ->					Any:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: List[Any]     			=self.get_dummy_components()
     SCREAMING_SNAKE_CASE_: Union[str, Any]     			=StableDiffusionInstructPixaPixPipeline(**lowerCAmelCase		)
     SCREAMING_SNAKE_CASE_: Union[str, Any]     			=VaeImageProcessor(do_resize=lowerCAmelCase       ,		do_normalize=lowerCAmelCase		)
     SCREAMING_SNAKE_CASE_: Any     			=pipe.to(lowerCAmelCase		)
     pipe.set_progress_bar_config(disable=lowerCAmelCase		)

     SCREAMING_SNAKE_CASE_: Optional[int]     			=pipe(**self.get_dummy_inputs_by_type(lowerCAmelCase       ,		input_image_type="""pt"""		)		)[0]

     SCREAMING_SNAKE_CASE_: Optional[int]     			=components["""vae"""]
     SCREAMING_SNAKE_CASE_: Optional[Any]     			=self.get_dummy_inputs_by_type(lowerCAmelCase       ,		input_image_type="""pt"""		)

     for image_param in self.image_latents_params:
        if image_param in inputs.keys():
           SCREAMING_SNAKE_CASE_: Any     			=vae.encode(inputs[image_param]		).latent_dist.mode()

     SCREAMING_SNAKE_CASE_: Optional[Any]     			=pipe(**lowerCAmelCase		)[0]

     SCREAMING_SNAKE_CASE_: int     			=np.abs(out - out_latents_inputs		).max()
     self.assertLess(lowerCAmelCase       ,		1E-4       ,		"""passing latents as image input generate different result from passing image"""		)







@slow
@require_torch_gpu
class 					a	(  unittest.TestCase       ):



  def 	lowerCamelCase__       (						self :					Any		)     ->					Union[str, Any]:


     '''simple docstring'''




     super().tearDown()
     gc.collect()
     torch.cuda.empty_cache()



  def 	lowerCamelCase__       (						self :					Optional[int]       ,		lowerCAmelCase :					List[Any]=0		)     ->					int:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: Tuple     			=torch.manual_seed(lowerCAmelCase		)
     SCREAMING_SNAKE_CASE_: List[str]     			=load_image(
         """https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_pix2pix/example.jpg"""		)
     SCREAMING_SNAKE_CASE_: int     			={
         """prompt""": """turn him into a cyborg""",
         """image""": image,
         """generator""": generator,
         """num_inference_steps""": 3,
         """guidance_scale""": 7.5,
         """image_guidance_scale""": 1.0,
         """output_type""": """numpy""",
     }
     return inputs



  def 	lowerCamelCase__       (						self :					Tuple		)     ->					List[Any]:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: Union[str, Any]     			=StableDiffusionInstructPixaPixPipeline.from_pretrained(
         """timbrooks/instruct-pix2pix"""       ,		safety_checker=lowerCAmelCase		)
     pipe.to(lowerCAmelCase		)
     pipe.set_progress_bar_config(disable=lowerCAmelCase		)
     pipe.enable_attention_slicing()

     SCREAMING_SNAKE_CASE_: Dict     			=self.get_inputs()
     SCREAMING_SNAKE_CASE_: str     			=pipe(**lowerCAmelCase		).images
     SCREAMING_SNAKE_CASE_: Optional[Any]     			=image[0, -3:, -3:, -1].flatten()

     assert image.shape == (1, 512, 512, 3)
     SCREAMING_SNAKE_CASE_: str     			=np.array([0.5_9_0_2, 0.6_0_1_5, 0.6_0_2_7, 0.5_9_8_3, 0.6_0_9_2, 0.6_0_6_1, 0.5_7_6_5, 0.5_7_8_5, 0.5_5_5_5]		)

     assert np.abs(expected_slice - image_slice		).max() < 1E-3



  def 	lowerCamelCase__       (						self :					Any		)     ->					Tuple:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: List[Any]     			=StableDiffusionInstructPixaPixPipeline.from_pretrained(
         """timbrooks/instruct-pix2pix"""       ,		safety_checker=lowerCAmelCase		)
     SCREAMING_SNAKE_CASE_: List[Any]     			=LMSDiscreteScheduler.from_config(pipe.scheduler.config		)
     pipe.to(lowerCAmelCase		)
     pipe.set_progress_bar_config(disable=lowerCAmelCase		)
     pipe.enable_attention_slicing()

     SCREAMING_SNAKE_CASE_: List[Any]     			=self.get_inputs()
     SCREAMING_SNAKE_CASE_: Tuple     			=pipe(**lowerCAmelCase		).images
     SCREAMING_SNAKE_CASE_: Union[str, Any]     			=image[0, -3:, -3:, -1].flatten()

     assert image.shape == (1, 512, 512, 3)
     SCREAMING_SNAKE_CASE_: str     			=np.array([0.6_5_7_8, 0.6_8_1_7, 0.6_9_7_2, 0.6_7_6_1, 0.6_8_5_6, 0.6_9_1_6, 0.6_4_2_8, 0.6_5_1_6, 0.6_3_0_1]		)

     assert np.abs(expected_slice - image_slice		).max() < 1E-3



  def 	lowerCamelCase__       (						self :					Optional[int]		)     ->					Optional[Any]:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: Any     			=StableDiffusionInstructPixaPixPipeline.from_pretrained(
         """timbrooks/instruct-pix2pix"""       ,		safety_checker=lowerCAmelCase		)
     SCREAMING_SNAKE_CASE_: Tuple     			=DDIMScheduler.from_config(pipe.scheduler.config		)
     pipe.to(lowerCAmelCase		)
     pipe.set_progress_bar_config(disable=lowerCAmelCase		)
     pipe.enable_attention_slicing()

     SCREAMING_SNAKE_CASE_: Dict     			=self.get_inputs()
     SCREAMING_SNAKE_CASE_: Any     			=pipe(**lowerCAmelCase		).images
     SCREAMING_SNAKE_CASE_: int     			=image[0, -3:, -3:, -1].flatten()

     assert image.shape == (1, 512, 512, 3)
     SCREAMING_SNAKE_CASE_: Any     			=np.array([0.3_8_2_8, 0.3_8_3_4, 0.3_8_1_8, 0.3_7_9_2, 0.3_8_6_5, 0.3_7_5_2, 0.3_7_9_2, 0.3_8_4_7, 0.3_7_5_3]		)

     assert np.abs(expected_slice - image_slice		).max() < 1E-3



  def 	lowerCamelCase__       (						self :					int		)     ->					Union[str, Any]:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: int     			=0

     def callback_fn(lowerCAmelCase :					int       ,		lowerCAmelCase :					int       ,		lowerCAmelCase :					torch.FloatTensor		) -> None:
        SCREAMING_SNAKE_CASE_: str     			=True
        nonlocal number_of_steps
        number_of_steps += 1
        if step == 1:
           SCREAMING_SNAKE_CASE_: List[str]     			=latents.detach().cpu().numpy()
           assert latents.shape == (1, 4, 64, 64)
           SCREAMING_SNAKE_CASE_: str     			=latents[0, -3:, -3:, -1]
           SCREAMING_SNAKE_CASE_: Tuple     			=np.array([-0.2_4_6_3, -0.4_6_4_4, -0.9_7_5_6, 1.5_1_7_6, 1.4_4_1_4, 0.7_8_6_6, 0.9_8_9_7, 0.8_5_2_1, 0.7_9_8_3]		)

           assert np.abs(latents_slice.flatten() - expected_slice		).max() < 5E-2
        elif step == 2:
           SCREAMING_SNAKE_CASE_: int     			=latents.detach().cpu().numpy()
           assert latents.shape == (1, 4, 64, 64)
           SCREAMING_SNAKE_CASE_: Union[str, Any]     			=latents[0, -3:, -3:, -1]
           SCREAMING_SNAKE_CASE_: List[str]     			=np.array([-0.2_6_4_4, -0.4_6_2_6, -0.9_6_5_3, 1.5_1_7_6, 1.4_5_5_1, 0.7_6_8_6, 0.9_8_0_5, 0.8_4_5_2, 0.8_1_1_5]		)

           assert np.abs(latents_slice.flatten() - expected_slice		).max() < 5E-2

     SCREAMING_SNAKE_CASE_: Any     			=False

     SCREAMING_SNAKE_CASE_: int     			=StableDiffusionInstructPixaPixPipeline.from_pretrained(
         """timbrooks/instruct-pix2pix"""       ,		safety_checker=lowerCAmelCase       ,		torch_dtype=torch.floataa		)
     SCREAMING_SNAKE_CASE_: List[str]     			=pipe.to(lowerCAmelCase		)
     pipe.set_progress_bar_config(disable=lowerCAmelCase		)
     pipe.enable_attention_slicing()

     SCREAMING_SNAKE_CASE_: int     			=self.get_inputs()
     pipe(**lowerCAmelCase       ,		callback=lowerCAmelCase       ,		callback_steps=1		)
     assert callback_fn.has_been_called
     assert number_of_steps == 3



  def 	lowerCamelCase__       (						self :					Optional[Any]		)     ->					Dict:


     '''simple docstring'''




     torch.cuda.empty_cache()
     torch.cuda.reset_max_memory_allocated()
     torch.cuda.reset_peak_memory_stats()

     SCREAMING_SNAKE_CASE_: List[Any]     			=StableDiffusionInstructPixaPixPipeline.from_pretrained(
         """timbrooks/instruct-pix2pix"""       ,		safety_checker=lowerCAmelCase       ,		torch_dtype=torch.floataa		)
     SCREAMING_SNAKE_CASE_: Union[str, Any]     			=pipe.to(lowerCAmelCase		)
     pipe.set_progress_bar_config(disable=lowerCAmelCase		)
     pipe.enable_attention_slicing(1		)
     pipe.enable_sequential_cpu_offload()

     SCREAMING_SNAKE_CASE_: Any     			=self.get_inputs()
     SCREAMING_SNAKE_CASE_: Dict     			=pipe(**lowerCAmelCase		)

     SCREAMING_SNAKE_CASE_: Optional[int]     			=torch.cuda.max_memory_allocated()
     # make sure that less than 2.2 GB is allocated
     assert mem_bytes < 2.2 * 10**9





  def 	lowerCamelCase__       (						self :					Optional[int]		)     ->					Optional[int]:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: Optional[int]     			=self.get_inputs()
     # resize to resolution that is divisible by 8 but not 16 or 32
     SCREAMING_SNAKE_CASE_: Optional[Any]     			=inputs["""image"""].resize((504, 504)		)

     SCREAMING_SNAKE_CASE_: List[str]     			="""timbrooks/instruct-pix2pix"""
     SCREAMING_SNAKE_CASE_: str     			=StableDiffusionInstructPixaPixPipeline.from_pretrained(
         lowerCAmelCase       ,		safety_checker=lowerCAmelCase       ,		)
     pipe.to(lowerCAmelCase		)
     pipe.set_progress_bar_config(disable=lowerCAmelCase		)
     pipe.enable_attention_slicing()

     SCREAMING_SNAKE_CASE_: int     			=pipe(**lowerCAmelCase		)
     SCREAMING_SNAKE_CASE_: int     			=output.images[0]

     SCREAMING_SNAKE_CASE_: Optional[int]     			=image[255:258, 383:386, -1]

     assert image.shape == (504, 504, 3)
     SCREAMING_SNAKE_CASE_: List[str]     			=np.array([0.2_7_2_6, 0.2_5_2_9, 0.2_6_6_4, 0.2_6_5_5, 0.2_6_4_1, 0.2_6_4_2, 0.2_5_9_1, 0.2_6_4_9, 0.2_5_9_0]		)

     assert np.abs(image_slice.flatten() - expected_slice		).max() < 5E-3








"""simple docstring"""
def      __magic_name__				(							lowercase ):
   if upper_limit < 0:
      raise ValueError("""Limit for the Catalan sequence must be ≥ 0""" )

   SCREAMING_SNAKE_CASE_: Tuple     			=[0] * (upper_limit + 1)

   # Base case: C(0) = C(1) = 1
   SCREAMING_SNAKE_CASE_: Any     			=1
   if upper_limit > 0:
      SCREAMING_SNAKE_CASE_: List[str]     			=1

   # Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i
   for i in range(2							,			upper_limit + 1 ):
      for j in range(lowercase ):
         catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1]

   return catalan_list


if __name__ == "__main__":
   print("""\n********* Catalan Numbers Using Dynamic Programming ************\n""")
   print("""\n*** Enter -1 at any time to quit ***""")
   print("""\nEnter the upper limit (≥ 0) for the Catalan number sequence: """, end="""""")
   try:
      while True:
         _UpperCAmelCase     =			int(input().strip())
         if N < 0:
            print("""\n********* Goodbye!! ************""")
            break
         else:
            print(f"""The Catalan numbers from 0 through {N} are:""")
            print(catalan_numbers(N))
            print("""Try another upper limit for the sequence: """, end="""""")
   except (NameError, ValueError):
      print("""\n********* Invalid input, goodbye! ************\n""")

   import doctest

   doctest.testmod()



