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

1""" 

2Ackley's Function. 

3 

4Ackley's function is a continuous, multimodal, differentiable, non-separable, 

5and scalable benchmark function for continuous optimization. 

6 

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""" 

12 

13from math import tau 

14 

15import numba # type: ignore 

16from numpy import cos, exp, mean, ndarray, sqrt 

17 

18from moptipy.api.objective import Objective 

19 

20 

21@numba.njit(nogil=True, cache=True) 

22def ackley(x: ndarray) -> float: 

23 """ 

24 Compute Ackley's function. 

25 

26 :param x: the np array 

27 :return: the result of Ackley's function 

28 

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) 

46 

47 

48class Ackley(Objective): 

49 """Ackley's function.""" 

50 

51 def __init__(self) -> None: 

52 """Initialize Ackley's function.""" 

53 self.evaluate = ackley # type: ignore 

54 

55 def lower_bound(self) -> float: 

56 """ 

57 Get the lower bound of the sphere problem. 

58 

59 :return: 0 

60 

61 >>> print(Ackley().lower_bound()) 

62 0.0 

63 """ 

64 return 0.0 

65 

66 def __str__(self) -> str: 

67 """ 

68 Get the name of Ackley's function. 

69 

70 :return: `ackley` 

71 :retval "ackley": always 

72 

73 >>> print(Ackley()) 

74 ackley 

75 """ 

76 return "ackley"