Passed
Push — master ( 13200e...4b50d2 )
by Simon
04:24
created

create_search_path_gifs.plot_search_paths()   B

Complexity

Conditions 3

Size

Total Lines 95
Code Lines 70

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 70
nop 9
dl 0
loc 95
rs 7.9818
c 0
b 0
f 0

How to fix   Long Method    Many Parameters   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
import os
2
import glob
3
4
import numpy as np
5
import pandas as pd
6
from tqdm import tqdm
7
import matplotlib.pyplot as plt
8
9
from gradient_free_optimizers.converter import Converter
10
11
12
def plot_search_paths(
13
    opt_name,
14
    optimizer,
15
    opt_para,
16
    n_iter_list,
17
    objective_function,
18
    objective_function_np,
19
    search_space,
20
    initialize,
21
    random_state,
22
):
23
    for n_iter in tqdm(n_iter_list):
24
        opt = optimizer(search_space, **opt_para)
25
26
        opt.search(
27
            objective_function,
28
            n_iter=n_iter,
29
            random_state=random_state,
30
            memory=False,
31
            verbosity=False,
32
            initialize=initialize,
33
        )
34
35
        conv = Converter(search_space)
36
37
        plt.figure(figsize=(10, 8))
38
        plt.set_cmap("jet_r")
39
40
        x_all, y_all = search_space["x"], search_space["y"]
41
        xi, yi = np.meshgrid(x_all, y_all)
42
        zi = objective_function_np(xi, yi)
43
44
        plt.imshow(
45
            zi,
46
            alpha=0.15,
47
            # vmin=z.min(),
48
            # vmax=z.max(),
49
            # origin="lower",
50
            extent=[x_all.min(), x_all.max(), y_all.min(), y_all.max()],
51
        )
52
53
        # print("\n Results \n", opt.results)
54
55
        for n, opt_ in enumerate(opt.optimizers):
56
            pos_list = np.array(opt_.pos_new_list)
57
            score_list = np.array(opt_.score_new_list)
58
59
            values_list = conv.positions2values(pos_list)
60
            values_list = np.array(values_list)
61
62
            plt.plot(
63
                values_list[:, 0],
64
                values_list[:, 1],
65
                linestyle="--",
66
                marker=",",
67
                color="black",
68
                alpha=0.33,
69
                label=n,
70
                linewidth=0.5,
71
            )
72
            plt.scatter(
73
                values_list[:, 0],
74
                values_list[:, 1],
75
                c=score_list,
76
                marker="H",
77
                s=15,
78
                vmin=-20000,
79
                vmax=0,
80
                label=n,
81
                edgecolors="black",
82
                linewidth=0.3,
83
            )
84
85
        plt.xlabel("x")
86
        plt.ylabel("y")
87
88
        nth_iteration = "\n\nnth Iteration: " + str(n_iter)
89
90
        plt.title(opt_name + nth_iteration)
91
92
        plt.xlim((-101, 101))
93
        plt.ylim((-101, 101))
94
        plt.colorbar()
95
        # plt.legend(loc="upper left", bbox_to_anchor=(-0.10, 1.2))
96
97
        plt.tight_layout()
98
        plt.savefig(
99
            "./_plots/"
100
            + str(opt.__class__.__name__)
101
            + "_"
102
            + "{0:0=3d}".format(n_iter)
103
            + ".jpg",
104
            dpi=300,
105
        )
106
        plt.close()
107
108
109
def create_search_path_gif(
110
    opt_name,
111
    optimizer,
112
    opt_para,
113
    n_iter,
114
    objective_function,
115
    objective_function_np,
116
    search_space,
117
):
118
    pass
119
120
121
########################################################################
122
123
124
from gradient_free_optimizers import HillClimbingOptimizer
125
126
optimizer_keys = ["HillClimbingOptimizer"]
127
n_iter_list = range(1, 51)
128
129
130
def get_path(optimizer_key, nth_iteration):
131
    return (
132
        "./_plots/"
133
        + str(optimizer_key)
134
        + "_"
135
        + "{0:0=2d}".format(nth_iteration)
136
        + ".jpg"
137
    )
138
139
140
def objective_function(pos_new):
141
    score = -(pos_new["x"] * pos_new["x"] + pos_new["y"] * pos_new["y"])
142
    return score
143
144
145
def objective_function_np(x1, x2):
146
    score = -(x1 * x1 + x2 * x2)
147
    return score
148
149
150
search_space = {"x": np.arange(-100, 101, 1), "y": np.arange(-100, 101, 1)}
151
152
n_iter_list = range(1, 3)
153
opt_para = {}
154
initialize = {"vertices": 2}
155
random_state = 0
156
157
para_dict = (
158
    "hill_climbing.gif",
159
    {
160
        "opt_name": "Hill climbing",
161
        "optimizer": HillClimbingOptimizer,
162
        "opt_para": opt_para,
163
        "n_iter_list": n_iter_list,
164
        "objective_function": objective_function,
165
        "objective_function_np": objective_function_np,
166
        "search_space": search_space,
167
        "initialize": initialize,
168
        "random_state": random_state,
169
    },
170
)
171
172
173
for _para_dict in tqdm([para_dict]):
174
    plot_search_paths(**_para_dict[1])
175
176
    _framerate = " -framerate 3 "
177
    _input = " -i ./_plots/HillClimbingOptimizer_%03d.jpg "
178
    _scale = " -vf scale=1200:-1 "
179
    _output = " ./_gifs/" + _para_dict[0]
180
181
    ffmpeg_command = "ffmpeg -y" + _framerate + _input + _scale + _output
182
    print("\n\n -----> ffmpeg_command \n", ffmpeg_command, "\n\n")
183
    print(_para_dict[0])
184
185
    os.system(ffmpeg_command)
186
187
    rm_files = glob.glob("./_plots/*.jpg")
188
189
    for f in rm_files:
190
        os.remove(f)
191
192