Skip to content

Mono

This module provides mono-objective optimization test functions for evolutionary experiments.

Example

from metazoo.gym.mono import Function

available = Function().available_functions
print(available)

#['Rastrigin', 'Ackley', 'Sphere', 'Rosenbrock', 'Beale', 'GoldsteinPrice', 'Booth', 'Bukin', 'Matyas', 'Levi_N13', 'Griewank', 'Himmelblau', 'ThreeHumpCamel', 'Easom', 'Cross_In_Tray', 'EggHolder', 'HolderTable', 'McCormick', 'Schaffer_N2', 'StyblinskiTang', 'Shekel']

fitness_function = Function('Ackley', reverse=False)
print(fitness_function.bounds)

# [(-5, 5), (-5, 5)]

fitness_function.plot(bounds=fitness_function.bounds, dim=2, num_points=100, mode='surface')
fitness_function.plot(bounds=fitness_function.bounds, dim=2, num_points=100, mode='contour')

Reference

Class: Function

A class representing a mathematical function for optimization testing.

Source code in metazoo/src/metazoo/gym/mono.py
  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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
class Function:
    """
    A class representing a mathematical function for optimization testing.
    """

    def __init__(self, name: str = 'Ackley', reverse: bool = False):
        self.__name__ = name
        self.reverse = reverse
        self.metadata = {

            'Rastrigin': {
                'formula': r'f(\mathbf{x}) = 10n + \sum_{i=1}^n \left[x_i^2 - 10 \cos(2\pi x_i)\right]',
                'bounds': [(-5.12, 5.12), (-5.12, 5.12)]
            },
            'Ackley': {
                'formula': r'f(\mathbf{x}) = -20 \exp\left(-0.2 \sqrt{\frac{1}{n} \sum_{i=1}^n x_i^2}\right) - \exp\left(\frac{1}{n} \sum_{i=1}^n \cos(2\pi x_i)\right) + 20 + e',
                'bounds': [(-5, 5), (-5, 5)]
            },
            'Sphere': {
                'formula': r'f(\mathbf{x}) = \sum_{i=1}^n x_i^2',
                'bounds': [(-5.12, 5.12),(-5.12, 5.12)]
            },
            'Rosenbrock': {
                'formula': r'f(x_1, x_2) = (1 - x_1)^2 + 100 (x_2 - x_1^2)^2',
                'bounds': [(-2, 2), (-1, 3)]
            },
            'Beale': {
                'formula': r'f(x_1, x_2) = (1.5 - x_1 + x_1 x_2)^2 + (2.25 - x_1 + x_1 x_2^2)^2 + (2.625 - x_1 + x_1 x_2^3)^2',
                'bounds': [(-4.5, 4.5), (-4.5, 4.5)]
            },
            'GoldsteinPrice': {
                'formula': r'f(x_1, x_2) = (1 + \frac{(x_1 + x_2 + 1)^2}{(x_1 + x_2)^2}) (19 - 14x_1 + 3x_1^2 - 14x_2 + 6x_1x_2)',
                'bounds': [(-2, 2), (-2, 2)]
            },
            'Booth': {
                'formula': r'f(x_1, x_2) = (x_1 + 2x_2 - 7)^2 + (2x_1 + x_2 - 5)^2',
                'bounds': [(-10, 10), (-10, 10)]
            },

            'Bukin': {
                'formula': r'f(x_1, x_2) = 100 \sqrt{|x_2 - 0.01 x_1^2|} + 0.01 |x_1 + 10|',
                'bounds': [(-15, -5), (-3, 3)]
            },
            'Matyas': {
                'formula': r'f(x_1, x_2) = 0.26(x_1^2 + x_2^2) - 0.48x_1x_2',
                'bounds': [(-10, 10), (-10, 10)]
            },
            'Levi_N13': {
                'formula': r'f(x_1, x_2) = \sin(3\pi x_1)^2 + (x_1 - 1)^2(1 + \sin(3\pi x_2)^2) + (x_2 - 1)^2(1 + \sin(2\pi x_2)^2)',
                'bounds': [(-10, 10), (-10, 10)]
            },
            'Griewank': {
                'formula': r'f(\mathbf{x}) = 1 + \frac{1}{4000} \sum_{i=1}^n x_i^2 - \prod_{i=1}^n \cos\left(\frac{x_i}{\sqrt{i}}\right)',
                'bounds': [(-600, 600), (-600, 600)]
            },
            'Himmelblau': {
                'formula': r'f(x_1, x_2) = (x_1^2 + x_2 - 11)^2 + (x_1 + x_2^2 - 7)^2',
                'bounds': [(-5, 5), (-5, 5)]
            },
            'ThreeHumpCamel': {
                'formula': r'f(x_1, x_2) = 2x_1^2 - 1.05x_1^4 + \frac{x_1^6}{6} + x_1x_2 + x_2^2',
                'bounds': [(-5, 5), (-5, 5)]
            },
            'Easom': {
                'formula': r'f(x_1, x_2) = -\cos(x_1) \cos(x_2) \exp\left(-\left(x_1 - \pi\right)^2 - \left(x_2 - \pi\right)^2\right)',
                'bounds': [(-100, 100), (-100, 100)]
            },
            'Cross_In_Tray': {
                'formula': r'f(x_1, x_2)=-0.0001\left[\left|\sin x_1\sin x_2\exp \left(\left|100-{\frac {\sqrt {x_1^{2}+x_2^{2}}}{\pi }}\right|\right)\right|+1\right]^{0.1}',
                'bounds': [(-10, 10), (-10, 10)]
            },
            'EggHolder': {
                'formula': r'f(x_1, x_2) = -(x_2 + 47) \sin\left(\sqrt{|x_1/2 + (x_2 + 47)|}\right) - x_1 \sin\left(\sqrt{|x_1 - (x_2 + 47)|}\right)',
                'bounds': [(-512, 512), (-512, 512)]
            },
            'HolderTable': {
                'formula': r'f(x_1, x_2) = -\sin(x_1) \cos(x_2) \exp\left(-\left(x_1 + x_2\right)^2\right)',
                'bounds': [(-10, 10), (-10, 10)]
            },
            'McCormick': {
                'formula': r'f(x_1, x_2) = \sin(x_1 + x_2) + (x_1 - x_2)^2 - 1.5x_1 + 2.5x_2 + 1',
                'bounds': [(-1.5, 4), (-3, 4)]
            },
            'Schaffer_N2': {
                'formula': r'f(x_1, x_2) = 0.5 + \frac{\sin^2(x_1^2 - x_2^2)}{1 + 0.001(x_1^2 + x_2^2)}',
                'bounds': [(-100, 100), (-100, 100)]
            },
            'StyblinskiTang': {
                'formula': r'f(x_1, x_2) = \sum_{i=1}^n \left[x_i^3 - 5x_i\right]',
                'bounds': [(-5, 5), (-5, 5)]
            },
            'Shekel': {
                'formula': r'f(x_1, x_2) = \left(1 - \frac{x_1}{\sqrt{1 + x_2^2}}\right)^2 + \left(1 - \frac{x_2}{\sqrt{1 + x_1^2}}\right)^2',
                'bounds': [(-100, 100), (-100, 100)]
            }
        }

        self.bounds = self.metadata.get(name, {}).get('bounds', [])
        self.available_functions = list(self.metadata.keys())
        if name not in self.available_functions:
            raise ValueError(f"The function '{name}' is not available. Options: {self.available_functions}")

    def formula(self):
        """ 
        Displays the LaTeX formula of the function if available.
        """
        formula = self.metadata.get(self.__name__, None)
        if formula:
            return formula['formula']
        else:
            return "No LaTeX formula available for this function."

    def __call__(self, X: np.ndarray) -> float:
        """
        Evaluates the function at a given point X.
        """
        value = getattr(self, self.__name__)(X)
        if self.reverse:
            return -value
        return value

    @staticmethod
    def Rastrigin(X: np.ndarray) -> float:
        """
        Rastrigin Function
        Wiki: https://en.wikipedia.org/wiki/Rastrigin_function
        """
        n = len(X)
        A = 10
        return A * n + np.sum(X**2 - A * np.cos(2 * np.pi * X))

    @staticmethod
    def Ackley(X: np.ndarray) -> float:
        """
        Ackley
        Wiki: https://en.wikipedia.org/wiki/Ackley_function
        """
        n = len(X)
        square_sum = (1 / n) * np.sum(X * X)
        trigonometric_sum = (1 / n) * np.sum(np.cos(2 * np.pi * X))
        return -20 * np.exp(-0.2 * np.sqrt(square_sum)) - np.exp(trigonometric_sum) + 20 + np.e

    @staticmethod
    def Sphere(X: np.ndarray) -> float:
        """
        Sphere
        """
        return np.sum(X * X)

    @staticmethod
    def Rosenbrock(X: np.ndarray) -> float:
        """
        Rosenbrock
        Wiki: https://en.wikipedia.org/wiki/Rosenbrock_function
        """
        if len(X) != 2:
            raise ValueError("Rosenbrock function is only defined for 2D inputs.")
        x1, x2 = X
        return (1 - x1)**2 + 100 * (x2 - x1**2)**2

    @staticmethod
    def Beale(X: np.ndarray) -> float:
        """
        Beale
        Wiki: https://en.wikipedia.org/wiki/Beale_function
        """
        if len(X) != 2:
            raise ValueError("Beale function is only defined for 2D inputs.")
        x1, x2 = X
        return (1.5 - x1 + x1 * x2)**2 + (2.25 - x1 + x1 * x2**2)**2 + (2.625 - x1 + x1 * x2**3)**2

    @staticmethod
    def GoldsteinPrice(X: np.ndarray) -> float:
        """
        Goldstein-Price
        """
        if len(X) != 2:
            raise ValueError("Goldstein-Price function is only defined for 2D inputs.")
        x1, x2 = X
        term1 = 1 + ((x1 + x2 + 1)**2) * (19 - 14 * x1 + 3 * x1**2 - 14 * x2 + 6 * x1 * x2)
        term2 = (x1 + x2)**2
        if term2 == 0:
            return np.inf
        return term1 / term2

    @staticmethod
    def Booth(X: np.ndarray) -> float:
        """
        Booth
        """
        if len(X) != 2:
            raise ValueError("Booth function is only defined for 2D inputs.")
        x1, x2 = X
        return (x1 + 2 * x2 - 7)**2 + (2 * x1 + x2 - 5)**2

    @staticmethod
    def Bukin(X: np.ndarray) -> float:
        """
        Bukin
        """
        if len(X) != 2:
            raise ValueError("Bukin function is only defined for 2D inputs.")
        x1, x2 = X
        return 100 * np.sqrt(np.abs(x2 - 0.01 * x1**2)) + 0.01 * np.abs(x1 + 10)

    @staticmethod
    def Matyas(X: np.ndarray) -> float:
        """
        Matyas
        """
        if len(X) != 2:
            raise ValueError("Matyas function is only defined for 2D inputs.")
        x1, x2 = X
        return 0.26 * (x1**2 + x2**2) - 0.48 * x1 * x2

    @staticmethod
    def Levi_N13(X: np.ndarray) -> float:
        """
        Levi N.13
        """
        if len(X) != 2:
            raise ValueError("Levi N.13 function is only defined for 2D inputs.")
        x1, x2 = X
        return np.sin(x1 + x2)**2 + (x1 - x2)**2

    @staticmethod
    def Griewank(X: np.ndarray) -> float:
        """
        Griewank
        """
        if len(X) != 2:
            raise ValueError("Griewank function is only defined for 2D inputs.")
        x1, x2 = X
        return 1 + (x1**2 + x2**2) / 4000 - np.cos(x1 / np.sqrt(1)) * np.cos(x2 / np.sqrt(2))

    @staticmethod
    def Himmelblau(X: np.ndarray) -> float:
        """
        Himmelblau
        """
        if len(X) != 2:
            raise ValueError("Himmelblau function is only defined for 2D inputs.")
        x1, x2 = X
        return (x1**2 + x2 - 11)**2 + (x1 + x2**2 - 7)**2

    @staticmethod
    def ThreeHumpCamel(X: np.ndarray) -> float:
        """
        Three Hump Camel
        """
        if len(X) != 2:
            raise ValueError("Three Hump Camel function is only defined for 2D inputs.")
        x1, x2 = X
        return 2 * x1**2 - 1.05 * x1**4 + (x1**6) / 6 + x1 * x2 + x2**2

    @staticmethod
    def Easom(X: np.ndarray) -> float:
        """
        Easom
        """
        if len(X) != 2:
            raise ValueError("Easom function is only defined for 2D inputs.")
        x1, x2 = X
        return -np.cos(x1) * np.cos(x2) * np.exp(-((x1 - np.pi)**2 + (x2 - np.pi)**2))

    @staticmethod
    def Cross_In_Tray(X: np.ndarray) -> float:
        """
        Cross In Tray
        """
        if len(X) != 2:
            raise ValueError("Cross In Tray function is only defined for 2D inputs.")
        x1, x2 = X
        return -0.0001 * ((np.abs(np.sin(x1) * np.sin(x2) * np.exp(np.abs(100 - (np.sqrt(x1**2 + x2**2) / np.pi))))) + 1) ** 0.1

    @staticmethod
    def EggHolder(X: np.ndarray) -> float:
        """
        EggHolder
        """
        if len(X) != 2:
            raise ValueError("EggHolder function is only defined for 2D inputs.")
        x1, x2 = X
        return -(x2 + 47) * np.sin(np.sqrt(np.abs(x1 / 2 + (x2 + 47)))) - x1 * np.sin(np.sqrt(np.abs(x1 - (x2 + 47))))

    @staticmethod
    def HolderTable(X: np.ndarray) -> float:
        """
        Holder Table
        """
        if len(X) != 2:
            raise ValueError("Holder Table function is only defined for 2D inputs.")
        x1, x2 = X
        return -np.abs(np.sin(x1) * np.cos(x2) * np.exp(np.abs(1 - np.sqrt(x1**2 + x2**2) / np.pi)))

    @staticmethod
    def McCormick(X: np.ndarray) -> float:
        """
        McCormick
        """
        if len(X) != 2:
            raise ValueError("McCormick function is only defined for 2D inputs.")
        x1, x2 = X
        return np.sin(x1 + x2) + (x1 - x2)**2 - 1.5 * x1 + (2.5 * x2) + 1

    @staticmethod
    def Schaffer_N2(X: np.ndarray) -> float:
        """
        Schaffer N.2
        """
        if len(X) != 2:
            raise ValueError("Schaffer N.2 function is only defined for 2D inputs.")
        x1, x2 = X
        return 0.5 + (np.sin(x1**2 - x2**2)**2 - 0.5) / (1 + 0.001 * (x1**2 + x2**2))**2

    @staticmethod
    def StyblinskiTang(X: np.ndarray) -> float:
        """
        Styblinski-Tang
        """
        if len(X) != 2:
            raise ValueError("Styblinski-Tang function is only defined for 2D inputs.")
        x1, x2 = X
        return 0.5 * (x1**4 - 16 * x1**2 + 5 * x1 + x2**4 - 16 * x2**2 + 5 * x2)

    @staticmethod
    def Shekel(X: np.ndarray) -> float:
        """
        Shekel
        """
        c = np.array([0.1, 0.2, 0.2, 0.4, 0.4, 0.6, 0.3, 0.7, 0.5, 0.5])
        a = np.array([
            [9.0, 0.0, 9.0, 6.0, 6.0, 3.0, 1.0, 2.0, 7.0, 8.0],
            [0.0, 9.0, 6.0, 3.0, 1.0, 2.0, 7.0, 8.0, 9.0, 0.0]
        ])
        if len(X) != 2:
            raise ValueError("Shekel function is only defined for 2D inputs.")
        result = 0.0
        for i in range(len(c)):
            s = 0.0
            for j in range(len(X)):
                s += (X[j] - a[j, i]) ** 2
            result += 1.0 / (c[i] + s)
        return result


    def plot(self, bounds, dim=1, num_points=100, population=None, mode='surface', colorscale='Viridis') -> go.Figure:
        """
        Plots the function in 1D or 2D.
        If a population is provided, it will be overlaid on the function plot.
        Parameters:
            bounds: Tuple specifying the range for each dimension.
            dim: Dimension of the function (1 or 2).
            num_points: Number of points to sample for the plot.
            population: Optional numpy array of shape (n_individuals, dim) to overlay on the plot.
            mode: 'surface' or 'contour' for 2D plots.
            colorscale: Plotly colorscale for the function surface/contour.
        Returns:
            A Plotly Figure object.
        """

        metadata = getattr(self, 'metadata', {}).get(self.__name__, None)
        title = f'${{\\text{{{self.__name__.capitalize()} function }}:{metadata["formula"]}}}$' if metadata else f'{self.__name__.capitalize()} function'
        subtitle = f'Bounds: {bounds}' if bounds else ""
        func = self.__call__
        if dim == 1:
            if isinstance(bounds[0], (tuple, list)):
                x_bounds = bounds[0]
            else:
                x_bounds = bounds
            x = np.linspace(x_bounds[0], x_bounds[1], num_points)
            y = np.array([func(np.array([xi])) for xi in x])
            fig = go.Figure()
            fig.add_trace(go.Scatter(x=x, y=y, mode='lines', name='Function'))
            if population is not None:
                pop_x = population[:, 0]
                pop_y = np.array([func(np.array([xi])) for xi in pop_x])
                pop_label = 'Best Individual' if population.shape[0] == 1 else 'Population'
                fig.add_trace(go.Scatter(x=pop_x, y=pop_y, mode='markers', name=pop_label, marker=dict(color='red', size=8)))
            fig.update_layout(title=title, xaxis_title='x', yaxis_title='f(x)')
        elif dim == 2:
            if isinstance(bounds[0], (tuple, list)) and isinstance(bounds[1], (tuple, list)):
                x_bounds = bounds[0]
                y_bounds = bounds[1]
            else:
                x_bounds = y_bounds = bounds
            x = np.linspace(x_bounds[0], x_bounds[1], num_points)
            y = np.linspace(y_bounds[0], y_bounds[1], num_points)
            X, Y = np.meshgrid(x, y)
            Z = np.array([func(np.array([xi, yi])) for xi, yi in zip(np.ravel(X), np.ravel(Y))])
            Z = Z.reshape(X.shape)
            fig = go.Figure()
            if mode == 'surface':
                fig.add_trace(go.Surface(z=Z, x=X, y=Y, colorscale=colorscale, opacity=0.7, name='Function'))
                if population is not None:
                    pop_x = population[:, 0]
                    pop_y = population[:, 1]
                    pop_z = np.array([func(np.array([xi, yi])) for xi, yi in zip(pop_x, pop_y)])
                    pop_label = 'Best Individual' if population.shape[0] == 1 else 'Population'
                    fig.add_trace(go.Scatter3d(x=pop_x, y=pop_y, z=pop_z, mode='markers', name=pop_label, marker=dict(color='red', size=4)))
                fig.update_layout(title=title, scene=dict(xaxis_title='x', yaxis_title='y', zaxis_title='f(x, y)'))
            elif mode == 'contour':
                fig.add_trace(go.Contour(z=Z, x=x, y=y, colorscale=colorscale, name='Function'))
                if population is not None:
                    pop_x = population[:, 0]
                    pop_y = population[:, 1]
                    pop_label = 'Best Individual' if population.shape[0] == 1 else 'Population'
                    fig.add_trace(go.Scatter(x=pop_x, y=pop_y, mode='markers', name=pop_label, marker=dict(color='red', size=8)))
                fig.update_layout(title=title, xaxis_title='x', yaxis_title='y')
            else:
                raise ValueError("Mode should be 'surface' or 'contour'.")
        else:
            raise ValueError('Only 1D or 2D functions are supported for plotting.')

        fig.update_layout(
            title={'text': title, 'x':0.5},
            annotations=[dict(text=subtitle, x=0.5, y=-0.15, showarrow=False, xref="paper", yref="paper", xanchor='center', yanchor='top')],
            legend=dict(orientation='h', x=0.5, xanchor='center', y=-0.2),
            showlegend=True
        )
        return fig

Ackley(X) staticmethod

Ackley Wiki: https://en.wikipedia.org/wiki/Ackley_function

Source code in metazoo/src/metazoo/gym/mono.py
137
138
139
140
141
142
143
144
145
146
@staticmethod
def Ackley(X: np.ndarray) -> float:
    """
    Ackley
    Wiki: https://en.wikipedia.org/wiki/Ackley_function
    """
    n = len(X)
    square_sum = (1 / n) * np.sum(X * X)
    trigonometric_sum = (1 / n) * np.sum(np.cos(2 * np.pi * X))
    return -20 * np.exp(-0.2 * np.sqrt(square_sum)) - np.exp(trigonometric_sum) + 20 + np.e

Beale(X) staticmethod

Beale Wiki: https://en.wikipedia.org/wiki/Beale_function

Source code in metazoo/src/metazoo/gym/mono.py
166
167
168
169
170
171
172
173
174
175
@staticmethod
def Beale(X: np.ndarray) -> float:
    """
    Beale
    Wiki: https://en.wikipedia.org/wiki/Beale_function
    """
    if len(X) != 2:
        raise ValueError("Beale function is only defined for 2D inputs.")
    x1, x2 = X
    return (1.5 - x1 + x1 * x2)**2 + (2.25 - x1 + x1 * x2**2)**2 + (2.625 - x1 + x1 * x2**3)**2

Booth(X) staticmethod

Booth

Source code in metazoo/src/metazoo/gym/mono.py
191
192
193
194
195
196
197
198
199
@staticmethod
def Booth(X: np.ndarray) -> float:
    """
    Booth
    """
    if len(X) != 2:
        raise ValueError("Booth function is only defined for 2D inputs.")
    x1, x2 = X
    return (x1 + 2 * x2 - 7)**2 + (2 * x1 + x2 - 5)**2

Bukin(X) staticmethod

Bukin

Source code in metazoo/src/metazoo/gym/mono.py
201
202
203
204
205
206
207
208
209
@staticmethod
def Bukin(X: np.ndarray) -> float:
    """
    Bukin
    """
    if len(X) != 2:
        raise ValueError("Bukin function is only defined for 2D inputs.")
    x1, x2 = X
    return 100 * np.sqrt(np.abs(x2 - 0.01 * x1**2)) + 0.01 * np.abs(x1 + 10)

Cross_In_Tray(X) staticmethod

Cross In Tray

Source code in metazoo/src/metazoo/gym/mono.py
271
272
273
274
275
276
277
278
279
@staticmethod
def Cross_In_Tray(X: np.ndarray) -> float:
    """
    Cross In Tray
    """
    if len(X) != 2:
        raise ValueError("Cross In Tray function is only defined for 2D inputs.")
    x1, x2 = X
    return -0.0001 * ((np.abs(np.sin(x1) * np.sin(x2) * np.exp(np.abs(100 - (np.sqrt(x1**2 + x2**2) / np.pi))))) + 1) ** 0.1

Easom(X) staticmethod

Easom

Source code in metazoo/src/metazoo/gym/mono.py
261
262
263
264
265
266
267
268
269
@staticmethod
def Easom(X: np.ndarray) -> float:
    """
    Easom
    """
    if len(X) != 2:
        raise ValueError("Easom function is only defined for 2D inputs.")
    x1, x2 = X
    return -np.cos(x1) * np.cos(x2) * np.exp(-((x1 - np.pi)**2 + (x2 - np.pi)**2))

EggHolder(X) staticmethod

EggHolder

Source code in metazoo/src/metazoo/gym/mono.py
281
282
283
284
285
286
287
288
289
@staticmethod
def EggHolder(X: np.ndarray) -> float:
    """
    EggHolder
    """
    if len(X) != 2:
        raise ValueError("EggHolder function is only defined for 2D inputs.")
    x1, x2 = X
    return -(x2 + 47) * np.sin(np.sqrt(np.abs(x1 / 2 + (x2 + 47)))) - x1 * np.sin(np.sqrt(np.abs(x1 - (x2 + 47))))

GoldsteinPrice(X) staticmethod

Goldstein-Price

Source code in metazoo/src/metazoo/gym/mono.py
177
178
179
180
181
182
183
184
185
186
187
188
189
@staticmethod
def GoldsteinPrice(X: np.ndarray) -> float:
    """
    Goldstein-Price
    """
    if len(X) != 2:
        raise ValueError("Goldstein-Price function is only defined for 2D inputs.")
    x1, x2 = X
    term1 = 1 + ((x1 + x2 + 1)**2) * (19 - 14 * x1 + 3 * x1**2 - 14 * x2 + 6 * x1 * x2)
    term2 = (x1 + x2)**2
    if term2 == 0:
        return np.inf
    return term1 / term2

Griewank(X) staticmethod

Griewank

Source code in metazoo/src/metazoo/gym/mono.py
231
232
233
234
235
236
237
238
239
@staticmethod
def Griewank(X: np.ndarray) -> float:
    """
    Griewank
    """
    if len(X) != 2:
        raise ValueError("Griewank function is only defined for 2D inputs.")
    x1, x2 = X
    return 1 + (x1**2 + x2**2) / 4000 - np.cos(x1 / np.sqrt(1)) * np.cos(x2 / np.sqrt(2))

Himmelblau(X) staticmethod

Himmelblau

Source code in metazoo/src/metazoo/gym/mono.py
241
242
243
244
245
246
247
248
249
@staticmethod
def Himmelblau(X: np.ndarray) -> float:
    """
    Himmelblau
    """
    if len(X) != 2:
        raise ValueError("Himmelblau function is only defined for 2D inputs.")
    x1, x2 = X
    return (x1**2 + x2 - 11)**2 + (x1 + x2**2 - 7)**2

HolderTable(X) staticmethod

Holder Table

Source code in metazoo/src/metazoo/gym/mono.py
291
292
293
294
295
296
297
298
299
@staticmethod
def HolderTable(X: np.ndarray) -> float:
    """
    Holder Table
    """
    if len(X) != 2:
        raise ValueError("Holder Table function is only defined for 2D inputs.")
    x1, x2 = X
    return -np.abs(np.sin(x1) * np.cos(x2) * np.exp(np.abs(1 - np.sqrt(x1**2 + x2**2) / np.pi)))

Levi_N13(X) staticmethod

Levi N.13

Source code in metazoo/src/metazoo/gym/mono.py
221
222
223
224
225
226
227
228
229
@staticmethod
def Levi_N13(X: np.ndarray) -> float:
    """
    Levi N.13
    """
    if len(X) != 2:
        raise ValueError("Levi N.13 function is only defined for 2D inputs.")
    x1, x2 = X
    return np.sin(x1 + x2)**2 + (x1 - x2)**2

Matyas(X) staticmethod

Matyas

Source code in metazoo/src/metazoo/gym/mono.py
211
212
213
214
215
216
217
218
219
@staticmethod
def Matyas(X: np.ndarray) -> float:
    """
    Matyas
    """
    if len(X) != 2:
        raise ValueError("Matyas function is only defined for 2D inputs.")
    x1, x2 = X
    return 0.26 * (x1**2 + x2**2) - 0.48 * x1 * x2

McCormick(X) staticmethod

McCormick

Source code in metazoo/src/metazoo/gym/mono.py
301
302
303
304
305
306
307
308
309
@staticmethod
def McCormick(X: np.ndarray) -> float:
    """
    McCormick
    """
    if len(X) != 2:
        raise ValueError("McCormick function is only defined for 2D inputs.")
    x1, x2 = X
    return np.sin(x1 + x2) + (x1 - x2)**2 - 1.5 * x1 + (2.5 * x2) + 1

Rastrigin(X) staticmethod

Rastrigin Function Wiki: https://en.wikipedia.org/wiki/Rastrigin_function

Source code in metazoo/src/metazoo/gym/mono.py
127
128
129
130
131
132
133
134
135
@staticmethod
def Rastrigin(X: np.ndarray) -> float:
    """
    Rastrigin Function
    Wiki: https://en.wikipedia.org/wiki/Rastrigin_function
    """
    n = len(X)
    A = 10
    return A * n + np.sum(X**2 - A * np.cos(2 * np.pi * X))

Rosenbrock(X) staticmethod

Rosenbrock Wiki: https://en.wikipedia.org/wiki/Rosenbrock_function

Source code in metazoo/src/metazoo/gym/mono.py
155
156
157
158
159
160
161
162
163
164
@staticmethod
def Rosenbrock(X: np.ndarray) -> float:
    """
    Rosenbrock
    Wiki: https://en.wikipedia.org/wiki/Rosenbrock_function
    """
    if len(X) != 2:
        raise ValueError("Rosenbrock function is only defined for 2D inputs.")
    x1, x2 = X
    return (1 - x1)**2 + 100 * (x2 - x1**2)**2

Schaffer_N2(X) staticmethod

Schaffer N.2

Source code in metazoo/src/metazoo/gym/mono.py
311
312
313
314
315
316
317
318
319
@staticmethod
def Schaffer_N2(X: np.ndarray) -> float:
    """
    Schaffer N.2
    """
    if len(X) != 2:
        raise ValueError("Schaffer N.2 function is only defined for 2D inputs.")
    x1, x2 = X
    return 0.5 + (np.sin(x1**2 - x2**2)**2 - 0.5) / (1 + 0.001 * (x1**2 + x2**2))**2

Shekel(X) staticmethod

Shekel

Source code in metazoo/src/metazoo/gym/mono.py
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
@staticmethod
def Shekel(X: np.ndarray) -> float:
    """
    Shekel
    """
    c = np.array([0.1, 0.2, 0.2, 0.4, 0.4, 0.6, 0.3, 0.7, 0.5, 0.5])
    a = np.array([
        [9.0, 0.0, 9.0, 6.0, 6.0, 3.0, 1.0, 2.0, 7.0, 8.0],
        [0.0, 9.0, 6.0, 3.0, 1.0, 2.0, 7.0, 8.0, 9.0, 0.0]
    ])
    if len(X) != 2:
        raise ValueError("Shekel function is only defined for 2D inputs.")
    result = 0.0
    for i in range(len(c)):
        s = 0.0
        for j in range(len(X)):
            s += (X[j] - a[j, i]) ** 2
        result += 1.0 / (c[i] + s)
    return result

Sphere(X) staticmethod

Sphere

Source code in metazoo/src/metazoo/gym/mono.py
148
149
150
151
152
153
@staticmethod
def Sphere(X: np.ndarray) -> float:
    """
    Sphere
    """
    return np.sum(X * X)

StyblinskiTang(X) staticmethod

Styblinski-Tang

Source code in metazoo/src/metazoo/gym/mono.py
321
322
323
324
325
326
327
328
329
@staticmethod
def StyblinskiTang(X: np.ndarray) -> float:
    """
    Styblinski-Tang
    """
    if len(X) != 2:
        raise ValueError("Styblinski-Tang function is only defined for 2D inputs.")
    x1, x2 = X
    return 0.5 * (x1**4 - 16 * x1**2 + 5 * x1 + x2**4 - 16 * x2**2 + 5 * x2)

ThreeHumpCamel(X) staticmethod

Three Hump Camel

Source code in metazoo/src/metazoo/gym/mono.py
251
252
253
254
255
256
257
258
259
@staticmethod
def ThreeHumpCamel(X: np.ndarray) -> float:
    """
    Three Hump Camel
    """
    if len(X) != 2:
        raise ValueError("Three Hump Camel function is only defined for 2D inputs.")
    x1, x2 = X
    return 2 * x1**2 - 1.05 * x1**4 + (x1**6) / 6 + x1 * x2 + x2**2

__call__(X)

Evaluates the function at a given point X.

Source code in metazoo/src/metazoo/gym/mono.py
118
119
120
121
122
123
124
125
def __call__(self, X: np.ndarray) -> float:
    """
    Evaluates the function at a given point X.
    """
    value = getattr(self, self.__name__)(X)
    if self.reverse:
        return -value
    return value

formula()

Displays the LaTeX formula of the function if available.

Source code in metazoo/src/metazoo/gym/mono.py
108
109
110
111
112
113
114
115
116
def formula(self):
    """ 
    Displays the LaTeX formula of the function if available.
    """
    formula = self.metadata.get(self.__name__, None)
    if formula:
        return formula['formula']
    else:
        return "No LaTeX formula available for this function."

plot(bounds, dim=1, num_points=100, population=None, mode='surface', colorscale='Viridis')

Plots the function in 1D or 2D. If a population is provided, it will be overlaid on the function plot. Parameters: bounds: Tuple specifying the range for each dimension. dim: Dimension of the function (1 or 2). num_points: Number of points to sample for the plot. population: Optional numpy array of shape (n_individuals, dim) to overlay on the plot. mode: 'surface' or 'contour' for 2D plots. colorscale: Plotly colorscale for the function surface/contour. Returns: A Plotly Figure object.

Source code in metazoo/src/metazoo/gym/mono.py
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
def plot(self, bounds, dim=1, num_points=100, population=None, mode='surface', colorscale='Viridis') -> go.Figure:
    """
    Plots the function in 1D or 2D.
    If a population is provided, it will be overlaid on the function plot.
    Parameters:
        bounds: Tuple specifying the range for each dimension.
        dim: Dimension of the function (1 or 2).
        num_points: Number of points to sample for the plot.
        population: Optional numpy array of shape (n_individuals, dim) to overlay on the plot.
        mode: 'surface' or 'contour' for 2D plots.
        colorscale: Plotly colorscale for the function surface/contour.
    Returns:
        A Plotly Figure object.
    """

    metadata = getattr(self, 'metadata', {}).get(self.__name__, None)
    title = f'${{\\text{{{self.__name__.capitalize()} function }}:{metadata["formula"]}}}$' if metadata else f'{self.__name__.capitalize()} function'
    subtitle = f'Bounds: {bounds}' if bounds else ""
    func = self.__call__
    if dim == 1:
        if isinstance(bounds[0], (tuple, list)):
            x_bounds = bounds[0]
        else:
            x_bounds = bounds
        x = np.linspace(x_bounds[0], x_bounds[1], num_points)
        y = np.array([func(np.array([xi])) for xi in x])
        fig = go.Figure()
        fig.add_trace(go.Scatter(x=x, y=y, mode='lines', name='Function'))
        if population is not None:
            pop_x = population[:, 0]
            pop_y = np.array([func(np.array([xi])) for xi in pop_x])
            pop_label = 'Best Individual' if population.shape[0] == 1 else 'Population'
            fig.add_trace(go.Scatter(x=pop_x, y=pop_y, mode='markers', name=pop_label, marker=dict(color='red', size=8)))
        fig.update_layout(title=title, xaxis_title='x', yaxis_title='f(x)')
    elif dim == 2:
        if isinstance(bounds[0], (tuple, list)) and isinstance(bounds[1], (tuple, list)):
            x_bounds = bounds[0]
            y_bounds = bounds[1]
        else:
            x_bounds = y_bounds = bounds
        x = np.linspace(x_bounds[0], x_bounds[1], num_points)
        y = np.linspace(y_bounds[0], y_bounds[1], num_points)
        X, Y = np.meshgrid(x, y)
        Z = np.array([func(np.array([xi, yi])) for xi, yi in zip(np.ravel(X), np.ravel(Y))])
        Z = Z.reshape(X.shape)
        fig = go.Figure()
        if mode == 'surface':
            fig.add_trace(go.Surface(z=Z, x=X, y=Y, colorscale=colorscale, opacity=0.7, name='Function'))
            if population is not None:
                pop_x = population[:, 0]
                pop_y = population[:, 1]
                pop_z = np.array([func(np.array([xi, yi])) for xi, yi in zip(pop_x, pop_y)])
                pop_label = 'Best Individual' if population.shape[0] == 1 else 'Population'
                fig.add_trace(go.Scatter3d(x=pop_x, y=pop_y, z=pop_z, mode='markers', name=pop_label, marker=dict(color='red', size=4)))
            fig.update_layout(title=title, scene=dict(xaxis_title='x', yaxis_title='y', zaxis_title='f(x, y)'))
        elif mode == 'contour':
            fig.add_trace(go.Contour(z=Z, x=x, y=y, colorscale=colorscale, name='Function'))
            if population is not None:
                pop_x = population[:, 0]
                pop_y = population[:, 1]
                pop_label = 'Best Individual' if population.shape[0] == 1 else 'Population'
                fig.add_trace(go.Scatter(x=pop_x, y=pop_y, mode='markers', name=pop_label, marker=dict(color='red', size=8)))
            fig.update_layout(title=title, xaxis_title='x', yaxis_title='y')
        else:
            raise ValueError("Mode should be 'surface' or 'contour'.")
    else:
        raise ValueError('Only 1D or 2D functions are supported for plotting.')

    fig.update_layout(
        title={'text': title, 'x':0.5},
        annotations=[dict(text=subtitle, x=0.5, y=-0.15, showarrow=False, xref="paper", yref="paper", xanchor='center', yanchor='top')],
        legend=dict(orientation='h', x=0.5, xanchor='center', y=-0.2),
        showlegend=True
    )
    return fig

Methods

available_functions

Returns a list of available functions.

bounds

Gets the bounds of the function.

plot

Plots the function in 2D or 3D.

Plots the function in 1D or 2D. If a population is provided, it will be overlaid on the function plot. Parameters: bounds: Tuple specifying the range for each dimension. dim: Dimension of the function (1 or 2). num_points: Number of points to sample for the plot. population: Optional numpy array of shape (n_individuals, dim) to overlay on the plot. mode: 'surface' or 'contour' for 2D plots. colorscale: Plotly colorscale for the function surface/contour. Returns: A Plotly Figure object.

Source code in metazoo/src/metazoo/gym/mono.py
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
def plot(self, bounds, dim=1, num_points=100, population=None, mode='surface', colorscale='Viridis') -> go.Figure:
    """
    Plots the function in 1D or 2D.
    If a population is provided, it will be overlaid on the function plot.
    Parameters:
        bounds: Tuple specifying the range for each dimension.
        dim: Dimension of the function (1 or 2).
        num_points: Number of points to sample for the plot.
        population: Optional numpy array of shape (n_individuals, dim) to overlay on the plot.
        mode: 'surface' or 'contour' for 2D plots.
        colorscale: Plotly colorscale for the function surface/contour.
    Returns:
        A Plotly Figure object.
    """

    metadata = getattr(self, 'metadata', {}).get(self.__name__, None)
    title = f'${{\\text{{{self.__name__.capitalize()} function }}:{metadata["formula"]}}}$' if metadata else f'{self.__name__.capitalize()} function'
    subtitle = f'Bounds: {bounds}' if bounds else ""
    func = self.__call__
    if dim == 1:
        if isinstance(bounds[0], (tuple, list)):
            x_bounds = bounds[0]
        else:
            x_bounds = bounds
        x = np.linspace(x_bounds[0], x_bounds[1], num_points)
        y = np.array([func(np.array([xi])) for xi in x])
        fig = go.Figure()
        fig.add_trace(go.Scatter(x=x, y=y, mode='lines', name='Function'))
        if population is not None:
            pop_x = population[:, 0]
            pop_y = np.array([func(np.array([xi])) for xi in pop_x])
            pop_label = 'Best Individual' if population.shape[0] == 1 else 'Population'
            fig.add_trace(go.Scatter(x=pop_x, y=pop_y, mode='markers', name=pop_label, marker=dict(color='red', size=8)))
        fig.update_layout(title=title, xaxis_title='x', yaxis_title='f(x)')
    elif dim == 2:
        if isinstance(bounds[0], (tuple, list)) and isinstance(bounds[1], (tuple, list)):
            x_bounds = bounds[0]
            y_bounds = bounds[1]
        else:
            x_bounds = y_bounds = bounds
        x = np.linspace(x_bounds[0], x_bounds[1], num_points)
        y = np.linspace(y_bounds[0], y_bounds[1], num_points)
        X, Y = np.meshgrid(x, y)
        Z = np.array([func(np.array([xi, yi])) for xi, yi in zip(np.ravel(X), np.ravel(Y))])
        Z = Z.reshape(X.shape)
        fig = go.Figure()
        if mode == 'surface':
            fig.add_trace(go.Surface(z=Z, x=X, y=Y, colorscale=colorscale, opacity=0.7, name='Function'))
            if population is not None:
                pop_x = population[:, 0]
                pop_y = population[:, 1]
                pop_z = np.array([func(np.array([xi, yi])) for xi, yi in zip(pop_x, pop_y)])
                pop_label = 'Best Individual' if population.shape[0] == 1 else 'Population'
                fig.add_trace(go.Scatter3d(x=pop_x, y=pop_y, z=pop_z, mode='markers', name=pop_label, marker=dict(color='red', size=4)))
            fig.update_layout(title=title, scene=dict(xaxis_title='x', yaxis_title='y', zaxis_title='f(x, y)'))
        elif mode == 'contour':
            fig.add_trace(go.Contour(z=Z, x=x, y=y, colorscale=colorscale, name='Function'))
            if population is not None:
                pop_x = population[:, 0]
                pop_y = population[:, 1]
                pop_label = 'Best Individual' if population.shape[0] == 1 else 'Population'
                fig.add_trace(go.Scatter(x=pop_x, y=pop_y, mode='markers', name=pop_label, marker=dict(color='red', size=8)))
            fig.update_layout(title=title, xaxis_title='x', yaxis_title='y')
        else:
            raise ValueError("Mode should be 'surface' or 'contour'.")
    else:
        raise ValueError('Only 1D or 2D functions are supported for plotting.')

    fig.update_layout(
        title={'text': title, 'x':0.5},
        annotations=[dict(text=subtitle, x=0.5, y=-0.15, showarrow=False, xref="paper", yref="paper", xanchor='center', yanchor='top')],
        legend=dict(orientation='h', x=0.5, xanchor='center', y=-0.2),
        showlegend=True
    )
    return fig