Coverage for moptipy / examples / vectors / sphere.py: 92%

13 statements  

« prev     ^ index     » next       coverage.py v7.12.0, created at 2025-11-24 08:49 +0000

1"""The well-known sphere function.""" 

2 

3import numba # type: ignore 

4import numpy as np 

5 

6from moptipy.api.objective import Objective 

7 

8 

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

10def sphere(x: np.ndarray) -> float: 

11 """ 

12 Get the sum of the squares of the elements in an array. 

13 

14 :param x: the np array 

15 :return: the sum of the squares of all elements 

16 

17 >>> print(sphere(np.array([1.0, -2.0, 3.0]))) 

18 14.0 

19 >>> print(sphere(np.array([0.0, 0.0, 0.0]))) 

20 0.0 

21 """ 

22 return float(np.sum(x ** 2)) 

23 

24 

25class Sphere(Objective): 

26 """The well-known sphere function.""" 

27 

28 def __init__(self) -> None: 

29 """Initialize the sphere function.""" 

30 self.evaluate = sphere # type: ignore 

31 

32 def lower_bound(self) -> float: 

33 """ 

34 Get the lower bound of the sphere problem. 

35 

36 :return: 0 

37 

38 >>> print(Sphere().lower_bound()) 

39 0.0 

40 """ 

41 return 0.0 

42 

43 def __str__(self) -> str: 

44 """ 

45 Get the name of the sphere problem. 

46 

47 :return: `sphere` 

48 :retval "sphere": always 

49 

50 >>> print(Sphere()) 

51 sphere 

52 """ 

53 return "sphere"