Completed
Push — master ( ce1e03...f67568 )
by Simon
14:21
created

Particle.move_part()   A

Complexity

Conditions 1

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 1
nop 3
1
# Author: Simon Blanke
2
# Email: [email protected]
3
# License: MIT License
4
5
6
import random
7
8
import numpy as np
9
10
from ...base_optimizer import BaseOptimizer
11
from ...base_positioner import BasePositioner
12
13
14
class ParticleSwarmOptimizer(BaseOptimizer):
15
    def __init__(self, _opt_args_):
16
        super().__init__(_opt_args_)
17
        self.n_positioners = self._opt_args_.n_particles
18
19
    def _init_particle(self, _cand_):
20
        _p_ = Particle()
21
        _p_.pos_new = _cand_._space_.get_random_pos()
22
        _p_.velo = np.zeros(len(_cand_._space_.search_space))
23
24
        self._optimizer_eval(_cand_, _p_)
25
        self._update_pos(_cand_, _p_)
26
27
        return _p_
28
29
    def _move_positioner(self, _cand_, _p_):
30
        r1, r2 = random.random(), random.random()
31
32
        A = self._opt_args_.inertia * _p_.velo
33
        B = (
34
            self._opt_args_.cognitive_weight
35
            * r1
36
            * np.subtract(_p_.pos_best, _p_.pos_new)
37
        )
38
        C = (
39
            self._opt_args_.social_weight
40
            * r2
41
            * np.subtract(_cand_.pos_best, _p_.pos_new)
42
        )
43
44
        new_velocity = A + B + C
45
46
        _p_.velo = new_velocity
47
        _p_.move_part(_cand_, _p_.pos_new)
48
49
    def _iterate(self, i, _cand_):
50
        _p_current = self.p_list[i % self.n_positioners]
51
        self._move_positioner(_cand_, _p_current)
52
53
        self._optimizer_eval(_cand_, _p_current)
54
        self._update_pos(_cand_, _p_current)
55
56
        return _cand_
57
58
    def _init_iteration(self, _cand_):
59
        p = self._init_particle(_cand_)
60
61
        self._optimizer_eval(_cand_, p)
62
        self._update_pos(_cand_, p)
63
64
        return p
65
66
67
class Particle(BasePositioner):
68
    def __init__(self):
69
        super().__init__(self)
70
        self.velo = None
71
72
    def move_part(self, _cand_, pos):
73
        pos_new = (pos + self.velo).astype(int)
74
        # limit movement
75
        n_zeros = [0] * len(_cand_._space_.dim)
76
        self.pos_new = np.clip(pos_new, n_zeros, _cand_._space_.dim)
77