b069dd921a667219668ffdc9f05cebaa7b14eda8
[csit.git] / resources / libraries / python / MLRsearch / PerDurationDatabase.py
1 # Copyright (c) 2021 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 PerDurationDatabase class."""
15
16 import copy
17
18
19 class PerDurationDatabase:
20     """List-like structure holding measurement results for one duration.
21
22     This is a building block for MeasurementDatabase.
23
24     This class hold measurements for single target duration value only,
25     so the logic is quite simple.
26
27     Several utility methods are added, accomplishing tasks useful for MLRsearch
28     (to be called by MeasurementDatabade).
29     """
30
31     def __init__(self, duration, measurements):
32         """Store (deep copy of) measurement results and normalize them.
33
34         The results have to have the corresponding target duration,
35         and there should be no duplicate target_tr values.
36         Empty iterable (zero measurements) is an acceptable input.
37
38         :param duration: All measurements have to have this target duration [s].
39         :param measurements: The measurement results to store.
40         :type duration: float
41         :type measurements: Iterable[ReceiveRateMeasurement]
42         :raises ValueError: If duration does not match or if TR duplicity.
43         """
44         self.duration = duration
45         self.measurements = [copy.deepcopy(meas) for meas in measurements]
46         self._normalize()
47
48     def __repr__(self):
49         """Return string executable to get equivalent instance.
50
51         :returns: Code to construct equivalent instance.
52         :rtype: str
53         """
54         return (
55             u"PerDurationDatabase("
56             f"duration={self.duration!r},"
57             f"measurements={self.measurements!r})"
58         )
59
60     def _normalize(self):
61         """Sort by target_tr, fail on detecting duplicate target_tr.
62
63         Also set effective loss ratios.
64         """
65         measurements = self.measurements
66         measurements.sort(key=lambda measurement: measurement.target_tr)
67         # Detect duplicated TRs.
68         previous_tr = None
69         for measurement in measurements:
70             current_tr = measurement.target_tr
71             if current_tr == previous_tr:
72                 raise ValueError(
73                     u"Transmit rate conflict:"
74                     f" {measurement!r} {previous_tr!r}"
75                 )
76             previous_tr = current_tr
77         # Update effective ratios.
78         ratio_previous = None
79         for measurement in measurements:
80             if ratio_previous is None:
81                 ratio_previous = measurement.loss_ratio
82                 measurement.effective_loss_ratio = ratio_previous
83                 continue
84             ratio_previous = max(ratio_previous, measurement.loss_ratio)
85             measurement.effective_loss_ratio = ratio_previous
86
87     def add(self, measurement):
88         """Add measurement and normalize.
89
90         :param measurement: Measurement result to add to the database.
91         :type measurement: ReceiveRateMeasurement
92         """
93         # TODO: We should deepcopy either everywhere or nowhere.
94         self.measurements.append(measurement)
95         self._normalize()
96
97     def get_valid_bounds(self, ratio):
98         """Return None or a valid measurement for two tightest bounds.
99
100         The validity of a measurement to act as a bound is determined
101         by comparing the argument ratio with measurement's effective loss ratio.
102
103         Both lower and upper bounds are returned, both tightest and second
104         tightest. If some value is not available, None is returned instead.
105
106         :param ratio: Target ratio, valid has to be lower or equal.
107         :type ratio: float
108         :returns: Tightest lower bound, tightest upper bound,
109             second tightest lower bound, second tightest upper bound.
110         :rtype: 4-tuple of Optional[ReceiveRateMeasurement]
111         """
112         lower_1, upper_1, lower_2, upper_2 = None, None, None, None
113         for measurement in self.measurements:
114             if measurement.effective_loss_ratio > ratio:
115                 if upper_1 is None:
116                     upper_1 = measurement
117                     continue
118                 upper_2 = measurement
119                 break
120             lower_1, lower_2 = measurement, lower_1
121         return lower_1, upper_1, lower_2, upper_2