My code in books
Created:
During a “vanity search” of this blog “btbytes.github.io”, I found out that some of my code have been quoted in published books:
(A Particle Swarm Optimization) implementation in Python in “Intelligent IoT Projects in 7 Days”. I remember writing this code for Dr Eberhart’s “Computation Intelligence” class at IUPUI.
The code in question:
#!/usr/bin/env python
'''
pso.py
A simple implementation of the Particle Swarm Optimisation Algorithm.
Uses Numpy for matrix operations.
Pradeep Gowda 2009-03-16
'''
from numpy import array
from random import random
from math import sin, sqrt
= 10000
iter_max = 100
pop_size = 2
dimensions = 2
c1 = 2
c2 = 0.00001
err_crit
class Particle:
pass
def f6(param):
'''Schaffer's F6 function'''
= param*10
para = param[0:2]
para = (sin(sqrt((para[0] * para[0]) + (para[1] * para[1])))) * \
num 0] * para[0]) + (para[1] * para[1])))) - 0.5
(sin(sqrt((para[= (1.0 + 0.001 * ((para[0] * para[0]) + (para[1] * para[1]))) * \
denom 1.0 + 0.001 * ((para[0] * para[0]) + (para[1] * para[1])))
(= 0.5 - (num/denom)
f6 = 1 - f6
errorf6 return f6, errorf6;
#initialize the particles
= []
particles for i in range(pop_size):
= Particle()
p = array([random() for i in range(dimensions)])
p.params = 0.0
p.fitness = 0.0
p.v
particles.append(p)
# let the first particle be the global best
= particles[0]
gbest = 999999999
err while i < iter_max :
for p in particles:
= f6(p.params)
fitness,err if fitness > p.fitness:
= fitness
p.fitness = p.params
p.best
if fitness > gbest.fitness:
= p
gbest = p.v + c1 * random() * (p.best - p.params) \
v + c2 * random() * (gbest.params - p.params)
= p.params + v
p.params
+= 1
i if err < err_crit:
break
#progress bar. '.' = 10%
if i % (iter_max/10) == 0:
print '.'
print '\nParticle Swarm Optimisation\n'
print 'PARAMETERS\n','-'*9
print 'Population size : ', pop_size
print 'Dimensions : ', dimensions
print 'Error Criterion : ', err_crit
print 'c1 : ', c1
print 'c2 : ', c2
print 'function : f6'
print 'RESULTS\n', '-'*7
print 'gbest fitness : ', gbest.fitness
print 'gbest params : ', gbest.params
print 'iterations : ', i+1
## Uncomment to print particles
#for p in particles:
# print 'params: %s, fitness: %s, best: %s' % (p.params, p.fitness, p.best)
That’s in Python2.x. Should probably rewrite it in Python3 one of these days.
A link to my PyOFC2 Python charting library in “Building a Cloud Computing Service: An Introduction to the Cloud”.