Skip to content

2. Getting started

Iannick Gagnon edited this page May 20, 2025 · 13 revisions

Importing objective functions

The MDAF_objective_functions library provides a variety of well-known objective functions that you can import as follows:

from MDAF_objective_functions import Ackley, Rastrigin, StyblinskiTang, DropWave

To see a list of all available objective functions:

>>> import MDAF_objective_functions as of
>>> of.show_all()
Ackley
Buckin6
DropWave
...

Visualizing objective functions

Each ObjectiveFunction class provides a .visualize() method for quick 2D/3D visualizations:

>>> from MDAF_objective_functions import Bukin6
>>> Bukin6().visualize()

The previous commands will generate the following interactive graph:

Bukin No. 6

Note: The star (⭐) symbol represents the global minimum.

Evaluating objective functions

To evaluate a function at a single position:

>>> from MDAF_objective_functions import Sphere
>>> foo = Sphere()
>>> val = foo.evaluate(np.array([[1, 1]]))
>>> print(val)
[2]

To evaluate a function at multiple positions:

>>> from MDAF_objective_functions import Sphere
>>> foo = Sphere()
>>> val = foo.evaluate(np.array([[1, 1], [2, 2]]))
>>> print(val)
[2, 8]

You can also customize the visualization by passing parameters such as dimensions, bounds, and resolution. See the ObjectiveFunction class documentation for details.

Adding noise and shifting

To make the optimization landscape more challenging, you can add Gaussian noise with the .apply_noise() method, or shift the function using the .apply_shift() method.

For example, here is a noisy Sphere function:

>>> from MDAF_objective_functions import Sphere
>>> foo = Sphere()
>>> foo.apply_noise(mean=0, variance=0.5)
>>> foo.visualize()
Noisy Sphere function

Here is a shifted version:

>>> from MDAF_objective_functions import Sphere
>>> foo = Sphere()
>>> foo.apply_shift(np.array([-1, 2]))
>>> foo.visualize()
Shifted Sphere function

Noising and shifting can be combined like so:

>>> from MDAF_objective_functions import Sphere
>>> foo = Sphere()
>>> foo.apply_noise(mean=0.0, variance=0.5)
>>> foo.apply_shift(np.array([-1, 2]))
>>> foo.visualize()
Shifted Sphere function

Optimization example

To explore these functions using traditional libraries such as SciPy's minimize [link], you can do the following:

>>> from MDAF_objective_functions import Ackley
>>> from scipy.optimize import minimize
>>> foo = Ackley()
>>> result = minimize(foo.evaluate, x0=[1, 10], bounds=[(0, 10), (0, 10)])
>>> print(f'Minimum value = {result.fun} @ x = {result.x}')
Minimum value = 8.64630561830099 @ x = [9.99747615 9.99747615]

Here, we can see that the L-BFGS-B optimizer failed to find the global minimum of 0.0 at [0.0, 0.0], which is not surprising given that it's a local optimizer. You can change the starting point x0 and bring it nearer to [0.0, 0.0] to see it succeed.

Clone this wiki locally