01.from numpy import array
02.from random import random
03.from math import sin, sqrt
04.
05.iter_max = 10000
06.pop_size = 100
07.dimensions = 28.c1 = 29.c2 = 2
10.err_crit = 0.00001
11.
12.class Particle:
13. pass
14.
15.def f6(param):
16. '''Schaffer's F6 function'''
17. para = param*10
18. para = param[0:2]
19. num = (sin(sqrt((para[0] * para[0]) + (para[1] * para[1])))) * \
20. (sin(sqrt((para[0] * para[0]) + (para[1] * para[1])))) - 0.5
21. denom = (1.0 + 0.001 * ((para[0] * para[0]) + (para[1] * para[1]))) * \
22. (1.0 + 0.001 * ((para[0] * para[0]) + (para[1] * para[1])))
23. f6 = 0.5 - (num/denom)
24. errorf6 = 1 - f6
25. return f6, errorf6;
26.
27.#initialize the particles
28.particles = []
29.for i in range(pop_size):
30. p = Particle()
31. p.params = array([random() for i in range(dimensions)])
32. p.fitness = 0.0
33. p.v = 0.0
34. particles.append(p)
35.
36.# let the first particle be the global best
37.gbest = particles[0]
38.err = 999999999
39.while i < iter_max :
40. for p in particles:
41. fitness,err = f6(p.params)
42. if fitness > p.fitness:
43. p.fitness = fitness
44. p.best = p.params
45.
46. if fitness > gbest.fitness:
47. gbest = p
48. v = p.v + c1 * random() * (p.best - p.params) \
49. + c2 * random() * (gbest.params - p.params)
50. p.params = p.params + v
51.
52. i += 1
53. if err < err_crit:
54. break
55. #progress bar. '.' = 10%
56. if i % (iter_max/10) == 0:
57. print '.'
58.
59.print '\nParticle Swarm Optimisation\n'
60.print 'PARAMETERS\n','-'*9
61.print 'Population size : ', pop_size
62.print 'Dimensions : ', dimensions
63.print 'Error Criterion : ', err_crit
64.print 'c1 : ', c1
65.print 'c2 : ', c2
66.print 'function : f6'
67.
68.print 'RESULTS\n', '-'*7
69.print 'gbest fitness : ', gbest.fitness
70.print 'gbest params : ', gbest.params
71.print 'iterations : ', i+1
72.## Uncomment to print particles
73.#for p in particles:
74.# print 'params: %s, fitness: %s, best: %s' % (p.params, p.fitness, p.best)