-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathsimanneal.py
executable file
·198 lines (151 loc) · 5.01 KB
/
simanneal.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
#!/usr/bin/env python
# http://www.theprojectspot.com/tutorial-post/simulated-annealing-algorithm-for-beginners/6
# http://www.psychicorigami.com/2007/06/28/tackling-the-travelling-salesman-problem-simmulated-annealing/
import argparse, sys, random, math
from argparse import RawTextHelpFormatter
__author__ = "Author ([email protected])"
__version__ = "$Revision: 0.0.1 $"
__date__ = "$Date: 2013-05-09 14:31 $"
# --------------------------------------
# define functions
def get_args():
parser = argparse.ArgumentParser(formatter_class=RawTextHelpFormatter, description="\
pythonTemplate.py\n\
author: " + __author__ + "\n\
version: " + __version__ + "\n\
description: Basic python script template")
parser.add_argument('-s', '--seed', required=False, help='random seed')
parser.add_argument('-n', '--num_cities', type=int, required=True, help='number of cities')
# parser.add_argument('-b', '--argB', metavar='argB', required=False, help='description of argument B')
# parser.add_argument('-c', '--flagC', required=False, action='store_true', help='sets flagC to true')
# parser.add_argument('input', nargs='?', type=argparse.FileType('r'), default=None, help='file to read. If \'-\' or absent then defaults to stdin.')
# parse the arguments
args = parser.parse_args()
# if no input, check if part of pipe and if so, read stdin.
# if args.input == None:
# if sys.stdin.isatty():
# parser.print_help()
# exit(1)
# else:
# args.input = sys.stdin
# send back the user input
return args
# return the euclidian distance between point a and point b
def dist(a, b):
# if not the same vector length then error
if len(a) != len(b):
return -1
sq_sum = 0
for i in xrange(len(a)):
sq_sum += (a[i] - b[i])**2
return sq_sum**(0.5)
def total_dist(points, route):
d = 0
a = points[route[0]]
for r in xrange(1,len(route)):
b = points[route[r]]
d += dist(a,b)
a = b
return d
def binary_flip(route, a, b):
new_route = route[:]
new_route[a], new_route[b] = route[b], route[a]
return new_route
# decide if to switch
def switch(dist, new_dist, temp):
if new_dist < dist:
p = 1.0
else:
p = math.exp(-abs(new_dist - dist)/temp)
print temp, dist, new_dist, p
if random.random() < p:
return True
else:
return False
def kirkpatrick_cooling(start_temp, alpha):
T = start_temp
while True:
yield T
T = alpha * T
# primary function
def myFunction(size):
start_temp = 1000
alpha = 0.9999
max_evals = 1000000000
points = []
for i in xrange(size):
coord = [random.random(), random.random()]
points.append(coord)
# print points
# print points[5], points[9]
# print dist(points[5], points[9])
route = range(size)
random.shuffle(route)
route.append(route[0])
print route
d = total_dist(points, route)
print 'initial dist', d
best_route = route
min_dist = d
i = 0
i_since_best = 0
cooling_schedule = kirkpatrick_cooling(start_temp, alpha)
path_exhaust = 0 # number of temps that have iterated because of exhausted paths
for temp in cooling_schedule:
done = False
tried = set()
while not done:
while 1:
a,b = random.sample(xrange(1, len(route)-1),2)
if (a,b) not in tried: break
flip_route = binary_flip(route, a, b)
flip_d = total_dist(points, flip_route)
tried.add((a,b))
print i
print len(tried)
if switch(d, flip_d, temp):
route = flip_route
d = flip_d
# only iterate temp if accept
i += 1
done = True
if d < min_dist:
min_dist = d
best_route = route[:]
else:
i_since_best += 1
if len(tried) >= (size - 2) * (size - 1):
i += 1
path_exhaust += 1
done = True
if i % 2000 == 0:
f = open('routes/route_%s.txt' % i, 'w')
for r in route:
f.write('\t'.join(map(str, points[r])) + '\n')
f.close()
if i_since_best > size**3 or path_exhaust > 5 or i >= max_evals:
break
f = open('routes/route_best.txt', 'w')
for r in best_route:
f.write('\t'.join(map(str, points[r])) + '\n')
f.close()
print best_route
print min_dist
return
# --------------------------------------
# main function
def main():
# parse the command line args
args = get_args()
random.seed(args.seed)
# call primary function
myFunction(args.num_cities)
# close the input file
# args.input.close()
# initialize the script
if __name__ == '__main__':
try:
sys.exit(main())
except IOError, e:
if e.errno != 32: # ignore SIGPIPE
raise