1
|
|
|
# Author: Simon Blanke |
2
|
|
|
# Email: [email protected] |
3
|
|
|
# License: MIT License |
4
|
|
|
|
5
|
|
|
import random |
6
|
|
|
import numpy as np |
7
|
|
|
|
8
|
|
|
from ..local import HillClimbingOptimizer |
9
|
|
|
|
10
|
|
|
|
11
|
|
|
class Particle(HillClimbingOptimizer): |
12
|
|
|
def __init__( |
13
|
|
|
self, |
14
|
|
|
search_space, |
15
|
|
|
inertia=0.5, |
16
|
|
|
cognitive_weight=0.5, |
17
|
|
|
social_weight=0.5, |
18
|
|
|
temp_weight=0.2, |
19
|
|
|
rand_rest_p=0.03, |
20
|
|
|
): |
21
|
|
|
super().__init__(search_space) |
22
|
|
|
self.global_pos_best = None |
23
|
|
|
|
24
|
|
|
self.inertia = inertia |
25
|
|
|
self.cognitive_weight = cognitive_weight |
26
|
|
|
self.social_weight = social_weight |
27
|
|
|
self.temp_weight = temp_weight |
28
|
|
|
self.rand_rest_p = rand_rest_p |
29
|
|
|
|
30
|
|
|
def _move_part(self, pos, velo): |
31
|
|
|
pos_new = (pos + velo).astype(int) |
32
|
|
|
# limit movement |
33
|
|
|
n_zeros = [0] * len(self.max_positions) |
34
|
|
|
|
35
|
|
|
return np.clip(pos_new, n_zeros, self.max_positions) |
36
|
|
|
|
37
|
|
|
def _move_positioner(self): |
38
|
|
|
r1, r2 = random.random(), random.random() |
39
|
|
|
|
40
|
|
|
A = self.inertia * self.velo |
41
|
|
|
B = ( |
42
|
|
|
self.cognitive_weight |
43
|
|
|
* r1 |
44
|
|
|
* np.subtract(self.pos_best, self.pos_current) |
45
|
|
|
) |
46
|
|
|
C = ( |
47
|
|
|
self.social_weight |
48
|
|
|
* r2 |
49
|
|
|
* np.subtract(self.global_pos_best, self.pos_current) |
50
|
|
|
) |
51
|
|
|
|
52
|
|
|
new_velocity = A + B + C |
53
|
|
|
return self._move_part(self.pos_current, new_velocity) |
54
|
|
|
|
55
|
|
|
@HillClimbingOptimizer.track_nth_iter |
56
|
|
|
@HillClimbingOptimizer.random_restart |
57
|
|
|
def iterate(self): |
58
|
|
|
return self._move_positioner() |
59
|
|
|
|
60
|
|
|
def evaluate(self, score_new): |
61
|
|
|
self.score_new = score_new |
62
|
|
|
|
63
|
|
|
self._evaluate_new2current(score_new) |
64
|
|
|
self._evaluate_current2best() |
65
|
|
|
|