





'''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 			_lowercase						(       UpperCAmelCase__				,		UpperCAmelCase__				,		unittest.TestCase					):
     _UpperCAmelCase										=					StableDiffusionPanoramaPipeline
     _UpperCAmelCase										=					TEXT_TO_IMAGE_PARAMS
     _UpperCAmelCase										=					TEXT_TO_IMAGE_BATCH_PARAMS
     _UpperCAmelCase										=					TEXT_TO_IMAGE_IMAGE_PARAMS
     _UpperCAmelCase										=					TEXT_TO_IMAGE_IMAGE_PARAMS







     def     UpperCamelCase			( self    ) ->	List[str]:
      torch.manual_seed(0    )
      snake_case				=			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    ,   )
      snake_case				=			DDIMScheduler()
      torch.manual_seed(0    )
      snake_case				=			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    )
      snake_case				=			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    ,   )
      snake_case				=			CLIPTextModel(__lowerCAmelCase    )
      snake_case				=			CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''    )

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







     def     UpperCamelCase			( self    ,   A__    ,   A__=0    ) ->	Optional[int]:
      snake_case				=			torch.manual_seed(__lowerCAmelCase    )
      snake_case				=			{
          '''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     UpperCamelCase			( self    ) ->	str:
      snake_case				=			'''cpu'''  # ensure determinism for the device-dependent torch.Generator
      snake_case				=			self.get_dummy_components()
      snake_case				=			StableDiffusionPanoramaPipeline(**__lowerCAmelCase    )
      snake_case				=			sd_pipe.to(__lowerCAmelCase    )
      sd_pipe.set_progress_bar_config(disable=__lowerCAmelCase    )

      snake_case				=			self.get_dummy_inputs(__lowerCAmelCase    )
      snake_case				=			sd_pipe(**__lowerCAmelCase    ).images
      snake_case				=			image[0, -3:, -3:, -1]
      assert image.shape == (1, 64, 64, 3)

      snake_case				=			np.array([0.6_1_8_6, 0.5_3_7_4, 0.4_9_1_5, 0.4_1_3_5, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_7, 0.4_7_5_7]    )

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







     def     UpperCamelCase			( self    ) ->	Dict:
      super().test_inference_batch_consistent(batch_sizes=[1, 2]    )







     def     UpperCamelCase			( self    ) ->	Optional[Any]:
      super().test_inference_batch_single_identical(batch_size=2    ,   expected_max_diff=3.25e-3    )







     def     UpperCamelCase			( self    ) ->	Optional[int]:
      snake_case				=			'''cpu'''  # ensure determinism for the device-dependent torch.Generator
      snake_case				=			self.get_dummy_components()
      snake_case				=			StableDiffusionPanoramaPipeline(**__lowerCAmelCase    )
      snake_case				=			sd_pipe.to(__lowerCAmelCase    )
      sd_pipe.set_progress_bar_config(disable=__lowerCAmelCase    )

      snake_case				=			self.get_dummy_inputs(__lowerCAmelCase    )
      snake_case				=			'''french fries'''
      snake_case				=			sd_pipe(**__lowerCAmelCase    ,   negative_prompt=__lowerCAmelCase    )
      snake_case				=			output.images
      snake_case				=			image[0, -3:, -3:, -1]

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

      snake_case				=			np.array([0.6_1_8_7, 0.5_3_7_5, 0.4_9_1_5, 0.4_1_3_6, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_6, 0.4_7_5_7]    )

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







     def     UpperCamelCase			( self    ) ->	str:
      snake_case				=			'''cpu'''  # ensure determinism for the device-dependent torch.Generator
      snake_case				=			self.get_dummy_components()
      snake_case				=			StableDiffusionPanoramaPipeline(**__lowerCAmelCase    )
      snake_case				=			sd_pipe.to(__lowerCAmelCase    )
      sd_pipe.set_progress_bar_config(disable=__lowerCAmelCase    )

      snake_case				=			self.get_dummy_inputs(__lowerCAmelCase    )
      snake_case				=			sd_pipe(**__lowerCAmelCase    ,   view_batch_size=2    )
      snake_case				=			output.images
      snake_case				=			image[0, -3:, -3:, -1]

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

      snake_case				=			np.array([0.6_1_8_7, 0.5_3_7_5, 0.4_9_1_5, 0.4_1_3_6, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_6, 0.4_7_5_7]    )

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







     def     UpperCamelCase			( self    ) ->	Any:
      snake_case				=			'''cpu'''  # ensure determinism for the device-dependent torch.Generator
      snake_case				=			self.get_dummy_components()
      snake_case				=			EulerAncestralDiscreteScheduler(
          beta_start=0.0_0_0_8_5    ,   beta_end=0.0_1_2    ,   beta_schedule='''scaled_linear'''    )
      snake_case				=			StableDiffusionPanoramaPipeline(**__lowerCAmelCase    )
      snake_case				=			sd_pipe.to(__lowerCAmelCase    )
      sd_pipe.set_progress_bar_config(disable=__lowerCAmelCase    )

      snake_case				=			self.get_dummy_inputs(__lowerCAmelCase    )
      snake_case				=			sd_pipe(**__lowerCAmelCase    ).images
      snake_case				=			image[0, -3:, -3:, -1]

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

      snake_case				=			np.array([0.4_0_2_4, 0.6_5_1_0, 0.4_9_0_1, 0.5_3_7_8, 0.5_8_1_3, 0.5_6_2_2, 0.4_7_9_5, 0.4_4_6_7, 0.4_9_5_2]    )

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







     def     UpperCamelCase			( self    ) ->	List[Any]:
      snake_case				=			'''cpu'''  # ensure determinism for the device-dependent torch.Generator
      snake_case				=			self.get_dummy_components()
      snake_case				=			PNDMScheduler(
          beta_start=0.0_0_0_8_5    ,   beta_end=0.0_1_2    ,   beta_schedule='''scaled_linear'''    ,   skip_prk_steps=__lowerCAmelCase    )
      snake_case				=			StableDiffusionPanoramaPipeline(**__lowerCAmelCase    )
      snake_case				=			sd_pipe.to(__lowerCAmelCase    )
      sd_pipe.set_progress_bar_config(disable=__lowerCAmelCase    )

      snake_case				=			self.get_dummy_inputs(__lowerCAmelCase    )
      snake_case				=			sd_pipe(**__lowerCAmelCase    ).images
      snake_case				=			image[0, -3:, -3:, -1]

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

      snake_case				=			np.array([0.6_3_9_1, 0.6_2_9_1, 0.4_8_6_1, 0.5_1_3_4, 0.5_5_5_2, 0.4_5_7_8, 0.5_0_3_2, 0.5_0_2_3, 0.4_5_3_9]    )

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




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







     def     UpperCamelCase			( self    ) ->	Union[str, Any]:
      super().tearDown()
      gc.collect()
      torch.cuda.empty_cache()







     def     UpperCamelCase			( self    ,   A__=0    ) ->	Tuple:
      snake_case				=			torch.manual_seed(__lowerCAmelCase    )
      snake_case				=			{
          '''prompt''': '''a photo of the dolomites''',
          '''generator''': generator,
          '''num_inference_steps''': 3,
          '''guidance_scale''': 7.5,
          '''output_type''': '''numpy''',
      }
      return inputs







     def     UpperCamelCase			( self    ) ->	Union[str, Any]:
      snake_case				=			'''stabilityai/stable-diffusion-2-base'''
      snake_case				=			DDIMScheduler.from_pretrained(__lowerCAmelCase    ,   subfolder='''scheduler'''    )
      snake_case				=			StableDiffusionPanoramaPipeline.from_pretrained(__lowerCAmelCase    ,   scheduler=__lowerCAmelCase    ,   safety_checker=__lowerCAmelCase    )
      pipe.to(__lowerCAmelCase    )
      pipe.set_progress_bar_config(disable=__lowerCAmelCase    )
      pipe.enable_attention_slicing()

      snake_case				=			self.get_inputs()
      snake_case				=			pipe(**__lowerCAmelCase    ).images
      snake_case				=			image[0, -3:, -3:, -1].flatten()

      assert image.shape == (1, 5_12, 20_48, 3)

      snake_case				=			np.array(
          [
              0.3_6_9_6_8_3_9_2,
              0.2_7_0_2_5_3_7_2,
              0.3_2_4_4_6_7_6_6,
              0.2_8_3_7_9_3_8_7,
              0.3_6_3_6_3_2_7_4,
              0.3_0_7_3_3_3_4_7,
              0.2_7_1_0_0_0_2_7,
              0.2_7_0_5_4_1_2_5,
              0.2_5_5_3_6_0_9_6,
          ]    )

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







     def     UpperCamelCase			( self    ) ->	List[Any]:
      snake_case				=			StableDiffusionPanoramaPipeline.from_pretrained(
          '''stabilityai/stable-diffusion-2-base'''    ,   safety_checker=__lowerCAmelCase    )
      snake_case				=			LMSDiscreteScheduler.from_config(pipe.scheduler.config    )
      pipe.to(__lowerCAmelCase    )
      pipe.set_progress_bar_config(disable=__lowerCAmelCase    )
      pipe.enable_attention_slicing()

      snake_case				=			self.get_inputs()
      snake_case				=			pipe(**__lowerCAmelCase    ).images
      snake_case				=			image[0, -3:, -3:, -1].flatten()

      assert image.shape == (1, 5_12, 20_48, 3)

      snake_case				=			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     UpperCamelCase			( self    ) ->	int:
      snake_case				=			0

      def callback_fn(A__    ,   A__    ,   A__    ) -> None:
       snake_case				=			True
       nonlocal number_of_steps
       number_of_steps += 1
       if step == 1:
        snake_case				=			latents.detach().cpu().numpy()
        assert latents.shape == (1, 4, 64, 2_56)
        snake_case				=			latents[0, -3:, -3:, -1]

        snake_case				=			np.array(
            [
                0.1_8_6_8_1_8_6_9,
                0.3_3_9_0_7_8_1_6,
                0.5_3_6_1_2_7_6,
                0.1_4_4_3_2_8_6_5,
                -0.0_2_8_5_6_6_1_1,
                -0.7_3_9_4_1_1_2_3,
                0.2_3_3_9_7_9_8_7,
                0.4_7_3_2_2_6_8_2,
                -0.3_7_8_2_3_1_6_4,
            ]    )
        assert np.abs(latents_slice.flatten() - expected_slice    ).max() < 5e-2
       elif step == 2:
        snake_case				=			latents.detach().cpu().numpy()
        assert latents.shape == (1, 4, 64, 2_56)
        snake_case				=			latents[0, -3:, -3:, -1]

        snake_case				=			np.array(
            [
                0.1_8_5_3_9_6_4_5,
                0.3_3_9_8_7_2_4_8,
                0.5_3_7_8_5_5_9,
                0.1_4_4_3_7_1_4_2,
                -0.0_2_4_5_5_2_6_1,
                -0.7_3_3_8_3_1_7,
                0.2_3_9_9_0_7_5_5,
                0.4_7_3_5_6_2_7_2,
                -0.3_7_8_6_5_0_5,
            ]    )

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

      snake_case				=			False

      snake_case				=			'''stabilityai/stable-diffusion-2-base'''
      snake_case				=			DDIMScheduler.from_pretrained(__lowerCAmelCase    ,   subfolder='''scheduler'''    )
      snake_case				=			StableDiffusionPanoramaPipeline.from_pretrained(__lowerCAmelCase    ,   scheduler=__lowerCAmelCase    ,   safety_checker=__lowerCAmelCase    )
      snake_case				=			pipe.to(__lowerCAmelCase    )
      pipe.set_progress_bar_config(disable=__lowerCAmelCase    )
      pipe.enable_attention_slicing()

      snake_case				=			self.get_inputs()
      pipe(**__lowerCAmelCase    ,   callback=__lowerCAmelCase    ,   callback_steps=1    )
      assert callback_fn.has_been_called
      assert number_of_steps == 3







     def     UpperCamelCase			( self    ) ->	Optional[Any]:
      torch.cuda.empty_cache()
      torch.cuda.reset_max_memory_allocated()
      torch.cuda.reset_peak_memory_stats()

      snake_case				=			'''stabilityai/stable-diffusion-2-base'''
      snake_case				=			DDIMScheduler.from_pretrained(__lowerCAmelCase    ,   subfolder='''scheduler'''    )
      snake_case				=			StableDiffusionPanoramaPipeline.from_pretrained(__lowerCAmelCase    ,   scheduler=__lowerCAmelCase    ,   safety_checker=__lowerCAmelCase    )
      snake_case				=			pipe.to(__lowerCAmelCase    )
      pipe.set_progress_bar_config(disable=__lowerCAmelCase    )
      pipe.enable_attention_slicing(1    )
      pipe.enable_sequential_cpu_offload()

      snake_case				=			self.get_inputs()
      snake_case				=			pipe(**__lowerCAmelCase    )

      snake_case				=			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    __UpperCamelCase	(	a    : Union[str, Any]     ) ->Tuple:
 snake_case				=			{}

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

 return dict_of_neighbours

def    __UpperCamelCase	(	a    : Dict					,   a    : Tuple     ) ->int:

 with open(a     ) as f:
  snake_case				=			f.read(1     )
 snake_case				=			start_node

 snake_case				=			[]

 snake_case				=			start_node

 snake_case				=			0
 while visiting not in first_solution:
  snake_case				=			1_0000
  for k in dict_of_neighbours[visiting]:
   if int(k[1]     ) < int(a     ) and k[0] not in first_solution:
    snake_case				=			k[1]
    snake_case				=			k[0]

  first_solution.append(a     )
  snake_case				=			distance_of_first_solution + int(a     )
  snake_case				=			best_node

 first_solution.append(a     )

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

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

def    __UpperCamelCase	(	a    : Optional[int]					,   a    : str     ) ->str:
 snake_case				=			[]

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

   snake_case				=			copy.deepcopy(a     )
   snake_case				=			kn
   snake_case				=			n

   snake_case				=			0

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

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

 snake_case				=			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    __UpperCamelCase	(	a    : Any					,   a    : Optional[Any]					,   a    : int					,   a    : Optional[int]					,   a    : Union[str, Any]     ) ->List[Any]:
 snake_case				=			1
 snake_case				=			first_solution
 snake_case				=			[]
 snake_case				=			distance_of_first_solution
 snake_case				=			solution

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

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

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

  snake_case				=			count + 1

 return best_solution_ever, best_cost

def    __UpperCamelCase	(	a    : Union[str, Any]=None     ) ->Optional[Any]:
 snake_case				=			generate_neighbours(args.File     )

 snake_case				,		snake_case				=			generate_first_solution(
     args.File					,   a     )

 snake_case				,		snake_case				=			tabu_search(
     a					,   a					,   a					,   args.Iterations					,   args.Size					,   )

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


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

