<jupyter_start><jupyter_text>Simulated Annealing - TSP Example Case- <NAME> | June. 2020- https://github.com/nathanrooy/simulated-annealing  Import dependencies<jupyter_code>from simulated_annealing import sa
from landscapes.single_objective import tsp

import pandas as pd
import osmnx as ox
import networkx as nx<jupyter_output><empty_output><jupyter_text>TSP - Breweries (network distance)<jupyter_code># load distance matrix as dict
dist_dict = {}
with open('dist_table.csv','r') as csv_file:
    for i, row in enumerate(csv_file.readlines()):
        if i == 0: pass
        else:
            n1, n2, dist = row.split(',')
            dist_dict[n1, n2] = float(dist.replace('\n',''))
# new distance function based on network lookup table
def calc_dict(p1, p2, dist_dict=dist_dict):   
    return dist_dict[p1,p2]
# create initial tsp path
x0 = []
for item in dist_dict.keys():
    x0.append(item[0])
    x0.append(item[1])
x0 = list(set(x0))
tsp_bike = tsp(dist_func=calc_dict, close_loop=True).dist
# initial energy
tsp_bike(x0)
# initial distance (miles)
tsp_bike(x0) * 0.000621371
# minimize
opt = sa.minimize(tsp_bike, x0, opt_mode='combinatorial', step_max=1000, t_max=1000, t_min=0) 
opt.results()
# shortest distance (miles)
tsp_bike(opt.best_state) * 0.000621371
opt.best_state
# sanity check
G =  ox.io.load_graphml('cincy.graphml')
# load brewery locations
locs_df = pd.read_csv('brewery_locations.csv')
# calculate bounding box
lats = locs_df['lat'].values
lngs = locs_df['lng'].values
bbox = [max(lats), min(lats), max(lngs), min(lngs)]
def calc_route(n0, n1):
    p0 = locs_df[locs_df['name']==n0][['lat','lng']].values[0]
    p1 = locs_df[locs_df['name']==n1][['lat','lng']].values[0]
    p0_node = ox.get_nearest_node(G, p0)
    p1_node = ox.get_nearest_node(G, p1)
    return nx.shortest_path(G, p0_node, p1_node, weight="length")
# generate initial route
route_initial = []
for i in range(len(x0)-1):
    n0 = x0[i]
    n1 = x0[i+1]
    route_initial.append(calc_route(n0, n1))
    
# close the loop
route_initial.append(calc_route(x0[0], x0[-1]))
# generate optimal route
route_final = []
for i in range(len(opt.best_state)-1):
    n0 = opt.best_state[i]
    n1 = opt.best_state[i+1]
    route_final.append(calc_route(n0, n1))
    
# close the loop
route_final.append(calc_route(opt.best_state[0], opt.best_state[-1]))
# initial
fig, ax = ox.plot_graph_routes(
    G, 
    route_initial,
    bbox=bbox,
    margin=0.1,
    edge_linewidth=0.5,
    route_linewidth=2,
    orig_dest_node_size=50,
    node_size=0,
    save=True,
    filename='cincy_initial',
    dpi=100)
# final
lats = locs_df['lat'].values
lngs = locs_df['lng'].values

bbox = [max(lats), min(lats), max(lngs), min(lngs)]

fig, ax = ox.plot_graph_routes(
    G, 
    route_final,
    bbox=bbox,
    margin=0.1,
    edge_linewidth=0.5,
    route_linewidth=2,
    orig_dest_node_size=50,
    node_size=0,
    save=True,
    filename='cincy_final',
    dpi=100)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.14444071212630163, 'fraction_numerical': 0.036614040980853205, 'mean_word_length': 4.414545454545454, 'pattern_counts': {'":': 0, '<': 10, '<?xml version=': 0, '>': 10, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '410802', 'license': 'MIT', 'n_tokens_mistral': 1247, 'n_tokens_neox': 1194, 'n_words': 229, 'path': 'examples/breweries/tsp-breweries.ipynb', 'repo_name': 'nathanrooy/simulated-annealing', 'size': '2982'}