Coverage for moptipy / algorithms / so / record.py: 100%

10 statements  

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

1"""A simple record for storing a solution with its quality.""" 

2 

3from typing import Final 

4 

5 

6# start record 

7class Record: 

8 """ 

9 A point in the search space, its quality, and creation time. 

10 

11 A record stores a point in the search space :attr:`x` together with 

12 the corresponding objective value :attr:`f`. It also stores a 

13 "iteration index" :attr:`it`, i.e., the time when the point was 

14 created or modified. 

15 

16 This allows for representing and storing solutions in a population. 

17 If the population is sorted, then records with better objective 

18 value will be moved to the beginning of the list. Ties are broken 

19 such that younger individuals (with higher :attr:`it` value) are 

20 preferred. 

21 """ 

22 

23 def __init__(self, x, f: int | float): 

24 """ 

25 Create the record. 

26 

27 :param x: the data structure for a point in the search space 

28 :param f: the corresponding objective value 

29 """ 

30 #: the point in the search space 

31 self.x: Final = x 

32 #: the objective value corresponding to :attr:`x` 

33 self.f: int | float = f 

34 #: the iteration index when :attr:`x` was sampled 

35 self.it: int = 0 

36 

37 def __lt__(self, other) -> bool: 

38 """ 

39 Precedence if 1) better or b) equally good but younger. 

40 

41 :param other: the other record 

42 :returns: `True` if this record has a better objective value 

43 (:attr:`f`) or if it has the same objective value but is newer, 

44 i.e., has a larger :attr:`it` value 

45 

46 >>> r1 = Record(None, 10) 

47 >>> r2 = Record(None, 9) 

48 >>> r1 < r2 

49 False 

50 >>> r2 < r1 

51 True 

52 >>> r1.it = 22 

53 >>> r2.f = r1.f 

54 >>> r2.it = r1.it 

55 >>> r1 < r2 

56 False 

57 >>> r2 < r1 

58 False 

59 >>> r2.it = r1.it + 1 

60 >>> r1 < r2 

61 False 

62 >>> r2 < r1 

63 True 

64 """ 

65 f1: Final[int | float] = self.f 

66 f2: Final[int | float] = other.f 

67 return (f1 < f2) or ((f1 == f2) and (self.it > other.it)) 

68# end record