






"""simple docstring"""
import gc
import random
import unittest

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

import diffusers
from diffusers import (
    AutoencoderKL,
    EulerDiscreteScheduler,
    StableDiffusionLatentUpscalePipeline,
    StableDiffusionPipeline,
    UNetaDConditionModel,
)
from diffusers.schedulers import KarrasDiffusionSchedulers
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()


def 							A						(				__snake_case: List[Any]  )    ->		Union[str, Any]:

       """simple docstring"""





       __magic_name__      				=    [tensor.shape for tensor in tensor_list]
       return all(shape == shapes[0] for shape in shapes[1:]  )



class        UpperCamelCase__ (				a_							,	a_							,	a_							,	unittest.TestCase):







    """simple docstring"""
    __UpperCAmelCase           = StableDiffusionLatentUpscalePipeline
    __UpperCAmelCase           = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {
        """height""",
        """width""",
        """cross_attention_kwargs""",
        """negative_prompt_embeds""",
        """prompt_embeds""",
    }
    __UpperCAmelCase           = PipelineTesterMixin.required_optional_params - {"""num_images_per_prompt"""}
    __UpperCAmelCase           = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
    __UpperCAmelCase           = frozenset(
        [])  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
    __UpperCAmelCase           = frozenset([])

    __UpperCAmelCase           = True







    @property
    def 				a__			(		self :	Tuple ):





           '''simple docstring'''

           __magic_name__      				=    1
           __magic_name__      				=    4
           __magic_name__      				=    (1_6, 1_6)

           __magic_name__      				=    floats_tensor((batch_size, num_channels) + sizes				,    rng=random.Random(0 ) ).to(UpperCamelCase_ )
           return image







    def 				a__			(		self :	Union[str, Any] ):





           '''simple docstring'''

           torch.manual_seed(0 )
           __magic_name__      				=    UNetaDConditionModel(
               act_fn='gelu'				,    attention_head_dim=8				,    norm_num_groups=UpperCamelCase_				,    block_out_channels=[3_2, 3_2, 6_4, 6_4]				,    time_cond_proj_dim=1_6_0				,    conv_in_kernel=1				,    conv_out_kernel=1				,    cross_attention_dim=3_2				,    down_block_types=(
                   'KDownBlock2D',
                   'KCrossAttnDownBlock2D',
                   'KCrossAttnDownBlock2D',
                   'KCrossAttnDownBlock2D',
               )				,    in_channels=8				,    mid_block_type=UpperCamelCase_				,    only_cross_attention=UpperCamelCase_				,    out_channels=5				,    resnet_time_scale_shift='scale_shift'				,    time_embedding_type='fourier'				,    timestep_post_act='gelu'				,    up_block_types=('KCrossAttnUpBlock2D', 'KCrossAttnUpBlock2D', 'KCrossAttnUpBlock2D', 'KUpBlock2D')				,    )
           __magic_name__      				=    AutoencoderKL(
               block_out_channels=[3_2, 3_2, 6_4, 6_4]				,    in_channels=3				,    out_channels=3				,    down_block_types=[
                   'DownEncoderBlock2D',
                   'DownEncoderBlock2D',
                   'DownEncoderBlock2D',
                   'DownEncoderBlock2D',
               ]				,    up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D', 'UpDecoderBlock2D', 'UpDecoderBlock2D']				,    latent_channels=4				,    )
           __magic_name__      				=    EulerDiscreteScheduler(prediction_type='sample' )
           __magic_name__      				=    CLIPTextConfig(
               bos_token_id=0				,    eos_token_id=2				,    hidden_size=3_2				,    intermediate_size=3_7				,    layer_norm_eps=1e-0_5				,    num_attention_heads=4				,    num_hidden_layers=5				,    pad_token_id=1				,    vocab_size=1_0_0_0				,    hidden_act='quick_gelu'				,    projection_dim=5_1_2				,    )
           __magic_name__      				=    CLIPTextModel(UpperCamelCase_ )
           __magic_name__      				=    CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' )

           __magic_name__      				=    {
               'unet': model.eval(),
               'vae': vae.eval(),
               'scheduler': scheduler,
               'text_encoder': text_encoder,
               'tokenizer': tokenizer,
           }

           return components







    def 				a__			(		self :	List[Any]				,    UpperCamelCase_ :	str				,    UpperCamelCase_ :	Tuple=0 ):





           '''simple docstring'''

           if str(UpperCamelCase_ ).startswith('mps' ):
                  __magic_name__      				=    torch.manual_seed(UpperCamelCase_ )
           else:
                  __magic_name__      				=    torch.Generator(device=UpperCamelCase_ ).manual_seed(UpperCamelCase_ )
           __magic_name__      				=    {
               'prompt': 'A painting of a squirrel eating a burger',
               'image': self.dummy_image.cpu(),
               'generator': generator,
               'num_inference_steps': 2,
               'output_type': 'numpy',
           }
           return inputs







    def 				a__			(		self :	Dict ):





           '''simple docstring'''

           __magic_name__      				=    'cpu'

           __magic_name__      				=    self.get_dummy_components()
           __magic_name__      				=    self.pipeline_class(**UpperCamelCase_ )
           pipe.to(UpperCamelCase_ )
           pipe.set_progress_bar_config(disable=UpperCamelCase_ )

           __magic_name__      				=    self.get_dummy_inputs(UpperCamelCase_ )
           __magic_name__      				=    pipe(**UpperCamelCase_ ).images
           __magic_name__      				=    image[0, -3:, -3:, -1]

           self.assertEqual(image.shape				,    (1, 2_5_6, 2_5_6, 3) )
           __magic_name__      				=    np.array(
               [0.47_222_412, 0.41_921_633, 0.44_717_434, 0.46_874_192, 0.42_588_258, 0.46_150_726, 0.4_677_534, 0.45_583_832, 0.48_579_055] )
           __magic_name__      				=    np.abs(image_slice.flatten() - expected_slice ).max()
           self.assertLessEqual(UpperCamelCase_				,    1e-3 )







    def 				a__			(		self :	Tuple ):





           '''simple docstring'''

           super().test_attention_slicing_forward_pass(expected_max_diff=7e-3 )







    def 				a__			(		self :	Any ):





           '''simple docstring'''

           super().test_cpu_offload_forward_pass(expected_max_diff=3e-3 )







    def 				a__			(		self :	Optional[int] ):





           '''simple docstring'''

           super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 )







    def 				a__			(		self :	Union[str, Any] ):





           '''simple docstring'''

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







    def 				a__			(		self :	Tuple ):





           '''simple docstring'''

           super().test_pt_np_pil_outputs_equivalent(expected_max_diff=3e-3 )







    def 				a__			(		self :	Dict ):





           '''simple docstring'''

           super().test_save_load_local(expected_max_difference=3e-3 )







    def 				a__			(		self :	Tuple ):





           '''simple docstring'''

           super().test_save_load_optional_components(expected_max_difference=3e-3 )







    def 				a__			(		self :	List[Any] ):





           '''simple docstring'''

           __magic_name__      				=    [
               'DDIMScheduler',
               'DDPMScheduler',
               'PNDMScheduler',
               'HeunDiscreteScheduler',
               'EulerAncestralDiscreteScheduler',
               'KDPM2DiscreteScheduler',
               'KDPM2AncestralDiscreteScheduler',
               'DPMSolverSDEScheduler',
           ]
           __magic_name__      				=    self.get_dummy_components()
           __magic_name__      				=    self.pipeline_class(**UpperCamelCase_ )

           # make sure that PNDM does not need warm-up
           pipe.scheduler.register_to_config(skip_prk_steps=UpperCamelCase_ )

           pipe.to(UpperCamelCase_ )
           pipe.set_progress_bar_config(disable=UpperCamelCase_ )
           __magic_name__      				=    self.get_dummy_inputs(UpperCamelCase_ )
           __magic_name__      				=    2

           __magic_name__      				=    []
           for scheduler_enum in KarrasDiffusionSchedulers:
                  if scheduler_enum.name in skip_schedulers:
                         # no sigma schedulers are not supported
                         # no schedulers
                         continue

                  __magic_name__      				=    getattr(UpperCamelCase_				,    scheduler_enum.name )
                  __magic_name__      				=    scheduler_cls.from_config(pipe.scheduler.config )
                  __magic_name__      				=    pipe(**UpperCamelCase_ )[0]
                  outputs.append(UpperCamelCase_ )

           assert check_same_shape(UpperCamelCase_ )



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







    """simple docstring"""







    def 				a__			(		self :	Union[str, Any] ):





           '''simple docstring'''

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







    def 				a__			(		self :	Tuple ):





           '''simple docstring'''

           __magic_name__      				=    torch.manual_seed(3_3 )

           __magic_name__      				=    StableDiffusionPipeline.from_pretrained('CompVis/stable-diffusion-v1-4'				,    torch_dtype=torch.floataa )
           pipe.to('cuda' )

           __magic_name__      				=    StableDiffusionLatentUpscalePipeline.from_pretrained(
               'stabilityai/sd-x2-latent-upscaler'				,    torch_dtype=torch.floataa )
           upscaler.to('cuda' )

           __magic_name__      				=    'a photo of an astronaut high resolution, unreal engine, ultra realistic'

           __magic_name__      				=    pipe(UpperCamelCase_				,    generator=UpperCamelCase_				,    output_type='latent' ).images

           __magic_name__      				=    upscaler(
               prompt=UpperCamelCase_				,    image=UpperCamelCase_				,    num_inference_steps=2_0				,    guidance_scale=0				,    generator=UpperCamelCase_				,    output_type='np'				,    ).images[0]

           __magic_name__      				=    load_numpy(
               'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/astronaut_1024.npy' )
           assert np.abs((expected_image - image).mean() ) < 5e-2







    def 				a__			(		self :	Any ):





           '''simple docstring'''

           __magic_name__      				=    torch.manual_seed(3_3 )

           __magic_name__      				=    StableDiffusionLatentUpscalePipeline.from_pretrained(
               'stabilityai/sd-x2-latent-upscaler'				,    torch_dtype=torch.floataa )
           upscaler.to('cuda' )

           __magic_name__      				=    'the temple of fire by Ross Tran and Gerardo Dottori, oil on canvas'

           __magic_name__      				=    load_image(
               'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/fire_temple_512.png' )

           __magic_name__      				=    upscaler(
               prompt=UpperCamelCase_				,    image=UpperCamelCase_				,    num_inference_steps=2_0				,    guidance_scale=0				,    generator=UpperCamelCase_				,    output_type='np'				,    ).images[0]

           __magic_name__      				=    load_numpy(
               'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/fire_temple_1024.npy' )
           assert np.abs((expected_image - image).max() ) < 5e-2







"""simple docstring"""
import argparse
import copy


def 							A						(				__snake_case: Union[str, Any]  )    ->		Tuple:

       """simple docstring"""





       __magic_name__      				=    {}

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

       return dict_of_neighbours


def 							A						(				__snake_case: Optional[Any] ,     __snake_case: str  )    ->		List[str]:

       """simple docstring"""





       with open(__snake_case  ) as f:
              __magic_name__      				=    f.read(1  )
       __magic_name__      				=    start_node

       __magic_name__      				=    []

       __magic_name__      				=    start_node

       __magic_name__      				=    0
       while visiting not in first_solution:
              __magic_name__      				=    1_0_0_0_0
              for k in dict_of_neighbours[visiting]:
                     if int(k[1]  ) < int(__snake_case  ) and k[0] not in first_solution:
                            __magic_name__      				=    k[1]
                            __magic_name__      				=    k[0]

              first_solution.append(__snake_case  )
              __magic_name__      				=    distance_of_first_solution + int(__snake_case  )
              __magic_name__      				=    best_node

       first_solution.append(__snake_case  )

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

       __magic_name__      				=    (
           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 							A						(				__snake_case: Union[str, Any] ,     __snake_case: Optional[Any]  )    ->		Dict:

       """simple docstring"""





       __magic_name__      				=    []

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

                     __magic_name__      				=    copy.deepcopy(__snake_case  )
                     __magic_name__      				=    kn
                     __magic_name__      				=    n

                     __magic_name__      				=    0

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

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

       __magic_name__      				=    len(neighborhood_of_solution[0]  ) - 1

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


def 							A						(				__snake_case: List[str] ,     __snake_case: Union[str, Any] ,     __snake_case: List[str] ,     __snake_case: Optional[int] ,     __snake_case: List[str]  )    ->		Dict:

       """simple docstring"""





       __magic_name__      				=    1
       __magic_name__      				=    first_solution
       __magic_name__      				=    []
       __magic_name__      				=    distance_of_first_solution
       __magic_name__      				=    solution

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

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

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

              __magic_name__      				=    count + 1

       return best_solution_ever, best_cost


def 							A						(				__snake_case: Union[str, Any]=None  )    ->		Tuple:

       """simple docstring"""





       __magic_name__      				=    generate_neighbours(args.File  )

       __magic_name__				,  __magic_name__      				=    generate_first_solution(
           args.File ,     __snake_case  )

       __magic_name__				,  __magic_name__      				=    tabu_search(
           __snake_case ,     __snake_case ,     __snake_case ,     args.Iterations ,     args.Size ,     )

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


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