Passed
Pull Request — master (#107)
by
unknown
01:20
created

ParticleSwarmAlgorithm.moveSwarm()   B

Complexity

Conditions 7

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
c 0
b 0
f 0
dl 0
loc 20
rs 7.3333
1
import random
2
import numpy
3
from NiaPy.benchmarks.utility import Utility
4
5
__all__ = ['ParticleSwarmAlgorithm']
6
7
8
class ParticleSwarmAlgorithm(object):
9
    r"""Implementation of Particle Swarm Optimization algorithm.
10
11
    **Algorithm:** Particle Swarm Optimization algorithm
12
13
    **Date:** 2018
14
15
    **Author:** Lucija Brezočnik, Grega Vrbančič, and Iztok Fister Jr.
16
17
    **License:** MIT
18
19
    **Reference paper:**
20
        Kennedy, J. and Eberhart, R. "Particle Swarm Optimization".
21
        Proceedings of IEEE International Conference on Neural Networks.
22
        IV. pp. 1942--1948, 1995.
23
    """
24
25
    def __init__(self, D, NP, nFES, C1, C2, w, vMin, vMax, benchmark):
0 ignored issues
show
Unused Code introduced by
The argument vMax seems to be unused.
Loading history...
Unused Code introduced by
The argument vMin seems to be unused.
Loading history...
26
        r"""**__init__(self, NP, D, nFES, C1, C2, w, vMin, vMax, benchmark)**.
27
28
        Arguments:
29
            NP {integer} -- population size
30
31
            D {integer} -- dimension of problem
32
33
            nFES {integer} -- number of function evaluations
34
35
            C1 {decimal} -- cognitive component
36
37
            C2 {decimal} -- social component
38
39
            w {decimal} -- inertia weight
40
41
            vMin {decimal} -- minimal velocity
42
43
            vMax {decimal} -- maximal velocity
44
45
            benchmark {object} -- benchmark implementation object
46
47
        """
48
49
        self.benchmark = Utility().get_benchmark(benchmark)
50
        self.NP = NP  # population size; number of search agents
51
        self.D = D  # dimension of the problem
52
        self.C1 = C1  # cognitive component
53
        self.C2 = C2  # social component
54
        self.w = w  # initial inertia weight
55
        self.wMin = weightMin 
0 ignored issues
show
Coding Style introduced by
Trailing whitespace
Loading history...
Comprehensibility Best Practice introduced by
Undefined variable 'weightMin'
Loading history...
56
        self.wMax = weightMax
0 ignored issues
show
Comprehensibility Best Practice introduced by
Undefined variable 'weightMax'
Loading history...
57
        self.vMin = velocityMin  # minimal velocity
0 ignored issues
show
Comprehensibility Best Practice introduced by
Undefined variable 'velocityMin'
Loading history...
58
        self.vMax = velocityMax  # maximal velocity
0 ignored issues
show
Comprehensibility Best Practice introduced by
Undefined variable 'velocityMax'
Loading history...
59
        self.Lower = self.benchmark.Lower  # lower bound
60
        self.Upper = self.benchmark.Upper  # upper bound
61
        self.nFES = nFES  # number of function evaluations
62
        self.eval_flag = True  # evaluations flag
63
        self.evaluations = 0  # evaluations counter
64
        self.Fun = self.benchmark.function()
65
66
        self.Solution = numpy.zeros((self.NP, self.D))  # positions of search agents
67
        self.Velocity = numpy.zeros((self.NP, self.D))  # velocities of search agents
68
69
        self.pBestFitness = numpy.zeros(self.NP)  # personal best fitness
70
        self.pBestFitness.fill(float("inf"))
71
        self.pBestSolution = numpy.zeros((self.NP, self.D))  # personal best solution
72
73
        self.gBestFitness = float("inf")  # global best fitness
74
        self.gBestSolution = numpy.zeros(self.D)  # global best solution
75
76
    def init(self):
77
        """Initialize positions."""
78
        for i in range(self.NP):
79
            for j in range(self.D):
80
                self.Solution[i][j] = random.random() * \
81
                    (self.Upper - self.Lower) + self.Lower
82
83
    def eval_true(self):
84
        """Check evaluations."""
85
86
        if self.evaluations == self.nFES:
87
            self.eval_flag = False
88
89
    def bounds(self, position):
90
        for i in range(self.D):
91
            if position[i] < self.Lower:
92
                position[i] = self.Lower
93
            if position[i] > self.Upper:
94
                position[i] = self.Upper
95
        return position
96
97
    def move_particles(self):
98
99
        self.init()
100
101
        while self.eval_flag is not False:
102
            for i in range(self.NP):
103
                self.Solution[i] = self.bounds(self.Solution[i])
104
105
                self.eval_true()
106
                if self.eval_flag is not True:
107
                    break
108
109
                Fit = self.Fun(self.D, self.Solution[i])
110
                self.evaluations = self.evaluations + 1
111
112
                if Fit < self.pBestFitness[i]:
113
                    self.pBestFitness[i] = Fit
114
                    self.pBestSolution[i] = self.Solution[i]
115
116
                if Fit < self.gBestFitness:
117
                    self.gBestFitness = Fit
118
                    self.gBestSolution = self.Solution[i]
119
120
            for i in range(self.NP):
121
                for j in range(self.D):
122
                    self.Velocity[i][j] = (self.w * self.Velocity[i][j]) + \
123
                        (self.C1 * random.random() * (self.pBestSolution[i][j] - self.Solution[i][j])) + \
124
                        (self.C2 * random.random() * (self.gBestSolution[j] - self.Solution[i][j]))
125
126
                    if self.Velocity[i][j] < self.vMin:
127
                        self.Velocity[i][j] = self.vMin
128
                    if self.Velocity[i][j] > self.vMax:
129
                        self.Velocity[i][j] = self.vMax
130
131
                    self.Solution[i][j] = self.Solution[i][j] + \
132
                        self.Velocity[i][j]
133
134
        return self.gBestFitness
135
136
    def run(self):
137
        return self.move_particles()
0 ignored issues
show
Coding Style introduced by
Final newline missing
Loading history...