Completed
Push — master ( 602eea...026eaa )
by
unknown
04:14 queued 01:18
created

ParticleSwarmAlgorithm.initSwarm()   A

Complexity

Conditions 2

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
import random as rnd
2
import copy
3
4
__all__ = ['ParticleSwarmAlgorithm']
5
6
7
class Particle(object):
8
    """Defines particle for population."""
9
    # pylint: disable=too-many-instance-attributes
10
    def __init__(self, D, LB, UB, vMin, vMax):
11
        self.D = D  # dimension of the problem
12
        self.LB = LB  # lower bound
13
        self.UB = UB  # upper bound
14
        self.vMin = vMin  # velocity min
15
        self.vMax = vMax  # velocity max
16
        self.Solution = []
17
        self.Velocity = []
18
19
        self.pBestPosition = []
20
        self.pBestSolution = []
21
        self.bestFitness = float('inf')
22
23
        self.Fitness = float('inf')
24
        self.generateParticle()
25
26
27
    def generateParticle(self):
28
        self.Solution = [self.LB + (self.UB - self.LB) * rnd.random()
29
                         for _i in range(self.D)]
30
        self.Velocity = [0 for _i in range(self.D)]
31
32
        self.pBestSolution = [0 for _i in range(self.D)]
33
        self.bestFitness = float('inf')
34
35
    def evaluate(self):
36
        self.Fitness = Particle.FuncEval(self.D, self.Solution)
37
        self.checkPersonalBest()
38
39
    def checkPersonalBest(self):
40
        if self.Fitness < self.bestFitness:
41
            self.pBestSolution = self.Solution
42
            self.bestFitness = self.Fitness
43
            
0 ignored issues
show
Coding Style introduced by
Trailing whitespace
Loading history...
44
45
    def simpleBound(self):
46
        for i in range(self.D):
47
            if self.Solution[i] < self.LB:
48
                self.Solution[i] = self.LB
49
            if self.Solution[i] > self.UB:
50
                self.Solution[i] = self.UB
51
            if self.Velocity[i] < self.vMin:
52
                self.Velocity[i] = self.vMin
53
            if self.Velocity[i] > self.vMax:
54
                self.Velocity[i] = self.vMax
55
56
    def toString(self):
57
        pass
58
59
    def __eq__(self, other):
60
        return self.Solution == other.Solution and self.Fitness == other.Fitness
61
62
63
class ParticleSwarmAlgorithm(object):
64
    """Particle Swarm Optimization algorithm.
65
66
    Date: 12. 2. 2018
67
68
    Authors : Uros Mlakar
69
70
    License: MIT
71
72
    Reference paper: Kennedy, J. and Eberhart, R. "Particle Swarm Optimization".
73
    Proceedings of IEEE International Conference on Neural Networks. IV. pp. 1942--1948, 1995.
74
75
    EDITED: TODO: Tests and validation! Bug in code.
76
    """
77
78 View Code Duplication
    def __init__(self, Np, D, nFES, C1, C2, w, vMin, vMax, Lower, Upper, function):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
79
        """Constructor."""
80
        self.Np = Np
81
        self.D = D
82
        self.C1 = C1
83
        self.C2 = C2
84
        self.w = w
85
        self.vMin = vMin
86
        self.vMax = vMax
87
        self.Lower = Lower
88
        self.Upper = Upper
89
        self.Swarm = []
90
        self.nFES = nFES
91
        self.FEs = 0
92
        self.Done = False
93
        Particle.FuncEval = staticmethod(function)
94
95
        self.gBest = Particle(self.D, self.Lower, self.Upper, self.vMin, self.vMax)
96
97
    def evalSwarm(self):
98
        for p in self.Swarm:
99
            p.evaluate()
100
            if p.Fitness < self.gBest.Fitness:
101
                self.gBest = copy.deepcopy(p)
102
103
    def initSwarm(self):
104
        for _i in range(self.Np):
105
            self.Swarm.append(Particle(self.D, self.Lower, self.Upper, self.vMin, self.vMax))
106
107
    def tryEval(self,p):
0 ignored issues
show
Coding Style introduced by
Exactly one space required after comma
Loading history...
108
        if self.FEs <= self.nFES:
109
            p.evaluate()
110
            self.FEs+=1
0 ignored issues
show
Coding Style introduced by
Exactly one space required around assignment
Loading history...
111
        else:
112
            self.Done = True
113
114
    def moveSwarm(self, Swarm):
115
        MovedSwarm = []
116
        for p in Swarm:
117
118
            part1 = ([(a - b) * rnd.random() * self.C1 for a,
119
                      b in zip(p.pBestSolution, p.Solution)])
120
            part2 = ([(a - b) * rnd.random() * self.C2 for a,
121
                      b in zip(self.gBest.Solution, p.Solution)])
122
123
            p.Velocity = ([self.w * a + b + c for a, b,
124
                           c in zip(p.Velocity, part1, part2)])
125
            p.Solution = ([a + b for a, b in zip(p.Solution, p.Velocity)])
126
127
            p.simpleBound()
128
            self.tryEval(p)
129
            if p.Fitness < self.gBest.Fitness:
130
                self.gBest = copy.deepcopy(p)
131
132
            MovedSwarm.append(p)
133
        return MovedSwarm
134
135
    def run(self):
136
        self.initSwarm()
137
        self.evalSwarm()
138
        self.FEs += self.Np
139
        while not self.Done:
140
            MovedSwarm = self.moveSwarm(self.Swarm)
141
            self.Swarm = MovedSwarm
142
143
        return self.gBest.Fitness
144