Passed
Push — master ( d39371...69bf6f )
by Simon
03:38
created

gradient_free_optimizers.init_positions   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 23
dl 0
loc 39
rs 10
c 0
b 0
f 0
wmc 5

2 Functions

Rating   Name   Duplication   Size   Complexity  
A init_grid_search() 0 22 3
A init_random_search() 0 7 2
1
# Author: Simon Blanke
2
# Email: [email protected]
3
# License: MIT License
4
5
import numpy as np
6
7
8
def init_grid_search(space_dim, n_pos):
9
    positions = []
10
11
    n_dim = len(space_dim)
12
    p_per_dim = int(np.power(n_pos, 1 / n_dim))
13
14
    for dim in space_dim:
15
        dim_dist = int(dim / (p_per_dim + 1))
16
        n_points = [n * dim_dist for n in range(1, p_per_dim + 1)]
17
18
        positions.append(n_points)
19
20
    pos_mesh = np.array(np.meshgrid(*positions))
21
    positions = list(pos_mesh.T.reshape(-1, n_dim))
22
23
    diff_pos = n_pos - len(positions)
24
    if diff_pos > 0:
25
        pos_rnd = init_random_search(space_dim, n_pos=diff_pos)
26
27
        return positions + pos_rnd
28
29
    return positions
30
31
32
def init_random_search(space_dim, n_pos):
33
    positions = []
34
    for nth_pos in range(n_pos):
35
        pos = np.random.randint(space_dim, size=space_dim.shape)
36
        positions.append(pos)
37
38
    return positions
39