Change TSP to search closest neighbors. Make lines for plotting thinner and plot neighbor connections.
This commit is contained in:
30
tsp/tsp.py
30
tsp/tsp.py
@@ -174,9 +174,9 @@ def local_search_k_opt(route, goal, m):
|
||||
no_improvement_iterations = 0
|
||||
|
||||
no_improvement_iterations += 1
|
||||
if no_improvement_iterations > 10:
|
||||
if no_improvement_iterations > 3:
|
||||
break
|
||||
# print("[random k-opt] current_total={}".format(current_total))
|
||||
print("[random k-opt] current_total={}".format(current_total))
|
||||
while True:
|
||||
point = choice(route.points)
|
||||
try:
|
||||
@@ -189,7 +189,7 @@ def local_search_k_opt(route, goal, m):
|
||||
|
||||
if current_total < goal:
|
||||
return
|
||||
#
|
||||
|
||||
|
||||
class Route(object):
|
||||
def __init__(self, points):
|
||||
@@ -322,6 +322,13 @@ class Route(object):
|
||||
for i, p in enumerate(self.points):
|
||||
p.index = i
|
||||
|
||||
def calculate_neighbors(self, n=3):
|
||||
for p in self.points:
|
||||
def d(other_point):
|
||||
return distance(p, other_point)
|
||||
ps = sorted(self.points, key=d)[1:n + 1]
|
||||
p.add_neighbors(ps)
|
||||
|
||||
|
||||
def solve_tsp(points):
|
||||
r = Route(points)
|
||||
@@ -334,9 +341,6 @@ def solve_tsp(points):
|
||||
|
||||
def solve_it(input_data):
|
||||
r = Route(parse_input_data(input_data))
|
||||
m = ClusterMap(4)
|
||||
m.cluster(r.points)
|
||||
|
||||
goal = {51: 429, # 4
|
||||
100: 20800, # 4
|
||||
200: 30000, # 8
|
||||
@@ -345,16 +349,18 @@ def solve_it(input_data):
|
||||
1889: 378069,
|
||||
33810: 78478868,
|
||||
}[r.len_points]
|
||||
m = ClusterMap(4)
|
||||
r.calculate_neighbors(8)
|
||||
# m.cluster(r.points)
|
||||
# r.route_from_clusters(m)
|
||||
|
||||
r.route_from_clusters(m)
|
||||
local_search_k_opt(r, goal, m)
|
||||
m.plot(r.points, plt)
|
||||
|
||||
r.verify_total_distance()
|
||||
return prepare_output_data(r.points)
|
||||
|
||||
|
||||
def solve_it_(input_data):
|
||||
def solve_it_precomputed(input_data):
|
||||
r = Route(parse_input_data(input_data))
|
||||
n = len(r.points)
|
||||
if n == 51:
|
||||
@@ -379,9 +385,9 @@ def solve_it_(input_data):
|
||||
if __name__ == "__main__":
|
||||
# file_location = "data/tsp_6_1"
|
||||
file_location = "data/tsp_51_1"
|
||||
# file_location = "data/tsp_100_3"
|
||||
# file_location = "data/tsp_200_2"
|
||||
# file_location = "data/tsp_574_1"
|
||||
file_location = "data/tsp_100_3"
|
||||
file_location = "data/tsp_200_2"
|
||||
file_location = "data/tsp_574_1"
|
||||
# file_location = "data/tsp_1889_1"
|
||||
# file_location = "data/tsp_33810_1"
|
||||
with open(file_location, 'r') as input_data_file:
|
||||
|
||||
Reference in New Issue
Block a user