# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: 'Python 3.9.4 64-bit (''solenv'': conda)'
#     name: python3
# ---

# %load_ext autoreload
# %autoreload 2


from TSP_utils import TSP_solver, TSP_plotter, TSP_generator, TSP_loader
import numpy as np
import networkx as nx
import tqdm
import tsplib95
import time

loader = TSP_loader()
solver = TSP_solver()
generator = TSP_generator(g_type='tsp_2d', num_min=50, num_max=50)

# + tags=["outputPrepend"]
solver.add_lengths_and_sols(data_dir='test_sets/tsp_min-n=100_max-n=200_num-graph=1000_type=random', scale_factor=1000000)
# -

solver.del_tmp_files()

path = 'TSPLIB samples/kroA100.tsp'
# path = 'TSPLIB samples/kroD00.tsp'
# path = 'TSPLIB samples/kroC100.tsp'
# path = 'TSPLIB samples/ch150.tsp'
path = 'TSPLIB samples/ch130.tsp'
# path = 'TSPLIB samples/berlin52.tsp'
graph = loader.load_tsp_as_nx(file_path=path, scale_factor=1)

graph = generator.gen_graph()
solver.calc_opt_tour_from_nx(graph, scale=5)[0]

solver.calc_opt_tour_from_nx(graph, scale=8)[0]

solver.calc_opt_tour_from_file(path)[0]

generator = TSP_generator(g_type='tsp_2d', num_min=50, num_max=50)
solver = TSP_solver()

# + tags=["outputPrepend"]
num_samples = 10000
# graph_list = generator.gen_graphs(num_samples)
# generator.save_nx_as_tsp(graph_list=graph_list, start_index=0, save_path=f'test_sets/synthetic_n_50_{num_samples}', 
#                          scale=6, init_pos='0,1', goal_pos='-0.5,0.5')
solver.add_lengths_and_sols(data_dir=f'training_sets/synthetic_n_50_{num_samples}', scale_factor=1000000)

# + tags=[]
graph, cparam, iter = generator.calc_cparam_problem(desired_cparam=0.80, delta=0.005)

# + tags=[]
import gc
save_interval = 10
delta = 0.005
num_samples = 10000
data_root = 'training_sets/'
for desired_cparam in [0.85]:#np.arange(0.85,0.77,0.01): 
    folder = '{}synthetic_n_50_cparam_{}_delta_{}_{}/'.format(data_root, desired_cparam, delta, num_samples)
    maximum = 0
    file_numbers = []
    try:
        fnames = os.listdir(folder)
        for fname in fnames:
            if '.tsp' in fname:
                file_numbers.append(int(fname.split('_')[-1].split('.')[0]))
        maximum = np.max(file_numbers) + 1
    except:
        pass
    print(maximum)
    if maximum == num_samples:
        continue
    start_num = maximum
    graph_list = []
    num = 0
    
    

    num = start_num
    while num in range(start_num, num_samples):
        graph, cparam, iter = generator.calc_cparam_problem(desired_cparam=desired_cparam, delta=delta, max_iter=200, verbose=0, 
                                                            pos='0,1')
        if np.abs(cparam - desired_cparam) > delta:
            continue
        else:
            num += 1
            graph_list.append(graph) 
            print("desired cparam: {}, number of calculated graphs: {}".format(desired_cparam, num))
        if num%save_interval == 0:
            generator.save_nx_as_tsp(graph_list=graph_list, start_index=num-save_interval, 
                                     save_path=folder, 
                                     scale=6, init_pos='0,1', goal_pos='-0.5,0.5')
            graph_list=[]
            gc.collect()
    solver.add_lengths_and_sols(data_dir=folder,  
                                scale_factor=1000000)

# + tags=["outputPrepend"]
import gc
save_interval = 10
delta = 0.005
num_samples = 10000
data_root = 'training_sets/'
desired_cparam = 0.85
folder = '{}synthetic_n_50_cparam_{}_delta_{}_{}/'.format(data_root, desired_cparam, delta, num_samples)
solver.add_lengths_and_sols(data_dir=folder, scale_factor=1000000)
# -

import re
data_dir = 'test_sets/synthetic_n_50_1000/'
atoi = lambda text : int(text) if text.isdigit() else text
natural_keys = lambda text : [atoi(c) for c in re.split('(\d+)', text)]
if data_dir[-1] != '/':
    data_dir = data_dir + '/'
fnames = os.listdir(data_dir)
fnames.sort(key=natural_keys)
cparam_list = []
for fname in fnames:
    if not '.tsp' in fname or '.sol' in fname:
        continue
    cparam, sol_time= solver.calc_control_param_from_file(data_dir+fname)
    cparam_list.append(cparam)
    print(cparam)
    print(fname)


plt.style.use('seaborn-paper')
fig, ax = plt.subplots(1, 1, figsize=(5, 4), sharex=True, sharey=True)
ax.boxplot(cparam_list, meanline=True)
ax.set_xlabel('50 nodes, random cparam')
ax.tick_params(left=True, bottom=True, labelleft=True, labelbottom=True)
ax.set_ylabel('cparam')
# ax.set_title(title)
plt.tight_layout()
plt.savefig('cparam_boxplot.png', dpi=400)
plt.show()

# +

graph_list = generator.gen_graphs()
generator.save_nx_as_tsp(graph_list=graph_list, start_index=0, save_path='test_sets/synthetic_n_50_1000', scale=6, init_pos='0,1', 
                         goal_pos='-0.5,0.5')
solver.add_lengths_and_sols(data_dir='test_sets/synthetic_n_50_1000', scale_factor=1000000)
# -



generator.save_nx_as_tsp(graph_list=graph_list, start_index=0, save_path='test_sets/synthetic_n_50_cparam_0.75_delta_0.005_1000')

generator.save_nx_as_tsp(graph_list=graph_list, save_path='test_sets/synthetic_n_50_cparam_0.75_delta_0.005_1000')

# + tags=["outputPrepend"]
for fname in os.listdir('test_sets/synthetic_n_50_cparam_0.75_delta_0.005_1000/'):
    print(solver.calc_control_param_from_file('test_sets/synthetic_n_50_cparam_0.75_delta_0.005_1000/'+fname, generated=True))
# -

solver.calc_opt_tour_from_nx(graph)[0] / np.sqrt(calc_square_area(graph) * graph.number_of_nodes())

plotter = TSP_plotter()
plotter.plot_nx_graph(graph, draw_edges=False)


# + tags=[]
def calc_avg_edge_weight(graph):
    num_edges = 0
    edge_weight_sum = 0
    for edge_data in graph.edges(data=True):
        edge_weight_sum += edge_data[2]['weight']
        num_edges += 1
    return edge_weight_sum / num_edges


# -

generator = TSP_generator(g_type='tsp_2d', num_min=20, num_max=20)





test_graph = test_g
solver.calc_opt_tour_from_nx(test_graph)[0] / (calc_avg_edge_weight(test_graph)*test_graph.number_of_nodes())

solver.calc_control_param_from_nx(graph=test_graph)

plotter = TSP_plotter()
plotter.plot_nx_graph(test_g)

plotter = TSP_plotter()
plotter.plot_nx_graph(best_g)

StarcoderdataJupyterScriptsDedupFiltered