import argparse
import copy



def lowerCamelCase  (       SCREAMING_SNAKE_CASE     ):
    '''simple docstring'''







    __UpperCamelCase					:Dict        =		{}

    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					:Tuple        =		_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					:List[Any]        =		[]
                _list.append([line.split()[0], line.split()[2]]     )
                __UpperCamelCase					:List[Any]        =		_list
            else:
                dict_of_neighbours[line.split()[1]].append(
                    [line.split()[0], line.split()[2]]     )

    return dict_of_neighbours



def lowerCamelCase  (       SCREAMING_SNAKE_CASE  ,      SCREAMING_SNAKE_CASE     ):
    '''simple docstring'''







    with open(SCREAMING_SNAKE_CASE     ) as f:
        __UpperCamelCase					:Union[str, Any]        =		f.read(1     )
    __UpperCamelCase					:Optional[Any]        =		start_node

    __UpperCamelCase					:Dict        =		[]

    __UpperCamelCase					:List[str]        =		start_node

    __UpperCamelCase					:Any        =		0
    while visiting not in first_solution:
        __UpperCamelCase					:Tuple        =		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					:Optional[Any]        =		k[1]
                __UpperCamelCase					:str        =		k[0]

        first_solution.append(SCREAMING_SNAKE_CASE     )
        __UpperCamelCase					:Any        =		distance_of_first_solution + int(SCREAMING_SNAKE_CASE     )
        __UpperCamelCase					:Tuple        =		best_node

    first_solution.append(SCREAMING_SNAKE_CASE     )

    __UpperCamelCase					:Dict        =		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 lowerCamelCase  (       SCREAMING_SNAKE_CASE  ,      SCREAMING_SNAKE_CASE     ):
    '''simple docstring'''







    __UpperCamelCase					:Optional[Any]        =		[]

    for n in solution[1:-1]:
        __UpperCamelCase					:Optional[Any]        =		solution.index(SCREAMING_SNAKE_CASE     )
        for kn in solution[1:-1]:
            __UpperCamelCase					:Union[str, Any]        =		solution.index(SCREAMING_SNAKE_CASE     )
            if n == kn:
                continue

            __UpperCamelCase					:Tuple        =		copy.deepcopy(SCREAMING_SNAKE_CASE     )
            __UpperCamelCase					:List[str]        =		kn
            __UpperCamelCase					:Dict        =		n

            __UpperCamelCase					:Optional[Any]        =		0

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

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

    __UpperCamelCase					:Tuple        =		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 lowerCamelCase  (       SCREAMING_SNAKE_CASE  ,      SCREAMING_SNAKE_CASE  ,      SCREAMING_SNAKE_CASE  ,      SCREAMING_SNAKE_CASE  ,      SCREAMING_SNAKE_CASE     ):
    '''simple docstring'''







    __UpperCamelCase					:Union[str, Any]        =		1
    __UpperCamelCase					:Union[str, Any]        =		first_solution
    __UpperCamelCase					:Any        =		[]
    __UpperCamelCase					:List[str]        =		distance_of_first_solution
    __UpperCamelCase					:Any        =		solution

    while count <= iters:
        __UpperCamelCase					:List[Any]        =		find_neighborhood(SCREAMING_SNAKE_CASE  ,      SCREAMING_SNAKE_CASE     )
        __UpperCamelCase					:str        =		0
        __UpperCamelCase					:Tuple        =		neighborhood[index_of_best_solution]
        __UpperCamelCase					:List[str]        =		len(SCREAMING_SNAKE_CASE     ) - 1

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

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

        __UpperCamelCase					:Tuple        =		count + 1

    return best_solution_ever, best_cost



def lowerCamelCase  (       SCREAMING_SNAKE_CASE=None     ):
    '''simple docstring'''







    __UpperCamelCase					:Union[str, Any]        =		generate_neighbours(args.File     )

    __UpperCamelCase  ,	__UpperCamelCase					:Any        =		generate_first_solution(
        args.File  ,      SCREAMING_SNAKE_CASE     )

    __UpperCamelCase  ,	__UpperCamelCase					:List[Any]        =		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__":
    __lowercase										= 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 json
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
from transformers import (
    CONFIG_MAPPING,
    IMAGE_PROCESSOR_MAPPING,
    AutoConfig,
    AutoImageProcessor,
    CLIPConfig,
    CLIPImageProcessor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER


sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils'''))

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_image_processing import CustomImageProcessor  # noqa E402


class      lowerCamelCase_					(       unittest.TestCase			):






    '''simple docstring'''






    def       UpperCamelCase__       (     self)	->     int:
        __UpperCamelCase					:str        =		0







    def       UpperCamelCase__       (     self)	->     Optional[Any]:
        __UpperCamelCase					:Dict        =		AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''')
        self.assertIsInstance(__lowercase			,			__lowercase)







    def       UpperCamelCase__       (     self)	->     Optional[int]:
        with tempfile.TemporaryDirectory() as tmpdirname:
            __UpperCamelCase					:int        =		Path(__lowercase) / '''preprocessor_config.json'''
            __UpperCamelCase					:Dict        =		Path(__lowercase) / '''config.json'''
            json.dump(
                {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''}			,			open(__lowercase			,			'''w''')			,			)
            json.dump({'''model_type''': '''clip'''}			,			open(__lowercase			,			'''w'''))

            __UpperCamelCase					:Union[str, Any]        =		AutoImageProcessor.from_pretrained(__lowercase)
            self.assertIsInstance(__lowercase			,			__lowercase)







    def       UpperCamelCase__       (     self)	->     Union[str, Any]:
        # Ensure we can load the image processor from the feature extractor config
        with tempfile.TemporaryDirectory() as tmpdirname:
            __UpperCamelCase					:str        =		Path(__lowercase) / '''preprocessor_config.json'''
            __UpperCamelCase					:Union[str, Any]        =		Path(__lowercase) / '''config.json'''
            json.dump(
                {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''}			,			open(__lowercase			,			'''w''')			,			)
            json.dump({'''model_type''': '''clip'''}			,			open(__lowercase			,			'''w'''))

            __UpperCamelCase					:Dict        =		AutoImageProcessor.from_pretrained(__lowercase)
            self.assertIsInstance(__lowercase			,			__lowercase)







    def       UpperCamelCase__       (     self)	->     Optional[int]:
        with tempfile.TemporaryDirectory() as tmpdirname:
            __UpperCamelCase					:int        =		CLIPConfig()

            # Create a dummy config file with image_proceesor_type
            __UpperCamelCase					:Tuple        =		Path(__lowercase) / '''preprocessor_config.json'''
            __UpperCamelCase					:Optional[Any]        =		Path(__lowercase) / '''config.json'''
            json.dump(
                {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''}			,			open(__lowercase			,			'''w''')			,			)
            json.dump({'''model_type''': '''clip'''}			,			open(__lowercase			,			'''w'''))

            # remove image_processor_type to make sure config.json alone is enough to load image processor locally
            __UpperCamelCase					:Optional[Any]        =		AutoImageProcessor.from_pretrained(__lowercase).to_dict()

            config_dict.pop('''image_processor_type''')
            __UpperCamelCase					:List[str]        =		CLIPImageProcessor(**__lowercase)

            # save in new folder
            model_config.save_pretrained(__lowercase)
            config.save_pretrained(__lowercase)

            __UpperCamelCase					:Dict        =		AutoImageProcessor.from_pretrained(__lowercase)

            # make sure private variable is not incorrectly saved
            __UpperCamelCase					:Union[str, Any]        =		json.loads(config.to_json_string())
            self.assertTrue('''_processor_class''' not in dict_as_saved)

        self.assertIsInstance(__lowercase			,			__lowercase)







    def       UpperCamelCase__       (     self)	->     List[str]:
        with tempfile.TemporaryDirectory() as tmpdirname:
            __UpperCamelCase					:Tuple        =		Path(__lowercase) / '''preprocessor_config.json'''
            json.dump(
                {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''}			,			open(__lowercase			,			'''w''')			,			)

            __UpperCamelCase					:List[str]        =		AutoImageProcessor.from_pretrained(__lowercase)
            self.assertIsInstance(__lowercase			,			__lowercase)







    def       UpperCamelCase__       (     self)	->     Optional[int]:
        with self.assertRaisesRegex(
            __lowercase			,			'''clip-base is not a local folder and is not a valid model identifier'''):
            __UpperCamelCase					:Optional[Any]        =		AutoImageProcessor.from_pretrained('''clip-base''')







    def       UpperCamelCase__       (     self)	->     List[Any]:
        with self.assertRaisesRegex(
            __lowercase			,			r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'''):
            __UpperCamelCase					:str        =		AutoImageProcessor.from_pretrained(__lowercase			,			revision='''aaaaaa''')







    def       UpperCamelCase__       (     self)	->     List[str]:
        with self.assertRaisesRegex(
            __lowercase			,			'''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.'''			,			):
            __UpperCamelCase					:Optional[Any]        =		AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''')







    def       UpperCamelCase__       (     self)	->     str:
        # If remote code is not set, we will time out when asking whether to load the model.
        with self.assertRaises(__lowercase):
            __UpperCamelCase					:Dict        =		AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''')
        # If remote code is disabled, we can't load this config.
        with self.assertRaises(__lowercase):
            __UpperCamelCase					:List[Any]        =		AutoImageProcessor.from_pretrained(
                '''hf-internal-testing/test_dynamic_image_processor'''			,			trust_remote_code=__lowercase)

        __UpperCamelCase					:Optional[Any]        =		AutoImageProcessor.from_pretrained(
            '''hf-internal-testing/test_dynamic_image_processor'''			,			trust_remote_code=__lowercase)
        self.assertEqual(image_processor.__class__.__name__			,			'''NewImageProcessor''')

        # Test image processor can be reloaded.
        with tempfile.TemporaryDirectory() as tmp_dir:
            image_processor.save_pretrained(__lowercase)
            __UpperCamelCase					:List[Any]        =		AutoImageProcessor.from_pretrained(__lowercase			,			trust_remote_code=__lowercase)
        self.assertEqual(reloaded_image_processor.__class__.__name__			,			'''NewImageProcessor''')







    def       UpperCamelCase__       (     self)	->     Optional[Any]:
        try:
            AutoConfig.register('''custom'''			,			__lowercase)
            AutoImageProcessor.register(__lowercase			,			__lowercase)
            # Trying to register something existing in the Transformers library will raise an error
            with self.assertRaises(__lowercase):
                AutoImageProcessor.register(__lowercase			,			__lowercase)

            with tempfile.TemporaryDirectory() as tmpdirname:
                __UpperCamelCase					:int        =		Path(__lowercase) / '''preprocessor_config.json'''
                __UpperCamelCase					:List[str]        =		Path(__lowercase) / '''config.json'''
                json.dump(
                    {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''}			,			open(__lowercase			,			'''w''')			,			)
                json.dump({'''model_type''': '''clip'''}			,			open(__lowercase			,			'''w'''))

                __UpperCamelCase					:int        =		CustomImageProcessor.from_pretrained(__lowercase)

            # Now that the config is registered, it can be used as any other config with the auto-API
            with tempfile.TemporaryDirectory() as tmp_dir:
                image_processor.save_pretrained(__lowercase)
                __UpperCamelCase					:int        =		AutoImageProcessor.from_pretrained(__lowercase)
                self.assertIsInstance(__lowercase			,			__lowercase)

        finally:
            if "custom" in CONFIG_MAPPING._extra_content:
                del CONFIG_MAPPING._extra_content["custom"]
            if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
                del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]







    def       UpperCamelCase__       (     self)	->     List[Any]:


        class      lowerCamelCase_					(       UpperCAmelCase_			):






            '''simple docstring'''






            a__     :						List[str]      =				True

        try:
            AutoConfig.register('''custom'''			,			__lowercase)
            AutoImageProcessor.register(__lowercase			,			__lowercase)
            # If remote code is not set, the default is to use local
            __UpperCamelCase					:str        =		AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''')
            self.assertEqual(image_processor.__class__.__name__			,			'''NewImageProcessor''')
            self.assertTrue(image_processor.is_local)

            # If remote code is disabled, we load the local one.
            __UpperCamelCase					:Optional[Any]        =		AutoImageProcessor.from_pretrained(
                '''hf-internal-testing/test_dynamic_image_processor'''			,			trust_remote_code=__lowercase)
            self.assertEqual(image_processor.__class__.__name__			,			'''NewImageProcessor''')
            self.assertTrue(image_processor.is_local)

            # If remote is enabled, we load from the Hub
            __UpperCamelCase					:List[str]        =		AutoImageProcessor.from_pretrained(
                '''hf-internal-testing/test_dynamic_image_processor'''			,			trust_remote_code=__lowercase)
            self.assertEqual(image_processor.__class__.__name__			,			'''NewImageProcessor''')
            self.assertTrue(not hasattr(__lowercase			,			'''is_local'''))

        finally:
            if "custom" in CONFIG_MAPPING._extra_content:
                del CONFIG_MAPPING._extra_content["custom"]
            if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
                del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]





