Revert "fix(IPsecUtil): Delete keywords no longer used"
[csit.git] / resources / libraries / python / MLRsearch / load_stats.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 LoadStats class."""
15
16 from __future__ import annotations
17
18 from dataclasses import dataclass
19 from typing import Dict, Tuple
20
21 from .target_spec import TargetSpec
22 from .target_stat import TargetStat
23 from .discrete_load import DiscreteLoad
24 from .discrete_result import DiscreteResult
25
26
27 # The eq=False part is needed to make sure comparison is inherited properly.
28 @dataclass(eq=False)
29 class LoadStats(DiscreteLoad):
30     """An offered load together with stats for all possible targets.
31
32     As LoadStats is frequently passed instead of plan DiscreteLoad,
33     equality and ordering is dictated by the float load.
34     """
35
36     target_to_stat: Dict[TargetSpec, TargetStat] = None
37     """Mapping from target specification to its current stat for this load."""
38
39     def __post_init__(self) -> None:
40         """Initialize load value and check there are targets to track."""
41         super().__post_init__()
42         if not self.target_to_stat:
43             raise ValueError(f"No targets: {self.target_to_stat!r}")
44
45     def __str__(self) -> str:
46         """Convert into a short human-readable string.
47
48         This works well only for trimmed stats,
49         as only the stat for the first target present is shown.
50
51         :returns: The short string.
52         :rtype: str
53         """
54         return (
55             f"fl={self.float_load}"
56             f",s=({next(iter(self.target_to_stat.values()))})"
57         )
58
59     def __hash__(self) -> int:
60         """Raise as stats are mutable by definition.
61
62         :returns: Hash value for this instance if possible.
63         :rtype: int
64         :raises TypeError: Not immutable.
65         """
66         raise TypeError("Loadstats are mutable so constant hash is impossible.")
67
68     def add(self, result: DiscreteResult) -> None:
69         """Take into account one more trial measurement result.
70
71         :param result: The result to take into account.
72         :type result: DiscreteResult
73         :raises RuntimeError: If result load does is not equal to the self load.
74         """
75         if result.intended_load != float(self):
76             raise RuntimeError(
77                 f"Attempting to add load {result.intended_load}"
78                 f" to result set for {float(self)}"
79             )
80         for stat in self.target_to_stat.values():
81             stat.add(result)
82
83     @staticmethod
84     def new_empty(load: DiscreteLoad, targets: Tuple[TargetSpec]) -> LoadStats:
85         """Factory method to initialize mapping for given targets.
86
87         :param load: The intended load value for the new instance.
88         :param targets: The target specifications to track stats for.
89         :type load: DiscreteLoad
90         :type targets: Tuple[TargetSpec]
91         :returns: New instance with empty stats initialized.
92         :rtype: LoadStats
93         :raise ValueError: Is the load is not rounded.
94         """
95         if not load.is_round:
96             raise ValueError(f"Not round: {load!r}")
97         return LoadStats(
98             rounding=load.rounding,
99             int_load=int(load),
100             target_to_stat={target: TargetStat(target) for target in targets},
101         )
102
103     def estimates(self, target: TargetSpec) -> Tuple[bool, bool]:
104         """Classify this load according to given target.
105
106         :param target: According to which target this should be classified.
107         :type target: TargetSpec
108         :returns: Tuple of two estimates whether load can be lower bound.
109             (True, False) means target is not reached yet.
110         :rtype: Tuple[bool, bool]
111         """
112         return self.target_to_stat[target].estimates()