




import gc
import unittest

import numpy as np
import torch

from diffusers import DanceDiffusionPipeline, IPNDMScheduler, UNetaDModel
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps

from ..pipeline_params import UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS, UNCONDITIONAL_AUDIO_GENERATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()







class a (     __a       ,						unittest.TestCase  ):
						"""simple docstring"""

						UpperCamelCase_	:       Union[str, Any]       	=		DanceDiffusionPipeline
						UpperCamelCase_	:       Optional[int]       	=		UNCONDITIONAL_AUDIO_GENERATION_PARAMS
						UpperCamelCase_	:       Dict       	=		PipelineTesterMixin.required_optional_params - {
						    '''callback''',
						    '''latents''',
						    '''callback_steps''',
						    '''output_type''',
						    '''num_images_per_prompt''',
						}
						UpperCamelCase_	:       Any       	=		UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS
						UpperCamelCase_	:       List[Any]       	=		False
						UpperCamelCase_	:       List[Any]       	=		False






						def     UpperCAmelCase_      ( self :     Any				)    ->						Any:
													"""simple docstring"""


													torch.manual_seed(0				)
													__lowercase      =    UNetaDModel(
													    block_out_channels=(32, 32, 64)				,							extra_in_channels=16				,							sample_size=512				,							sample_rate=16_000				,							in_channels=2				,							out_channels=2				,							flip_sin_to_cos=snake_case__				,							use_timestep_embedding=snake_case__				,							time_embedding_type='''fourier'''				,							mid_block_type='''UNetMidBlock1D'''				,							down_block_types=('''DownBlock1DNoSkip''', '''DownBlock1D''', '''AttnDownBlock1D''')				,							up_block_types=('''AttnUpBlock1D''', '''UpBlock1D''', '''UpBlock1DNoSkip''')				,							)
													__lowercase      =    IPNDMScheduler()

													__lowercase      =    {
													    '''unet''': unet,
													    '''scheduler''': scheduler,
													}
													return components






						def     UpperCAmelCase_      ( self :     List[Any]				,							lowerCamelCase__ :     Tuple				,							lowerCamelCase__ :     Optional[Any]=0				)    ->						List[Any]:
													"""simple docstring"""


													if str(snake_case__				).startswith('''mps'''				):
																				__lowercase      =    torch.manual_seed(snake_case__				)
													else:
																				__lowercase      =    torch.Generator(device=snake_case__				).manual_seed(snake_case__				)
													__lowercase      =    {
													    '''batch_size''': 1,
													    '''generator''': generator,
													    '''num_inference_steps''': 4,
													}
													return inputs






						def     UpperCAmelCase_      ( self :     Tuple				)    ->						List[str]:
													"""simple docstring"""


													__lowercase      =    '''cpu'''  # ensure determinism for the device-dependent torch.Generator
													__lowercase      =    self.get_dummy_components()
													__lowercase      =    DanceDiffusionPipeline(**snake_case__				)
													__lowercase      =    pipe.to(snake_case__				)
													pipe.set_progress_bar_config(disable=snake_case__				)

													__lowercase      =    self.get_dummy_inputs(snake_case__				)
													__lowercase      =    pipe(**snake_case__				)
													__lowercase      =    output.audios

													__lowercase      =    audio[0, -3:, -3:]

													assert audio.shape == (1, 2, components["unet"].sample_size)
													__lowercase      =    np.array([-0.7_2_6_5, 1.0_0_0_0, -0.8_3_8_8, 0.1_1_7_5, 0.9_4_9_8, -1.0_0_0_0]				)
													assert np.abs(audio_slice.flatten() - expected_slice				).max() < 1e-2






						@skip_mps
						def     UpperCAmelCase_      ( self :     List[str]				)    ->						Optional[Any]:
													"""simple docstring"""


													return super().test_save_load_local()






						@skip_mps
						def     UpperCAmelCase_      ( self :     str				)    ->						Tuple:
													"""simple docstring"""


													return super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3				)






						@skip_mps
						def     UpperCAmelCase_      ( self :     Optional[int]				)    ->						Union[str, Any]:
													"""simple docstring"""


													return super().test_save_load_optional_components()






						@skip_mps
						def     UpperCAmelCase_      ( self :     Optional[Any]				)    ->						Union[str, Any]:
													"""simple docstring"""


													return super().test_attention_slicing_forward_pass()






						def     UpperCAmelCase_      ( self :     Optional[Any]				)    ->						str:
													"""simple docstring"""


													super().test_inference_batch_single_identical(expected_max_diff=3e-3				)







@slow
@require_torch_gpu
class a (     unittest.TestCase  ):
						"""simple docstring"""

						def     UpperCAmelCase_      ( self :     str				)    ->						Dict:
													"""simple docstring"""


													super().tearDown()
													gc.collect()
													torch.cuda.empty_cache()






						def     UpperCAmelCase_      ( self :     int				)    ->						str:
													"""simple docstring"""


													__lowercase      =    torch_device

													__lowercase      =    DanceDiffusionPipeline.from_pretrained('''harmonai/maestro-150k'''				)
													__lowercase      =    pipe.to(snake_case__				)
													pipe.set_progress_bar_config(disable=snake_case__				)

													__lowercase      =    torch.manual_seed(0				)
													__lowercase      =    pipe(generator=snake_case__				,							num_inference_steps=100				,							audio_length_in_s=4.0_9_6				)
													__lowercase      =    output.audios

													__lowercase      =    audio[0, -3:, -3:]

													assert audio.shape == (1, 2, pipe.unet.sample_size)
													__lowercase      =    np.array([-0.0_1_9_2, -0.0_2_3_1, -0.0_3_1_8, -0.0_0_5_9, 0.0_0_0_2, -0.0_0_2_0]				)

													assert np.abs(audio_slice.flatten() - expected_slice				).max() < 1e-2






						def     UpperCAmelCase_      ( self :     int				)    ->						Optional[int]:
													"""simple docstring"""


													__lowercase      =    torch_device

													__lowercase      =    DanceDiffusionPipeline.from_pretrained('''harmonai/maestro-150k'''				,							torch_dtype=torch.floataa				)
													__lowercase      =    pipe.to(snake_case__				)
													pipe.set_progress_bar_config(disable=snake_case__				)

													__lowercase      =    torch.manual_seed(0				)
													__lowercase      =    pipe(generator=snake_case__				,							num_inference_steps=100				,							audio_length_in_s=4.0_9_6				)
													__lowercase      =    output.audios

													__lowercase      =    audio[0, -3:, -3:]

													assert audio.shape == (1, 2, pipe.unet.sample_size)
													__lowercase      =    np.array([-0.0_3_6_7, -0.0_4_8_8, -0.0_7_7_1, -0.0_5_2_5, -0.0_4_4_4, -0.0_3_4_1]				)

													assert np.abs(audio_slice.flatten() - expected_slice				).max() < 1e-2












import argparse
import copy







def 		_A(       UpperCamelCase__							:			Union[str, Any]				)    -> Tuple:
							'''simple docstring'''


							__lowercase      =    {}

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

							return dict_of_neighbours







def 		_A(       UpperCamelCase__							:			Optional[int]				,       UpperCamelCase__							:			Optional[Any]				)    -> Dict:
							'''simple docstring'''


							with open(UpperCamelCase__				) as f:
														__lowercase      =    f.read(1				)
							__lowercase      =    start_node

							__lowercase      =    []

							__lowercase      =    start_node

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

														first_solution.append(UpperCamelCase__				)
														__lowercase      =    distance_of_first_solution + int(UpperCamelCase__				)
														__lowercase      =    best_node

							first_solution.append(UpperCamelCase__				)

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

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







def 		_A(       UpperCamelCase__							:			int				,       UpperCamelCase__							:			Optional[Any]				)    -> Optional[int]:
							'''simple docstring'''


							__lowercase      =    []

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

																					__lowercase      =    copy.deepcopy(UpperCamelCase__				)
																					__lowercase      =    kn
																					__lowercase      =    n

																					__lowercase      =    0

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

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

							__lowercase      =    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__							:			List[Any]				,       UpperCamelCase__							:			List[str]				,       UpperCamelCase__							:			Optional[int]				,       UpperCamelCase__							:			Optional[int]				,       UpperCamelCase__							:			Optional[int]				)    -> List[str]:
							'''simple docstring'''


							__lowercase      =    1
							__lowercase      =    first_solution
							__lowercase      =    []
							__lowercase      =    distance_of_first_solution
							__lowercase      =    solution

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

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

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

														__lowercase      =    count + 1

							return best_solution_ever, best_cost







def 		_A(       UpperCamelCase__							:			List[Any]=None				)    -> int:
							'''simple docstring'''


							__lowercase      =    generate_neighbours(args.File				)

							__lowercase     ,     __lowercase      =    generate_first_solution(
							    args.File				,       UpperCamelCase__				)

							__lowercase     ,     __lowercase      =    tabu_search(
							    UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       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())






