

'''simple docstring'''





import gc
import unittest

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

from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    load_numpy,
    nightly,
    require_torch_gpu,
    slow,
    torch_device,
)

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()





class 		__SCREAMING_SNAKE_CASE       ( lowercase__	,       unittest.TestCase			):
				lowerCamelCase_							=						LDMTextToImagePipeline
				lowerCamelCase_							=						TEXT_TO_IMAGE_PARAMS - {
				    'negative_prompt',
				    'negative_prompt_embeds',
				    'cross_attention_kwargs',
				    'prompt_embeds',
				}
				lowerCamelCase_							=						PipelineTesterMixin.required_optional_params - {
				    'num_images_per_prompt',
				    'callback',
				    'callback_steps',
				}
				lowerCamelCase_							=						TEXT_TO_IMAGE_BATCH_PARAMS
				lowerCamelCase_							=						False







				def    lowerCamelCase_  (					self    :		Optional[Any]      ):
										'''simple docstring'''
										torch.manual_seed(0      )
										lowercase   :       List[Any]								=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		,				)
										lowercase   :       Any								=DDIMScheduler(
										    beta_start=0.0_00_85		,				beta_end=0.0_12		,				beta_schedule='''scaled_linear'''		,				clip_sample=UpperCAmelCase__		,				set_alpha_to_one=UpperCAmelCase__		,				)
										torch.manual_seed(0      )
										lowercase   :       Dict								=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      )
										lowercase   :       List[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		,				)
										lowercase   :       Tuple								=CLIPTextModel(UpperCAmelCase__      )
										lowercase   :       Tuple								=CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''      )

										lowercase   :       str								={
										    '''unet''': unet,
										    '''scheduler''': scheduler,
										    '''vqvae''': vae,
										    '''bert''': text_encoder,
										    '''tokenizer''': tokenizer,
										}
										return components







				def    lowerCamelCase_  (					self    :		Optional[int]		,				UpperCAmelCase__    :		Optional[int]		,				UpperCAmelCase__    :		List[Any]=0      ):
										'''simple docstring'''
										if str(UpperCAmelCase__      ).startswith('''mps'''      ):
																lowercase   :       Optional[Any]								=torch.manual_seed(UpperCAmelCase__      )
										else:
																lowercase   :       Tuple								=torch.Generator(device=UpperCAmelCase__      ).manual_seed(UpperCAmelCase__      )
										lowercase   :       Tuple								={
										    '''prompt''': '''A painting of a squirrel eating a burger''',
										    '''generator''': generator,
										    '''num_inference_steps''': 2,
										    '''guidance_scale''': 6.0,
										    '''output_type''': '''numpy''',
										}
										return inputs







				def    lowerCamelCase_  (					self    :		str      ):
										'''simple docstring'''
										lowercase   :       str								='''cpu'''  # ensure determinism for the device-dependent torch.Generator

										lowercase   :       Dict								=self.get_dummy_components()
										lowercase   :       Optional[Any]								=LDMTextToImagePipeline(**UpperCAmelCase__      )
										pipe.to(UpperCAmelCase__      )
										pipe.set_progress_bar_config(disable=UpperCAmelCase__      )

										lowercase   :       Optional[Any]								=self.get_dummy_inputs(UpperCAmelCase__      )
										lowercase   :       str								=pipe(**UpperCAmelCase__      ).images
										lowercase   :       Union[str, Any]								=image[0, -3:, -3:, -1]

										assert image.shape == (1, 16, 16, 3)
										lowercase   :       Tuple								=np.array([0.61_01, 0.61_56, 0.56_22, 0.48_95, 0.66_61, 0.38_04, 0.57_48, 0.61_36, 0.50_14]      )

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





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







				def    lowerCamelCase_  (					self    :		Any      ):
										'''simple docstring'''
										super().tearDown()
										gc.collect()
										torch.cuda.empty_cache()







				def    lowerCamelCase_  (					self    :		int		,				UpperCAmelCase__    :		Dict		,				UpperCAmelCase__    :		Dict=torch.floataa		,				UpperCAmelCase__    :		str=0      ):
										'''simple docstring'''
										lowercase   :       str								=torch.manual_seed(UpperCAmelCase__      )
										lowercase   :       Union[str, Any]								=np.random.RandomState(UpperCAmelCase__      ).standard_normal((1, 4, 32, 32)      )
										lowercase   :       str								=torch.from_numpy(UpperCAmelCase__      ).to(device=UpperCAmelCase__		,				dtype=UpperCAmelCase__      )
										lowercase   :       Tuple								={
										    '''prompt''': '''A painting of a squirrel eating a burger''',
										    '''latents''': latents,
										    '''generator''': generator,
										    '''num_inference_steps''': 3,
										    '''guidance_scale''': 6.0,
										    '''output_type''': '''numpy''',
										}
										return inputs







				def    lowerCamelCase_  (					self    :		Union[str, Any]      ):
										'''simple docstring'''
										lowercase   :       Optional[int]								=LDMTextToImagePipeline.from_pretrained('''CompVis/ldm-text2im-large-256'''      ).to(UpperCAmelCase__      )
										pipe.set_progress_bar_config(disable=UpperCAmelCase__      )

										lowercase   :       int								=self.get_inputs(UpperCAmelCase__      )
										lowercase   :       Tuple								=pipe(**UpperCAmelCase__      ).images
										lowercase   :       Tuple								=image[0, -3:, -3:, -1].flatten()

										assert image.shape == (1, 256, 256, 3)
										lowercase   :       List[Any]								=np.array([0.5_18_25, 0.5_28_50, 0.5_25_43, 0.5_42_58, 0.5_23_04, 0.5_25_69, 0.5_43_63, 0.5_52_76, 0.5_68_78]      )
										lowercase   :       str								=np.abs(expected_slice - image_slice      ).max()
										assert max_diff < 1E-3





@nightly
@require_torch_gpu
class 		__SCREAMING_SNAKE_CASE       ( unittest.TestCase			):







				def    lowerCamelCase_  (					self    :		int      ):
										'''simple docstring'''
										super().tearDown()
										gc.collect()
										torch.cuda.empty_cache()







				def    lowerCamelCase_  (					self    :		str		,				UpperCAmelCase__    :		Tuple		,				UpperCAmelCase__    :		Optional[int]=torch.floataa		,				UpperCAmelCase__    :		Any=0      ):
										'''simple docstring'''
										lowercase   :       Optional[Any]								=torch.manual_seed(UpperCAmelCase__      )
										lowercase   :       str								=np.random.RandomState(UpperCAmelCase__      ).standard_normal((1, 4, 32, 32)      )
										lowercase   :       Union[str, Any]								=torch.from_numpy(UpperCAmelCase__      ).to(device=UpperCAmelCase__		,				dtype=UpperCAmelCase__      )
										lowercase   :       Union[str, Any]								={
										    '''prompt''': '''A painting of a squirrel eating a burger''',
										    '''latents''': latents,
										    '''generator''': generator,
										    '''num_inference_steps''': 50,
										    '''guidance_scale''': 6.0,
										    '''output_type''': '''numpy''',
										}
										return inputs







				def    lowerCamelCase_  (					self    :		Any      ):
										'''simple docstring'''
										lowercase   :       Tuple								=LDMTextToImagePipeline.from_pretrained('''CompVis/ldm-text2im-large-256'''      ).to(UpperCAmelCase__      )
										pipe.set_progress_bar_config(disable=UpperCAmelCase__      )

										lowercase   :       Union[str, Any]								=self.get_inputs(UpperCAmelCase__      )
										lowercase   :       List[Any]								=pipe(**UpperCAmelCase__      ).images[0]

										lowercase   :       Tuple								=load_numpy(
										    '''https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy'''      )
										lowercase   :       str								=np.abs(expected_image - image      ).max()
										assert max_diff < 1E-3








'''simple docstring'''





import argparse
import copy






def 							_lowerCAmelCase (      __magic_name__	:    List[str]	)							->     Union[str, Any]:
						lowercase   :       int								={}

						with open(__magic_name__	) as f:
												for line in f:
																		if line.split()[0] not in dict_of_neighbours:
																								lowercase   :       List[str]								=[]
																								_list.append([line.split()[1], line.split()[2]]	)
																								lowercase   :       Tuple								=_list
																		else:
																								dict_of_neighbours[line.split()[0]].append(
																								    [line.split()[1], line.split()[2]]	)
																		if line.split()[1] not in dict_of_neighbours:
																								lowercase   :       List[Any]								=[]
																								_list.append([line.split()[0], line.split()[2]]	)
																								lowercase   :       Union[str, Any]								=_list
																		else:
																								dict_of_neighbours[line.split()[1]].append(
																								    [line.split()[0], line.split()[2]]	)

						return dict_of_neighbours






def 							_lowerCAmelCase (      __magic_name__	:    Optional[int]      ,   __magic_name__	:    List[Any]	)							->     str:

						with open(__magic_name__	) as f:
												lowercase   :       Optional[int]								=f.read(1	)
						lowercase   :       List[Any]								=start_node

						lowercase   :       List[Any]								=[]

						lowercase   :       str								=start_node

						lowercase   :       str								=0
						while visiting not in first_solution:
												lowercase   :       Optional[int]								=10000
												for k in dict_of_neighbours[visiting]:
																		if int(k[1]	) < int(__magic_name__	) and k[0] not in first_solution:
																								lowercase   :       List[Any]								=k[1]
																								lowercase   :       str								=k[0]

												first_solution.append(__magic_name__	)
												lowercase   :       Any								=distance_of_first_solution + int(__magic_name__	)
												lowercase   :       Optional[int]								=best_node

						first_solution.append(__magic_name__	)

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

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






def 							_lowerCAmelCase (      __magic_name__	:    str      ,   __magic_name__	:    Any	)							->     Tuple:
						lowercase   :       Tuple								=[]

						for n in solution[1:-1]:
												lowercase   :       Dict								=solution.index(__magic_name__	)
												for kn in solution[1:-1]:
																		lowercase   :       Tuple								=solution.index(__magic_name__	)
																		if n == kn:
																								continue

																		lowercase   :       Union[str, Any]								=copy.deepcopy(__magic_name__	)
																		lowercase   :       Optional[int]								=kn
																		lowercase   :       List[Any]								=n

																		lowercase   :       List[Any]								=0

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

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

						lowercase   :       Union[str, Any]								=len(neighborhood_of_solution[0]	) - 1

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






def 							_lowerCAmelCase (      __magic_name__	:    Any      ,   __magic_name__	:    str      ,   __magic_name__	:    List[Any]      ,   __magic_name__	:    Tuple      ,   __magic_name__	:    Dict	)							->     Union[str, Any]:
						lowercase   :       str								=1
						lowercase   :       List[Any]								=first_solution
						lowercase   :       Any								=[]
						lowercase   :       str								=distance_of_first_solution
						lowercase   :       str								=solution

						while count <= iters:
												lowercase   :       Union[str, Any]								=find_neighborhood(__magic_name__      ,   __magic_name__	)
												lowercase   :       Dict								=0
												lowercase   :       int								=neighborhood[index_of_best_solution]
												lowercase   :       Optional[int]								=len(__magic_name__	) - 1

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

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

												lowercase   :       Optional[int]								=count + 1

						return best_solution_ever, best_cost






def 							_lowerCAmelCase (      __magic_name__	:    str=None	)							->     Tuple:
						lowercase   :       List[str]								=generate_neighbours(args.File	)

						lowercase		,  lowercase   :       Optional[Any]								=generate_first_solution(
						    args.File      ,   __magic_name__	)

						lowercase		,  lowercase   :       int								=tabu_search(
						    __magic_name__      ,   __magic_name__      ,   __magic_name__      ,   args.Iterations      ,   args.Size      ,   )

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


if __name__ == "__main__":
							UpperCamelCase_							=					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())





