-
Notifications
You must be signed in to change notification settings - Fork 0
/
swamoptimization.py
76 lines (62 loc) · 2.49 KB
/
swamoptimization.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
# -*- coding: utf-8 -*-
"""swamoptimization.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1Q8JAky0_G9oXmjPnonD2nVgSqQqNwQNP
"""
import numpy as np
import random
def Fitness(x , y) :
h = x + 2 * - y + 3
k = 2 * x + y - 8
z = h**2 + k**2
return z
def VelocityUpdate(Particle, Velocity, PersonalBest, GlobalBest, WMin = 0.5 , Maximum = 1.0, C = 0.1):
ParticleSize = len(Particle)
NewVelocity = np.array([0.0 for i in range(ParticleSize)])
r1 = random.uniform(0 , Maximum)
r2 = random.uniform(0 , Maximum)
w = random.uniform(WMin , Maximum)
c1 = C
c2 = C
for i in range(ParticleSize):
NewVelocity[i] = w * Velocity[i] + c1 * r1 * (PersonalBest[i] - Particle[i]) + c2 * r2* (GlobalBest[i] - Particle[i])
return NewVelocity
def PositionUpdate(Particle , Velocity) :
NewParticle = Particle + Velocity
return NewParticle
def PSO(Population, Dimension, MinimumPosition, MaximumPosition, Generation, FitnessCriteria):
Particles = [[random.uniform(MinimumPosition, MaximumPosition) for j in range(Dimension)] for i in range(Population)]
PBestPosition = Particles
PBestFitness = [Fitness(p[0] , p[1]) for p in Particles]
GBestIndex = np.argmin(PBestFitness)
GBestPosition = PBestPosition[GBestIndex]
Velocity = [[0.0 for j in range(Dimension)] for i in range(Population)]
for t in range(Generation):
if np.average(PBestFitness) <= FitnessCriteria:
break
else:
for n in range(Population):
Velocity[n] = VelocityUpdate(Particles[n] , Velocity[n] , PBestPosition[n], GBestPosition)
Particles[n] = PositionUpdate(Particles[n], Velocity[n])
PBestFitness = [Fitness(p[0] , p[1]) for p in Particles]
GBestIndex = np.argmin(PBestFitness)
GBestPosition = PBestPosition[GBestIndex]
print('\nGlobal Best Position\t\t\t: ', GBestPosition)
print('Best Fitness Value\t\t\t: ', min(PBestFitness))
print('Average Particle Best Fitness Value\t: ', np.average(PBestFitness))
print('Number of Generation\t\t\t: ', t , "\n")
Population = 100
Dimension = 2
MinPosition = -100
MaxPostion = 100
Generation = 400
Criteria = 10e-4
PSO(
Population = Population ,
Dimension = Dimension ,
MinimumPosition = MinPosition ,
MaximumPosition = MaxPostion ,
Generation = Generation ,
FitnessCriteria = Criteria
)