



'''simple docstring'''




import argparse
import copy



def       __lowerCamelCase  (					_lowercase		)      ->			int:
							UpperCAmelCase     :		int							     =		{}

							with open(_lowercase		) as f:
														for line in f:
																					if line.split()[0] not in dict_of_neighbours:
																												UpperCAmelCase     :		str							     =		[]
																												_list.append([line.split()[1], line.split()[2]]		)
																												UpperCAmelCase     :		Union[str, Any]							     =		_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     :		Tuple							     =		[]
																												_list.append([line.split()[0], line.split()[2]]		)
																												UpperCAmelCase     :		Any							     =		_list
																					else:
																												dict_of_neighbours[line.split()[1]].append(
																												    [line.split()[0], line.split()[2]]		)

							return dict_of_neighbours



def       __lowerCamelCase  (					_lowercase	,				_lowercase		)      ->			int:

							with open(_lowercase		) as f:
														UpperCAmelCase     :		List[str]							     =		f.read(1		)
							UpperCAmelCase     :		Dict							     =		start_node

							UpperCAmelCase     :		int							     =		[]

							UpperCAmelCase     :		Dict							     =		start_node

							UpperCAmelCase     :		str							     =		0
							while visiting not in first_solution:
														UpperCAmelCase     :		str							     =		1_0_0_0_0
														for k in dict_of_neighbours[visiting]:
																					if int(k[1]		) < int(_lowercase		) and k[0] not in first_solution:
																												UpperCAmelCase     :		List[str]							     =		k[1]
																												UpperCAmelCase     :		int							     =		k[0]

														first_solution.append(_lowercase		)
														UpperCAmelCase     :		List[Any]							     =		distance_of_first_solution + int(_lowercase		)
														UpperCAmelCase     :		str							     =		best_node

							first_solution.append(_lowercase		)

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

							UpperCAmelCase     :		Dict							     =		(
							    distance_of_first_solution
							    + int(dict_of_neighbours[first_solution[-2]][position][1]		)
							    - 1_0_0_0_0
							)
							return first_solution, distance_of_first_solution



def       __lowerCamelCase  (					_lowercase	,				_lowercase		)      ->			Union[str, Any]:
							UpperCAmelCase     :		Optional[int]							     =		[]

							for n in solution[1:-1]:
														UpperCAmelCase     :		int							     =		solution.index(_lowercase		)
														for kn in solution[1:-1]:
																					UpperCAmelCase     :		Optional[int]							     =		solution.index(_lowercase		)
																					if n == kn:
																												continue

																					UpperCAmelCase     :		Union[str, Any]							     =		copy.deepcopy(_lowercase		)
																					UpperCAmelCase     :		Any							     =		kn
																					UpperCAmelCase     :		str							     =		n

																					UpperCAmelCase     :		Any							     =		0

																					for k in _tmp[:-1]:
																												UpperCAmelCase     :		int							     =		_tmp[_tmp.index(_lowercase		) + 1]
																												for i in dict_of_neighbours[k]:
																																			if i[0] == next_node:
																																										UpperCAmelCase     :		Union[str, Any]							     =		distance + int(i[1]		)
																					_tmp.append(_lowercase		)

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

							UpperCAmelCase     :		Optional[int]							     =		len(neighborhood_of_solution[0]		) - 1

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



def       __lowerCamelCase  (					_lowercase	,				_lowercase	,				_lowercase	,				_lowercase	,				_lowercase		)      ->			List[str]:
							UpperCAmelCase     :		str							     =		1
							UpperCAmelCase     :		Optional[Any]							     =		first_solution
							UpperCAmelCase     :		Tuple							     =		[]
							UpperCAmelCase     :		int							     =		distance_of_first_solution
							UpperCAmelCase     :		Tuple							     =		solution

							while count <= iters:
														UpperCAmelCase     :		Tuple							     =		find_neighborhood(_lowercase	,				_lowercase		)
														UpperCAmelCase     :		List[str]							     =		0
														UpperCAmelCase     :		str							     =		neighborhood[index_of_best_solution]
														UpperCAmelCase     :		Dict							     =		len(_lowercase		) - 1

														UpperCAmelCase     :		Tuple							     =		False
														while not found:
																					UpperCAmelCase     :		Dict							     =		0
																					while i < len(_lowercase		):
																												if best_solution[i] != solution[i]:
																																			UpperCAmelCase     :		Any							     =		best_solution[i]
																																			UpperCAmelCase     :		Union[str, Any]							     =		solution[i]
																																			break
																												UpperCAmelCase     :		str							     =		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     :		List[str]							     =		True
																												UpperCAmelCase     :		List[Any]							     =		best_solution[:-1]
																												UpperCAmelCase     :		Optional[Any]							     =		neighborhood[index_of_best_solution][best_cost_index]
																												if cost < best_cost:
																																			UpperCAmelCase     :		Tuple							     =		cost
																																			UpperCAmelCase     :		Optional[Any]							     =		solution
																					else:
																												UpperCAmelCase     :		List[str]							     =		index_of_best_solution + 1
																												UpperCAmelCase     :		Optional[int]							     =		neighborhood[index_of_best_solution]

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

														UpperCAmelCase     :		Union[str, Any]							     =		count + 1

							return best_solution_ever, best_cost



def       __lowerCamelCase  (					_lowercase=None		)      ->			Optional[int]:
							UpperCAmelCase     :		str							     =		generate_neighbours(args.File		)

							UpperCAmelCase     ,     UpperCAmelCase     :		Optional[int]							     =		generate_first_solution(
							    args.File	,				_lowercase		)

							UpperCAmelCase     ,     UpperCAmelCase     :		Optional[Any]							     =		tabu_search(
							    _lowercase	,				_lowercase	,				_lowercase	,				args.Iterations	,				args.Size	,				)

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


if __name__ == "__main__":
							a   :			List[str]					  =    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())






'''simple docstring'''




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_ (							__magic_name__      ,     __magic_name__      ,     unittest.TestCase			):
	lowercase          = StableDiffusionDiffEditPipeline
	lowercase          = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'height', 'width', 'image'} | {'image_latents'}
	lowercase          = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {'image'} | {'image_latents'}
	lowercase          = frozenset(
	    []			)  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
	lowercase          = frozenset([]			)





	def  _lowercase(  self    )			->			Optional[int]:
								torch.manual_seed(0    )
								UpperCAmelCase     :		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=A		,		)
								UpperCAmelCase     :		int							     =		DDIMScheduler(
								    beta_start=0.0_0_0_8_5		,		beta_end=0.0_1_2		,		beta_schedule="""scaled_linear"""		,		clip_sample=A		,		set_alpha_to_one=A		,		)
								UpperCAmelCase     :		List[Any]							     =		DDIMInverseScheduler(
								    beta_start=0.0_0_0_8_5		,		beta_end=0.0_1_2		,		beta_schedule="""scaled_linear"""		,		clip_sample=A		,		set_alpha_to_zero=A		,		)
								torch.manual_seed(0    )
								UpperCAmelCase     :		int							     =		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=128		,		)
								torch.manual_seed(0    )
								UpperCAmelCase     :		Optional[int]							     =		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		,		hidden_act="""gelu"""		,		projection_dim=512		,		)
								UpperCAmelCase     :		Optional[Any]							     =		CLIPTextModel(A    )
								UpperCAmelCase     :		List[str]							     =		CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""    )

								UpperCAmelCase     :		int							     =		{
								    """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  _lowercase(  self		,		A		,		A=0    )			->			Optional[Any]:
								UpperCAmelCase     :		Any							     =		floats_tensor((1, 16, 16)		,		rng=random.Random(A    )    ).to(A    )
								UpperCAmelCase     :		Any							     =		floats_tensor((1, 2, 4, 16, 16)		,		rng=random.Random(A    )    ).to(A    )
								if str(A    ).startswith("""mps"""    ):
															UpperCAmelCase     :		List[Any]							     =		torch.manual_seed(A    )
								else:
															UpperCAmelCase     :		List[Any]							     =		torch.Generator(device=A    ).manual_seed(A    )
								UpperCAmelCase     :		int							     =		{
								    """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  _lowercase(  self		,		A		,		A=0    )			->			Optional[int]:
								UpperCAmelCase     :		Optional[Any]							     =		floats_tensor((1, 3, 32, 32)		,		rng=random.Random(A    )    ).to(A    )
								UpperCAmelCase     :		Union[str, Any]							     =		image.cpu().permute(0		,		2		,		3		,		1    )[0]
								UpperCAmelCase     :		int							     =		Image.fromarray(np.uinta(A    )    ).convert("""RGB"""    )
								if str(A    ).startswith("""mps"""    ):
															UpperCAmelCase     :		Optional[int]							     =		torch.manual_seed(A    )
								else:
															UpperCAmelCase     :		Optional[Any]							     =		torch.Generator(device=A    ).manual_seed(A    )
								UpperCAmelCase     :		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  _lowercase(  self		,		A		,		A=0    )			->			str:
								UpperCAmelCase     :		int							     =		floats_tensor((1, 3, 32, 32)		,		rng=random.Random(A    )    ).to(A    )
								UpperCAmelCase     :		str							     =		image.cpu().permute(0		,		2		,		3		,		1    )[0]
								UpperCAmelCase     :		int							     =		Image.fromarray(np.uinta(A    )    ).convert("""RGB"""    )
								if str(A    ).startswith("""mps"""    ):
															UpperCAmelCase     :		Optional[int]							     =		torch.manual_seed(A    )
								else:
															UpperCAmelCase     :		Optional[int]							     =		torch.Generator(device=A    ).manual_seed(A    )
								UpperCAmelCase     :		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  _lowercase(  self    )			->			List[Any]:
								if not hasattr(self.pipeline_class		,		"""_optional_components"""    ):
															return

								UpperCAmelCase     :		Dict							     =		self.get_dummy_components()
								UpperCAmelCase     :		int							     =		self.pipeline_class(**A    )
								pipe.to(A    )
								pipe.set_progress_bar_config(disable=A    )

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

								UpperCAmelCase     :		Any							     =		self.get_dummy_inputs(A    )
								UpperCAmelCase     :		Optional[Any]							     =		pipe(**A    )[0]

								with tempfile.TemporaryDirectory() as tmpdir:
															pipe.save_pretrained(A    )
															UpperCAmelCase     :		Dict							     =		self.pipeline_class.from_pretrained(A    )
															pipe_loaded.to(A    )
															pipe_loaded.set_progress_bar_config(disable=A    )

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

								UpperCAmelCase     :		Union[str, Any]							     =		self.get_dummy_inputs(A    )
								UpperCAmelCase     :		Tuple							     =		pipe_loaded(**A    )[0]

								UpperCAmelCase     :		Optional[Any]							     =		np.abs(output - output_loaded    ).max()
								self.assertLess(A		,		1e-4    )





	def  _lowercase(  self    )			->			Optional[int]:
								UpperCAmelCase     :		Optional[int]							     =		"""cpu"""

								UpperCAmelCase     :		Optional[Any]							     =		self.get_dummy_components()
								UpperCAmelCase     :		List[str]							     =		self.pipeline_class(**A    )
								pipe.to(A    )
								pipe.set_progress_bar_config(disable=A    )

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

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





	def  _lowercase(  self    )			->			Optional[Any]:
								UpperCAmelCase     :		Optional[Any]							     =		"""cpu"""

								UpperCAmelCase     :		List[str]							     =		self.get_dummy_components()
								UpperCAmelCase     :		Optional[Any]							     =		self.pipeline_class(**A    )
								pipe.to(A    )
								pipe.set_progress_bar_config(disable=A    )

								UpperCAmelCase     :		Optional[int]							     =		self.get_dummy_inversion_inputs(A    )
								UpperCAmelCase     :		List[str]							     =		pipe.invert(**A    ).images
								UpperCAmelCase     :		Union[str, Any]							     =		image[0, -1, -3:, -3:]

								self.assertEqual(image.shape		,		(2, 32, 32, 3)    )
								UpperCAmelCase     :		Dict							     =		np.array(
								    [0.5_1_5_0, 0.5_1_3_4, 0.5_0_4_3, 0.5_3_7_6, 0.4_6_9_4, 0.5_1_0_5_0, 0.5_0_1_5, 0.4_4_0_7, 0.4_7_9_9]		,		)
								UpperCAmelCase     :		Dict							     =		np.abs(image_slice.flatten() - expected_slice    ).max()
								self.assertLessEqual(A		,		1e-3    )





	def  _lowercase(  self    )			->			Dict:
								super().test_inference_batch_single_identical(expected_max_diff=5e-3    )






	def  _lowercase(  self    )			->			int:
								UpperCAmelCase     :		List[Any]							     =		"""cpu"""

								UpperCAmelCase     :		int							     =		self.get_dummy_components()

								UpperCAmelCase     :		List[Any]							     =		{"""beta_start""": 0.0_0_0_8_5, """beta_end""": 0.0_1_2, """beta_schedule""": """scaled_linear"""}
								UpperCAmelCase     :		int							     =		DPMSolverMultistepScheduler(**A    )
								UpperCAmelCase     :		int							     =		DPMSolverMultistepInverseScheduler(**A    )

								UpperCAmelCase     :		List[str]							     =		self.pipeline_class(**A    )
								pipe.to(A    )
								pipe.set_progress_bar_config(disable=A    )

								UpperCAmelCase     :		Tuple							     =		self.get_dummy_inversion_inputs(A    )
								UpperCAmelCase     :		Any							     =		pipe.invert(**A    ).images
								UpperCAmelCase     :		Dict							     =		image[0, -1, -3:, -3:]

								self.assertEqual(image.shape		,		(2, 32, 32, 3)    )
								UpperCAmelCase     :		Any							     =		np.array(
								    [0.5_1_5_0, 0.5_1_3_4, 0.5_0_4_3, 0.5_3_7_6, 0.4_6_9_4, 0.5_1_0_5_0, 0.5_0_1_5, 0.4_4_0_7, 0.4_7_9_9]		,		)
								UpperCAmelCase     :		Optional[int]							     =		np.abs(image_slice.flatten() - expected_slice    ).max()
								self.assertLessEqual(A		,		1e-3    )




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





	def  _lowercase(  self    )			->			int:
								super().tearDown()
								gc.collect()
								torch.cuda.empty_cache()





	@classmethod
	def  _lowercase(  cls    )			->			Dict:
								UpperCAmelCase     :		Tuple							     =		load_image(
								    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png"""    )

								UpperCAmelCase     :		Union[str, Any]							     =		raw_image.convert("""RGB"""    ).resize((768, 768)    )

								UpperCAmelCase     :		List[str]							     =		raw_image





	def  _lowercase(  self    )			->			Optional[Any]:
								UpperCAmelCase     :		Dict							     =		torch.manual_seed(0    )

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

								UpperCAmelCase     :		Tuple							     =		"""a bowl of fruit"""
								UpperCAmelCase     :		List[Any]							     =		"""a bowl of pears"""

								UpperCAmelCase     :		str							     =		pipe.generate_mask(
								    image=self.raw_image		,		source_prompt=A		,		target_prompt=A		,		generator=A		,		)

								UpperCAmelCase     :		Tuple							     =		pipe.invert(
								    prompt=A		,		image=self.raw_image		,		inpaint_strength=0.7		,		generator=A    ).latents

								UpperCAmelCase     :		Any							     =		pipe(
								    prompt=A		,		mask_image=A		,		image_latents=A		,		generator=A		,		negative_prompt=A		,		inpaint_strength=0.7		,		output_type="""numpy"""		,		).images[0]

								UpperCAmelCase     :		List[str]							     =		(
								    np.array(
								        load_image(
								            """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
								            """/diffedit/pears.png"""    ).resize((768, 768)    )    )
								    / 255
								)
								assert np.abs((expected_image - image).max()    ) < 5e-1






	def  _lowercase(  self    )			->			Optional[Any]:
								UpperCAmelCase     :		Optional[Any]							     =		torch.manual_seed(0    )

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

								UpperCAmelCase     :		int							     =		"""a bowl of fruit"""
								UpperCAmelCase     :		int							     =		"""a bowl of pears"""

								UpperCAmelCase     :		str							     =		pipe.generate_mask(
								    image=self.raw_image		,		source_prompt=A		,		target_prompt=A		,		generator=A		,		)

								UpperCAmelCase     :		Any							     =		pipe.invert(
								    prompt=A		,		image=self.raw_image		,		inpaint_strength=0.7		,		generator=A		,		num_inference_steps=25		,		).latents

								UpperCAmelCase     :		str							     =		pipe(
								    prompt=A		,		mask_image=A		,		image_latents=A		,		generator=A		,		negative_prompt=A		,		inpaint_strength=0.7		,		num_inference_steps=25		,		output_type="""numpy"""		,		).images[0]

								UpperCAmelCase     :		Tuple							     =		(
								    np.array(
								        load_image(
								            """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
								            """/diffedit/pears.png"""    ).resize((768, 768)    )    )
								    / 255
								)
								assert np.abs((expected_image - image).max()    ) < 5e-1

