9d30d51b9cc3c5e9b4755159f85ee4df9de2a25a
[csit.git] / resources / libraries / python / MLRsearch / target_stat.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 LoadStat class."""
15
16 from dataclasses import dataclass, field
17 from typing import Tuple
18
19 from .target_spec import TargetSpec
20 from .discrete_result import DiscreteResult
21
22
23 @dataclass
24 class TargetStat:
25     """Class for aggregating trial results for a single load and target.
26
27     Reference to the target is included for convenience.
28
29     The main usage is for load classification, done in estimates method.
30     If both estimates agree, the load is classified as either a lower bound
31     or an upper bound. For additional logic for dealing with loss inversion
32     see MeasurementDatabase.
33
34     Besides the duration sums needed for determining upper and lower bound,
35     a field useful for computing the conditional throughput is also included.
36     The conditional throughput is average of the (relative) forwarding rates
37     of good long trials weighted by gool long trial durations.
38     As the intended load is stored elsewhere, the one additional field here
39     has a peculiar unit, it is a sum of products of seconds and loss ratios.
40     """
41
42     target: TargetSpec = field(repr=False)
43     """The target for which this instance is aggregating results."""
44     good_long: float = 0.0
45     """Sum of durations of long enough trials satisfying target loss ratio."""
46     bad_long: float = 0.0
47     """Sum of durations of long trials not satisfying target loss ratio."""
48     good_short: float = 0.0
49     """Sum of durations of shorter trials satisfying target loss ratio."""
50     bad_short: float = 0.0
51     """Sum of durations of shorter trials not satisfying target loss ratio."""
52     dur_rat_sum: float = 0.0
53     """Sum over good long trials, of duration multiplied by loss ratio."""
54
55     def __str__(self) -> str:
56         """Convert into a short human-readable string.
57
58         :returns: The short string.
59         :rtype: str
60         """
61         return (
62             f"gl={self.good_long},bl={self.bad_long}"
63             f",gs={self.good_short},bs={self.bad_short}"
64         )
65
66     def add(self, result: DiscreteResult) -> None:
67         """Take into account one more trial result.
68
69         Use intended duration for deciding between long and short trials,
70         but use offered duation (with overheads) to increase the duration sums.
71
72         :param result: The trial result to add to the stats.
73         :type result: DiscreteResult
74         """
75         dwo = result.duration_with_overheads
76         if result.intended_duration >= self.target.trial_duration:
77             if result.loss_ratio > self.target.loss_ratio:
78                 self.bad_long += dwo
79             else:
80                 self.good_long += dwo
81                 self.dur_rat_sum += dwo * result.loss_ratio
82         else:
83             if result.loss_ratio > self.target.loss_ratio:
84                 self.bad_short += dwo
85             else:
86                 self.good_short += dwo
87
88     def estimates(self) -> Tuple[bool, bool]:
89         """Return whether this load can become a lower bound.
90
91         This returns two estimates, hence the weird nonverb name of this method.
92         One estimate assumes all following results will satisfy the loss ratio,
93         the other assumes all results will not satisfy the loss ratio.
94         The sum of durations of the assumed results
95         is the minimum to reach target duration sum, or zero if already reached.
96
97         If both estimates are the same, it means the load is a definite bound.
98         This may happen even when the sum of durations of already
99         measured trials is less than the target, when the missing measurements
100         cannot change the classification.
101
102         :returns: Tuple of two estimates whether the load can be a lower bound.
103             (True, False) means more trial results are needed.
104         :rtype: Tuple[bool, bool]
105         """
106         coeff = self.target.exceed_ratio
107         decrease = self.good_short * coeff / (1.0 - coeff)
108         short_excess = self.bad_short - decrease
109         effective_excess = self.bad_long + max(0.0, short_excess)
110         effective_dursum = max(
111             self.good_long + effective_excess,
112             self.target.duration_sum,
113         )
114         limit_dursum = effective_dursum * self.target.exceed_ratio
115         optimistic = effective_excess <= limit_dursum
116         pessimistic = (effective_dursum - self.good_long) <= limit_dursum
117         return optimistic, pessimistic