Passed
Push — master ( 530393...1bac85 )
by Simon
01:30
created

search_path_gif.search_path_gif()   B

Complexity

Conditions 2

Size

Total Lines 58
Code Lines 45

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 45
nop 10
dl 0
loc 58
rs 8.8
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
def warn(*args, **kwargs):
2
    pass
3
4
5
import warnings
6
7
warnings.warn = warn
8
9
import os
10
import gc
11
import glob
12
13
import numpy as np
14
import pandas as pd
15
from tqdm import tqdm
16
17
import matplotlib as mpl
18
import matplotlib.pyplot as plt
19
20
plt.rcParams["figure.facecolor"] = "w"
21
22
mpl.use("agg")
23
24
from gradient_free_optimizers.optimizers.core_optimizer.converter import Converter
25
26
27
def plot_search_paths(
28
    path,
29
    optimizer,
30
    opt_para,
31
    n_iter_max,
32
    objective_function,
33
    search_space,
34
    initialize,
35
    random_state,
36
    title,
37
):
38
    if opt_para == {}:
39
        show_opt_para = False
40
    else:
41
        show_opt_para = True
42
43
    opt = optimizer(
44
        search_space, initialize=initialize, random_state=random_state, **opt_para
45
    )
46
    opt.search(
47
        objective_function,
48
        n_iter=n_iter_max,
49
        # memory=False,
50
        verbosity=False,
51
    )
52
53
    conv = Converter(search_space)
54
    for n_iter in tqdm(range(1, n_iter_max + 1)):
55
56
        def objective_function_np(args):
57
            params = {}
58
            for i, para_name in enumerate(search_space):
59
                params[para_name] = args[i]
60
61
            return objective_function(params)
62
63
        plt.figure(figsize=(7, 7))
64
        plt.set_cmap("jet_r")
65
        # jet_r
66
67
        x_all, y_all = search_space["x0"], search_space["x1"]
68
        xi, yi = np.meshgrid(x_all, y_all)
69
        zi = objective_function_np((xi, yi))
70
71
        zi = np.rot90(zi, k=1)
72
73
        plt.imshow(
74
            zi,
75
            alpha=0.15,
76
            # interpolation="antialiased",
77
            # vmin=z.min(),
78
            # vmax=z.max(),
79
            # origin="lower",
80
            extent=[x_all.min(), x_all.max(), y_all.min(), y_all.max()],
81
        )
82
83
        for n, opt_ in enumerate(opt.optimizers):
84
            n_optimizers = len(opt.optimizers)
85
            n_iter_tmp = int(n_iter / n_optimizers)
86
            n_iter_mod = n_iter % n_optimizers
87
88
            if n_iter_mod > n:
89
                n_iter_tmp += 1
90
            if n_iter_tmp == 0:
91
                continue
92
93
            pos_list = np.array(opt_.pos_new_list)
94
            score_list = np.array(opt_.score_new_list)
95
96
            # print("\n pos_list \n", pos_list, "\n")
97
            # print("\n score_list \n", score_list, "\n")
98
99
            if len(pos_list) == 0:
100
                continue
101
102
            values_list = conv.positions2values(pos_list)
103
            values_list = np.array(values_list)
104
105
            plt.plot(
106
                values_list[:n_iter_tmp, 0],
107
                values_list[:n_iter_tmp, 1],
108
                linestyle="--",
109
                marker=",",
110
                color="black",
111
                alpha=0.33,
112
                label=n,
113
                linewidth=0.5,
114
            )
115
            plt.scatter(
116
                values_list[:n_iter_tmp, 0],
117
                values_list[:n_iter_tmp, 1],
118
                c=score_list[:n_iter_tmp],
119
                marker="H",
120
                s=15,
121
                vmin=np.amin(score_list[:n_iter_tmp]),
122
                vmax=np.amax(score_list[:n_iter_tmp]),
123
                label=n,
124
                edgecolors="black",
125
                linewidth=0.3,
126
            )
127
128
        plt.xlabel("x")
129
        plt.ylabel("y")
130
131
        nth_iteration = "\n\nnth Iteration: " + str(n_iter)
132
        opt_para_name = ""
133
        opt_para_value = "\n\n"
134
135
        if show_opt_para:
136
            opt_para_name += "\n Parameter:"
137
            for para_name, para_value in opt_para.items():
138
                opt_para_name += "\n " + "     " + para_name + ": "
139
                opt_para_value += "\n " + str(para_value) + "                "
140
141
        if title == True:
142
            title_name = opt.name + "\n" + opt_para_name
143
            plt.title(title_name, loc="left")
144
            plt.title(opt_para_value, loc="center")
145
        elif isinstance(title, str):
146
            plt.title(title, loc="left")
147
148
        plt.title(nth_iteration, loc="right", fontsize=8)
149
150
        # plt.xlim((-101, 201))
151
        # plt.ylim((-101, 201))
152
        clb = plt.colorbar()
153
        clb.set_label("score", labelpad=-50, y=1.03, rotation=0)
154
155
        # plt.legend(loc="upper left", bbox_to_anchor=(-0.10, 1.2))
156
157
        # plt.axis("off")
158
159
        if show_opt_para:
160
            plt.subplots_adjust(top=0.75)
161
        plt.tight_layout()
162
163
        # plt.margins(0, 0)
164
        plt.savefig(
165
            path + "/_plots/" + opt._name_ + "_" + "{0:0=3d}".format(n_iter) + ".jpg",
166
            dpi=150,
167
            pad_inches=0,
168
            # bbox_inches="tight",
169
        )
170
171
        plt.ioff()
172
        # Clear the current axes.
173
        plt.cla()
174
        # Clear the current figure.
175
        plt.clf()
176
        # Closes all the figure windows.
177
        plt.close("all")
178
179
        gc.collect()
180
181
182
def search_path_gif(
183
    path,
184
    optimizer,
185
    opt_para,
186
    name,
187
    n_iter,
188
    objective_function,
189
    search_space,
190
    initialize,
191
    random_state=0,
192
    title=True,
193
):
194
    path = os.path.join(os.getcwd(), path)
195
196
    print("\n\nname", name)
197
    plots_dir = path + "/_plots/"
198
    print("plots_dir", plots_dir)
199
    os.makedirs(plots_dir, exist_ok=True)
200
201
    plot_search_paths(
202
        path=path,
203
        optimizer=optimizer,
204
        opt_para=opt_para,
205
        n_iter_max=n_iter,
206
        objective_function=objective_function,
207
        search_space=search_space,
208
        initialize=initialize,
209
        random_state=random_state,
210
        title=title,
211
    )
212
213
    ### ffmpeg
214
    framerate = str(n_iter / 10)
215
    # framerate = str(10)
216
    _framerate = " -framerate " + framerate + " "
217
218
    _opt_ = optimizer(search_space)
219
    _input = " -i " + path + "/_plots/" + str(_opt_._name_) + "_" + "%03d.jpg "
220
    _scale = " -vf scale=1200:-1:flags=lanczos "
221
    _output = os.path.join(path, name)
222
223
    ffmpeg_command = (
224
        "ffmpeg -hide_banner -loglevel error -y"
225
        + _framerate
226
        + _input
227
        + _scale
228
        + _output
229
    )
230
    print("\n -----> ffmpeg_command \n", ffmpeg_command, "\n")
231
    print("create " + name)
232
233
    os.system(ffmpeg_command)
234
235
    ### remove _plots
236
    rm_files = glob.glob(path + "/_plots/*.jpg")
237
    for f in rm_files:
238
        os.remove(f)
239
    os.rmdir(plots_dir)
240