


"""simple docstring"""



import warnings
from typing import Dict

import numpy as np

from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline


if is_tf_available():
 from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

if is_torch_available():
 from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING






def       lowerCamelCase					(a_						:Union[str, Any])     ->							List[Any]:
       return 1.0 / (1.0 + np.exp(-_outputs))






def       lowerCamelCase					(a_						:Tuple)     ->							Union[str, Any]:
       lowercase		:Optional[Any]       							=				np.max(_outputs				,				axis=-1				,				keepdims=a_)
       lowercase		:Union[str, Any]       							=				np.exp(_outputs - maxes)
       return shifted_exp / shifted_exp.sum(axis=-1				,				keepdims=a_)
class 					__magic_name__		(			__UpperCAmelCase     ):
       __A			:      Tuple        =   "sigmoid"
       __A			:      Optional[Any]        =   "softmax"
       __A			:      Any        =   "none"







@add_end_docstrings(
    __UpperCAmelCase			,						R"\n        return_all_scores (`bool`, *optional*, defaults to `False`):\n            Whether to return all prediction scores or just the one of the predicted class.\n        function_to_apply (`str`, *optional*, defaults to `\"default\"`):\n            The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:\n\n            - `\"default\"`: if the model has a single label, will apply the sigmoid function on the output. If the model\n              has several labels, will apply the softmax function on the output.\n            - `\"sigmoid\"`: Applies the sigmoid function on the output.\n            - `\"softmax\"`: Applies the softmax function on the output.\n            - `\"none\"`: Does not apply any function on the output.\n    "			,						)
class 					__magic_name__		(			__UpperCAmelCase     ):
       __A			:      str        =   False
       __A			:      Any        =   ClassificationFunction.NONE






       def __init__(   self  :    Optional[int]  ,     **snake_case__  :    Optional[Any]				):

              '''simple docstring'''






              super().__init__(**snake_case__				)

              self.check_model_type(
                  TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
                  if self.framework == '''tf'''
                  else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING				)






       def  __snake_case						(   self  :    Tuple  ,     snake_case__  :    str=None  ,     snake_case__  :    str=None  ,     snake_case__  :    Dict=""  ,     **snake_case__  :    int				):

              '''simple docstring'''






              lowercase		:Optional[int]       							=				tokenizer_kwargs

              lowercase		:str       							=				{}
              if hasattr(self.model.config  ,     '''return_all_scores'''				) and return_all_scores is None:
                     lowercase		:Optional[int]       							=				self.model.config.return_all_scores

              if isinstance(snake_case__  ,     snake_case__				) or top_k is None:
                     lowercase		:Tuple       							=				top_k
                     lowercase		:List[Any]       							=				False
              elif return_all_scores is not None:
                     warnings.warn(
                         '''`return_all_scores` is now deprecated,  if want a similar functionality use `top_k=None` instead of'''
                         ''' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.'''  ,     snake_case__  ,     )
                     if return_all_scores:
                            lowercase		:Dict       							=				None
                     else:
                            lowercase		:Any       							=				1

              if isinstance(snake_case__  ,     snake_case__				):
                     lowercase		:List[Any]       							=				ClassificationFunction[function_to_apply.upper()]

              if function_to_apply is not None:
                     lowercase		:int       							=				function_to_apply
              return preprocess_params, {}, postprocess_params






       def __call__(   self  :    List[Any]  ,     *snake_case__  :    List[str]  ,     **snake_case__  :    int				):

              '''simple docstring'''






              lowercase		:Tuple       							=				super().__call__(*snake_case__  ,     **snake_case__				)
              # TODO try and retrieve it in a nicer way from _sanitize_parameters.
              lowercase		:Optional[int]       							=				'''top_k''' not in kwargs
              if isinstance(args[0]  ,     snake_case__				) and _legacy:
                     # This pipeline is odd, and return a list when single item is run
                     return [result]
              else:
                     return result






       def  __snake_case						(   self  :    Union[str, Any]  ,     snake_case__  :    Optional[Any]  ,     **snake_case__  :    List[str]				):

              '''simple docstring'''






              lowercase		:str       							=				self.framework
              if isinstance(snake_case__  ,     snake_case__				):
                     return self.tokenizer(**snake_case__  ,     return_tensors=snake_case__  ,     **snake_case__				)
              elif isinstance(snake_case__  ,     snake_case__				) and len(snake_case__				) == 1 and isinstance(inputs[0]  ,     snake_case__				) and len(inputs[0]				) == 2:
                     # It used to be valid to use a list of list of list for text pairs, keeping this path for BC
                     return self.tokenizer(
                         text=inputs[0][0]  ,     text_pair=inputs[0][1]  ,     return_tensors=snake_case__  ,     **snake_case__				)
              elif isinstance(snake_case__  ,     snake_case__				):
                     # This is likely an invalid usage of the pipeline attempting to pass text pairs.
                     raise ValueError(
                         '''The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a'''
                         ''' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.'''				)
              return self.tokenizer(snake_case__  ,     return_tensors=snake_case__  ,     **snake_case__				)






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

              '''simple docstring'''






              return self.model(**snake_case__				)







       def  __snake_case						(   self  :    str  ,     snake_case__  :    List[Any]  ,     snake_case__  :    List[str]=None  ,     snake_case__  :    List[Any]=1  ,     snake_case__  :    List[str]=True				):

              '''simple docstring'''






              if function_to_apply is None:
                     if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1:
                            lowercase		:Union[str, Any]       							=				ClassificationFunction.SIGMOID
                     elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
                            lowercase		:Optional[int]       							=				ClassificationFunction.SOFTMAX
                     elif hasattr(self.model.config  ,     '''function_to_apply'''				) and function_to_apply is None:
                            lowercase		:List[Any]       							=				self.model.config.function_to_apply
                     else:
                            lowercase		:Tuple       							=				ClassificationFunction.NONE

              lowercase		:Any       							=				model_outputs['''logits'''][0]
              lowercase		:Optional[int]       							=				outputs.numpy()

              if function_to_apply == ClassificationFunction.SIGMOID:
                     lowercase		:int       							=				sigmoid(snake_case__				)
              elif function_to_apply == ClassificationFunction.SOFTMAX:
                     lowercase		:List[Any]       							=				softmax(snake_case__				)
              elif function_to_apply == ClassificationFunction.NONE:
                     lowercase		:str       							=				outputs
              else:
                     raise ValueError(f"""Unrecognized `function_to_apply` argument: {function_to_apply}"""				)

              if top_k == 1 and _legacy:
                     return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()}

              lowercase		:List[str]       							=				[
                  {'''label''': self.model.config.idalabel[i], '''score''': score.item()} for i, score in enumerate(snake_case__				)
              ]
              if not _legacy:
                     dict_scores.sort(key=lambda snake_case__				: x["score"]  ,     reverse=snake_case__				)
                     if top_k is not None:
                            lowercase		:Tuple       							=				dict_scores[:top_k]
              return dict_scores





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

