-
Notifications
You must be signed in to change notification settings - Fork 0
/
Swarm.py
331 lines (287 loc) · 13.9 KB
/
Swarm.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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
import math
from Particle import Particle
import random
import numpy
class Swarm:
# Initialize swarm as square matrix (will truncate if population not perfect square)
def __init__(self, popSize, c1, c2):
length = int(math.sqrt(popSize))
self.pop = numpy.empty([length, length], dtype=Particle)
self.c1 = c1
self.c2 = c2
self.phi = c1 + c2
self.bestPerGen = [] # Stores value of best sol per generation
self.bestSol = [0, 0]
self.bestSolValue = 99999
self.averagePerGen = [] # Stores average fitness per generation
self.iter = 0
for i in range(length): # init pop
for j in range(length):
tempX = random.random() * 10.0 - 5.0
tempY = random.random() * 10.0 - 5.0
initW = 0.792
self.pop[i][j] = Particle([tempX, tempY], [0, 0], initW)
for i in range(length): # init neighbours for pop
for j in range(length):
self.setNeighbours(i, j, self.pop[i][j])
# Set neighbourhood best values
for i in range(len(self.pop)):
for j in range(len(self.pop)):
self.pop[i][j].nbestUpdate()
# Set neighbours of a particle
def setNeighbours(self, i, j, ind):
if i > 0:
ind.neighbours.append(self.pop[i-1][j])
if i < (len(self.pop) - 1):
ind.neighbours.append(self.pop[i+1][j])
if j > 0:
ind.neighbours.append(self.pop[i][j-1])
if j < (len(self.pop) - 1):
ind.neighbours.append(self.pop[i][j+1])
def runBasic(self):
# Run search
self.iter = 0
while self.iter < 100: # set max of 100 iterations
bestGen = [0, 0] # temp for best in a gen
bestGenVal = 99999 # value for the above
fitnessSum = 0.0
currGenVals = [] # Fitnesses for current gen
for i in range(len(self.pop)):
for j in range(len(self.pop)):
curr = self.pop[i][j]
curr.velUpdateBasic(self.c1, self.c2) # Velocity update
curr.posUpdate() # Position update
# Update neighbourhood best - for this particle and all others in its neighbourhood
curr.nbestUpdate()
curr.nbestUpdateNeighbours()
# Set best in generation
tempVal = curr.evalSelf()
if tempVal < bestGenVal:
bestGenVal = tempVal
bestGen = curr.pos
currGenVals.append(tempVal)
fitnessSum += tempVal # for average fitness in gen
# Add to best per gen
if len(self.bestPerGen):
if min(currGenVals) < self.bestPerGen[-1]:
self.bestPerGen.append(numpy.min(currGenVals))
else:
self.bestPerGen.append(numpy.min(self.bestPerGen))
else:
self.bestPerGen.append(numpy.min(currGenVals))
# Change global best if applicable and set best in gen
if bestGenVal < self.bestSolValue:
self.bestSol = bestGen
self.bestSolValue = bestGenVal
# Append to average per gen
self.averagePerGen.append(fitnessSum / pow(len(self.pop), 2))
self.iter += 1
# Inertia weight
def runInerWeight(self):
# Run search
self.iter = 0
maxW = 1.0
minW = 0.1
self.k = 2 / abs(2 - self.phi - math.sqrt(pow(self.phi, 2) - 4 * self.phi))
while self.iter < 100: # set max of 100 iterations
bestGen = [0, 0] # temp for best in a gen
bestGenVal = 99999 # value for the above
fitnessSum = 0.0
currGenVals = [] # Fitnesses for current gen
for i in range(len(self.pop)):
for j in range(len(self.pop)):
curr = self.pop[i][j]
curr.velUpdateInertia(self.c1, self.c2, maxW, minW, self.iter, 100) # Velocity update
curr.posUpdate() # Position update
# Update neighbourhood best - for this particle and all others in its neighbourhood
curr.nbestUpdate()
curr.nbestUpdateNeighbours()
# Set best in generation
tempVal = curr.evalSelf()
if tempVal < bestGenVal:
bestGenVal = tempVal
bestGen = curr.pos
currGenVals.append(tempVal)
fitnessSum += tempVal # for average fitness in gen
# Add to best per gen
if len(self.bestPerGen):
if min(currGenVals) < self.bestPerGen[-1]:
self.bestPerGen.append(numpy.min(currGenVals))
else:
self.bestPerGen.append(numpy.min(self.bestPerGen))
else:
self.bestPerGen.append(numpy.min(currGenVals))
# Change global best if applicable and set best in gen
if bestGenVal < self.bestSolValue:
self.bestSol = bestGen
self.bestSolValue = bestGenVal
# Append to average per gen
self.averagePerGen.append(fitnessSum / pow(len(self.pop), 2))
self.iter += 1
# Constriction factor
def runConstriction(self):
self.iter = 0
self.k = 2 / abs(2 - self.phi - math.sqrt(pow(self.phi, 2) - 4 * self.phi))
while self.iter < 100: # set max of 100 iterations
bestGen = [0, 0] # temp for best in a gen
bestGenVal = 99999 # value for the above
fitnessSum = 0.0
gbest = [0, 0]
currGenVals = [] # Fitnesses for current gen
for i in range(len(self.pop)):
for j in range(len(self.pop)):
gbest = self.gbestFind() # Get global best for velocity update
curr = self.pop[i][j]
curr.velUpdateConstriction(self.c1, self.c2, self.k, gbest) # Velocity update
curr.posUpdate() # Position update
# Update neighbourhood best - for this particle and all others in its neighbourhood
curr.nbestUpdate()
curr.nbestUpdateNeighbours()
# Set best in generation
tempVal = curr.evalSelf()
if tempVal < bestGenVal:
bestGenVal = tempVal
bestGen = curr.pos
currGenVals.append(tempVal)
fitnessSum += tempVal # for average fitness in gen
# Add to best per gen
if len(self.bestPerGen):
if min(currGenVals) < self.bestPerGen[-1]:
self.bestPerGen.append(numpy.min(currGenVals))
else:
self.bestPerGen.append(numpy.min(self.bestPerGen))
else:
self.bestPerGen.append(numpy.min(currGenVals))
# Change global best if applicable and set best in gen
if bestGenVal < self.bestSolValue:
self.bestSol = bestGen
self.bestSolValue = bestGenVal
# Append to average per gen
self.averagePerGen.append(fitnessSum / pow(len(self.pop), 2))
self.iter += 1
# GCPSO
def runGC(self):
self.iter = 0
currBestVal = 99999
currBest = self.pop[0][0]
maxW = 1.0
minW = 0.1
while self.iter < 100: # set max of 100 iterations
# Reset appropriate values
prevBestVal = currBestVal
prevBest = currBest
currBestVal = 99999
currBest = self.pop[0][0]
bestGen = [0, 0] # temp for best in a gen
bestGenVal = 99999 # value for the above
fitnessSum = 0.0
currGenVals = [] # Fitnesses for current gen
if self.iter == 0: # first iteration - this is the SAME as inertia weight, since no successes/failures
# For initial population - set the 'previous best' values for the next iteration to compare to
for i in range(len(self.pop)):
for j in range(len(self.pop)):
curr = self.pop[i][j]
tempVal = curr.evalSelf()
if tempVal < currBestVal:
currBestVal = tempVal
currBest = curr
# Update velocities, positions by inertia weight
for i in range(len(self.pop)):
for j in range(len(self.pop)):
curr = self.pop[i][j]
curr.velUpdateInertia(self.c1, self.c2, maxW, minW, self.iter, 200) # Velocity update
curr.posUpdate() # Position update
# Update neighbourhood best - for this particle and all others in its neighbourhood
curr.nbestUpdate()
curr.nbestUpdateNeighbours()
# Set best in generation
tempVal = curr.evalSelf()
if tempVal < bestGenVal:
bestGenVal = tempVal
bestGen = curr.pos
currGenVals.append(tempVal)
fitnessSum += tempVal # for average fitness in gen
# Add to best per gen
if len(self.bestPerGen):
if min(currGenVals) < self.bestPerGen[-1]:
self.bestPerGen.append(numpy.min(currGenVals))
else:
self.bestPerGen.append(numpy.min(self.bestPerGen))
else:
self.bestPerGen.append(numpy.min(currGenVals))
# Change global best if applicable and set best in gen
if bestGenVal < self.bestSolValue:
self.bestSol = bestGen
self.bestSolValue = bestGenVal
# Append to average per gen
self.averagePerGen.append(fitnessSum / pow(len(self.pop), 2))
self.iter += 1
else: # all non-first iterations
# Determine the current best
for i in range(len(self.pop)):
for j in range(len(self.pop)):
curr = self.pop[i][j]
tempVal = curr.evalSelf()
if tempVal < currBestVal:
currBestVal = tempVal
currBest = curr
# Compare to previous best, and update appropriate success/failure counter
if currBest is prevBest:
if currBestVal == prevBestVal: # increase failure count if best was stagnant
currBest.successes = 0
currBest.failures += 1
else: # increase success count if the prev best particle is still the best, but has a dif position
currBest.failures = 0
currBest.successes += 1
else: # Reset counts for previous best if the best particle changed
prevBest.successes = 0
prevBest.failures = 0
# Update velocities, positions by GCPSO for best particle, and inertia weight for the rest
for i in range(len(self.pop)):
for j in range(len(self.pop)):
curr = self.pop[i][j]
if curr is currBest: # GCPSO update for current best particle
oldVel = curr.velUpdateGCPSO(self.bestSol)
curr.posUpdateGCPSO(self.bestSol, oldVel)
else: # Inertia weight update for all other particles
curr.velUpdateInertia(self.c1, self.c2, maxW, minW, self.iter, 200) # Velocity update
curr.posUpdate() # Position update
# Update neighbourhood best - for this particle and all others in its neighbourhood
curr.nbestUpdate()
curr.nbestUpdateNeighbours()
# Set best in generation
tempVal = curr.evalSelf()
if tempVal < bestGenVal:
bestGenVal = tempVal
bestGen = curr.pos
currGenVals.append(tempVal)
fitnessSum += tempVal # for average fitness in gen
# Add to best per gen
if len(self.bestPerGen):
if min(currGenVals) < self.bestPerGen[-1]:
self.bestPerGen.append(numpy.min(currGenVals))
else:
self.bestPerGen.append(numpy.min(self.bestPerGen))
else:
self.bestPerGen.append(numpy.min(currGenVals))
# Change global best if applicable and set best in gen
if bestGenVal < self.bestSolValue:
self.bestSol = bestGen
self.bestSolValue = bestGenVal
# Append to average per gen
self.averagePerGen.append(fitnessSum / pow(len(self.pop), 2))
self.iter += 1
# Returns global best solution (not the value with it)
def gbestFind(self):
tempBestVal = 99999
tempBest = [0, 0]
for i in range(len(self.pop)):
for j in range(len(self.pop)):
tempVal = self.pop[i][j].evalSelf()
if tempVal < tempBestVal:
tempBest = self.pop[i][j].pos
return tempBest
def __str__(self):
for i in range(len(self.pop)):
for j in range(len(self.pop)):
print(self.pop[i][j])