-
Notifications
You must be signed in to change notification settings - Fork 0
/
plot2d-opt.py
executable file
·341 lines (297 loc) · 9.33 KB
/
plot2d-opt.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
#!/usr/bin/env python3
"""
Create visualizations of optimization algorithms solutions in 2d.
"""
import json
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
#
# Test Functions
#
def rosenbrock(x):
"""
rosenbrock evaluates Rosenbrock function at vector x
Parameters
----------
x : array
x is a D-dimensional vector, [x1, x2, ..., xD]
Returns
-------
float
scalar result
"""
D = len(x)
i, iplus1 = np.arange(0,D-1), np.arange(1,D)
return np.sum(100*(x[iplus1] - x[i]**2)**2 + (1-x[i])**2)
def goldstein_price(x):
"""
goldstein_price evaluates Goldstein-Price function at vector x
Parameters
----------
x : array
x is a 2-dimensional vector, [x1, x2]
Returns
-------
float
scalar result
"""
a = (x[0] + x[1] + 1)**2
b = 19 - 14*x[0] + 3*x[0]**2 - 14*x[1] + 6*x[0]*x[1] + 3*x[1]**2
c = (2*x[0] - 3*x[1])**2
d = 18 - 32*x[0] + 12*x[0]**2 + 48*x[1] - 36*x[0]*x[1] + 27*x[1]**2
return (1. + a*b) * (30. + c*d)
def bartels_conn(x):
"""
bartels_conn evaluates Bartels-Conn function at vector x
Parameters
----------
x : array
x is a 2-dimensional vector, [x1, x2]
Returns
-------
float
scalar result
"""
a = np.abs(x[0]**2 + x[1]**2 + x[0]*x[1])
b = np.abs(np.sin(x[0]))
c = np.abs(np.cos(x[1]))
return a + b +c
def egg_crate(x):
"""
egg_crate evaluates Egg Crate function at vector x
Parameters
----------
x : array
x is a 2-dimensional vector, [x1, x2]
Returns
-------
float
scalar result
"""
return x[0]**2 + x[1]**2 + 25.*(np.sin(x[0])**2 + np.sin(x[1])**2)
#
# Surface Generation
#
def surface(fx, start=-30, stop=30, num=60):
"""
surface evaluates fx at regularly spaced grid of points
Parameters
----------
fx : func
fx is a vector valued function that returns a scalar result
start : float
lower bound of the coordinate grid
stop : float
upper bound of the coordinate grid
num : int
number of points along one dimension of the grid
Returns
-------
array
2D array formed by evaluating fx at each grid point
"""
x = np.linspace(start=start, stop=stop, num=num)
x1, x2 = np.meshgrid(x, x, indexing='ij')
X = np.vstack((x1.ravel(), x2.ravel()))
z = np.apply_along_axis(fx, 0, X).reshape(num,num)
return x1, x2, z
#
# Solution Results
#
def load_steps(**params):
"""Return solution steps based on simulation properties."""
savefn = os.path.join(params['base_dirn'],
params['savefn_fmt'].format(**params))
return np.load(savefn)
def load_meta(**params):
"""Return metafile based on simulation properties."""
metafn = os.path.join(params['base_dirn'],
params['metafn_fmt'].format(**params))
return json.load(open(metafn, 'r'))
def plot2d_solutions(**params):
"""
plot2d_solutions creates 2d solution plot from simulation results
"""
algstr = params['alg'].replace('_',' ').title()
funcstr = params['func'].replace('_',' ').title()
ngridpts = params.get('ngridpts', 500)
bounds = params['bounds']
trial = params['trial'] # Single trial only.
xkmind = params.get('xkmind', slice(2))
color = params.get('color', 'darkorange')
ticker_locator = params.get('ticker_locator', 'LinearLocator')
colorbar_label = params.get('colorbar_label', 'z')
show_legend = params.get('show_legend', True)
# Imbue title with simulation meta information.
meta = load_meta(**params)
expmin, expxkmin = meta['exp_fxkmin'], meta['exp_xkmin']
expminstr = 'abs $\\min(f)$={0:.0f}'.format(expmin)
algstr = algstr if len(algstr) > 4 else algstr.upper()
algmeta = [('nx0','n'),('T0','$T_0$'),
('alpha','$\\alpha$'),('tol','tol')]
algmetastr = ' '.join(['{0}={1}'.format(n2, meta[n1])
for n1, n2 in algmeta if n1 in meta])
nitstr = 'nit={0:d}'.format(meta['nsteps'][trial-1])
minfx = meta['f(xk)'][trial-1]
minfmt = '.2e' if minfx < 1e-1 else '.1f'
minstr = '$\\min(f)$={0:{1}}'.format(minfx, minfmt)
metastrs = [algstr, minstr, nitstr, algmetastr]
titlestr = ' '.join([s for s in metastrs if len(s) > 0])
suptitlestr = 'Solution Trajectories: {0} Function'.format(funcstr)
# Generate surface for filled contour plot.
fx = globals()[params['func']]
start, stop = np.min(bounds[::2]), np.max(bounds[1::2])
x1, x2, z = surface(fx, start, stop, ngridpts)
fig = plt.figure(figsize=(8,6))
# Plot 2d filled contour.
locator = getattr(ticker, ticker_locator)
cs = plt.contourf(x1, x2, z, locator=locator(), cmap='viridis_r',
alpha=0.7)
# Plot expected minimum.
plt.scatter(expxkmin[0], expxkmin[1], marker='D', c='red', s=30,
label=expminstr)
# Plot initial point.
x0 = np.array(meta['x0'][trial-1]).reshape(-1,2)
plt.scatter(x0[:,0], x0[:,1], marker='X', c='dodgerblue', s=30,
label='$x_0$')
# Plot solution trajectory.
steps = load_steps(**params)
nx0 = meta.get('nx0', 1) # Multiple particles?
xks = steps[:,xkmind]
xks = np.clip(xks, a_min=bounds[::2], a_max=bounds[1::2])
nxks = 0 if np.isnan(xks).any() else len(xks)//nx0
for p in range(nx0):
p0, pN, pstep = p, nxks, nx0
plt.plot(xks[p0:pN:pstep,0], xks[p0:pN:pstep,1],
marker='.', ms=5, markevery=0.25,
ls='-', lw=1, c=color,
label='$x_k$, trial={:d}'.format(trial))
plt.suptitle(suptitlestr)
plt.title(titlestr)
plt.xlabel('x1')
plt.xlim(bounds[:2])
plt.ylabel('x2')
plt.ylim(bounds[2:])
plt.colorbar(cs, label=colorbar_label)
if show_legend:
plt.legend()
if params.get('plot2dfn_fmt') is not None:
imgn = params['plot2dfn_fmt'].format(**params)
plotfn = os.path.join(params['base_dirn'], imgn)
plt.savefig(plotfn)
else:
plt.show()
plt.close(fig)
#
# Solution Plots
#
def plot2d(**kwargs):
"""Plot simulation results in 2d."""
params = [
{
'alg': 'gradient_descent',
'func': 'rosenbrock',
'bounds': [-2.,2.,-2.,2.],
'ticker_locator': 'LogLocator',
'colorbar_label': 'log(z)',
},
{
'alg': 'bfgs',
'func': 'rosenbrock',
'bounds': [-2.,2.,-2.,2.],
'ticker_locator': 'LogLocator',
'colorbar_label': 'log(z)',
},
{
'alg': 'simulated_annealing',
'func': 'rosenbrock',
'bounds': [-2.,2.,-2.,2.],
'xkmind': slice(3,5),
'ticker_locator': 'LogLocator',
'colorbar_label': 'log(z)',
},
{
'alg': 'particle_swarm',
'func': 'rosenbrock',
'bounds': [-2.,2.,-2.,2.],
'xkmind': slice(4,6),
'ticker_locator': 'LogLocator',
'colorbar_label': 'log(z)',
'color': None,
},
{
'alg': 'gradient_descent',
'func': 'goldstein_price',
'bounds': [-2.,2.,-2.,2.],
'ticker_locator': 'LogLocator',
'colorbar_label': 'log(z)',
},
{
'alg': 'bfgs',
'func': 'goldstein_price',
'bounds': [-2.,2.,-2.,2.],
'ticker_locator': 'LogLocator',
'colorbar_label': 'log(z)',
},
{
'alg': 'simulated_annealing',
'func': 'goldstein_price',
'bounds': [-2.,2.,-2.,2.],
'xkmind': slice(3,5),
'ticker_locator': 'LogLocator',
'colorbar_label': 'log(z)',
},
{
'alg': 'particle_swarm',
'func': 'goldstein_price',
'bounds': [-2.,2.,-2.,2.],
'xkmind': slice(4,6),
'ticker_locator': 'LogLocator',
'colorbar_label': 'log(z)',
'color': None,
},
{
'alg': 'simulated_annealing',
'func': 'bartels_conn',
'bounds': [-5.,5.,-5.,5.],
'xkmind': slice(3,5),
},
{
'alg': 'particle_swarm',
'func': 'bartels_conn',
'bounds': [-5.,5.,-5.,5.],
'xkmind': slice(4,6),
'color': None,
},
{
'alg': 'simulated_annealing',
'func': 'egg_crate',
'bounds': [-5.,5.,-5.,5.],
'xkmind': slice(3,5),
},
{
'alg': 'particle_swarm',
'func': 'egg_crate',
'bounds': [-5.,5.,-5.,5.],
'xkmind': slice(4,6),
'color': None,
}
]
# One set of parameters for each algo-func combination.
for param in params:
param.update(kwargs)
# Create one-plot-per-trial.
for trial in range(1,param['ntrials']+1):
param.update(trial=trial)
plot2d_solutions(**param)
if __name__ == '__main__':
opts = {
'ntrials': 12,
'base_dirn': './sims/',
'savefn_fmt': '{alg}-{func}-steps-{trial:02d}.npy',
'metafn_fmt': '{alg}-{func}-meta.json',
'plot2dfn_fmt': '{alg}-{func}-plot2d-{trial:02d}.png',
}
plot2d(**opts)