Passed
Push — master ( 82152a...125377 )
by Simon
04:39
created

Particle.__init__()   A

Complexity

Conditions 1

Size

Total Lines 18
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 16
nop 8
dl 0
loc 18
rs 9.6
c 0
b 0
f 0

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
# Author: Simon Blanke
2
# Email: [email protected]
3
# License: MIT License
4
5
import random
6
import numpy as np
7
from scipy.spatial.transform import Rotation as R
8
9
from ..local_opt import HillClimbingOptimizer
10
11
12
class Particle(HillClimbingOptimizer):
13
    def __init__(
14
        self,
15
        *args,
16
        inertia=0.5,
17
        cognitive_weight=0.5,
18
        social_weight=0.5,
19
        temp_weight=0.2,
20
        rand_rest_p=0.03,
21
        **kwargs
22
    ):
23
        super().__init__(*args, **kwargs)
24
        self.global_pos_best = None
25
26
        self.inertia = inertia
27
        self.cognitive_weight = cognitive_weight
28
        self.social_weight = social_weight
29
        self.temp_weight = temp_weight
30
        self.rand_rest_p = rand_rest_p
31
32
    def _move_part(self, pos, velo):
33
        pos_new = (pos + velo).astype(int)
34
        # limit movement
35
        n_zeros = [0] * len(self.conv.max_positions)
36
37
        return np.clip(pos_new, n_zeros, self.conv.max_positions)
38
39
    @HillClimbingOptimizer.track_new_pos
40
    @HillClimbingOptimizer.random_iteration
41
    def move_linear(self):
42
        r1, r2 = random.random(), random.random()
43
44
        A = self.inertia * self.velo
45
        B = self.cognitive_weight * r1 * np.subtract(self.pos_best, self.pos_current)
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