-
Notifications
You must be signed in to change notification settings - Fork 38
/
benchmark.py
251 lines (215 loc) · 8.31 KB
/
benchmark.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
#!/usr/bin/env python
# Created by "Thieu" at 16:47, 28/06/2022 ----------%
# Email: nguyenthieu2102@gmail.com %
# Github: https://github.com/thieu1995 %
# --------------------------------------------------%
import numpy as np
class Benchmark:
"""
Defines an abstract class for optimization benchmark problem.
All subclasses should implement the ``evaluate`` method for a particular optimization problem.
Attributes
----------
bounds : list
The lower/upper bounds of the problem. This a 2D-matrix of [lower, upper] array that contain the lower and upper bounds.
By default, each problem has its own bounds. But user can try to put different bounds to test the problem.
ndim : int
The dimensionality of the problem. It is calculated from bounds
lb : np.ndarray
The lower bounds for the problem
ub : np.ndarray
The upper bounds for the problem
f_global : float
The global optimum of the evaluated function.
x_global : np.ndarray
A list of vectors that provide the locations of the global minimum.
Note that some problems have multiple global minima, not all of which may be listed.
n_fe : int
The number of function evaluations that the object has been asked to calculate.
dim_changeable : bool
Whether we can change the benchmark function `x` variable length (i.e., the dimensionality of the problem)
"""
name = "Benchmark name"
latex_formula = r'f(\mathbf{x})'
latex_formula_dimension = r'd \in \mathbb{N}_{+}^{*}'
latex_formula_bounds = r'x_i \in [-2\pi, 2\pi], \forall i \in \llbracket 1, d\rrbracket'
latex_formula_global_optimum = r'f(0, ..., 0)=-1, \text{ for}, m=5, \beta=15'
continuous = True
linear = False
convex = True
unimodal = False
separable = False
differentiable = True
scalable = True
randomized_term = False
parametric = True
modality = True # Number of ambiguous peaks, unknown # peaks
# n_basins = 1
# n_valleys = 1
def __init__(self):
self._bounds = None
self._ndim = None
self.dim_changeable = False
self.dim_default = 2
self.f_global = None
self.x_global = None
self.n_fe = 0
self.paras = {}
self.epsilon = 1e-8
def check_ndim_and_bounds(self, ndim=None, bounds=None, default_bounds=None):
"""
Check the bounds when initializing the object.
Parameters
----------
ndim : int
The number of dimensions (variables)
bounds : list, tuple, np.ndarray
List of lower bound and upper bound, should use default None value
default_bounds : np.ndarray
List of initial lower bound and upper bound values
"""
if ndim is None:
self._bounds = default_bounds if bounds is None else np.array(bounds).T
self._ndim = self._bounds.shape[1]
else:
if bounds is None:
if self.dim_changeable:
if type(ndim) is int and ndim > 1:
self._ndim = int(ndim)
self._bounds = np.array([default_bounds[0] for _ in range(self._ndim)])
else:
raise ValueError('ndim must be an integer and > 1!')
else:
self._ndim = self.dim_default
self._bounds = default_bounds
print(f"{self.__class__.__name__} is fixed problem with {self.dim_default} variables!")
else:
if self.dim_changeable:
self._bounds = np.array(bounds).T
self._ndim = self._bounds.shape[0]
print(f"{self.__class__.__name__} problem is set with {self._ndim} variables!")
else:
self._bounds = np.array(bounds).T
if self._bounds.shape[0] != self.dim_default:
raise ValueError(f"{self.__class__.__name__} is fixed problem with {self._ndim} variables. Please setup the correct bounds!")
else:
self._ndim = self.dim_default
def check_solution(self, x):
"""
Raise the error if the problem size is not equal to the solution length
Parameters
----------
x : np.ndarray
The solution
"""
if not self.dim_changeable and (len(x) != self._ndim):
raise ValueError(f"The length of solution should have {self._ndim} variables!")
def get_paras(self):
"""
Return the parameters of the problem. Depended on function
"""
default = {"bounds": self._bounds, "ndim": self._ndim, }
return {**default, **self.paras}
def evaluate(self, x):
"""
Evaluation of the benchmark function.
Parameters
----------
x : np.ndarray
The candidate vector for evaluating the benchmark problem. Must have ``len(x) == self.ndim``.
Returns
-------
val : float
the evaluated benchmark function
"""
raise NotImplementedError
def is_ndim_compatible(self, ndim):
"""
Method to support searching the functions with input ndim
Parameters
----------
ndim : int
The number of dimensions
Returns
-------
val: bool
Always true if dim_changeable = True, Else return ndim == self.ndim
"""
assert (ndim is None) or (isinstance(ndim, int) and (not ndim < 0)), "The dimension ndim must be None or a positive integer"
if ndim is None:
return True
else:
if self.dim_changeable:
return ndim > 0
else:
return ndim == self.ndim
def is_succeed(self, x, tol=1.e-5):
"""
Check if a candidate solution at the global minimum.
Parameters
----------
x : np.ndarray
The candidate vector for testing if the global minimum has been reached. Must have ``len(x) == self.ndim``
tol : float
The evaluated function and known global minimum must differ by less than this amount to be at a global minimum.
Returns
-------
is_succeed : bool
Answer the question: is the candidate vector at the global minimum?
"""
# the solution should still be in bounds, otherwise immediate fail.
if np.any(x > self.ub) or np.any(x < self.lb):
return False
val = self.evaluate(np.squeeze(x))
if np.abs(val - self.f_global) < tol:
return True
# you found a lower global minimum. This shouldn't happen.
if val < self.f_global:
raise ValueError("Found a lower global minimum", x, val, self.f_global)
return False
@property
def bounds(self):
"""
The lower/upper bounds to be used for optimization problem. This a 2D-matrix of [lower, upper] array that contain the lower and upper
bounds for the problem. The problem should not be asked for evaluation outside these bounds. ``len(bounds) == ndim``.
"""
return self._bounds
@property
def ndim(self):
"""
The dimensionality of the problem.
Returns
-------
ndim : int
The dimensionality of the problem
"""
return self._ndim
@property
def lb(self):
"""
The lower bounds for the problem
Returns
-------
lb : 1D-vector
The lower bounds for the problem
"""
return np.array([x[0] for x in self.bounds])
@property
def ub(self):
"""
The upper bounds for the problem
Returns
-------
ub : 1D-vector
The upper bounds for the problem
"""
return np.array([x[1] for x in self.bounds])
def create_solution(self):
"""
Create a random solution for the current problem
Returns
-------
solution: 1D-vector
The random solution
"""
return np.random.uniform(self.lb, self.ub)