






import argparse
import copy







def       lowercase__	(					A_:						Tuple		)	->				Dict:







       """simple docstring"""






       __UpperCAmelCase     				={}

       with open(A_		) as f:
              for line in f:
                     if line.split()[0] not in dict_of_neighbours:
                            __UpperCAmelCase     				=[]
                            _list.append([line.split()[1], line.split()[2]]		)
                            __UpperCAmelCase     				=_list
                     else:
                            dict_of_neighbours[line.split()[0]].append(
                                [line.split()[1], line.split()[2]]		)
                     if line.split()[1] not in dict_of_neighbours:
                            __UpperCAmelCase     				=[]
                            _list.append([line.split()[0], line.split()[2]]		)
                            __UpperCAmelCase     				=_list
                     else:
                            dict_of_neighbours[line.split()[1]].append(
                                [line.split()[0], line.split()[2]]		)

       return dict_of_neighbours







def       lowercase__	(					A_:						str  ,      A_:						List[str]		)	->				Optional[Any]:







       """simple docstring"""






       with open(A_		) as f:
              __UpperCAmelCase     				=f.read(1		)
       __UpperCAmelCase     				=start_node

       __UpperCAmelCase     				=[]

       __UpperCAmelCase     				=start_node

       __UpperCAmelCase     				=0
       while visiting not in first_solution:
              __UpperCAmelCase     				=10000
              for k in dict_of_neighbours[visiting]:
                     if int(k[1]		) < int(A_		) and k[0] not in first_solution:
                            __UpperCAmelCase     				=k[1]
                            __UpperCAmelCase     				=k[0]

              first_solution.append(A_		)
              __UpperCAmelCase     				=distance_of_first_solution + int(A_		)
              __UpperCAmelCase     				=best_node

       first_solution.append(A_		)

       __UpperCAmelCase     				=0
       for k in dict_of_neighbours[first_solution[-2]]:
              if k[0] == start_node:
                     break
              position += 1

       __UpperCAmelCase     				=(
           distance_of_first_solution
           + int(dict_of_neighbours[first_solution[-2]][position][1]		)
           - 10000
       )
       return first_solution, distance_of_first_solution







def       lowercase__	(					A_:						Any  ,      A_:						Optional[Any]		)	->				str:







       """simple docstring"""






       __UpperCAmelCase     				=[]

       for n in solution[1:-1]:
              __UpperCAmelCase     				=solution.index(A_		)
              for kn in solution[1:-1]:
                     __UpperCAmelCase     				=solution.index(A_		)
                     if n == kn:
                            continue

                     __UpperCAmelCase     				=copy.deepcopy(A_		)
                     __UpperCAmelCase     				=kn
                     __UpperCAmelCase     				=n

                     __UpperCAmelCase     				=0

                     for k in _tmp[:-1]:
                            __UpperCAmelCase     				=_tmp[_tmp.index(A_		) + 1]
                            for i in dict_of_neighbours[k]:
                                   if i[0] == next_node:
                                          __UpperCAmelCase     				=distance + int(i[1]		)
                     _tmp.append(A_		)

                     if _tmp not in neighborhood_of_solution:
                            neighborhood_of_solution.append(_tmp		)

       __UpperCAmelCase     				=len(neighborhood_of_solution[0]		) - 1

       neighborhood_of_solution.sort(key=lambda A_		: x[index_of_last_item_in_the_list]		)
       return neighborhood_of_solution







def       lowercase__	(					A_:						List[Any]  ,      A_:						List[str]  ,      A_:						Union[str, Any]  ,      A_:						Optional[Any]  ,      A_:						Optional[Any]		)	->				List[Any]:







       """simple docstring"""






       __UpperCAmelCase     				=1
       __UpperCAmelCase     				=first_solution
       __UpperCAmelCase     				=[]
       __UpperCAmelCase     				=distance_of_first_solution
       __UpperCAmelCase     				=solution

       while count <= iters:
              __UpperCAmelCase     				=find_neighborhood(A_  ,      A_		)
              __UpperCAmelCase     				=0
              __UpperCAmelCase     				=neighborhood[index_of_best_solution]
              __UpperCAmelCase     				=len(A_		) - 1

              __UpperCAmelCase     				=False
              while not found:
                     __UpperCAmelCase     				=0
                     while i < len(A_		):
                            if best_solution[i] != solution[i]:
                                   __UpperCAmelCase     				=best_solution[i]
                                   __UpperCAmelCase     				=solution[i]
                                   break
                            __UpperCAmelCase     				=i + 1

                     if [first_exchange_node, second_exchange_node] not in tabu_list and [
                         second_exchange_node,
                         first_exchange_node,
                     ] not in tabu_list:
                            tabu_list.append([first_exchange_node, second_exchange_node]		)
                            __UpperCAmelCase     				=True
                            __UpperCAmelCase     				=best_solution[:-1]
                            __UpperCAmelCase     				=neighborhood[index_of_best_solution][best_cost_index]
                            if cost < best_cost:
                                   __UpperCAmelCase     				=cost
                                   __UpperCAmelCase     				=solution
                     else:
                            __UpperCAmelCase     				=index_of_best_solution + 1
                            __UpperCAmelCase     				=neighborhood[index_of_best_solution]

              if len(A_		) >= size:
                     tabu_list.pop(0		)

              __UpperCAmelCase     				=count + 1

       return best_solution_ever, best_cost







def       lowercase__	(					A_:						Union[str, Any]=None		)	->				Tuple:







       """simple docstring"""






       __UpperCAmelCase     				=generate_neighbours(args.File		)

       __UpperCAmelCase				, __UpperCAmelCase     				=generate_first_solution(
           args.File  ,      A_		)

       __UpperCAmelCase				, __UpperCAmelCase     				=tabu_search(
           A_  ,      A_  ,      A_  ,      args.Iterations  ,      args.Size  ,      )

       print(F'''Best solution: {best_sol}, with total distance: {best_cost}.'''		)


if __name__ == "__main__":
   __A					=	argparse.ArgumentParser(description="Tabu Search")
   parser.add_argument(
       "-f",
       "--File",
       type=str,
       help="Path to the file containing the data",
       required=True,
   )
   parser.add_argument(
       "-i",
       "--Iterations",
       type=int,
       help="How many iterations the algorithm should perform",
       required=True,
   )
   parser.add_argument(
       "-s", "--Size", type=int, help="Size of the tabu list", required=True
   )

   # Pass the arguments to main method
   main(parser.parse_args())






import gc
import random
import tempfile
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMInverseScheduler,
    DDIMScheduler,
    DPMSolverMultistepInverseScheduler,
    DPMSolverMultistepScheduler,
    StableDiffusionDiffEditPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import load_image, slow
from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device

from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()






class     UpperCAmelCase						(		A_			,A_			,unittest.TestCase					):
   A__   :						Dict			=	StableDiffusionDiffEditPipeline
   A__   :						str			=	TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"height", "width", "image"} | {"image_latents"}
   A__   :						List[Any]			=	TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {"image"} | {"image_latents"}
   A__   :						Optional[Any]			=	frozenset(
       []					)  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
   A__   :						int			=	frozenset([]					)



   def 							_SCREAMING_SNAKE_CASE  (self						:   Tuple					)						->      Optional[Any]:


          '''simple docstring'''


          torch.manual_seed(0					)
          snake_case			:  Dict     							= UNetaDConditionModel(
              block_out_channels=(32, 64)       ,		layers_per_block=2       ,		sample_size=32       ,		in_channels=4       ,		out_channels=4       ,		down_block_types=("DownBlock2D", "CrossAttnDownBlock2D")       ,		up_block_types=("CrossAttnUpBlock2D", "UpBlock2D")       ,		cross_attention_dim=32       ,		attention_head_dim=(2, 4)       ,		use_linear_projection=snake_case__       ,		)
          snake_case			:  str     							= DDIMScheduler(
              beta_start=0.00085       ,		beta_end=0.012       ,		beta_schedule="scaled_linear"       ,		clip_sample=snake_case__       ,		set_alpha_to_one=snake_case__       ,		)
          snake_case			:  List[Any]     							= DDIMInverseScheduler(
              beta_start=0.00085       ,		beta_end=0.012       ,		beta_schedule="scaled_linear"       ,		clip_sample=snake_case__       ,		set_alpha_to_zero=snake_case__       ,		)
          torch.manual_seed(0					)
          snake_case			:  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       ,		sample_size=1_28       ,		)
          torch.manual_seed(0					)
          snake_case			:  Union[str, 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=10_00       ,		hidden_act="gelu"       ,		projection_dim=5_12       ,		)
          snake_case			:  str     							= CLIPTextModel(snake_case__					)
          snake_case			:  Optional[Any]     							= CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"					)

          snake_case			:  List[str]     							= {
              "unet": unet,
              "scheduler": scheduler,
              "inverse_scheduler": inverse_scheduler,
              "vae": vae,
              "text_encoder": text_encoder,
              "tokenizer": tokenizer,
              "safety_checker": None,
              "feature_extractor": None,
          }

          return components



   def 							_SCREAMING_SNAKE_CASE  (self						:   List[str]       ,		snake_case__						:   Dict       ,		snake_case__						:   Union[str, Any]=0					)						->      Optional[Any]:


          '''simple docstring'''


          snake_case			:  List[Any]     							= floats_tensor((1, 16, 16)       ,		rng=random.Random(snake_case__					)					).to(snake_case__					)
          snake_case			:  List[Any]     							= floats_tensor((1, 2, 4, 16, 16)       ,		rng=random.Random(snake_case__					)					).to(snake_case__					)
          if str(snake_case__					).startswith("mps"					):
                 snake_case			:  Any     							= torch.manual_seed(snake_case__					)
          else:
                 snake_case			:  Optional[Any]     							= torch.Generator(device=snake_case__					).manual_seed(snake_case__					)
          snake_case			:  Union[str, Any]     							= {
              "prompt": "a dog and a newt",
              "mask_image": mask,
              "image_latents": latents,
              "generator": generator,
              "num_inference_steps": 2,
              "inpaint_strength": 1.0,
              "guidance_scale": 6.0,
              "output_type": "numpy",
          }

          return inputs



   def 							_SCREAMING_SNAKE_CASE  (self						:   Tuple       ,		snake_case__						:   Optional[int]       ,		snake_case__						:   Optional[int]=0					)						->      Tuple:


          '''simple docstring'''


          snake_case			:  Tuple     							= floats_tensor((1, 3, 32, 32)       ,		rng=random.Random(snake_case__					)					).to(snake_case__					)
          snake_case			:  Optional[Any]     							= image.cpu().permute(0       ,		2       ,		3       ,		1					)[0]
          snake_case			:  Any     							= Image.fromarray(np.uinta(snake_case__					)					).convert("RGB"					)
          if str(snake_case__					).startswith("mps"					):
                 snake_case			:  int     							= torch.manual_seed(snake_case__					)
          else:
                 snake_case			:  Optional[int]     							= torch.Generator(device=snake_case__					).manual_seed(snake_case__					)
          snake_case			:  Any     							= {
              "image": image,
              "source_prompt": "a cat and a frog",
              "target_prompt": "a dog and a newt",
              "generator": generator,
              "num_inference_steps": 2,
              "num_maps_per_mask": 2,
              "mask_encode_strength": 1.0,
              "guidance_scale": 6.0,
              "output_type": "numpy",
          }

          return inputs



   def 							_SCREAMING_SNAKE_CASE  (self						:   Any       ,		snake_case__						:   Optional[Any]       ,		snake_case__						:   Tuple=0					)						->      Any:


          '''simple docstring'''


          snake_case			:  Optional[Any]     							= floats_tensor((1, 3, 32, 32)       ,		rng=random.Random(snake_case__					)					).to(snake_case__					)
          snake_case			:  Tuple     							= image.cpu().permute(0       ,		2       ,		3       ,		1					)[0]
          snake_case			:  List[Any]     							= Image.fromarray(np.uinta(snake_case__					)					).convert("RGB"					)
          if str(snake_case__					).startswith("mps"					):
                 snake_case			:  str     							= torch.manual_seed(snake_case__					)
          else:
                 snake_case			:  int     							= torch.Generator(device=snake_case__					).manual_seed(snake_case__					)
          snake_case			:  List[str]     							= {
              "image": image,
              "prompt": "a cat and a frog",
              "generator": generator,
              "num_inference_steps": 2,
              "inpaint_strength": 1.0,
              "guidance_scale": 6.0,
              "decode_latents": True,
              "output_type": "numpy",
          }
          return inputs



   def 							_SCREAMING_SNAKE_CASE  (self						:   List[str]					)						->      str:


          '''simple docstring'''


          if not hasattr(self.pipeline_class       ,		"_optional_components"					):
                 return

          snake_case			:  int     							= self.get_dummy_components()
          snake_case			:  Optional[int]     							= self.pipeline_class(**snake_case__					)
          pipe.to(snake_case__					)
          pipe.set_progress_bar_config(disable=snake_case__					)

          # set all optional components to None and update pipeline config accordingly
          for optional_component in pipe._optional_components:
                 setattr(snake_case__       ,		snake_case__       ,		snake_case__					)
          pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components}					)

          snake_case			:  Dict     							= self.get_dummy_inputs(snake_case__					)
          snake_case			:  int     							= pipe(**snake_case__					)[0]

          with tempfile.TemporaryDirectory() as tmpdir:
                 pipe.save_pretrained(snake_case__					)
                 snake_case			:  Any     							= self.pipeline_class.from_pretrained(snake_case__					)
                 pipe_loaded.to(snake_case__					)
                 pipe_loaded.set_progress_bar_config(disable=snake_case__					)

          for optional_component in pipe._optional_components:
                 self.assertTrue(
                     getattr(snake_case__       ,		snake_case__					) is None       ,		f"""`{optional_component}` did not stay set to None after loading."""       ,		)

          snake_case			:  Optional[int]     							= self.get_dummy_inputs(snake_case__					)
          snake_case			:  int     							= pipe_loaded(**snake_case__					)[0]

          snake_case			:  int     							= np.abs(output - output_loaded					).max()
          self.assertLess(snake_case__       ,		1e-4					)



   def 							_SCREAMING_SNAKE_CASE  (self						:   str					)						->      int:


          '''simple docstring'''


          snake_case			:  Union[str, Any]     							= "cpu"

          snake_case			:  int     							= self.get_dummy_components()
          snake_case			:  Any     							= self.pipeline_class(**snake_case__					)
          pipe.to(snake_case__					)
          pipe.set_progress_bar_config(disable=snake_case__					)

          snake_case			:  Any     							= self.get_dummy_mask_inputs(snake_case__					)
          snake_case			:  Union[str, Any]     							= pipe.generate_mask(**snake_case__					)
          snake_case			:  List[Any]     							= mask[0, -3:, -3:]

          self.assertEqual(mask.shape       ,		(1, 16, 16)					)
          snake_case			:  int     							= np.array([0] * 9					)
          snake_case			:  str     							= np.abs(mask_slice.flatten() - expected_slice					).max()
          self.assertLessEqual(snake_case__       ,		1e-3					)
          self.assertEqual(mask[0, -3, -4]       ,		0					)



   def 							_SCREAMING_SNAKE_CASE  (self						:   str					)						->      str:


          '''simple docstring'''


          snake_case			:  Any     							= "cpu"

          snake_case			:  List[Any]     							= self.get_dummy_components()
          snake_case			:  Optional[int]     							= self.pipeline_class(**snake_case__					)
          pipe.to(snake_case__					)
          pipe.set_progress_bar_config(disable=snake_case__					)

          snake_case			:  List[str]     							= self.get_dummy_inversion_inputs(snake_case__					)
          snake_case			:  List[str]     							= pipe.invert(**snake_case__					).images
          snake_case			:  Optional[Any]     							= image[0, -1, -3:, -3:]

          self.assertEqual(image.shape       ,		(2, 32, 32, 3)					)
          snake_case			:  int     							= np.array(
              [0.5150, 0.5134, 0.5043, 0.5376, 0.4694, 0.51050, 0.5015, 0.4407, 0.4799]       ,		)
          snake_case			:  Optional[Any]     							= np.abs(image_slice.flatten() - expected_slice					).max()
          self.assertLessEqual(snake_case__       ,		1e-3					)



   def 							_SCREAMING_SNAKE_CASE  (self						:   int					)						->      Any:


          '''simple docstring'''


          super().test_inference_batch_single_identical(expected_max_diff=5e-3					)



   def 							_SCREAMING_SNAKE_CASE  (self						:   str					)						->      Any:


          '''simple docstring'''


          snake_case			:  Any     							= "cpu"

          snake_case			:  int     							= self.get_dummy_components()

          snake_case			:  Tuple     							= {"beta_start": 0.00085, "beta_end": 0.012, "beta_schedule": "scaled_linear"}
          snake_case			:  int     							= DPMSolverMultistepScheduler(**snake_case__					)
          snake_case			:  Optional[Any]     							= DPMSolverMultistepInverseScheduler(**snake_case__					)

          snake_case			:  Any     							= self.pipeline_class(**snake_case__					)
          pipe.to(snake_case__					)
          pipe.set_progress_bar_config(disable=snake_case__					)

          snake_case			:  Tuple     							= self.get_dummy_inversion_inputs(snake_case__					)
          snake_case			:  Optional[int]     							= pipe.invert(**snake_case__					).images
          snake_case			:  Optional[Any]     							= image[0, -1, -3:, -3:]

          self.assertEqual(image.shape       ,		(2, 32, 32, 3)					)
          snake_case			:  int     							= np.array(
              [0.5150, 0.5134, 0.5043, 0.5376, 0.4694, 0.51050, 0.5015, 0.4407, 0.4799]       ,		)
          snake_case			:  Any     							= np.abs(image_slice.flatten() - expected_slice					).max()
          self.assertLessEqual(snake_case__       ,		1e-3					)






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



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


          '''simple docstring'''


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



   @classmethod
   def 							_SCREAMING_SNAKE_CASE  (cls						:   Optional[int]					)						->      Optional[int]:


          '''simple docstring'''


          snake_case			:  Tuple     							= load_image(
              "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png"					)

          snake_case			:  Tuple     							= raw_image.convert("RGB"					).resize((7_68, 7_68)					)

          snake_case			:  Tuple     							= raw_image



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


          '''simple docstring'''


          snake_case			:  Optional[int]     							= torch.manual_seed(0					)

          snake_case			:  List[str]     							= StableDiffusionDiffEditPipeline.from_pretrained(
              "stabilityai/stable-diffusion-2-1"       ,		safety_checker=snake_case__       ,		torch_dtype=torch.floataa					)
          snake_case			:  int     							= DDIMScheduler.from_config(pipe.scheduler.config					)
          snake_case			:  Dict     							= DDIMInverseScheduler.from_config(pipe.scheduler.config					)
          pipe.enable_model_cpu_offload()
          pipe.set_progress_bar_config(disable=snake_case__					)

          snake_case			:  Union[str, Any]     							= "a bowl of fruit"
          snake_case			:  int     							= "a bowl of pears"

          snake_case			:  List[Any]     							= pipe.generate_mask(
              image=self.raw_image       ,		source_prompt=snake_case__       ,		target_prompt=snake_case__       ,		generator=snake_case__       ,		)

          snake_case			:  Optional[int]     							= pipe.invert(
              prompt=snake_case__       ,		image=self.raw_image       ,		inpaint_strength=0.7       ,		generator=snake_case__					).latents

          snake_case			:  List[str]     							= pipe(
              prompt=snake_case__       ,		mask_image=snake_case__       ,		image_latents=snake_case__       ,		generator=snake_case__       ,		negative_prompt=snake_case__       ,		inpaint_strength=0.7       ,		output_type="numpy"       ,		).images[0]

          snake_case			:  Dict     							= (
              np.array(
                  load_image(
                      "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
                      "/diffedit/pears.png"					).resize((7_68, 7_68)					)					)
              / 2_55
          )
          assert np.abs((expected_image - image).max()					) < 5e-1



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


          '''simple docstring'''


          snake_case			:  int     							= torch.manual_seed(0					)

          snake_case			:  Tuple     							= StableDiffusionDiffEditPipeline.from_pretrained(
              "stabilityai/stable-diffusion-2-1"       ,		safety_checker=snake_case__       ,		torch_dtype=torch.floataa					)
          snake_case			:  Union[str, Any]     							= DPMSolverMultistepScheduler.from_config(pipe.scheduler.config					)
          snake_case			:  Optional[int]     							= DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config					)
          pipe.enable_model_cpu_offload()
          pipe.set_progress_bar_config(disable=snake_case__					)

          snake_case			:  str     							= "a bowl of fruit"
          snake_case			:  Optional[int]     							= "a bowl of pears"

          snake_case			:  Optional[Any]     							= pipe.generate_mask(
              image=self.raw_image       ,		source_prompt=snake_case__       ,		target_prompt=snake_case__       ,		generator=snake_case__       ,		)

          snake_case			:  List[str]     							= pipe.invert(
              prompt=snake_case__       ,		image=self.raw_image       ,		inpaint_strength=0.7       ,		generator=snake_case__       ,		num_inference_steps=25       ,		).latents

          snake_case			:  Dict     							= pipe(
              prompt=snake_case__       ,		mask_image=snake_case__       ,		image_latents=snake_case__       ,		generator=snake_case__       ,		negative_prompt=snake_case__       ,		inpaint_strength=0.7       ,		num_inference_steps=25       ,		output_type="numpy"       ,		).images[0]

          snake_case			:  int     							= (
              np.array(
                  load_image(
                      "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
                      "/diffedit/pears.png"					).resize((7_68, 7_68)					)					)
              / 2_55
          )
          assert np.abs((expected_image - image).max()					) < 5e-1





