




'''simple docstring'''







import itertools
import random
import unittest

import numpy as np

from transformers import ASTFeatureExtractor
from transformers.testing_utils import require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


lowerCAmelCase_     						=				random.Random()

if is_torch_available():
    import torch







def 						_A      ( UpperCAmelCase      ,UpperCAmelCase=1.0      ,UpperCAmelCase=None      ,UpperCAmelCase=None						):






   '''simple docstring'''







   if rng is None:
      A__       =     global_rng

   A__       =     []
   for batch_idx in range(shape[0]						):
      values.append([]						)
      for _ in range(shape[1]						):
         values[-1].append(rng.random() * scale						)

   return values

class 	_snake_case(			unittest.TestCase      ):






 def __init__(self       :  Union[str, Any]    ,		a       :  Dict    ,		a       :  Optional[Any]=7    ,		a       :  str=4_00    ,		a       :  Tuple=20_00    ,		a       :  str=1    ,		a       :  Union[str, Any]=0.0    ,		a       :  List[str]=1_60_00    ,		a       :  Any=True    ,		a       :  Optional[int]=True    ,		)       ->   Optional[Any]:






    """simple docstring"""


    A__       =     parent
    A__       =     batch_size
    A__       =     min_seq_length
    A__       =     max_seq_length
    A__       =     (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
    A__       =     feature_size
    A__       =     padding_value
    A__       =     sampling_rate
    A__       =     return_attention_mask
    A__       =     do_normalize






 def 						_UpperCamelCase (self       :  Optional[Any]    )       ->   Union[str, Any]:






    """simple docstring"""


    return {
        "feature_size": self.feature_size,
        "padding_value": self.padding_value,
        "sampling_rate": self.sampling_rate,
        "return_attention_mask": self.return_attention_mask,
        "do_normalize": self.do_normalize,
    }






 def 						_UpperCamelCase (self       :  str    ,		a       :  Optional[int]=False    ,		a       :  str=False    )       ->   Optional[int]:






    """simple docstring"""


    def _flatten(a       :  Optional[Any]    ):
       return list(itertools.chain(*a    )    )

    if equal_length:
       A__       =     floats_list((self.batch_size, self.max_seq_length)    )
    else:
       # make sure that inputs increase in size
       A__       =     [
           _flatten(floats_list((x, self.feature_size)    )    )
           for x in range(self.min_seq_length    ,		self.max_seq_length    ,		self.seq_length_diff    )
       ]

    if numpify:
       A__       =     [np.asarray(a    ) for x in speech_inputs]

    return speech_inputs




@require_torch
@require_torchaudio
class 	_snake_case(			UpperCAmelCase       , unittest.TestCase      ):
 __snake_case:							Union[str, Any]						=					ASTFeatureExtractor






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






    """simple docstring"""


    A__       =     ASTFeatureExtractionTester(self    )






 def 						_UpperCamelCase (self       :  int    )       ->   Optional[int]:






    """simple docstring"""


    A__       =     self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()    )
    # create three inputs of length 800, 1000, and 1200
    A__       =     [floats_list((1, x)    )[0] for x in range(8_00    ,		14_00    ,		2_00    )]
    A__       =     [np.asarray(a    ) for speech_input in speech_inputs]

    # Test not batched input
    A__       =     feat_extract(speech_inputs[0]    ,		return_tensors='np'    ).input_values
    A__       =     feat_extract(np_speech_inputs[0]    ,		return_tensors='np'    ).input_values
    self.assertTrue(np.allclose(a    ,		a    ,		atol=1e-3    )    )

    # Test batched
    A__       =     feat_extract(a    ,		padding=a    ,		return_tensors='np'    ).input_values
    A__       =     feat_extract(a    ,		padding=a    ,		return_tensors='np'    ).input_values
    for enc_seq_a, enc_seq_a in zip(a    ,		a    ):
       self.assertTrue(np.allclose(a    ,		a    ,		atol=1e-3    )    )

    # Test 2-D numpy arrays are batched.
    A__       =     [floats_list((1, x)    )[0] for x in (8_00, 8_00, 8_00)]
    A__       =     np.asarray(a    )
    A__       =     feat_extract(a    ,		return_tensors='np'    ).input_values
    A__       =     feat_extract(a    ,		return_tensors='np'    ).input_values
    for enc_seq_a, enc_seq_a in zip(a    ,		a    ):
       self.assertTrue(np.allclose(a    ,		a    ,		atol=1e-3    )    )






 @require_torch
 def 						_UpperCamelCase (self       :  Optional[Any]    )       ->   List[str]:






    """simple docstring"""


    import torch

    A__       =     self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()    )
    A__       =     np.random.rand(1_00    ).astype(np.floataa    )
    A__       =     np_speech_inputs.tolist()

    for inputs in [py_speech_inputs, np_speech_inputs]:
       A__       =     feature_extractor.pad([{'input_values': inputs}]    ,		return_tensors='np'    )
       self.assertTrue(np_processed.input_values.dtype == np.floataa    )
       A__       =     feature_extractor.pad([{'input_values': inputs}]    ,		return_tensors='pt'    )
       self.assertTrue(pt_processed.input_values.dtype == torch.floataa    )






 def 						_UpperCamelCase (self       :  str    ,		a       :  List[Any]    )       ->   Any:






    """simple docstring"""


    from datasets import load_dataset

    A__       =     load_dataset('hf-internal-testing/librispeech_asr_dummy'    ,		'clean'    ,		split='validation'    )
    # automatic decoding with librispeech
    A__       =     ds.sort('id'    ).select(range(a    )    )[:num_samples]['audio']

    return [x["array"] for x in speech_samples]






 @require_torch
 def 						_UpperCamelCase (self       :  int    )       ->   Optional[int]:






    """simple docstring"""


    A__       =     torch.tensor(
        [-0.9894, -1.2776, -0.9066, -1.2776, -0.9349, -1.2609, -1.0386, -1.2776,
         -1.1561, -1.2776, -1.2052, -1.2723, -1.2190, -1.2132, -1.2776, -1.1133,
         -1.1953, -1.1343, -1.1584, -1.2203, -1.1770, -1.2474, -1.2381, -1.1936,
         -0.9270, -0.8317, -0.8049, -0.7706, -0.7565, -0.7869]    )
    # fmt: on

    A__       =     self._load_datasamples(1    )
    A__       =     ASTFeatureExtractor()
    A__       =     feature_extractor(a    ,		return_tensors='pt'    ).input_values
    self.assertEquals(input_values.shape    ,		(1, 10_24, 1_28)    )
    self.assertTrue(torch.allclose(input_values[0, 0, :30]    ,		a    ,		atol=1e-4    )    )








'''simple docstring'''







import argparse
import copy







def 						_A      ( UpperCAmelCase						):






   '''simple docstring'''







   A__       =     {}

   with open(UpperCAmelCase						) as f:
      for line in f:
         if line.split()[0] not in dict_of_neighbours:
            A__       =     []
            _list.append([line.split()[1], line.split()[2]]						)
            A__       =     _list
         else:
            dict_of_neighbours[line.split()[0]].append(
                [line.split()[1], line.split()[2]]						)
         if line.split()[1] not in dict_of_neighbours:
            A__       =     []
            _list.append([line.split()[0], line.split()[2]]						)
            A__       =     _list
         else:
            dict_of_neighbours[line.split()[1]].append(
                [line.split()[0], line.split()[2]]						)

   return dict_of_neighbours







def 						_A      ( UpperCAmelCase      ,UpperCAmelCase						):






   '''simple docstring'''







   with open(UpperCAmelCase						) as f:
      A__       =     f.read(1						)
   A__       =     start_node

   A__       =     []

   A__       =     start_node

   A__       =     0
   while visiting not in first_solution:
      A__       =     10000
      for k in dict_of_neighbours[visiting]:
         if int(k[1]						) < int(UpperCAmelCase						) and k[0] not in first_solution:
            A__       =     k[1]
            A__       =     k[0]

      first_solution.append(UpperCAmelCase						)
      A__       =     distance_of_first_solution + int(UpperCAmelCase						)
      A__       =     best_node

   first_solution.append(UpperCAmelCase						)

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

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







def 						_A      ( UpperCAmelCase      ,UpperCAmelCase						):






   '''simple docstring'''







   A__       =     []

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

         A__       =     copy.deepcopy(UpperCAmelCase						)
         A__       =     kn
         A__       =     n

         A__       =     0

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

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

   A__       =     len(neighborhood_of_solution[0]						) - 1

   neighborhood_of_solution.sort(key=lambda UpperCAmelCase						: x[index_of_last_item_in_the_list]						)
   return neighborhood_of_solution







def 						_A      ( UpperCAmelCase      ,UpperCAmelCase      ,UpperCAmelCase      ,UpperCAmelCase      ,UpperCAmelCase						):






   '''simple docstring'''







   A__       =     1
   A__       =     first_solution
   A__       =     []
   A__       =     distance_of_first_solution
   A__       =     solution

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

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

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

      A__       =     count + 1

   return best_solution_ever, best_cost







def 						_A      ( UpperCAmelCase=None						):






   '''simple docstring'''







   A__       =     generate_neighbours(args.File						)

   A__  ,			A__       =     generate_first_solution(
       args.File      ,UpperCAmelCase						)

   A__  ,			A__       =     tabu_search(
       UpperCAmelCase      ,UpperCAmelCase      ,UpperCAmelCase      ,args.Iterations      ,args.Size      ,)

   print(F"""Best solution: {best_sol}, with total distance: {best_cost}."""						)


if __name__ == "__main__":
    lowerCAmelCase_     						=				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())


