Coverage for moptipy / examples / vectors / ackley.py: 87%
15 statements
« prev ^ index » next coverage.py v7.12.0, created at 2025-11-24 08:49 +0000
« prev ^ index » next coverage.py v7.12.0, created at 2025-11-24 08:49 +0000
1"""
2Ackley's Function.
4Ackley's function is a continuous, multimodal, differentiable, non-separable,
5and scalable benchmark function for continuous optimization.
71. David H. Ackley. *A Connectionist Machine for Genetic Hillclimbing.* 1987.
8 Volume 28 of The Kluwer International Series in Engineering and Computer
9 Science. Norwell, MA, USA: Kluwer Academic Publisher.
10 ISBN: 978-1-4612-9192. doi:10.1007/978-1-4613-199
11"""
13from math import tau
15import numba # type: ignore
16from numpy import cos, exp, mean, ndarray, sqrt
18from moptipy.api.objective import Objective
21@numba.njit(nogil=True, cache=True)
22def ackley(x: ndarray) -> float:
23 """
24 Compute Ackley's function.
26 :param x: the np array
27 :return: the result of Ackley's function
29 >>> from numpy import array
30 >>> print(ackley(array([0.0, 0.0, 0.0])))
31 0.0
32 >>> ackley(array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0]))
33 0.0
34 >>> print(abs(ackley(array([0.0, 0.0, 0.0]))) < 1e-15)
35 True
36 >>> print(ackley(array([2.0, 2.0])))
37 6.593599079287213
38 >>> print(ackley(array([-3.0, 2.0])))
39 7.9889108105187
40 """
41 # 22.718281828459045 equals 20.0 + e
42 # 6.283185307179586 equals 2.0 * pi
43 res = 22.718281828459045 + (-20.0 * exp(-0.2 * sqrt(
44 mean(x ** 2)))) - exp(mean(cos(tau * x)))
45 return 0.0 if res <= 0.0 else float(res)
48class Ackley(Objective):
49 """Ackley's function."""
51 def __init__(self) -> None:
52 """Initialize Ackley's function."""
53 self.evaluate = ackley # type: ignore
55 def lower_bound(self) -> float:
56 """
57 Get the lower bound of the sphere problem.
59 :return: 0
61 >>> print(Ackley().lower_bound())
62 0.0
63 """
64 return 0.0
66 def __str__(self) -> str:
67 """
68 Get the name of Ackley's function.
70 :return: `ackley`
71 :retval "ackley": always
73 >>> print(Ackley())
74 ackley
75 """
76 return "ackley"