



"""simple docstring"""




import argparse
import copy

def 		__snake_case		( SCREAMING_SNAKE_CASE__      :		Dict							)    ->  Any:





     '''simple docstring'''

     _UpperCAmelCase     :      int														=       {}

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

     return dict_of_neighbours

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





     '''simple docstring'''

     with open(SCREAMING_SNAKE_CASE__							) as f:
          _UpperCAmelCase     :      Tuple														=       f.read(1							)
     _UpperCAmelCase     :      Any														=       start_node

     _UpperCAmelCase     :      Optional[Any]														=       []

     _UpperCAmelCase     :      int														=       start_node

     _UpperCAmelCase     :      Optional[Any]														=       0
     while visiting not in first_solution:
          _UpperCAmelCase     :      List[str]														=       10_000
          for k in dict_of_neighbours[visiting]:
               if int(k[1]							) < int(SCREAMING_SNAKE_CASE__							) and k[0] not in first_solution:
                    _UpperCAmelCase     :      List[Any]														=       k[1]
                    _UpperCAmelCase     :      List[str]														=       k[0]

          first_solution.append(SCREAMING_SNAKE_CASE__							)
          _UpperCAmelCase     :      Optional[int]														=       distance_of_first_solution + int(SCREAMING_SNAKE_CASE__							)
          _UpperCAmelCase     :      Optional[int]														=       best_node

     first_solution.append(SCREAMING_SNAKE_CASE__							)

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

     _UpperCAmelCase     :      List[Any]														=       (
         distance_of_first_solution
         + int(dict_of_neighbours[first_solution[-2]][position][1]							)
         - 10_000
     )
     return first_solution, distance_of_first_solution

def 		__snake_case		( SCREAMING_SNAKE_CASE__      :		str		,    SCREAMING_SNAKE_CASE__      :		Optional[Any]							)    ->  Union[str, Any]:





     '''simple docstring'''

     _UpperCAmelCase     :      Any														=       []

     for n in solution[1:-1]:
          _UpperCAmelCase     :      List[str]														=       solution.index(SCREAMING_SNAKE_CASE__							)
          for kn in solution[1:-1]:
               _UpperCAmelCase     :      Any														=       solution.index(SCREAMING_SNAKE_CASE__							)
               if n == kn:
                    continue

               _UpperCAmelCase     :      Tuple														=       copy.deepcopy(SCREAMING_SNAKE_CASE__							)
               _UpperCAmelCase     :      Optional[int]														=       kn
               _UpperCAmelCase     :      List[str]														=       n

               _UpperCAmelCase     :      int														=       0

               for k in _tmp[:-1]:
                    _UpperCAmelCase     :      int														=       _tmp[_tmp.index(SCREAMING_SNAKE_CASE__							) + 1]
                    for i in dict_of_neighbours[k]:
                         if i[0] == next_node:
                              _UpperCAmelCase     :      List[Any]														=       distance + int(i[1]							)
               _tmp.append(SCREAMING_SNAKE_CASE__							)

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

     _UpperCAmelCase     :      Dict														=       len(neighborhood_of_solution[0]							) - 1

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

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





     '''simple docstring'''

     _UpperCAmelCase     :      Optional[Any]														=       1
     _UpperCAmelCase     :      Optional[Any]														=       first_solution
     _UpperCAmelCase     :      Tuple														=       []
     _UpperCAmelCase     :      Union[str, Any]														=       distance_of_first_solution
     _UpperCAmelCase     :      Union[str, Any]														=       solution

     while count <= iters:
          _UpperCAmelCase     :      str														=       find_neighborhood(SCREAMING_SNAKE_CASE__		,    SCREAMING_SNAKE_CASE__							)
          _UpperCAmelCase     :      int														=       0
          _UpperCAmelCase     :      int														=       neighborhood[index_of_best_solution]
          _UpperCAmelCase     :      Union[str, Any]														=       len(SCREAMING_SNAKE_CASE__							) - 1

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

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

          _UpperCAmelCase     :      Optional[int]														=       count + 1

     return best_solution_ever, best_cost

def 		__snake_case		( SCREAMING_SNAKE_CASE__      :		Optional[int]=None							)    ->  Union[str, Any]:





     '''simple docstring'''

     _UpperCAmelCase     :      int														=       generate_neighbours(args.File							)

     _UpperCAmelCase							,			_UpperCAmelCase     :      Union[str, Any]														=       generate_first_solution(
         args.File		,    SCREAMING_SNAKE_CASE__							)

     _UpperCAmelCase							,			_UpperCAmelCase     :      int														=       tabu_search(
         SCREAMING_SNAKE_CASE__		,    SCREAMING_SNAKE_CASE__		,    SCREAMING_SNAKE_CASE__		,    args.Iterations		,    args.Size		,    )

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


if __name__ == "__main__":
 _lowerCAmelCase							:   Optional[Any]				=				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 os
import tempfile
import unittest

import numpy as np

from diffusers.utils import is_flax_available
from diffusers.utils.testing_utils import require_flax, slow


if is_flax_available():
 import jax
 import jax.numpy as jnp
 from flax.jax_utils import replicate
 from flax.training.common_utils import shard

 from diffusers import FlaxDDIMScheduler, FlaxDiffusionPipeline, FlaxStableDiffusionPipeline






@require_flax
class       UpperCAmelCase_    (							unittest.TestCase		):



      def 		snake_case_   (	self	:      Optional[int]		):
           with tempfile.TemporaryDirectory() as tmpdirname:
                # pipeline has Flax weights
                _UpperCAmelCase     :      Union[str, Any]														=       FlaxDiffusionPipeline.from_pretrained(
                    "hf-internal-testing/tiny-stable-diffusion-pipe"	,      safety_checker=A	,      cache_dir=A		)

                _UpperCAmelCase     :      List[str]														=       [t[-1] for t in os.walk(os.path.join(A	,      os.listdir(A		)[0]	,      "snapshots"		)		)]
                _UpperCAmelCase     :      Union[str, Any]														=       [item for sublist in all_root_files for item in sublist]

                # None of the downloaded files should be a PyTorch file even if we have some here:
                # https://huggingface.co/hf-internal-testing/tiny-stable-diffusion-pipe/blob/main/unet/diffusion_pytorch_model.bin
                assert not any(f.endswith(".bin"		) for f in files		)







@slow
@require_flax
class       UpperCAmelCase_    (							unittest.TestCase		):



      def 		snake_case_   (	self	:      List[str]		):
           _UpperCAmelCase							,			_UpperCAmelCase     :      int														=       FlaxStableDiffusionPipeline.from_pretrained(
               "hf-internal-testing/tiny-stable-diffusion-pipe"	,      safety_checker=A		)

           _UpperCAmelCase     :      str														=       (
               "A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"
               " field, close up, split lighting, cinematic"
           )

           _UpperCAmelCase     :      int														=       jax.random.PRNGKey(0		)
           _UpperCAmelCase     :      List[str]														=       4

           _UpperCAmelCase     :      Any														=       jax.device_count()
           _UpperCAmelCase     :      Tuple														=       num_samples * [prompt]
           _UpperCAmelCase     :      Optional[int]														=       pipeline.prepare_inputs(A		)

           # shard inputs and rng
           _UpperCAmelCase     :      Union[str, Any]														=       replicate(A		)
           _UpperCAmelCase     :      List[Any]														=       jax.random.split(A	,      A		)
           _UpperCAmelCase     :      List[Any]														=       shard(A		)

           _UpperCAmelCase     :      Tuple														=       pipeline(A	,      A	,      A	,      A	,      jit=A		).images

           assert images.shape == (num_samples, 1, 6_4, 6_4, 3)
           if jax.device_count() == 8:
                assert np.abs(np.abs(images[0, 0, :2, :2, -2:]	,      dtype=np.floataa		).sum() - 4.1_514_745		) < 1e-3
                assert np.abs(np.abs(A	,      dtype=np.floataa		).sum() - 49_947.875		) < 5e-1

           _UpperCAmelCase     :      Optional[int]														=       pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:]		)		)		)
           assert len(A		) == num_samples



      def 		snake_case_   (	self	:      Union[str, Any]		):
           _UpperCAmelCase							,			_UpperCAmelCase     :      Optional[Any]														=       FlaxStableDiffusionPipeline.from_pretrained(
               "CompVis/stable-diffusion-v1-4"	,      revision="flax"	,      safety_checker=A		)

           _UpperCAmelCase     :      Dict														=       (
               "A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"
               " field, close up, split lighting, cinematic"
           )

           _UpperCAmelCase     :      Dict														=       jax.random.PRNGKey(0		)
           _UpperCAmelCase     :      str														=       5_0

           _UpperCAmelCase     :      List[str]														=       jax.device_count()
           _UpperCAmelCase     :      Any														=       num_samples * [prompt]
           _UpperCAmelCase     :      Dict														=       pipeline.prepare_inputs(A		)

           # shard inputs and rng
           _UpperCAmelCase     :      Dict														=       replicate(A		)
           _UpperCAmelCase     :      str														=       jax.random.split(A	,      A		)
           _UpperCAmelCase     :      Optional[Any]														=       shard(A		)

           _UpperCAmelCase     :      List[Any]														=       pipeline(A	,      A	,      A	,      A	,      jit=A		).images

           assert images.shape == (num_samples, 1, 5_1_2, 5_1_2, 3)
           if jax.device_count() == 8:
                assert np.abs((np.abs(images[0, 0, :2, :2, -2:]	,      dtype=np.floataa		).sum() - 0.05_652_401)		) < 1e-3
                assert np.abs((np.abs(A	,      dtype=np.floataa		).sum() - 2_383_808.2)		) < 5e-1



      def 		snake_case_   (	self	:      List[Any]		):
           _UpperCAmelCase							,			_UpperCAmelCase     :      List[Any]														=       FlaxStableDiffusionPipeline.from_pretrained(
               "CompVis/stable-diffusion-v1-4"	,      revision="bf16"	,      dtype=jnp.bfloataa	,      safety_checker=A		)

           _UpperCAmelCase     :      Any														=       (
               "A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"
               " field, close up, split lighting, cinematic"
           )

           _UpperCAmelCase     :      List[Any]														=       jax.random.PRNGKey(0		)
           _UpperCAmelCase     :      List[Any]														=       5_0

           _UpperCAmelCase     :      Union[str, Any]														=       jax.device_count()
           _UpperCAmelCase     :      Optional[int]														=       num_samples * [prompt]
           _UpperCAmelCase     :      Union[str, Any]														=       pipeline.prepare_inputs(A		)

           # shard inputs and rng
           _UpperCAmelCase     :      int														=       replicate(A		)
           _UpperCAmelCase     :      Optional[int]														=       jax.random.split(A	,      A		)
           _UpperCAmelCase     :      str														=       shard(A		)

           _UpperCAmelCase     :      Union[str, Any]														=       pipeline(A	,      A	,      A	,      A	,      jit=A		).images

           assert images.shape == (num_samples, 1, 5_1_2, 5_1_2, 3)
           if jax.device_count() == 8:
                assert np.abs((np.abs(images[0, 0, :2, :2, -2:]	,      dtype=np.floataa		).sum() - 0.04_003_906)		) < 1e-3
                assert np.abs((np.abs(A	,      dtype=np.floataa		).sum() - 2_373_516.75)		) < 5e-1



      def 		snake_case_   (	self	:      int		):
           _UpperCAmelCase							,			_UpperCAmelCase     :      Dict														=       FlaxStableDiffusionPipeline.from_pretrained(
               "CompVis/stable-diffusion-v1-4"	,      revision="bf16"	,      dtype=jnp.bfloataa		)

           _UpperCAmelCase     :      str														=       (
               "A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"
               " field, close up, split lighting, cinematic"
           )

           _UpperCAmelCase     :      Optional[int]														=       jax.random.PRNGKey(0		)
           _UpperCAmelCase     :      Dict														=       5_0

           _UpperCAmelCase     :      Union[str, Any]														=       jax.device_count()
           _UpperCAmelCase     :      str														=       num_samples * [prompt]
           _UpperCAmelCase     :      int														=       pipeline.prepare_inputs(A		)

           # shard inputs and rng
           _UpperCAmelCase     :      Optional[int]														=       replicate(A		)
           _UpperCAmelCase     :      Tuple														=       jax.random.split(A	,      A		)
           _UpperCAmelCase     :      Dict														=       shard(A		)

           _UpperCAmelCase     :      Optional[Any]														=       pipeline(A	,      A	,      A	,      A	,      jit=A		).images

           assert images.shape == (num_samples, 1, 5_1_2, 5_1_2, 3)
           if jax.device_count() == 8:
                assert np.abs((np.abs(images[0, 0, :2, :2, -2:]	,      dtype=np.floataa		).sum() - 0.04_003_906)		) < 1e-3
                assert np.abs((np.abs(A	,      dtype=np.floataa		).sum() - 2_373_516.75)		) < 5e-1



      def 		snake_case_   (	self	:      Optional[Any]		):
           _UpperCAmelCase     :      Dict														=       FlaxDDIMScheduler(
               beta_start=0.00_085	,      beta_end=0.012	,      beta_schedule="scaled_linear"	,      set_alpha_to_one=A	,      steps_offset=1	,      )

           _UpperCAmelCase							,			_UpperCAmelCase     :      Dict														=       FlaxStableDiffusionPipeline.from_pretrained(
               "CompVis/stable-diffusion-v1-4"	,      revision="bf16"	,      dtype=jnp.bfloataa	,      scheduler=A	,      safety_checker=A	,      )
           _UpperCAmelCase     :      Union[str, Any]														=       scheduler.create_state()

           _UpperCAmelCase     :      str														=       scheduler_state

           _UpperCAmelCase     :      Union[str, Any]														=       (
               "A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"
               " field, close up, split lighting, cinematic"
           )

           _UpperCAmelCase     :      str														=       jax.random.PRNGKey(0		)
           _UpperCAmelCase     :      List[str]														=       5_0

           _UpperCAmelCase     :      Optional[int]														=       jax.device_count()
           _UpperCAmelCase     :      int														=       num_samples * [prompt]
           _UpperCAmelCase     :      Optional[int]														=       pipeline.prepare_inputs(A		)

           # shard inputs and rng
           _UpperCAmelCase     :      List[Any]														=       replicate(A		)
           _UpperCAmelCase     :      Tuple														=       jax.random.split(A	,      A		)
           _UpperCAmelCase     :      Union[str, Any]														=       shard(A		)

           _UpperCAmelCase     :      Dict														=       pipeline(A	,      A	,      A	,      A	,      jit=A		).images

           assert images.shape == (num_samples, 1, 5_1_2, 5_1_2, 3)
           if jax.device_count() == 8:
                assert np.abs((np.abs(images[0, 0, :2, :2, -2:]	,      dtype=np.floataa		).sum() - 0.045_043_945)		) < 1e-3
                assert np.abs((np.abs(A	,      dtype=np.floataa		).sum() - 2_347_693.5)		) < 5e-1



      def 		snake_case_   (	self	:      int		):
           _UpperCAmelCase     :      Optional[Any]														=       (
               "A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"
               " field, close up, split lighting, cinematic"
           )

           _UpperCAmelCase     :      Optional[Any]														=       jax.device_count()
           _UpperCAmelCase     :      Union[str, Any]														=       num_samples * [prompt]
           _UpperCAmelCase     :      Optional[Any]														=       jax.random.split(jax.random.PRNGKey(0		)	,      A		)

           _UpperCAmelCase							,			_UpperCAmelCase     :      str														=       FlaxStableDiffusionPipeline.from_pretrained(
               "CompVis/stable-diffusion-v1-4"	,      revision="bf16"	,      dtype=jnp.bfloataa	,      safety_checker=A	,      )

           _UpperCAmelCase     :      int														=       replicate(A		)
           _UpperCAmelCase     :      Union[str, Any]														=       pipeline.prepare_inputs(A		)
           _UpperCAmelCase     :      int														=       shard(A		)
           _UpperCAmelCase     :      Dict														=       pipeline(A	,      A	,      A	,      jit=A		).images
           assert images.shape == (num_samples, 1, 5_1_2, 5_1_2, 3)
           _UpperCAmelCase     :      List[str]														=       images[2, 0, 2_5_6, 1_0:1_7, 1]

           # With memory efficient attention
           _UpperCAmelCase							,			_UpperCAmelCase     :      str														=       FlaxStableDiffusionPipeline.from_pretrained(
               "CompVis/stable-diffusion-v1-4"	,      revision="bf16"	,      dtype=jnp.bfloataa	,      safety_checker=A	,      use_memory_efficient_attention=A	,      )

           _UpperCAmelCase     :      Any														=       replicate(A		)
           _UpperCAmelCase     :      str														=       pipeline.prepare_inputs(A		)
           _UpperCAmelCase     :      Tuple														=       shard(A		)
           _UpperCAmelCase     :      Tuple														=       pipeline(A	,      A	,      A	,      jit=A		).images
           assert images_eff.shape == (num_samples, 1, 5_1_2, 5_1_2, 3)
           _UpperCAmelCase     :      str														=       images[2, 0, 2_5_6, 1_0:1_7, 1]

           # I checked the results visually and they are very similar. However, I saw that the max diff is `1` and the `sum`
           # over the 8 images is exactly `256`, which is very suspicious. Testing a random slice for now.
           assert abs(slice_eff - slice		).max() < 1e-2
