com2014-template/template/main.py

122 lines
3.6 KiB
Python

import os
import signal
import json
from model.anneal_model import SimAnneal
from model.my_model import MyModel
def log(msg):
print('[*] {msg}'.format(msg=msg))
def load_data(file):
coords = []
with open(file, "r") as infile:
line = infile.readline()
# Skip instance header
while "NODE_COORD_SECTION" not in line:
line = infile.readline()
for line in infile.readlines():
line = line.replace("\n", "")
if line and 'EOF' not in line:
line = [float(x) for x in line.lstrip().split(" ", 1)[1].split(" ") if x]
coords.append(line)
return coords
def timeout_handler(signum, frame):
print("Timeout")
raise Exception("Timeout")
def TSP(tsp_file, model):
best_solution = []
fitness_list = []
coords = load_data(tsp_file)
# Set timeout
# signal.signal(signal.SIGALRM, timeout_handler)
# signal.alarm(60)
# Try your algorithm
try:
model.init(coords)
best_solution, fitness_list = model.fit(max_it=10000)
except Exception as exc:
if(str(exc) == "Timeout"):
log("Timeout -3")
with open('output/' + os.path.splitext(os.path.basename(tsp_file))[0] + '.txt', "w") as outfile:
outfile.write("-3")
else:
print(exc)
log("Unkown -4")
with open('output/' + os.path.splitext(os.path.basename(tsp_file))[0] + '.txt', "w") as outfile:
outfile.write("-4")
# Collect results
if(len(fitness_list) > 0):
log("Best: " + str(fitness_list[-1]))
if (len(best_solution) == 0):
log("No Answer -1")
with open('output/' + os.path.splitext(os.path.basename(tsp_file))[0] + '.txt', "w") as outfile:
outfile.write("-1")
elif (len(best_solution) != len(coords)):
log("Invalid -2")
with open('output/' + os.path.splitext(os.path.basename(tsp_file))[0] + '.txt', "w") as outfile:
outfile.write("-2")
else:
log("Writing the best solution to file" )
with open('output/' + os.path.splitext(os.path.basename(tsp_file))[0] + '.txt', "w") as outfile:
outfile.write(str(model.fitness(best_solution)))
outfile.write("\n")
outfile.write(", ".join(str(item) for item in best_solution))
# Write to JSON
data = {}
data['nodes'] = []
for i in range(len(coords)):
data['nodes'].append({
'title': str(i),
'id': i,
'x': int(coords[i][0]),
'y': int(coords[i][1])
})
data['edges'] = []
for i in range(len(best_solution)):
if i == len(best_solution)-1:
data['edges'].append({
'source': best_solution[i],
'target': best_solution[0]
})
else:
data['edges'].append({
'source': best_solution[i],
'target': best_solution[i+1]
})
with open('output/' + os.path.splitext(os.path.basename(tsp_file))[0] + '.json', 'w') as outfile:
json.dump(data, outfile)
if __name__ == "__main__":
for root, _, files in os.walk('./data'):
if(files):
for f in files:
# Get input file name
tsp_file = str(root) + '/' + str(f)
log(tsp_file)
# Your Model
# model = MyModel()
# Simulated Annealing
model = SimAnneal()
TSP(tsp_file, model)
print()