





import argparse
import copy



def        __lowercase       (				_SCREAMING_SNAKE_CASE     ):


      '''simple docstring'''


      SCREAMING_SNAKE_CASE		=						{}

      with open(_SCREAMING_SNAKE_CASE     ) as f:
            for line in f:
                  if line.split()[0] not in dict_of_neighbours:
                        SCREAMING_SNAKE_CASE		=						[]
                        _list.append([line.split()[1], line.split()[2]]     )
                        SCREAMING_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:
                        SCREAMING_SNAKE_CASE		=						[]
                        _list.append([line.split()[0], line.split()[2]]     )
                        SCREAMING_SNAKE_CASE		=						_list
                  else:
                        dict_of_neighbours[line.split()[1]].append(
                            [line.split()[0], line.split()[2]]     )

      return dict_of_neighbours



def        __lowercase       (				_SCREAMING_SNAKE_CASE			,						_SCREAMING_SNAKE_CASE     ):


      '''simple docstring'''


      with open(_SCREAMING_SNAKE_CASE     ) as f:
            SCREAMING_SNAKE_CASE		=						f.read(1     )
      SCREAMING_SNAKE_CASE		=						start_node

      SCREAMING_SNAKE_CASE		=						[]

      SCREAMING_SNAKE_CASE		=						start_node

      SCREAMING_SNAKE_CASE		=						0
      while visiting not in first_solution:
            SCREAMING_SNAKE_CASE		=						1_00_00
            for k in dict_of_neighbours[visiting]:
                  if int(k[1]     ) < int(_SCREAMING_SNAKE_CASE     ) and k[0] not in first_solution:
                        SCREAMING_SNAKE_CASE		=						k[1]
                        SCREAMING_SNAKE_CASE		=						k[0]

            first_solution.append(_SCREAMING_SNAKE_CASE     )
            SCREAMING_SNAKE_CASE		=						distance_of_first_solution + int(_SCREAMING_SNAKE_CASE     )
            SCREAMING_SNAKE_CASE		=						best_node

      first_solution.append(_SCREAMING_SNAKE_CASE     )

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

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



def        __lowercase       (				_SCREAMING_SNAKE_CASE			,						_SCREAMING_SNAKE_CASE     ):


      '''simple docstring'''


      SCREAMING_SNAKE_CASE		=						[]

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

                  SCREAMING_SNAKE_CASE		=						copy.deepcopy(_SCREAMING_SNAKE_CASE     )
                  SCREAMING_SNAKE_CASE		=						kn
                  SCREAMING_SNAKE_CASE		=						n

                  SCREAMING_SNAKE_CASE		=						0

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

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

      SCREAMING_SNAKE_CASE		=						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        __lowercase       (				_SCREAMING_SNAKE_CASE			,						_SCREAMING_SNAKE_CASE			,						_SCREAMING_SNAKE_CASE			,						_SCREAMING_SNAKE_CASE			,						_SCREAMING_SNAKE_CASE     ):


      '''simple docstring'''


      SCREAMING_SNAKE_CASE		=						1
      SCREAMING_SNAKE_CASE		=						first_solution
      SCREAMING_SNAKE_CASE		=						[]
      SCREAMING_SNAKE_CASE		=						distance_of_first_solution
      SCREAMING_SNAKE_CASE		=						solution

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

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

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

            SCREAMING_SNAKE_CASE		=						count + 1

      return best_solution_ever, best_cost



def        __lowercase       (				_SCREAMING_SNAKE_CASE=None     ):


      '''simple docstring'''


      SCREAMING_SNAKE_CASE		=						generate_neighbours(args.File     )

      SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE		=						generate_first_solution(
          args.File			,						_SCREAMING_SNAKE_CASE     )

      SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE		=						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__":
      SCREAMING_SNAKE_CASE_						       =	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())









import logging
import random

import ray

from transformers import RagConfig, RagRetriever, RagTokenizer
from transformers.models.rag.retrieval_rag import CustomHFIndex


SCREAMING_SNAKE_CASE_						       =	logging.getLogger(__name__)

class 		UpperCamelCase__			:



     '''simple docstring'''

     def __init__(							self						:   str	)					->		List[str]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						False






     def     SCREAMING_SNAKE_CASE__  (							self						:   Any						,lowerCamelCase__						:   int						,lowerCamelCase__						:   Dict						,lowerCamelCase__						:   List[Any]						,lowerCamelCase__						:   Tuple	)					->		Optional[Any]:




           '''simple docstring'''


           if not self.initialized:
                 SCREAMING_SNAKE_CASE		=						RagRetriever(
                     lowerCamelCase__						,question_encoder_tokenizer=lowerCamelCase__						,generator_tokenizer=lowerCamelCase__						,index=lowerCamelCase__						,init_retrieval=lowerCamelCase__						,)
                 SCREAMING_SNAKE_CASE		=						True






     def     SCREAMING_SNAKE_CASE__  (							self						:   Dict	)					->		Any:




           '''simple docstring'''


           self.retriever.index.init_index()






     def     SCREAMING_SNAKE_CASE__  (							self						:   Any						,lowerCamelCase__						:   List[Any]						,lowerCamelCase__						:   List[str]	)					->		List[Any]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE		=						self.retriever._main_retrieve(lowerCamelCase__						,lowerCamelCase__	)
           return doc_ids, retrieved_doc_embeds

class 		UpperCamelCase__			(				lowerCAmelCase_       ):



     '''simple docstring'''

     def __init__(							self						:   int						,lowerCamelCase__						:   Dict						,lowerCamelCase__						:   Optional[Any]						,lowerCamelCase__						:   List[str]						,lowerCamelCase__						:   Optional[Any]						,lowerCamelCase__						:   Dict=None	)					->		Any:




           '''simple docstring'''


           if index is not None and index.is_initialized() and len(lowerCamelCase__	) > 0:
                 raise ValueError(
                     """When using Ray for distributed fine-tuning, """
                     """you'll need to provide the paths instead, """
                     """as the dataset and the index are loaded """
                     """separately. More info in examples/rag/use_own_knowledge_dataset.py """	)
           super().__init__(
               lowerCamelCase__						,question_encoder_tokenizer=lowerCamelCase__						,generator_tokenizer=lowerCamelCase__						,index=lowerCamelCase__						,init_retrieval=lowerCamelCase__						,)
           SCREAMING_SNAKE_CASE		=						retrieval_workers
           if len(self.retrieval_workers	) > 0:
                 ray.get(
                     [
                         worker.create_rag_retriever.remote(lowerCamelCase__						,lowerCamelCase__						,lowerCamelCase__						,lowerCamelCase__	)
                         for worker in self.retrieval_workers
                     ]	)






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




           '''simple docstring'''


           logger.info("""initializing retrieval"""	)

           if len(self.retrieval_workers	) > 0:
                 ray.get([worker.init_retrieval.remote() for worker in self.retrieval_workers]	)
           else:
                 # Non-distributed training. Load index into this same process.
                 self.index.init_index()






     def     SCREAMING_SNAKE_CASE__  (							self						:   Any						,lowerCamelCase__						:   Any						,lowerCamelCase__						:   int	)					->		Dict:




           '''simple docstring'''


           if len(self.retrieval_workers	) > 0:
                 # Select a random retrieval actor.
                 SCREAMING_SNAKE_CASE		=						self.retrieval_workers[random.randint(0						,len(self.retrieval_workers	) - 1	)]
                 SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE		=						ray.get(random_worker.retrieve.remote(lowerCamelCase__						,lowerCamelCase__	)	)
           else:
                 SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE		=						self._main_retrieve(lowerCamelCase__						,lowerCamelCase__	)
           return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(lowerCamelCase__	)






     @classmethod
     def     SCREAMING_SNAKE_CASE__  (							cls						:   Optional[Any]						,lowerCamelCase__						:   List[Any]						,lowerCamelCase__						:   Union[str, Any]=None						,**lowerCamelCase__						:   Optional[Any]	)					->		Any:




           '''simple docstring'''


           return super(lowerCamelCase__						,cls	).get_tokenizers(lowerCamelCase__						,lowerCamelCase__						,**lowerCamelCase__	)






     @classmethod
     def     SCREAMING_SNAKE_CASE__  (							cls						:   Any						,lowerCamelCase__						:   Tuple						,lowerCamelCase__						:   List[Any]						,lowerCamelCase__						:   List[Any]=None						,**lowerCamelCase__						:   Any	)					->		Tuple:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						kwargs.pop("""config"""						,lowerCamelCase__	) or RagConfig.from_pretrained(lowerCamelCase__						,**lowerCamelCase__	)
           SCREAMING_SNAKE_CASE		=						RagTokenizer.from_pretrained(lowerCamelCase__						,config=lowerCamelCase__	)
           SCREAMING_SNAKE_CASE		=						rag_tokenizer.question_encoder
           SCREAMING_SNAKE_CASE		=						rag_tokenizer.generator
           if indexed_dataset is not None:
                 SCREAMING_SNAKE_CASE		=						"""custom"""
                 SCREAMING_SNAKE_CASE		=						CustomHFIndex(config.retrieval_vector_size						,lowerCamelCase__	)
           else:
                 SCREAMING_SNAKE_CASE		=						cls._build_index(lowerCamelCase__	)
           return cls(
               lowerCamelCase__						,question_encoder_tokenizer=lowerCamelCase__						,generator_tokenizer=lowerCamelCase__						,retrieval_workers=lowerCamelCase__						,index=lowerCamelCase__						,)


