


"""simple docstring"""



import inspect
import unittest

from transformers import RegNetConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch
 from torch import nn

 from transformers import RegNetForImageClassification, RegNetModel
 from transformers.models.regnet.modeling_regnet import REGNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import AutoImageProcessor
class 					__magic_name__		:






       def __init__(   self  :    Optional[int]  ,     snake_case__  :    Union[str, Any]  ,     snake_case__  :    Optional[Any]=3  ,     snake_case__  :    int=3_2  ,     snake_case__  :    List[str]=3  ,     snake_case__  :    Any=1_0  ,     snake_case__  :    Optional[int]=[1_0, 2_0, 3_0, 4_0]  ,     snake_case__  :    Any=[1, 1, 2, 1]  ,     snake_case__  :    Optional[Any]=True  ,     snake_case__  :    Any=True  ,     snake_case__  :    Optional[int]="relu"  ,     snake_case__  :    List[Any]=3  ,     snake_case__  :    int=None  ,     ):

              '''simple docstring'''






              lowercase		:Any       							=				parent
              lowercase		:List[str]       							=				batch_size
              lowercase		:Dict       							=				image_size
              lowercase		:Dict       							=				num_channels
              lowercase		:Tuple       							=				embeddings_size
              lowercase		:Any       							=				hidden_sizes
              lowercase		:Any       							=				depths
              lowercase		:Optional[int]       							=				is_training
              lowercase		:int       							=				use_labels
              lowercase		:Tuple       							=				hidden_act
              lowercase		:Union[str, Any]       							=				num_labels
              lowercase		:Any       							=				scope
              lowercase		:int       							=				len(snake_case__				)






       def  __snake_case						(   self  :    Tuple				):

              '''simple docstring'''






              lowercase		:str       							=				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

              lowercase		:int       							=				None
              if self.use_labels:
                     lowercase		:Dict       							=				ids_tensor([self.batch_size]  ,     self.num_labels				)

              lowercase		:str       							=				self.get_config()

              return config, pixel_values, labels






       def  __snake_case						(   self  :    int				):

              '''simple docstring'''






              return RegNetConfig(
                  num_channels=self.num_channels  ,     embeddings_size=self.embeddings_size  ,     hidden_sizes=self.hidden_sizes  ,     depths=self.depths  ,     hidden_act=self.hidden_act  ,     num_labels=self.num_labels  ,     )






       def  __snake_case						(   self  :    Optional[int]  ,     snake_case__  :    List[Any]  ,     snake_case__  :    List[Any]  ,     snake_case__  :    Dict				):

              '''simple docstring'''






              lowercase		:Optional[Any]       							=				RegNetModel(config=snake_case__				)
              model.to(snake_case__				)
              model.eval()
              lowercase		:Union[str, Any]       							=				model(snake_case__				)
              # expected last hidden states: B, C, H // 32, W // 32
              self.parent.assertEqual(
                  result.last_hidden_state.shape  ,     (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2)  ,     )






       def  __snake_case						(   self  :    Union[str, Any]  ,     snake_case__  :    Tuple  ,     snake_case__  :    Any  ,     snake_case__  :    Any				):

              '''simple docstring'''






              lowercase		:int       							=				self.num_labels
              lowercase		:List[str]       							=				RegNetForImageClassification(snake_case__				)
              model.to(snake_case__				)
              model.eval()
              lowercase		:Tuple       							=				model(snake_case__  ,     labels=snake_case__				)
              self.parent.assertEqual(result.logits.shape  ,     (self.batch_size, self.num_labels)				)







       def  __snake_case						(   self  :    List[Any]				):

              '''simple docstring'''






              lowercase		:List[Any]       							=				self.prepare_config_and_inputs()
              lowercase		:Optional[Any]       							=				config_and_inputs
              lowercase		:Optional[Any]       							=				{'''pixel_values''': pixel_values}
              return config, inputs_dict





@require_torch
class 					__magic_name__		(			__UpperCAmelCase			,						__UpperCAmelCase			,						unittest.TestCase     ):
       __A			:      Union[str, Any]        =   (RegNetModel, RegNetForImageClassification) if is_torch_available() else ()
       __A			:      List[str]        =   (
           {"feature-extraction": RegNetModel, "image-classification": RegNetForImageClassification}
           if is_torch_available()
           else {}
       )

       __A			:      Any        =   False
       __A			:      int        =   False
       __A			:      Any        =   False
       __A			:      Optional[Any]        =   False






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

              '''simple docstring'''






              lowercase		:Any       							=				RegNetModelTester(self				)
              lowercase		:int       							=				ConfigTester(self  ,     config_class=snake_case__  ,     has_text_modality=snake_case__				)






       def  __snake_case						(   self  :    Dict				):

              '''simple docstring'''






              self.create_and_test_config_common_properties()
              self.config_tester.create_and_test_config_to_json_string()
              self.config_tester.create_and_test_config_to_json_file()
              self.config_tester.create_and_test_config_from_and_save_pretrained()
              self.config_tester.create_and_test_config_with_num_labels()
              self.config_tester.check_config_can_be_init_without_params()
              self.config_tester.check_config_arguments_init()






       def  __snake_case						(   self  :    Tuple				):

              '''simple docstring'''






              return






       @unittest.skip(reason='''RegNet does not use inputs_embeds'''				)
       def  __snake_case						(   self  :    Union[str, Any]				):

              '''simple docstring'''






              pass






       @unittest.skip(reason='''RegNet does not support input and output embeddings'''				)
       def  __snake_case						(   self  :    Tuple				):

              '''simple docstring'''






              pass






       def  __snake_case						(   self  :    List[str]				):

              '''simple docstring'''






              lowercase		:Union[str, Any]       							=				self.model_tester.prepare_config_and_inputs_for_common()

              for model_class in self.all_model_classes:
                     lowercase		:List[str]       							=				model_class(snake_case__				)
                     lowercase		:Optional[Any]       							=				inspect.signature(model.forward				)
                     # signature.parameters is an OrderedDict => so arg_names order is deterministic
                     lowercase		:Optional[Any]       							=				[*signature.parameters.keys()]

                     lowercase		:Dict       							=				['''pixel_values''']
                     self.assertListEqual(arg_names[:1]  ,     snake_case__				)






       def  __snake_case						(   self  :    Dict				):

              '''simple docstring'''






              lowercase		:Union[str, Any]       							=				self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_model(*snake_case__				)






       def  __snake_case						(   self  :    Any				):

              '''simple docstring'''






              lowercase		:List[str]       							=				self.model_tester.prepare_config_and_inputs_for_common()

              for model_class in self.all_model_classes:
                     lowercase		:List[Any]       							=				model_class(config=snake_case__				)
                     for name, module in model.named_modules():
                            if isinstance(snake_case__  ,     (nn.BatchNormad, nn.GroupNorm)				):
                                   self.assertTrue(
                                       torch.all(module.weight == 1				)  ,     msg=f"""Parameter {name} of model {model_class} seems not properly initialized"""  ,     )
                                   self.assertTrue(
                                       torch.all(module.bias == 0				)  ,     msg=f"""Parameter {name} of model {model_class} seems not properly initialized"""  ,     )






       def  __snake_case						(   self  :    str				):

              '''simple docstring'''






              def check_hidden_states_output(snake_case__  :    Optional[int]  ,     snake_case__  :    Optional[int]  ,     snake_case__  :    Dict				):
                     lowercase		:Union[str, Any]       							=				model_class(snake_case__				)
                     model.to(snake_case__				)
                     model.eval()

                     with torch.no_grad():
                            lowercase		:Optional[Any]       							=				model(**self._prepare_for_class(snake_case__  ,     snake_case__				)				)

                     lowercase		:Tuple       							=				outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                     lowercase		:Any       							=				self.model_tester.num_stages
                     self.assertEqual(len(snake_case__				)  ,     expected_num_stages + 1				)

                     # RegNet's feature maps are of shape (batch_size, num_channels, height, width)
                     self.assertListEqual(
                         list(hidden_states[0].shape[-2:]				)  ,     [self.model_tester.image_size // 2, self.model_tester.image_size // 2]  ,     )

              lowercase		:Union[str, Any]       							=				self.model_tester.prepare_config_and_inputs_for_common()
              lowercase		:Optional[int]       							=				['''basic''', '''bottleneck''']
              for model_class in self.all_model_classes:
                     for layer_type in layers_type:
                            lowercase		:int       							=				layer_type
                            lowercase		:Optional[int]       							=				True
                            check_hidden_states_output(snake_case__  ,     snake_case__  ,     snake_case__				)

                            # check that output_hidden_states also work using config
                            del inputs_dict["output_hidden_states"]
                            lowercase		:Dict       							=				True

                            check_hidden_states_output(snake_case__  ,     snake_case__  ,     snake_case__				)






       def  __snake_case						(   self  :    Optional[int]				):

              '''simple docstring'''






              lowercase		:Union[str, Any]       							=				self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_for_image_classification(*snake_case__				)







       @slow
       def  __snake_case						(   self  :    List[str]				):

              '''simple docstring'''






              for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                     lowercase		:Tuple       							=				RegNetModel.from_pretrained(snake_case__				)
                     self.assertIsNotNone(snake_case__				)






def       lowerCamelCase					()     ->							Dict:
       lowercase		:Any       							=				Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''')
       return image




@require_torch
@require_vision
class 					__magic_name__		(			unittest.TestCase     ):






       @cached_property
       def  __snake_case						(   self  :    List[str]				):

              '''simple docstring'''






              return (
                  AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]				)
                  if is_vision_available()
                  else None
              )







       @slow
       def  __snake_case						(   self  :    List[Any]				):

              '''simple docstring'''






              lowercase		:Optional[int]       							=				RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]				).to(snake_case__				)

              lowercase		:Optional[int]       							=				self.default_image_processor
              lowercase		:Optional[int]       							=				prepare_img()
              lowercase		:str       							=				image_processor(images=snake_case__  ,     return_tensors='''pt'''				).to(snake_case__				)

              # forward pass
              with torch.no_grad():
                     lowercase		:List[Any]       							=				model(**snake_case__				)

              # verify the logits
              lowercase		:str       							=				torch.Size((1, 1_0_0_0)				)
              self.assertEqual(outputs.logits.shape  ,     snake_case__				)

              lowercase		:Optional[int]       							=				torch.tensor([-0.41_80, -1.50_51, -3.48_36]				).to(snake_case__				)

              self.assertTrue(torch.allclose(outputs.logits[0, :3]  ,     snake_case__  ,     atol=1e-4				)				)





"""simple docstring"""



import argparse
import copy






def       lowerCamelCase					(a_						:Union[str, Any])     ->							Tuple:
       lowercase		:Dict       							=				{}

       with open(a_) 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		: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:
                            lowercase		:List[Any]       							=				[]
                            _list.append([line.split()[0], line.split()[2]])
                            lowercase		:Dict       							=				_list
                     else:
                            dict_of_neighbours[line.split()[1]].append(
                                [line.split()[0], line.split()[2]])

       return dict_of_neighbours






def       lowerCamelCase					(a_						:Any				,				a_						:Dict)     ->							Any:

       with open(a_) as f:
              lowercase		:Any       							=				f.read(1)
       lowercase		:Any       							=				start_node

       lowercase		:Any       							=				[]

       lowercase		:Union[str, Any]       							=				start_node

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

              first_solution.append(a_)
              lowercase		:int       							=				distance_of_first_solution + int(a_)
              lowercase		:Dict       							=				best_node

       first_solution.append(a_)

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

       lowercase		:List[str]       							=				(
           distance_of_first_solution
           + int(dict_of_neighbours[first_solution[-2]][position][1])
           - 1_0000
       )
       return first_solution, distance_of_first_solution






def       lowerCamelCase					(a_						:List[str]				,				a_						:str)     ->							str:
       lowercase		:Any       							=				[]

       for n in solution[1:-1]:
              lowercase		:int       							=				solution.index(a_)
              for kn in solution[1:-1]:
                     lowercase		:Union[str, Any]       							=				solution.index(a_)
                     if n == kn:
                            continue

                     lowercase		:int       							=				copy.deepcopy(a_)
                     lowercase		:str       							=				kn
                     lowercase		:List[Any]       							=				n

                     lowercase		:int       							=				0

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

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

       lowercase		:Dict       							=				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       lowerCamelCase					(a_						:int				,				a_						:Optional[int]				,				a_						:List[Any]				,				a_						:Any				,				a_						:Optional[Any])     ->							List[Any]:
       lowercase		:Union[str, Any]       							=				1
       lowercase		:str       							=				first_solution
       lowercase		:int       							=				[]
       lowercase		:int       							=				distance_of_first_solution
       lowercase		:List[str]       							=				solution

       while count <= iters:
              lowercase		:Optional[Any]       							=				find_neighborhood(a_				,				a_)
              lowercase		:Any       							=				0
              lowercase		:Optional[Any]       							=				neighborhood[index_of_best_solution]
              lowercase		:int       							=				len(a_) - 1

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

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

              lowercase		:int       							=				count + 1

       return best_solution_ever, best_cost






def       lowerCamelCase					(a_						:Tuple=None)     ->							Any:
       lowercase		:Tuple       							=				generate_neighbours(args.File)

       lowercase							,  lowercase		:List[str]       							=				generate_first_solution(
           args.File				,				a_)

       lowercase							,  lowercase		:Union[str, Any]       							=				tabu_search(
           a_				,				a_				,				a_				,				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())

