import numpy as np
from scipy import spatial
import matplotlib.pyplot as plt
import wandb
import os
import requests
from config import get_cfg_defaults
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
num_points = 50
points_coordinate = np.random.rand(num_points, 2) # generate coordinate of points
distance_matrix = spatial.distance.cdist(points_coordinate, points_coordinate, metric=‘euclidean’)
def cal_total_distance(routine):
‘’‘The objective function. input routine, return total distance.
cal_total_distance(np.arange(num_points))
‘’’
num_points, = routine.shape
return sum([distance_matrix[routine[i % num_points], routine[(i + 1) % num_points]] for i in range(num_points)])
%% do GA
from sko.GA import GA_TSP
cfg = get_cfg_defaults()
from mpi4py import MPI
comm = MPI.COMM_WORLD
size = comm.Get_size()
rank = comm.Get_rank()
node_name = MPI.Get_processor_name() # get the name of the node
model_name = “host_{}rank{}”.format(node_name, rank)
if cfg.WANDB.OPEN:
cfg.WANDB.LOG_DIR = os.path.join(“./logs/”, model_name)
wandb.login(key=“0207aab37bfb7f3e9d2d689792826b9550f729d9”, relogin=True)
# wandb.init()
# print(cfg)
wandb.init(project=cfg.WANDB.PROJECT_NAME,
resume=cfg.WANDB.RESUME,
notes=cfg.WANDB.LOG_DIR,
name=model_name,
entity=cfg.WANDB.ENTITY,
config=cfg)
ga_tsp = GA_TSP(func=cal_total_distance, n_dim=num_points, size_pop=60, max_iter=1, prob_mut=1)
for i in range(500):
best_points, best_distance = ga_tsp.run(1)
if cfg.WANDB.OPEN:
wandb.log({“best”: best_distance})
print("best: ", best_distance)
%% plot
fig, ax = plt.subplots(1, 2)
best_points_ = np.concatenate([best_points, [best_points[0]]])
best_points_coordinate = points_coordinate[best_points_, :]
ax[0].plot(best_points_coordinate[:, 0], best_points_coordinate[:, 1], ‘o-r’)
ax[1].plot(ga_tsp.generation_best_Y)
plt.show()
if cfg.WANDB.OPEN:
wandb.log({“route”: plt})
wandb.finish()