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

1""" 

2An objective function counting the number of zeros in a bit string. 

3 

4This problem exists mainly for testing purposes as counterpart of 

5:class:`~moptipy.examples.bitstrings.onemax.OneMax`. 

6""" 

7 

8import numba # type: ignore 

9import numpy as np 

10 

11from moptipy.examples.bitstrings.bitstring_problem import BitStringProblem 

12 

13 

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. 

18 

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 

22 

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()) 

37 

38 

39class ZeroMax(BitStringProblem): 

40 """Maximize the number of zeros in a bit string.""" 

41 

42 def __init__(self, n: int) -> None: 

43 """ 

44 Initialize the zeromax objective function. 

45 

46 :param n: the dimension of the problem 

47 

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 

55 

56 def __str__(self) -> str: 

57 """ 

58 Get the name of the zeromax objective function. 

59 

60 :return: `zeromax_` + length of string 

61 

62 >>> print(ZeroMax(13)) 

63 zeromax_13 

64 """ 

65 return f"zeromax_{self.n}"