

'''simple docstring'''



import gc
import random
import unittest

import numpy as np
import torch
from transformers import (
    CLIPImageProcessor,
    CLIPTextConfig,
    CLIPTextModelWithProjection,
    CLIPTokenizer,
    CLIPVisionConfig,
    CLIPVisionModelWithProjection,
)

from diffusers import (
    DiffusionPipeline,
    UnCLIPImageVariationPipeline,
    UnCLIPScheduler,
    UNetaDConditionModel,
    UNetaDModel,
)
from diffusers.pipelines.unclip.text_proj import UnCLIPTextProjModel
from diffusers.utils import floats_tensor, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, load_image, require_torch_gpu, skip_mps

from ..pipeline_params import IMAGE_VARIATION_BATCH_PARAMS, IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference


enable_full_determinism()







class 						lowerCAmelCase__   (      a ,					unittest.TestCase					):



 """simple docstring"""



 lowerCAmelCase__  					=      UnCLIPImageVariationPipeline
 lowerCAmelCase__  					=      IMAGE_VARIATION_PARAMS - {"height", "width", "guidance_scale"}
 lowerCAmelCase__  					=      IMAGE_VARIATION_BATCH_PARAMS

 lowerCAmelCase__  					=      [
     "generator",
     "return_dict",
     "decoder_num_inference_steps",
     "super_res_num_inference_steps",
 ]
 lowerCAmelCase__  					=      False
 @property
 def       UpperCAmelCase__		(		self					:       Optional[int]			)  -> Optional[int]:


      """simple docstring"""




      return 32
 @property
 def       UpperCAmelCase__		(		self					:       Union[str, Any]			)  -> Union[str, Any]:


      """simple docstring"""




      return 32
 @property
 def       UpperCAmelCase__		(		self					:       Optional[Any]			)  -> int:


      """simple docstring"""




      return self.time_input_dim
 @property
 def       UpperCAmelCase__		(		self					:       List[str]			)  -> Optional[Any]:


      """simple docstring"""




      return self.time_input_dim * 4
 @property
 def       UpperCAmelCase__		(		self					:       Any			)  -> str:


      """simple docstring"""




      return 100
 @property
 def       UpperCAmelCase__		(		self					:       Tuple			)  -> Dict:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""			)
      return tokenizer
 @property
 def       UpperCAmelCase__		(		self					:       List[str]			)  -> Optional[int]:


      """simple docstring"""




      torch.manual_seed(0			)
      __SCREAMING_SNAKE_CASE     =      CLIPTextConfig(
          bos_token_id=0					,							eos_token_id=2					,							hidden_size=self.text_embedder_hidden_size					,							projection_dim=self.text_embedder_hidden_size					,							intermediate_size=37					,							layer_norm_eps=1E-05					,							num_attention_heads=4					,							num_hidden_layers=5					,							pad_token_id=1					,							vocab_size=1_000					,							)
      return CLIPTextModelWithProjection(__SCREAMING_SNAKE_CASE			)
 @property
 def       UpperCAmelCase__		(		self					:       Union[str, Any]			)  -> Dict:


      """simple docstring"""




      torch.manual_seed(0			)
      __SCREAMING_SNAKE_CASE     =      CLIPVisionConfig(
          hidden_size=self.text_embedder_hidden_size					,							projection_dim=self.text_embedder_hidden_size					,							num_hidden_layers=5					,							num_attention_heads=4					,							image_size=32					,							intermediate_size=37					,							patch_size=1					,							)
      return CLIPVisionModelWithProjection(__SCREAMING_SNAKE_CASE			)
 @property
 def       UpperCAmelCase__		(		self					:       List[Any]			)  -> Any:


      """simple docstring"""




      torch.manual_seed(0			)

      __SCREAMING_SNAKE_CASE     =      {
          """clip_embeddings_dim""": self.text_embedder_hidden_size,
          """time_embed_dim""": self.time_embed_dim,
          """cross_attention_dim""": self.cross_attention_dim,
      }

      __SCREAMING_SNAKE_CASE     =      UnCLIPTextProjModel(**__SCREAMING_SNAKE_CASE			)
      return model
 @property
 def       UpperCAmelCase__		(		self					:       List[Any]			)  -> Optional[Any]:


      """simple docstring"""




      torch.manual_seed(0			)

      __SCREAMING_SNAKE_CASE     =      {
          """sample_size""": 32,
          # RGB in channels
          """in_channels""": 3,
          # Out channels is double in channels because predicts mean and variance
          """out_channels""": 6,
          """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""),
          """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""),
          """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""",
          """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2),
          """layers_per_block""": 1,
          """cross_attention_dim""": self.cross_attention_dim,
          """attention_head_dim""": 4,
          """resnet_time_scale_shift""": """scale_shift""",
          """class_embed_type""": """identity""",
      }

      __SCREAMING_SNAKE_CASE     =      UNetaDConditionModel(**__SCREAMING_SNAKE_CASE			)
      return model
 @property
 def       UpperCAmelCase__		(		self					:       Optional[Any]			)  -> Optional[int]:


      """simple docstring"""




      return {
          "sample_size": 64,
          "layers_per_block": 1,
          "down_block_types": ("ResnetDownsampleBlock2D", "ResnetDownsampleBlock2D"),
          "up_block_types": ("ResnetUpsampleBlock2D", "ResnetUpsampleBlock2D"),
          "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2),
          "in_channels": 6,
          "out_channels": 3,
      }
 @property
 def       UpperCAmelCase__		(		self					:       str			)  -> List[Any]:


      """simple docstring"""




      torch.manual_seed(0			)

      __SCREAMING_SNAKE_CASE     =      UNetaDModel(**self.dummy_super_res_kwargs			)
      return model
 @property
 def       UpperCAmelCase__		(		self					:       Any			)  -> str:


      """simple docstring"""




      torch.manual_seed(1			)

      __SCREAMING_SNAKE_CASE     =      UNetaDModel(**self.dummy_super_res_kwargs			)
      return model
 def       UpperCAmelCase__		(		self					:       Any			)  -> Any:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      self.dummy_decoder
      __SCREAMING_SNAKE_CASE     =      self.dummy_text_proj
      __SCREAMING_SNAKE_CASE     =      self.dummy_text_encoder
      __SCREAMING_SNAKE_CASE     =      self.dummy_tokenizer
      __SCREAMING_SNAKE_CASE     =      self.dummy_super_res_first
      __SCREAMING_SNAKE_CASE     =      self.dummy_super_res_last

      __SCREAMING_SNAKE_CASE     =      UnCLIPScheduler(
          variance_type="""learned_range"""					,							prediction_type="""epsilon"""					,							num_train_timesteps=1_000					,							)

      __SCREAMING_SNAKE_CASE     =      UnCLIPScheduler(
          variance_type="""fixed_small_log"""					,							prediction_type="""epsilon"""					,							num_train_timesteps=1_000					,							)

      __SCREAMING_SNAKE_CASE     =      CLIPImageProcessor(crop_size=32					,							size=32			)

      __SCREAMING_SNAKE_CASE     =      self.dummy_image_encoder

      return {
          "decoder": decoder,
          "text_encoder": text_encoder,
          "tokenizer": tokenizer,
          "text_proj": text_proj,
          "feature_extractor": feature_extractor,
          "image_encoder": image_encoder,
          "super_res_first": super_res_first,
          "super_res_last": super_res_last,
          "decoder_scheduler": decoder_scheduler,
          "super_res_scheduler": super_res_scheduler,
      }
 def       UpperCAmelCase__		(		self					:       str					,							__SCREAMING_SNAKE_CASE					:       List[str]					,							__SCREAMING_SNAKE_CASE					:       List[Any]=0					,							__SCREAMING_SNAKE_CASE					:       int=True			)  -> str:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      floats_tensor((1, 3, 32, 32)					,							rng=random.Random(__SCREAMING_SNAKE_CASE			)			).to(__SCREAMING_SNAKE_CASE			)
      if str(__SCREAMING_SNAKE_CASE			).startswith("""mps"""			):
           __SCREAMING_SNAKE_CASE     =      torch.manual_seed(__SCREAMING_SNAKE_CASE			)
      else:
           __SCREAMING_SNAKE_CASE     =      torch.Generator(device=__SCREAMING_SNAKE_CASE			).manual_seed(__SCREAMING_SNAKE_CASE			)

      if pil_image:
           __SCREAMING_SNAKE_CASE     =      input_image * 0.5 + 0.5
           __SCREAMING_SNAKE_CASE     =      input_image.clamp(0					,							1			)
           __SCREAMING_SNAKE_CASE     =      input_image.cpu().permute(0					,							2					,							3					,							1			).float().numpy()
           __SCREAMING_SNAKE_CASE     =      DiffusionPipeline.numpy_to_pil(__SCREAMING_SNAKE_CASE			)[0]

      return {
          "image": input_image,
          "generator": generator,
          "decoder_num_inference_steps": 2,
          "super_res_num_inference_steps": 2,
          "output_type": "np",
      }
 def       UpperCAmelCase__		(		self					:       List[Any]			)  -> Any:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      """cpu"""

      __SCREAMING_SNAKE_CASE     =      self.get_dummy_components()

      __SCREAMING_SNAKE_CASE     =      self.pipeline_class(**__SCREAMING_SNAKE_CASE			)
      __SCREAMING_SNAKE_CASE     =      pipe.to(__SCREAMING_SNAKE_CASE			)

      pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE			)

      __SCREAMING_SNAKE_CASE     =      self.get_dummy_inputs(__SCREAMING_SNAKE_CASE					,							pil_image=__SCREAMING_SNAKE_CASE			)

      __SCREAMING_SNAKE_CASE     =      pipe(**__SCREAMING_SNAKE_CASE			)
      __SCREAMING_SNAKE_CASE     =      output.images

      __SCREAMING_SNAKE_CASE     =      self.get_dummy_inputs(__SCREAMING_SNAKE_CASE					,							pil_image=__SCREAMING_SNAKE_CASE			)

      __SCREAMING_SNAKE_CASE     =      pipe(
          **__SCREAMING_SNAKE_CASE					,							return_dict=__SCREAMING_SNAKE_CASE					,							)[0]

      __SCREAMING_SNAKE_CASE     =      image[0, -3:, -3:, -1]
      __SCREAMING_SNAKE_CASE     =      image_from_tuple[0, -3:, -3:, -1]

      assert image.shape == (1, 64, 64, 3)

      __SCREAMING_SNAKE_CASE     =      np.array(
          [
              0.9997,
              0.0002,
              0.9997,
              0.9997,
              0.9969,
              0.0023,
              0.9997,
              0.9969,
              0.9970,
          ]			)

      assert np.abs(image_slice.flatten() - expected_slice			).max() < 1E-2
      assert np.abs(image_from_tuple_slice.flatten() - expected_slice			).max() < 1E-2
 def       UpperCAmelCase__		(		self					:       str			)  -> Any:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      """cpu"""

      __SCREAMING_SNAKE_CASE     =      self.get_dummy_components()

      __SCREAMING_SNAKE_CASE     =      self.pipeline_class(**__SCREAMING_SNAKE_CASE			)
      __SCREAMING_SNAKE_CASE     =      pipe.to(__SCREAMING_SNAKE_CASE			)

      pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE			)

      __SCREAMING_SNAKE_CASE     =      self.get_dummy_inputs(__SCREAMING_SNAKE_CASE					,							pil_image=__SCREAMING_SNAKE_CASE			)

      __SCREAMING_SNAKE_CASE     =      pipe(**__SCREAMING_SNAKE_CASE			)
      __SCREAMING_SNAKE_CASE     =      output.images

      __SCREAMING_SNAKE_CASE     =      self.get_dummy_inputs(__SCREAMING_SNAKE_CASE					,							pil_image=__SCREAMING_SNAKE_CASE			)

      __SCREAMING_SNAKE_CASE     =      pipe(
          **__SCREAMING_SNAKE_CASE					,							return_dict=__SCREAMING_SNAKE_CASE					,							)[0]

      __SCREAMING_SNAKE_CASE     =      image[0, -3:, -3:, -1]
      __SCREAMING_SNAKE_CASE     =      image_from_tuple[0, -3:, -3:, -1]

      assert image.shape == (1, 64, 64, 3)

      __SCREAMING_SNAKE_CASE     =      np.array([0.9997, 0.0003, 0.9997, 0.9997, 0.9970, 0.0024, 0.9997, 0.9971, 0.9971]			)

      assert np.abs(image_slice.flatten() - expected_slice			).max() < 1E-2
      assert np.abs(image_from_tuple_slice.flatten() - expected_slice			).max() < 1E-2
 def       UpperCAmelCase__		(		self					:       int			)  -> Tuple:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      """cpu"""

      __SCREAMING_SNAKE_CASE     =      self.get_dummy_components()

      __SCREAMING_SNAKE_CASE     =      self.pipeline_class(**__SCREAMING_SNAKE_CASE			)
      __SCREAMING_SNAKE_CASE     =      pipe.to(__SCREAMING_SNAKE_CASE			)

      pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE			)

      __SCREAMING_SNAKE_CASE     =      self.get_dummy_inputs(__SCREAMING_SNAKE_CASE					,							pil_image=__SCREAMING_SNAKE_CASE			)
      __SCREAMING_SNAKE_CASE     =      [
          pipeline_inputs["""image"""],
          pipeline_inputs["""image"""],
      ]

      __SCREAMING_SNAKE_CASE     =      pipe(**__SCREAMING_SNAKE_CASE			)
      __SCREAMING_SNAKE_CASE     =      output.images

      __SCREAMING_SNAKE_CASE     =      self.get_dummy_inputs(__SCREAMING_SNAKE_CASE					,							pil_image=__SCREAMING_SNAKE_CASE			)
      __SCREAMING_SNAKE_CASE     =      [
          tuple_pipeline_inputs["""image"""],
          tuple_pipeline_inputs["""image"""],
      ]

      __SCREAMING_SNAKE_CASE     =      pipe(
          **__SCREAMING_SNAKE_CASE					,							return_dict=__SCREAMING_SNAKE_CASE					,							)[0]

      __SCREAMING_SNAKE_CASE     =      image[0, -3:, -3:, -1]
      __SCREAMING_SNAKE_CASE     =      image_from_tuple[0, -3:, -3:, -1]

      assert image.shape == (2, 64, 64, 3)

      __SCREAMING_SNAKE_CASE     =      np.array(
          [
              0.9997,
              0.9989,
              0.0008,
              0.0021,
              0.9960,
              0.0018,
              0.0014,
              0.0002,
              0.9933,
          ]			)

      assert np.abs(image_slice.flatten() - expected_slice			).max() < 1E-2
      assert np.abs(image_from_tuple_slice.flatten() - expected_slice			).max() < 1E-2
 def       UpperCAmelCase__		(		self					:       Optional[int]			)  -> Any:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      torch.device("""cpu"""			)







      class 						lowerCAmelCase__   :



       """simple docstring"""



       lowerCAmelCase__  					=      1


      __SCREAMING_SNAKE_CASE     =      self.get_dummy_components()

      __SCREAMING_SNAKE_CASE     =      self.pipeline_class(**__SCREAMING_SNAKE_CASE			)
      __SCREAMING_SNAKE_CASE     =      pipe.to(__SCREAMING_SNAKE_CASE			)

      pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE			)

      __SCREAMING_SNAKE_CASE     =      torch.Generator(device=__SCREAMING_SNAKE_CASE			).manual_seed(0			)
      __SCREAMING_SNAKE_CASE     =      pipe.decoder.dtype
      __SCREAMING_SNAKE_CASE     =      1

      __SCREAMING_SNAKE_CASE     =      (
          batch_size,
          pipe.decoder.config.in_channels,
          pipe.decoder.config.sample_size,
          pipe.decoder.config.sample_size,
      )
      __SCREAMING_SNAKE_CASE     =      pipe.prepare_latents(
          __SCREAMING_SNAKE_CASE					,							dtype=__SCREAMING_SNAKE_CASE					,							device=__SCREAMING_SNAKE_CASE					,							generator=__SCREAMING_SNAKE_CASE					,							latents=__SCREAMING_SNAKE_CASE					,							scheduler=DummyScheduler()			)

      __SCREAMING_SNAKE_CASE     =      (
          batch_size,
          pipe.super_res_first.config.in_channels // 2,
          pipe.super_res_first.config.sample_size,
          pipe.super_res_first.config.sample_size,
      )
      __SCREAMING_SNAKE_CASE     =      pipe.prepare_latents(
          __SCREAMING_SNAKE_CASE					,							dtype=__SCREAMING_SNAKE_CASE					,							device=__SCREAMING_SNAKE_CASE					,							generator=__SCREAMING_SNAKE_CASE					,							latents=__SCREAMING_SNAKE_CASE					,							scheduler=DummyScheduler()			)

      __SCREAMING_SNAKE_CASE     =      self.get_dummy_inputs(__SCREAMING_SNAKE_CASE					,							pil_image=__SCREAMING_SNAKE_CASE			)

      __SCREAMING_SNAKE_CASE     =      pipe(
          **__SCREAMING_SNAKE_CASE					,							decoder_latents=__SCREAMING_SNAKE_CASE					,							super_res_latents=__SCREAMING_SNAKE_CASE			).images

      __SCREAMING_SNAKE_CASE     =      self.get_dummy_inputs(__SCREAMING_SNAKE_CASE					,							pil_image=__SCREAMING_SNAKE_CASE			)
      # Don't pass image, instead pass embedding
      __SCREAMING_SNAKE_CASE     =      pipeline_inputs.pop("""image"""			)
      __SCREAMING_SNAKE_CASE     =      pipe.image_encoder(__SCREAMING_SNAKE_CASE			).image_embeds

      __SCREAMING_SNAKE_CASE     =      pipe(
          **__SCREAMING_SNAKE_CASE					,							decoder_latents=__SCREAMING_SNAKE_CASE					,							super_res_latents=__SCREAMING_SNAKE_CASE					,							image_embeddings=__SCREAMING_SNAKE_CASE					,							).images

      # make sure passing text embeddings manually is identical
      assert np.abs(img_out_a - img_out_a			).max() < 1E-4
 @skip_mps
 def       UpperCAmelCase__		(		self					:       List[str]			)  -> List[Any]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      torch_device == """cpu"""

      # Check is relaxed because there is not a torch 2.0 sliced attention added kv processor
      __SCREAMING_SNAKE_CASE     =      1E-2

      self._test_attention_slicing_forward_pass(
          test_max_difference=__SCREAMING_SNAKE_CASE					,							expected_max_diff=__SCREAMING_SNAKE_CASE			)
 @skip_mps
 def       UpperCAmelCase__		(		self					:       Optional[int]			)  -> int:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      torch_device == """cpu"""
      __SCREAMING_SNAKE_CASE     =      True
      __SCREAMING_SNAKE_CASE     =      [
          """decoder_num_inference_steps""",
          """super_res_num_inference_steps""",
      ]

      self._test_inference_batch_single_identical(
          test_max_difference=__SCREAMING_SNAKE_CASE					,							relax_max_difference=__SCREAMING_SNAKE_CASE					,							additional_params_copy_to_batched_inputs=__SCREAMING_SNAKE_CASE					,							)
 def       UpperCAmelCase__		(		self					:       Tuple			)  -> Optional[int]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      [
          """decoder_num_inference_steps""",
          """super_res_num_inference_steps""",
      ]

      if torch_device == "mps":
           # TODO: MPS errors with larger batch sizes
           __SCREAMING_SNAKE_CASE     =      [2, 3]
           self._test_inference_batch_consistent(
               batch_sizes=__SCREAMING_SNAKE_CASE					,							additional_params_copy_to_batched_inputs=__SCREAMING_SNAKE_CASE					,							)
      else:
           self._test_inference_batch_consistent(
               additional_params_copy_to_batched_inputs=__SCREAMING_SNAKE_CASE			)
 @skip_mps
 def       UpperCAmelCase__		(		self					:       Any			)  -> Tuple:


      """simple docstring"""




      return super().test_dict_tuple_outputs_equivalent()
 @skip_mps
 def       UpperCAmelCase__		(		self					:       Tuple			)  -> List[str]:


      """simple docstring"""




      return super().test_save_load_local()


 @skip_mps
 def       UpperCAmelCase__		(		self					:       Dict			)  -> List[Any]:


      """simple docstring"""




      return super().test_save_load_optional_components()







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



 """simple docstring"""



 def       UpperCAmelCase__		(		self					:       Dict			)  -> str:


      """simple docstring"""




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


 def       UpperCAmelCase__		(		self					:       List[str]			)  -> List[Any]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      load_image(
          """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/unclip/cat.png"""			)
      __SCREAMING_SNAKE_CASE     =      load_numpy(
          """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
          """/unclip/karlo_v1_alpha_cat_variation_fp16.npy"""			)

      __SCREAMING_SNAKE_CASE     =      UnCLIPImageVariationPipeline.from_pretrained(
          """kakaobrain/karlo-v1-alpha-image-variations"""					,							torch_dtype=torch.floataa			)
      __SCREAMING_SNAKE_CASE     =      pipeline.to(__SCREAMING_SNAKE_CASE			)
      pipeline.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE			)

      __SCREAMING_SNAKE_CASE     =      torch.Generator(device="""cpu"""			).manual_seed(0			)
      __SCREAMING_SNAKE_CASE     =      pipeline(
          __SCREAMING_SNAKE_CASE					,							generator=__SCREAMING_SNAKE_CASE					,							output_type="""np"""					,							)

      __SCREAMING_SNAKE_CASE     =      output.images[0]

      assert image.shape == (256, 256, 3)

      assert_mean_pixel_difference(__SCREAMING_SNAKE_CASE					,							__SCREAMING_SNAKE_CASE					,							15			)









'''simple docstring'''



def    a__       (  a__      ,    a__						):




     """simple docstring"""


     _enforce_args(a__      ,    a__						)
     if n == 0:
          return 0
     __SCREAMING_SNAKE_CASE     =      float("""-inf"""						)
     for i in range(1      ,    n + 1						):
          __SCREAMING_SNAKE_CASE     =      max(
              a__      ,    prices[i - 1] + naive_cut_rod_recursive(n - i      ,    a__						)						)

     return max_revue







def    a__       (  a__      ,    a__						):




     """simple docstring"""


     _enforce_args(a__      ,    a__						)
     __SCREAMING_SNAKE_CASE     =      [float("""-inf"""						) for _ in range(n + 1						)]
     return _top_down_cut_rod_recursive(a__      ,    a__      ,    a__						)







def    a__       (  a__      ,    a__      ,    a__						):




     """simple docstring"""


     if max_rev[n] >= 0:
          return max_rev[n]
     elif n == 0:
          return 0
     else:
          __SCREAMING_SNAKE_CASE     =      float("""-inf"""						)
          for i in range(1      ,    n + 1						):
               __SCREAMING_SNAKE_CASE     =      max(
                   a__      ,    prices[i - 1] + _top_down_cut_rod_recursive(n - i      ,    a__      ,    a__						)      ,    )

          __SCREAMING_SNAKE_CASE     =      max_revenue

     return max_rev[n]







def    a__       (  a__      ,    a__						):




     """simple docstring"""


     _enforce_args(a__      ,    a__						)

     # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of
     # length 0.
     __SCREAMING_SNAKE_CASE     =      [float("""-inf"""						) for _ in range(n + 1						)]
     __SCREAMING_SNAKE_CASE     =      0

     for i in range(1      ,    n + 1						):
          __SCREAMING_SNAKE_CASE     =      max_rev[i]
          for j in range(1      ,    i + 1						):
               __SCREAMING_SNAKE_CASE     =      max(a__      ,    prices[j - 1] + max_rev[i - j]						)

          __SCREAMING_SNAKE_CASE     =      max_revenue_i

     return max_rev[n]







def    a__       (  a__      ,    a__						):




     """simple docstring"""


     if n < 0:
          __SCREAMING_SNAKE_CASE     =      F'n must be greater than or equal to 0. Got n = {n}'
          raise ValueError(a__						)

     if n > len(a__						):
          __SCREAMING_SNAKE_CASE     =      (
              """Each integral piece of rod must have a corresponding price. """
              F'Got n = {n} but length of prices = {len(a__						)}'
          )
          raise ValueError(a__						)







def    a__       (  ):




     """simple docstring"""


     __SCREAMING_SNAKE_CASE     =      [6, 10, 12, 15, 20, 23]
     __SCREAMING_SNAKE_CASE     =      len(a__						)

     # the best revenue comes from cutting the rod into 6 pieces, each
     # of length 1 resulting in a revenue of 6 * 6 = 36.
     __SCREAMING_SNAKE_CASE     =      36

     __SCREAMING_SNAKE_CASE     =      top_down_cut_rod(a__      ,    a__						)
     __SCREAMING_SNAKE_CASE     =      bottom_up_cut_rod(a__      ,    a__						)
     __SCREAMING_SNAKE_CASE     =      naive_cut_rod_recursive(a__      ,    a__						)

     assert expected_max_revenue == max_rev_top_down
     assert max_rev_top_down == max_rev_bottom_up
     assert max_rev_bottom_up == max_rev_naive


if __name__ == "__main__":
  main()






