-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathts.py
More file actions
executable file
·180 lines (140 loc) · 4.1 KB
/
ts.py
File metadata and controls
executable file
·180 lines (140 loc) · 4.1 KB
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
#!/usr/bin/python
from random import randrange, shuffle, random
import math
import sys
HEIGHT = 10000
WIDTH = 10000
NUM_CITIES = 300
InitPopulation = 1000
MatePcnt = 0.5
MutationRate = 0.01
NumIterations = 3000
class Point:
def __init__(self,x,y):
self.x = x
self.y = y
def __repr__(self):
return 'Point,'+str(self.x)+','+str(self.y)
def distanceTo(self,other):
dx = abs(self.x - other.x)
dy = abs(self.y - other.y)
return math.sqrt( dx*dx + dy*dy )
# Route for traveling to cities
# This is what gets "evolved"
class Route:
def __init__(self):
self.path = []
self.fitness_ = 0
def __repr__(self):
return str(self.fitness_)
# Generates a random route given a list of cities
# Used to spawn the initial population
def generateRoute(self,cities):
self.path = list(cities)
shuffle(self.path)
# Fitness function
# Inverse of distance
def fitness(self):
self.fitness_ = 1.0/self.distance()
return self.fitness_
# Computes the total distance of the path
def distance(self):
total = 0
for i in xrange(0,len(self.path)):
nx = i+1 if (i+1 != len(self.path)) else 0
total += self.path[i].distanceTo(self.path[nx])
return total
# Mates the route with another
# Grabs a random section from the first parent
# then fills in the missing points in order from the second parent
def sexyTime(self,mate):
child = Route()
midme = int(len(self.path)/2)
idx1 = randrange(0, midme)
idx2 = randrange(idx1+1, len(self.path))
child.path = self.path[idx1:idx2]
for p in mate.path:
if p not in child.path:
child.path.append(p)
return child
# Mutates the route by simple swap of points
def mutate(self):
idx1 = randrange(0, len(self.path))
idx2 = idx1
while idx1 == idx2:
idx2 = randrange(0, len(self.path))
self.path[idx1], self.path[idx2] = self.path[idx2], self.path[idx1]
# Random Util
def printPoints(self):
for p in self.path:
print p
def fancyRepr(self):
sx = 'X | '
sy = 'Y | '
for p in self.path:
sx += str(p.x) + ' '
sy += str(p.y) + ' '
return sy + '\n' + sx + '\n'
def addPoint(self,x,y):
self.path.append(Point(x,y))
# Randomly generates a grid of cities
class Grid:
def __init__(self):
self.height = HEIGHT
self.width = WIDTH
self.cities = []
def Init(self, count):
for i in xrange(count):
x = randrange(0,self.width)
y = randrange(0,self.height)
self.cities.append(Point(x,y))
g = Grid()
g.Init(NUM_CITIES)
population = []
# Even Population
if InitPopulation%2 != 0:
InitPopulation += 1
print 'Parameters ', HEIGHT, WIDTH, NUM_CITIES, InitPopulation, MatePcnt, MutationRate, NumIterations
print 'Generating Initial Population: Stand By'
for i in xrange(0,InitPopulation):
r = Route()
r.generateRoute(g.cities)
population.append(r)
iteration = 0
print 'Starting life.'
for i in xrange(0,NumIterations):
newPopulation = []
# Compute fitness
for indv in population:
indv.fitness()
# Most Fit Individual
maxFit = max(population, key = lambda v: v.fitness_)
# Split population into two halves
A = population[:int(len(population)/2)]
B = population[int(len(population)/2):]
# Sort them by fitness
A = sorted(A, key= lambda v: v.fitness_, reverse=True)
B = sorted(B, key= lambda v: v.fitness_, reverse=True)
# Mate the top MatePcnt%
for idx in xrange(0,int(len(A)*MatePcnt)):
newPopulation.append(A[idx].sexyTime(B[idx]))
# Mutate a few
for indv in population:
cpy = Route()
cpy.path = list(indv.path)
if(random() < MutationRate):
cpy.mutate()
newPopulation.append(cpy)
# Randomly add rest of population to keep the size of the universe the same
shuffle(population)
newPopulation += population[0:len(population)-len(newPopulation)]
population = list(newPopulation)
# Some logging
print ('Iteration: ' + str(iteration ))
print ('The most fit individual in this population is: ' + str(maxFit.fitness_))
print ('Data,'+str(maxFit)+','+str((1.0/maxFit.fitness_)))
print
sys.stdout.flush() # Used to watch progress
iteration += 1
max(population, key = lambda v: v.fitness_).printPoints()
print('Fitness: ' + str(max(population, key = lambda v: v.fitness_)))