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
« prev ^ index » next coverage.py v7.12.0, created at 2025-11-24 08:49 +0000
1"""The well-known sphere function."""
3import numba # type: ignore
4import numpy as np
6from moptipy.api.objective import Objective
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.
14 :param x: the np array
15 :return: the sum of the squares of all elements
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))
25class Sphere(Objective):
26 """The well-known sphere function."""
28 def __init__(self) -> None:
29 """Initialize the sphere function."""
30 self.evaluate = sphere # type: ignore
32 def lower_bound(self) -> float:
33 """
34 Get the lower bound of the sphere problem.
36 :return: 0
38 >>> print(Sphere().lower_bound())
39 0.0
40 """
41 return 0.0
43 def __str__(self) -> str:
44 """
45 Get the name of the sphere problem.
47 :return: `sphere`
48 :retval "sphere": always
50 >>> print(Sphere())
51 sphere
52 """
53 return "sphere"