-
Notifications
You must be signed in to change notification settings - Fork 0
/
Particle.cpp
33 lines (28 loc) · 1.28 KB
/
Particle.cpp
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
#include <iostream>
#include "Particle.h"
void Particle::update(std::vector<double> bestSwarmPosition, const Bounds &bounds, ObjectiveFunction *function, const SwarmParams ¶ms) {
updateVelocity(bestSwarmPosition, params);
updatePosition(bounds);
updateBestPosition(function);
}
Particle::Particle(const std::vector<double> &position, const std::vector<double> &velocity) :
position(position), velocity(velocity), bestPosition(position) {
}
void Particle::updateVelocity(const std::vector<double> &bestSwarmPosition, const SwarmParams ¶ms) {
for (int d = 0; d < velocity.size(); d++) {
velocity[d] = params.getInertiaFactor() * velocity[d] +
params.getPersonalWeight() * (bestPosition[d] - position[d]) +
params.getGlobalWeight() * (bestSwarmPosition[d] - position[d]);
}
}
void Particle::updatePosition(const Bounds &bounds) {
for (int d = 0; d < position.size(); d++) {
double sum = position[d] + velocity[d];
position[d] = constrict(sum, bounds.lowerBound(d), bounds.upperBound(d));
}
}
void Particle::updateBestPosition(ObjectiveFunction *objectiveFunction) {
if(objectiveFunction->fitness(position) < objectiveFunction->fitness(bestPosition)) {
bestPosition = position;
}
}