Passed
Push — master ( b0b7f3...e3d174 )
by Simon
04:31
created

ParticleSwarmOptimizer._move_positioner()   A

Complexity

Conditions 1

Size

Total Lines 17
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 13
nop 1
dl 0
loc 17
rs 9.75
c 0
b 0
f 0
1
# Author: Simon Blanke
2
# Email: [email protected]
3
# License: MIT License
4
5
6
import numpy as np
7
8
from .base_population_optimizer import BasePopulationOptimizer
9
from ...search import Search
10
from ._particle import Particle
11
12
13
class ParticleSwarmOptimizer(BasePopulationOptimizer, Search):
14
    def __init__(
15
        self,
16
        search_space,
17
        inertia=0.5,
18
        cognitive_weight=0.5,
19
        social_weight=0.5,
20
        temp_weight=0.2,
21
        rand_rest_p=0.03,
22
    ):
23
        super().__init__(search_space)
24
25
        self.inertia = inertia
26
        self.cognitive_weight = cognitive_weight
27
        self.social_weight = social_weight
28
        self.temp_weight = temp_weight
29
        self.rand_rest_p = rand_rest_p
30
31
        self.particles = self.optimizers
32
33
    def _sort_best(self):
34
        scores_list = []
35
        for _p_ in self.particles:
36
            scores_list.append(_p_.score_current)
37
38
        scores_np = np.array(scores_list)
39
        idx_sorted_ind = list(scores_np.argsort()[::-1])
40
41
        self.p_sorted = [self.particles[i] for i in idx_sorted_ind]
42
43
    def init_pos(self, pos):
44
        particle = Particle(
45
            self.search_space,
46
            inertia=self.inertia,
47
            cognitive_weight=self.cognitive_weight,
48
            social_weight=self.social_weight,
49
            temp_weight=self.temp_weight,
50
            rand_rest_p=self.rand_rest_p,
51
        )
52
        self.particles.append(particle)
53
        particle.init_pos(pos)
54
55
        self.p_current = particle
56
        self.p_current.velo = np.zeros(len(self.max_positions))
57
58
    def iterate(self):
59
        n_iter = self._iterations(self.particles)
60
        self.p_current = self.particles[n_iter % len(self.particles)]
61
62
        self._sort_best()
63
        self.p_current.global_pos_best = self.p_sorted[0].pos_best
64
65
        pos = self.p_current.iterate()
66
67
        return pos
68
69
    def evaluate(self, score_new):
70
        self.p_current.evaluate(score_new)
71
72