Coverage for moptipy / api / component.py: 94%

17 statements  

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

1""" 

2Provides the base class for all components of the moptipy API. 

3 

4All elements of the `moptipy` API inherit from 

5:class:`~moptipy.api.component.Component`. If you implement a new such 

6component, you can test it using the pre-defined unit test routine 

7:func:`~moptipy.tests.component.validate_component`. 

8""" 

9from typing import Final 

10 

11from pycommons.types import type_name_of 

12 

13from moptipy.api import logging 

14from moptipy.utils.logger import KeyValueLogSection 

15 

16 

17class Component: 

18 """The base class for all components of the moptipy API.""" 

19 

20 def __repr__(self): 

21 """ 

22 Get the string representation of this object. 

23 

24 :return: the value returned by :meth:`__str__` 

25 """ 

26 return str(self) 

27 

28 def __str__(self): 

29 """ 

30 Get the default to-string implementation returns the class name. 

31 

32 :returns: the class name of this component 

33 

34 >>> print(Component()) 

35 Component 

36 """ 

37 s: Final[str] = type_name_of(self) 

38 i: Final[int] = s.rfind(".") 

39 if i > 0: 

40 return s[i + 1:] 

41 return s 

42 

43 def initialize(self) -> None: 

44 """ 

45 Initialize this component before a new run. 

46 

47 Before every run of the optimization algorithm, its `initialize` 

48 method is called. The algorithm in turn must call all the `initialize` 

49 methods of all of its components. 

50 """ 

51 

52 def log_parameters_to(self, logger: KeyValueLogSection) -> None: 

53 """ 

54 Log all parameters of this component as key-value pairs. 

55 

56 :param logger: the logger for the parameters 

57 

58 >>> from moptipy.utils.logger import InMemoryLogger 

59 >>> with InMemoryLogger() as l: 

60 ... with l.key_values("C") as kv: 

61 ... Component().log_parameters_to(kv) 

62 ... text = l.get_log() 

63 >>> text[-2] 

64 'class: moptipy.api.component.Component' 

65 >>> text[-3] 

66 'name: Component' 

67 >>> len(text) 

68 4 

69 """ 

70 logger.key_value(logging.KEY_NAME, str(self)) 

71 logger.key_value(logging.KEY_CLASS, type_name_of(self))