

"""simple docstring"""




import unittest
from typing import Tuple

import torch

from diffusers.utils import floats_tensor, randn_tensor, torch_all_close, torch_device
from diffusers.utils.testing_utils import require_torch







@require_torch
class   __lowercase      :

  @property
  def  __lowercase							(	self		:      Union[str, Any]     ):






   '''simple docstring'''
   return self.get_dummy_input()

  @property
  def  __lowercase							(	self		:      Dict     ):






   '''simple docstring'''
   if self.block_type == "down":
    return (4, 32, 16, 16)
   elif self.block_type == "mid":
    return (4, 32, 32, 32)
   elif self.block_type == "up":
    return (4, 32, 64, 64)

   raise ValueError(f"'{self.block_type}' is not a supported block_type. Set it to 'up', 'mid', or 'down'."     )

  def  __lowercase							(	self		:      List[str]       ,A		:      List[str]=True       ,A		:      Optional[int]=False       ,A		:      Any=False       ,A		:      int=False       ,):






   '''simple docstring'''
   UpperCAmelCase__       :	int        =       4
   UpperCAmelCase__       :	Tuple        =       32
   UpperCAmelCase__       :	Optional[Any]        =       (32, 32)

   UpperCAmelCase__       :	Dict        =       torch.manual_seed(0     )
   UpperCAmelCase__       :	int        =       torch.device(A     )
   UpperCAmelCase__       :	List[str]        =       (batch_size, num_channels) + sizes
   UpperCAmelCase__       :	List[Any]        =       randn_tensor(A       ,generator=A       ,device=A     )
   UpperCAmelCase__       :	List[Any]        =       {"""hidden_states""": hidden_states}

   if include_temb:
    UpperCAmelCase__       :	List[Any]        =       128
    UpperCAmelCase__       :	Any        =       randn_tensor((batch_size, temb_channels)       ,generator=A       ,device=A     )

   if include_res_hidden_states_tuple:
    UpperCAmelCase__       :	Union[str, Any]        =       torch.manual_seed(1     )
    UpperCAmelCase__       :	Tuple        =       (randn_tensor(A       ,generator=A       ,device=A     ),)

   if include_encoder_hidden_states:
    UpperCAmelCase__       :	Any        =       floats_tensor((batch_size, 32, 32)     ).to(A     )

   if include_skip_sample:
    UpperCAmelCase__       :	Dict        =       randn_tensor(((batch_size, 3) + sizes)       ,generator=A       ,device=A     )

   return dummy_input

  def  __lowercase							(	self		:      Dict     ):






   '''simple docstring'''
   UpperCAmelCase__       :	Optional[Any]        =       {
       """in_channels""": 32,
       """out_channels""": 32,
       """temb_channels""": 128,
   }
   if self.block_type == "up":
    UpperCAmelCase__       :	Union[str, Any]        =       32

   if self.block_type == "mid":
    init_dict.pop("""out_channels"""     )

   UpperCAmelCase__       :	Union[str, Any]        =       self.dummy_input
   return init_dict, inputs_dict

  def  __lowercase							(	self		:      List[Any]       ,A		:      Optional[Any]     ):






   '''simple docstring'''
   UpperCAmelCase__ ,   UpperCAmelCase__       :	int        =       self.prepare_init_args_and_inputs_for_common()
   UpperCAmelCase__       :	List[Any]        =       self.block_class(**A     )
   unet_block.to(A     )
   unet_block.eval()

   with torch.no_grad():
    UpperCAmelCase__       :	Tuple        =       unet_block(**A     )

   if isinstance(A       ,A     ):
    UpperCAmelCase__       :	Optional[Any]        =       output[0]

   self.assertEqual(output.shape       ,self.output_shape     )

   UpperCAmelCase__       :	Optional[Any]        =       output[0, -1, -3:, -3:]
   UpperCAmelCase__       :	Dict        =       torch.tensor(A     ).to(A     )
   assert torch_all_close(output_slice.flatten()       ,A       ,atol=5e-3     )




  @unittest.skipIf(torch_device == """mps"""       ,"""Training is not supported in mps"""     )
  def  __lowercase							(	self		:      Optional[int]     ):






   '''simple docstring'''
   UpperCAmelCase__ ,   UpperCAmelCase__       :	int        =       self.prepare_init_args_and_inputs_for_common()
   UpperCAmelCase__       :	List[str]        =       self.block_class(**A     )
   model.to(A     )
   model.train()
   UpperCAmelCase__       :	List[Any]        =       model(**A     )

   if isinstance(A       ,A     ):
    UpperCAmelCase__       :	Tuple        =       output[0]

   UpperCAmelCase__       :	Any        =       torch.device(A     )
   UpperCAmelCase__       :	Dict        =       randn_tensor(output.shape       ,device=A     )
   UpperCAmelCase__       :	str        =       torch.nn.functional.mse_loss(A       ,A     )
   loss.backward()













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