feat(MLRsearch): MLRsearch v7
[csit.git] / resources / libraries / python / MLRsearch / strategy / base.py
1 # Copyright (c) 2023 Cisco and/or its affiliates.
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at:
5 #
6 #     http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13
14 """Module defining StrategyBase class."""
15
16
17 from abc import ABC, abstractmethod
18 from dataclasses import dataclass, field
19 from typing import Callable, Optional, Tuple
20
21 from ..discrete_interval import DiscreteInterval
22 from ..discrete_load import DiscreteLoad
23 from ..discrete_width import DiscreteWidth
24 from ..expander import TargetedExpander
25 from ..limit_handler import LimitHandler
26 from ..relevant_bounds import RelevantBounds
27 from ..target_spec import TargetSpec
28
29
30 @dataclass
31 class StrategyBase(ABC):
32     """Abstract class encompassing data common to most strategies.
33
34     A strategy is one piece of logic a selector may use
35     when nominating a candidate according to its current target.
36
37     The two initial bound arguments may not be bounds at all.
38     For initial targets, the two values are usually mrr and mrr2.
39     For subsequent targets, the initial values are usually
40     the relevant bounds of the preceding target,
41     but one of them may be None if hitting min or max load.
42
43     The initial values are mainly used as stable alternatives
44     to relevant bounds of preceding target,
45     because those bounds may have been unpredictably altered
46     by nominations from unrelated search goals.
47     This greatly simplifies reasoning about strategies making progress.
48     """
49
50     target: TargetSpec
51     """The target this strategy is focusing on."""
52     expander: TargetedExpander
53     """Instance to track width expansion during search (if applicable)."""
54     initial_lower_load: Optional[DiscreteLoad]
55     """Smaller of the two loads distinguished at instance creation.
56     Can be None if upper bound is the min load."""
57     initial_upper_load: Optional[DiscreteLoad]
58     """Larger of the two loads distinguished at instance creation.
59     Can be None if lower bound is the max load."""
60     handler: LimitHandler = field(repr=False)
61     """Reference to the limit handler instance."""
62     debug: Callable[[str], None] = field(repr=False)
63     """Injectable function for debug logging."""
64
65     @abstractmethod
66     def nominate(
67         self, bounds: RelevantBounds
68     ) -> Tuple[Optional[DiscreteLoad], Optional[DiscreteWidth]]:
69         """Nominate a load candidate if the conditions activate this strategy.
70
71         A complete candidate refers also to the nominating selector.
72         To prevent circular dependence (selector refers to nominating strategy),
73         this function returns only duration and width.
74
75         Width should only be non-None if global current width should be updated
76         when the candidate based on this becomes winner.
77         But currently all strategies return non-None width
78         if they return non-None load.
79
80         :param bounds: Freshly updated bounds relevant for current target.
81         :type bounds: RelevantBounds
82         :returns: Two nones or candidate intended load and duration.
83         :rtype: Tuple[Optional[DiscreteLoad], Optional[DiscreteWidth]]
84         """
85         return None, None
86
87     def won(self, bounds: RelevantBounds, load: DiscreteLoad) -> None:
88         """Notify the strategy its candidate became the winner.
89
90         Most strategies have no use for this information,
91         but some strategies may need to update their private information.
92
93         :param bounds: Freshly updated bounds relevant for current target.
94         :param load: The current load, so strategy does not need to remember.
95         :type bounds: RelevantBounds
96         :type load: DiscreteLoad
97         """
98         return
99
100     def not_worth(self, bounds: RelevantBounds, load: DiscreteLoad) -> bool:
101         """A check on bounds common for multiple strategies.
102
103         The load is worth measuring only if it can create or improve
104         either relevant bound.
105
106         Each strategy is designed to create a relevant bound for current target,
107         which is only needed if that (or better) bound does not exist yet.
108         Conversely, if a strategy does not nominate, it is because
109         the load it would nominate (if any) is found not worth by this method.
110
111         :param bounds: Current relevant bounds.
112         :param load: Load of a possible candidate.
113         :type bounds: RelevantBounds
114         :type load: DiscreteLoad
115         :returns: True if the load should NOT be nominated.
116         :rtype: bool
117         """
118         if bounds.clo and bounds.clo >= load:
119             return True
120         if bounds.chi and bounds.chi <= load:
121             return True
122         if bounds.clo and bounds.chi:
123             # We are not hitting min nor max load.
124             # Measuring at this load will create or improve clo or chi.
125             # The only reason not to nominate is if interval is narrow already.
126             wig = DiscreteInterval(
127                 lower_bound=bounds.clo,
128                 upper_bound=bounds.chi,
129             ).width_in_goals(self.target.discrete_width)
130             if wig <= 1.0:
131                 return True
132         return False