-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTSPClasses.py
234 lines (181 loc) · 6.46 KB
/
TSPClasses.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
#!/usr/bin/python3
import math
import numpy as np
import random
import time
class TSPSolution:
def __init__( self, listOfCities):
self.route = listOfCities
self.cost = self._costOfRoute()
#print( [c._index for c in listOfCities] )
def _costOfRoute( self ):
cost = 0
#print('cost = ',cost)
last = self.route[0]
for city in self.route[1:]:
#print('cost increasing by {} for leg {} to {}'.format(last.costTo(city),last._name,city._name))
cost += last.costTo(city)
last = city
#print('cost increasing by {} for leg {} to {}'.format(self.route[-1].costTo(self.route[0]),self.route[-1]._name,self.route[0]._name))
cost += self.route[-1].costTo( self.route[0] )
#print('cost = ',cost)
return cost
def enumerateEdges( self ):
elist = []
c1 = self.route[0]
for c2 in self.route[1:]:
dist = c1.costTo( c2 )
if dist == np.inf:
return None
elist.append( (c1, c2, int(math.ceil(dist))) )
c1 = c2
dist = self.route[-1].costTo( self.route[0] )
if dist == np.inf:
return None
elist.append( (self.route[-1], self.route[0], int(math.ceil(dist))) )
return elist
def nameForInt( num ):
if num == 0:
return ''
elif num <= 26:
return chr( ord('A')+num-1 )
else:
return nameForInt((num-1) // 26 ) + nameForInt((num-1)%26+1)
class Scenario:
HARD_MODE_FRACTION_TO_REMOVE = 0.20 # Remove 20% of the edges
def __init__( self, city_locations, difficulty, rand_seed ):
self._difficulty = difficulty
if difficulty == "Normal" or difficulty == "Hard":
self._cities = [City( pt.x(), pt.y(), \
random.uniform(0.0,1.0) \
) for pt in city_locations]
elif difficulty == "Hard (Deterministic)":
random.seed( rand_seed )
self._cities = [City( pt.x(), pt.y(), \
random.uniform(0.0,1.0) \
) for pt in city_locations]
else:
self._cities = [City( pt.x(), pt.y() ) for pt in city_locations]
num = 0
for city in self._cities:
#if difficulty == "Hard":
city.setScenario(self)
city.setIndexAndName( num, nameForInt( num+1 ) )
num += 1
# Assume all edges exists except self-edges
ncities = len(self._cities)
self._edge_exists = ( np.ones((ncities,ncities)) - np.diag( np.ones((ncities)) ) ) > 0
#print( self._edge_exists )
if difficulty == "Hard":
self.thinEdges()
elif difficulty == "Hard (Deterministic)":
self.thinEdges(deterministic=True)
def getCities( self ):
return self._cities
def randperm( self, n ): #isn't there a numpy function that does this and even gets called in Solver?
perm = np.arange(n)
for i in range(n):
randind = random.randint(i,n-1)
save = perm[i]
perm[i] = perm[randind]
perm[randind] = save
return perm
def thinEdges( self, deterministic=False ):
ncities = len(self._cities)
edge_count = ncities*(ncities-1) # can't have self-edge
num_to_remove = np.floor(self.HARD_MODE_FRACTION_TO_REMOVE*edge_count)
#edge_exists = ( np.ones((ncities,ncities)) - np.diag( np.ones((ncities)) ) ) > 0
can_delete = self._edge_exists.copy()
# Set aside a route to ensure at least one tour exists
route_keep = np.random.permutation( ncities )
if deterministic:
route_keep = self.randperm( ncities )
for i in range(ncities):
can_delete[route_keep[i],route_keep[(i+1)%ncities]] = False
# Now remove edges until
while num_to_remove > 0:
if deterministic:
src = random.randint(0,ncities-1)
dst = random.randint(0,ncities-1)
else:
src = np.random.randint(ncities)
dst = np.random.randint(ncities)
if self._edge_exists[src,dst] and can_delete[src,dst]:
self._edge_exists[src,dst] = False
num_to_remove -= 1
#print( self._edge_exists )
class City:
def __init__( self, x, y, elevation=0.0 ):
self._x = x
self._y = y
self._elevation = elevation
self._scenario = None
self._index = -1
self._name = None
def setIndexAndName( self, index, name ):
self._index = index
self._name = name
def setScenario( self, scenario ):
self._scenario = scenario
''' <summary>
How much does it cost to get from this city to the destination?
Note that this is an asymmetric cost function.
In advanced mode, it returns infinity when there is no connection.
</summary> '''
MAP_SCALE = 1000.0
def costTo( self, other_city ):
assert( type(other_city) == City )
# In hard mode, remove edges; this slows down the calculation...
# Use this in all difficulties, it ensures INF for self-edge
if not self._scenario._edge_exists[self._index, other_city._index]:
#print( 'Edge ({},{}) doesn\'t exist'.format(self._index,other_city._index) )
return np.inf
# Euclidean Distance
cost = math.sqrt( (other_city._x - self._x)**2 +
(other_city._y - self._y)**2 )
# For Medium and Hard modes, add in an asymmetric cost (in easy mode it is zero).
if not self._scenario._difficulty == 'Easy':
cost += (other_city._elevation - self._elevation)
if cost < 0.0:
cost = 0.0
#cost *= SCALE_FACTOR
return int(math.ceil(cost * self.MAP_SCALE))
class TSPNode:
def __init__(self, lower_bound, m, route, parent_cost):
self.route = route
self.cost = parent_cost
self.lower_bound = lower_bound
self.m = m
return
def __lt__(self, other):
return self.lower_bound / len(self.route) < other.lower_bound / len(other.route)
def reduceMatrix(self, c1, c2):
# inf out the correct col and row. also the individual cell. Update lower bound
if len(self.route) != 0:
# Add val to lower bound
self.lower_bound += self.m[c1][c2]
# Remove yx value as well
self.m[c2][c1] = np.inf
# inf out the correct row/column
self.m[c1] = [np.inf] * np.shape(self.m)[0]
self.m[:, c2] = [np.inf] * np.shape(self.m)[0]
# Reduce rows
for i, row in enumerate(self.m):
if 0 not in row and False in np.isinf(row):
min_val = np.min(row)
self.m[i] = [x - min_val for x in row]
self.lower_bound += min_val
# Reduce columns
for i in range(len(self.m)):
col = self.m[:, i]
if 0 not in col and False in np.isinf(col):
min_val = np.min(col)
self.m[:, i] = [x - min_val for x in col]
self.lower_bound += min_val
def addCityAndUpdateCost(self, city):
self.city = city
self.route.append(city)
if len(self.route) == 1:
self.cost = 0
else:
self.cost += self.route[-2].costTo(self.city)