-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbenchmarks.py
134 lines (100 loc) · 3.46 KB
/
benchmarks.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
"""
Particle Swarm Optimization applied to 3D test functions for unconstrained non-convex optimization algorithms.
"""
import numpy as np
from matplotlib import pyplot as plt
from swarm import Swarm
from utils import TEXT, ANIMATION, get_out_mode, gen_data, animate, save
def rastrigin(x, y):
"""
Rastrigin function R^2 -> R.
Global minimum = 0 = f(0, 0).
Single global minimum, lots of local minima around it.
"""
return x ** 2 - 10 * np.cos(2 * np.pi * x) + y ** 2 - 10 * np.cos(2 * np.pi * y) + 20
def rosenbrock(x, y):
"""
Rosenbrock function R^2 -> R.
Global minimum = 0 = f(1, 1).
The global minimum is inside a long, narrow, parabolic-shaped flat valley.
Finding the valley is trivial; converging to the global minimum, however, is not.
"""
return (1 - x) ** 2 + 100 * (y - x ** 2) ** 2
INFO = { # function parameters for the animation
rastrigin: {
"min_point": (0, 0),
"plot_3d": "contour",
"levels": 5,
"x_min": -5,
"x_max": 5,
"y_min": -5,
"y_max": 5,
"elevation": 30,
"azimuth": -60,
"fps": 20
},
rosenbrock: {
"min_point": (1, 1),
"plot_3d": "surface",
"levels": 50,
"x_min": -1.5,
"x_max": 2,
"y_min": -0.5,
"y_max": 3,
"elevation": 20,
"azimuth": -140,
"fps": 20
}
}
def plot(f):
"""Plot surface and contour of function ``f``: R^2 -> R."""
fig = plt.figure(f.__name__.capitalize() + " function", figsize=(12, 7))
x = np.arange(INFO[f]["x_min"], INFO[f]["x_max"], .01)
y = np.arange(INFO[f]["y_min"], INFO[f]["y_max"], .01)
x, y = np.meshgrid(x, y)
z = f(x, y)
ax1 = plt.subplot(121, projection="3d")
ax1.set_title("Surface")
if INFO[f]["plot_3d"] == "contour":
ax1.contour3D(x, y, z, 100, cmap="viridis")
else:
ax1.plot_surface(x, y, z, cmap="viridis")
ax1.view_init(INFO[f]["elevation"], INFO[f]["azimuth"])
ax2 = plt.subplot(122)
ax2.set_title("Contour")
ax2.set_aspect("equal")
ax2.contour(x, y, z, INFO[f]["levels"])
ax2.plot(INFO[f]["min_point"][0], INFO[f]["min_point"][1], "rx")
return fig, ax1, ax2
def display(f):
"""Display surface and contour of ``f`` without animation."""
plot(f)
plt.show()
def init(f):
"""Initialize animated objects."""
fig, ax1, ax2 = plot(f)
title = ax2.text(INFO[f]["x_min"], INFO[f]["y_max"], "", bbox={"facecolor": "w", "pad": 5}, fontsize=12)
particles, = ax2.plot([], [], "r.")
particles_3d, = ax1.plot([], [], "r.")
return fig, title, particles, particles_3d
def update(data):
"""Perform animation step."""
x, y, z, count = data
particles.set_data(x, y)
particles_3d.set_data(x, y)
particles_3d.set_3d_properties(z)
title.set_text("Epochs: {}".format(count))
return particles, particles_3d, title
if __name__ == "__main__":
out_mode = get_out_mode()
for f in INFO.keys():
print("\n" + f.__name__.capitalize() + " function")
swarm = Swarm([(INFO[f]["x_min"], INFO[f]["x_max"]), (INFO[f]["y_min"], INFO[f]["y_max"])], f, 1e-4)
if out_mode == ANIMATION:
display(f)
fig, title, particles, particles_3d = init(f)
anim = animate(fig, update, lambda: gen_data(swarm), INFO[f]["fps"])
# save(anim, f.__name__, INFO[f]["fps"], ".mp4")
elif out_mode == TEXT:
swarm.minimize()
print()