

'''simple docstring'''





import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    EulerAncestralDiscreteScheduler,
    LMSDiscreteScheduler,
    PNDMScheduler,
    StableDiffusionPanoramaPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps

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


enable_full_determinism()





@skip_mps
class 		__SCREAMING_SNAKE_CASE       ( lowercase__	,       lowercase__	,       unittest.TestCase			):
				lowerCamelCase_							=						StableDiffusionPanoramaPipeline
				lowerCamelCase_							=						TEXT_TO_IMAGE_PARAMS
				lowerCamelCase_							=						TEXT_TO_IMAGE_BATCH_PARAMS
				lowerCamelCase_							=						TEXT_TO_IMAGE_IMAGE_PARAMS
				lowerCamelCase_							=						TEXT_TO_IMAGE_IMAGE_PARAMS







				def    lowerCamelCase_  (					self    :		Tuple      ):
										'''simple docstring'''
										torch.manual_seed(0      )
										lowercase   :       int								=UNetaDConditionModel(
										    block_out_channels=(32, 64)		,				layers_per_block=1		,				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()
										torch.manual_seed(0      )
										lowercase   :       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		,				)
										torch.manual_seed(0      )
										lowercase   :       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		,				)
										lowercase   :       int								=CLIPTextModel(UpperCAmelCase__      )
										lowercase   :       int								=CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''      )

										lowercase   :       Tuple								={
										    '''unet''': unet,
										    '''scheduler''': scheduler,
										    '''vae''': vae,
										    '''text_encoder''': text_encoder,
										    '''tokenizer''': tokenizer,
										    '''safety_checker''': None,
										    '''feature_extractor''': None,
										}
										return components







				def    lowerCamelCase_  (					self    :		Tuple		,				UpperCAmelCase__    :		Any		,				UpperCAmelCase__    :		Any=0      ):
										'''simple docstring'''
										lowercase   :       Tuple								=torch.manual_seed(UpperCAmelCase__      )
										lowercase   :       List[Any]								={
										    '''prompt''': '''a photo of the dolomites''',
										    '''generator''': generator,
										    # Setting height and width to None to prevent OOMs on CPU.
										    '''height''': None,
										    '''width''': None,
										    '''num_inference_steps''': 1,
										    '''guidance_scale''': 6.0,
										    '''output_type''': '''numpy''',
										}
										return inputs







				def    lowerCamelCase_  (					self    :		Optional[Any]      ):
										'''simple docstring'''
										lowercase   :       List[str]								='''cpu'''  # ensure determinism for the device-dependent torch.Generator
										lowercase   :       Optional[Any]								=self.get_dummy_components()
										lowercase   :       Dict								=StableDiffusionPanoramaPipeline(**UpperCAmelCase__      )
										lowercase   :       List[str]								=sd_pipe.to(UpperCAmelCase__      )
										sd_pipe.set_progress_bar_config(disable=UpperCAmelCase__      )

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

										lowercase   :       int								=np.array([0.61_86, 0.53_74, 0.49_15, 0.41_35, 0.41_14, 0.45_63, 0.51_28, 0.49_77, 0.47_57]      )

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







				def    lowerCamelCase_  (					self    :		Dict      ):
										'''simple docstring'''
										super().test_inference_batch_consistent(batch_sizes=[1, 2]      )







				def    lowerCamelCase_  (					self    :		Tuple      ):
										'''simple docstring'''
										super().test_inference_batch_single_identical(batch_size=2		,				expected_max_diff=3.25E-3      )







				def    lowerCamelCase_  (					self    :		Tuple      ):
										'''simple docstring'''
										lowercase   :       Union[str, Any]								='''cpu'''  # ensure determinism for the device-dependent torch.Generator
										lowercase   :       int								=self.get_dummy_components()
										lowercase   :       List[Any]								=StableDiffusionPanoramaPipeline(**UpperCAmelCase__      )
										lowercase   :       Tuple								=sd_pipe.to(UpperCAmelCase__      )
										sd_pipe.set_progress_bar_config(disable=UpperCAmelCase__      )

										lowercase   :       Tuple								=self.get_dummy_inputs(UpperCAmelCase__      )
										lowercase   :       str								='''french fries'''
										lowercase   :       str								=sd_pipe(**UpperCAmelCase__		,				negative_prompt=UpperCAmelCase__      )
										lowercase   :       Dict								=output.images
										lowercase   :       str								=image[0, -3:, -3:, -1]

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

										lowercase   :       Optional[Any]								=np.array([0.61_87, 0.53_75, 0.49_15, 0.41_36, 0.41_14, 0.45_63, 0.51_28, 0.49_76, 0.47_57]      )

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







				def    lowerCamelCase_  (					self    :		Dict      ):
										'''simple docstring'''
										lowercase   :       Dict								='''cpu'''  # ensure determinism for the device-dependent torch.Generator
										lowercase   :       Optional[Any]								=self.get_dummy_components()
										lowercase   :       Optional[Any]								=StableDiffusionPanoramaPipeline(**UpperCAmelCase__      )
										lowercase   :       Tuple								=sd_pipe.to(UpperCAmelCase__      )
										sd_pipe.set_progress_bar_config(disable=UpperCAmelCase__      )

										lowercase   :       Tuple								=self.get_dummy_inputs(UpperCAmelCase__      )
										lowercase   :       Any								=sd_pipe(**UpperCAmelCase__		,				view_batch_size=2      )
										lowercase   :       Dict								=output.images
										lowercase   :       List[str]								=image[0, -3:, -3:, -1]

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

										lowercase   :       List[str]								=np.array([0.61_87, 0.53_75, 0.49_15, 0.41_36, 0.41_14, 0.45_63, 0.51_28, 0.49_76, 0.47_57]      )

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







				def    lowerCamelCase_  (					self    :		str      ):
										'''simple docstring'''
										lowercase   :       str								='''cpu'''  # ensure determinism for the device-dependent torch.Generator
										lowercase   :       str								=self.get_dummy_components()
										lowercase   :       str								=EulerAncestralDiscreteScheduler(
										    beta_start=0.0_00_85		,				beta_end=0.0_12		,				beta_schedule='''scaled_linear'''      )
										lowercase   :       Union[str, Any]								=StableDiffusionPanoramaPipeline(**UpperCAmelCase__      )
										lowercase   :       List[Any]								=sd_pipe.to(UpperCAmelCase__      )
										sd_pipe.set_progress_bar_config(disable=UpperCAmelCase__      )

										lowercase   :       Tuple								=self.get_dummy_inputs(UpperCAmelCase__      )
										lowercase   :       Optional[int]								=sd_pipe(**UpperCAmelCase__      ).images
										lowercase   :       Optional[int]								=image[0, -3:, -3:, -1]

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

										lowercase   :       Tuple								=np.array([0.40_24, 0.65_10, 0.49_01, 0.53_78, 0.58_13, 0.56_22, 0.47_95, 0.44_67, 0.49_52]      )

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







				def    lowerCamelCase_  (					self    :		Tuple      ):
										'''simple docstring'''
										lowercase   :       List[str]								='''cpu'''  # ensure determinism for the device-dependent torch.Generator
										lowercase   :       Optional[int]								=self.get_dummy_components()
										lowercase   :       Tuple								=PNDMScheduler(
										    beta_start=0.0_00_85		,				beta_end=0.0_12		,				beta_schedule='''scaled_linear'''		,				skip_prk_steps=UpperCAmelCase__      )
										lowercase   :       str								=StableDiffusionPanoramaPipeline(**UpperCAmelCase__      )
										lowercase   :       List[Any]								=sd_pipe.to(UpperCAmelCase__      )
										sd_pipe.set_progress_bar_config(disable=UpperCAmelCase__      )

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

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

										lowercase   :       str								=np.array([0.63_91, 0.62_91, 0.48_61, 0.51_34, 0.55_52, 0.45_78, 0.50_32, 0.50_23, 0.45_39]      )

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





@slow
@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    :		int		,				UpperCAmelCase__    :		int=0      ):
										'''simple docstring'''
										lowercase   :       Union[str, Any]								=torch.manual_seed(UpperCAmelCase__      )
										lowercase   :       int								={
										    '''prompt''': '''a photo of the dolomites''',
										    '''generator''': generator,
										    '''num_inference_steps''': 3,
										    '''guidance_scale''': 7.5,
										    '''output_type''': '''numpy''',
										}
										return inputs







				def    lowerCamelCase_  (					self    :		Any      ):
										'''simple docstring'''
										lowercase   :       int								='''stabilityai/stable-diffusion-2-base'''
										lowercase   :       List[Any]								=DDIMScheduler.from_pretrained(UpperCAmelCase__		,				subfolder='''scheduler'''      )
										lowercase   :       List[Any]								=StableDiffusionPanoramaPipeline.from_pretrained(UpperCAmelCase__		,				scheduler=UpperCAmelCase__		,				safety_checker=UpperCAmelCase__      )
										pipe.to(UpperCAmelCase__      )
										pipe.set_progress_bar_config(disable=UpperCAmelCase__      )
										pipe.enable_attention_slicing()

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

										assert image.shape == (1, 512, 2048, 3)

										lowercase   :       Any								=np.array(
										    [
										        0.36_96_83_92,
										        0.27_02_53_72,
										        0.32_44_67_66,
										        0.28_37_93_87,
										        0.36_36_32_74,
										        0.30_73_33_47,
										        0.27_10_00_27,
										        0.27_05_41_25,
										        0.25_53_60_96,
										    ]      )

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







				def    lowerCamelCase_  (					self    :		Any      ):
										'''simple docstring'''
										lowercase   :       Tuple								=StableDiffusionPanoramaPipeline.from_pretrained(
										    '''stabilityai/stable-diffusion-2-base'''		,				safety_checker=UpperCAmelCase__      )
										lowercase   :       Tuple								=LMSDiscreteScheduler.from_config(pipe.scheduler.config      )
										pipe.to(UpperCAmelCase__      )
										pipe.set_progress_bar_config(disable=UpperCAmelCase__      )
										pipe.enable_attention_slicing()

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

										assert image.shape == (1, 512, 2048, 3)

										lowercase   :       Any								=np.array(
										    [
										        [
										            0.0,
										            0.0,
										            0.0,
										            0.0,
										            0.0,
										            0.0,
										            0.0,
										            0.0,
										            0.0,
										        ]
										    ]      )

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







				def    lowerCamelCase_  (					self    :		Optional[int]      ):
										'''simple docstring'''
										lowercase   :       Optional[int]								=0

										def callback_fn(UpperCAmelCase__    :		int		,				UpperCAmelCase__    :		int		,				UpperCAmelCase__    :		torch.FloatTensor      ) -> None:
																lowercase   :       Optional[int]								=True
																nonlocal number_of_steps
																number_of_steps += 1
																if step == 1:
																						lowercase   :       Optional[Any]								=latents.detach().cpu().numpy()
																						assert latents.shape == (1, 4, 64, 256)
																						lowercase   :       Any								=latents[0, -3:, -3:, -1]

																						lowercase   :       int								=np.array(
																						    [
																						        0.18_68_18_69,
																						        0.33_90_78_16,
																						        0.5_36_12_76,
																						        0.14_43_28_65,
																						        -0.02_85_66_11,
																						        -0.73_94_11_23,
																						        0.23_39_79_87,
																						        0.47_32_26_82,
																						        -0.37_82_31_64,
																						    ]      )
																						assert np.abs(latents_slice.flatten() - expected_slice      ).max() < 5E-2
																elif step == 2:
																						lowercase   :       int								=latents.detach().cpu().numpy()
																						assert latents.shape == (1, 4, 64, 256)
																						lowercase   :       List[str]								=latents[0, -3:, -3:, -1]

																						lowercase   :       Any								=np.array(
																						    [
																						        0.18_53_96_45,
																						        0.33_98_72_48,
																						        0.5_37_85_59,
																						        0.14_43_71_42,
																						        -0.02_45_52_61,
																						        -0.7_33_83_17,
																						        0.23_99_07_55,
																						        0.47_35_62_72,
																						        -0.3_78_65_05,
																						    ]      )

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

										lowercase   :       Optional[int]								=False

										lowercase   :       Any								='''stabilityai/stable-diffusion-2-base'''
										lowercase   :       str								=DDIMScheduler.from_pretrained(UpperCAmelCase__		,				subfolder='''scheduler'''      )
										lowercase   :       List[Any]								=StableDiffusionPanoramaPipeline.from_pretrained(UpperCAmelCase__		,				scheduler=UpperCAmelCase__		,				safety_checker=UpperCAmelCase__      )
										lowercase   :       List[Any]								=pipe.to(UpperCAmelCase__      )
										pipe.set_progress_bar_config(disable=UpperCAmelCase__      )
										pipe.enable_attention_slicing()

										lowercase   :       List[Any]								=self.get_inputs()
										pipe(**UpperCAmelCase__		,				callback=UpperCAmelCase__		,				callback_steps=1      )
										assert callback_fn.has_been_called
										assert number_of_steps == 3







				def    lowerCamelCase_  (					self    :		int      ):
										'''simple docstring'''
										torch.cuda.empty_cache()
										torch.cuda.reset_max_memory_allocated()
										torch.cuda.reset_peak_memory_stats()

										lowercase   :       Optional[int]								='''stabilityai/stable-diffusion-2-base'''
										lowercase   :       int								=DDIMScheduler.from_pretrained(UpperCAmelCase__		,				subfolder='''scheduler'''      )
										lowercase   :       Union[str, Any]								=StableDiffusionPanoramaPipeline.from_pretrained(UpperCAmelCase__		,				scheduler=UpperCAmelCase__		,				safety_checker=UpperCAmelCase__      )
										lowercase   :       List[str]								=pipe.to(UpperCAmelCase__      )
										pipe.set_progress_bar_config(disable=UpperCAmelCase__      )
										pipe.enable_attention_slicing(1      )
										pipe.enable_sequential_cpu_offload()

										lowercase   :       str								=self.get_inputs()
										lowercase   :       Any								=pipe(**UpperCAmelCase__      )

										lowercase   :       Optional[Any]								=torch.cuda.max_memory_allocated()
										# make sure that less than 5.2 GB is allocated
										assert mem_bytes < 5.5 * 10**9








'''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())





