Coverage for moptipy / examples / bitstrings / zeromax.py: 92%
12 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"""
2An objective function counting the number of zeros in a bit string.
4This problem exists mainly for testing purposes as counterpart of
5:class:`~moptipy.examples.bitstrings.onemax.OneMax`.
6"""
8import numba # type: ignore
9import numpy as np
11from moptipy.examples.bitstrings.bitstring_problem import BitStringProblem
14@numba.njit(nogil=True, cache=True)
15def zeromax(x: np.ndarray) -> int:
16 """
17 Get the length of a string minus the number of zeros in it.
19 :param x: the np array
20 :return: the length of the string minus the number of zeros, i.e., the
21 number of ones
23 >>> print(zeromax(np.array([True, True, False, False, False])))
24 2
25 >>> print(zeromax(np.array([True, False, True, False, False])))
26 2
27 >>> print(zeromax(np.array([False, True, True, False, False])))
28 2
29 >>> print(zeromax(np.array([True, True, True, True, True])))
30 5
31 >>> print(zeromax(np.array([False, True, True, True, True])))
32 4
33 >>> print(zeromax(np.array([False, False, False, False, False])))
34 0
35 """
36 return int(x.sum())
39class ZeroMax(BitStringProblem):
40 """Maximize the number of zeros in a bit string."""
42 def __init__(self, n: int) -> None:
43 """
44 Initialize the zeromax objective function.
46 :param n: the dimension of the problem
48 >>> print(ZeroMax(2).n)
49 2
50 >>> print(ZeroMax(4).evaluate(np.array([True, True, False, True])))
51 3
52 """
53 super().__init__(n)
54 self.evaluate = zeromax # type: ignore
56 def __str__(self) -> str:
57 """
58 Get the name of the zeromax objective function.
60 :return: `zeromax_` + length of string
62 >>> print(ZeroMax(13))
63 zeromax_13
64 """
65 return f"zeromax_{self.n}"