blob: ccdb7239b5750d1737c4b52810a7f4f53bcfdd01 [file] [log] [blame]
George Liu7f41a0d2024-08-28 16:49:06 +08001#include "calculate.hpp"
2
Jayanth Othayothbfb17212024-10-15 10:52:15 -05003#include <algorithm>
George Liu7f41a0d2024-08-28 16:49:06 +08004#include <limits>
George Liu4e6081b2024-09-19 10:09:04 +08005#include <numeric>
George Liu7f41a0d2024-08-28 16:49:06 +08006
7namespace phosphor::virtual_sensor
8{
9
10double calculateModifiedMedianValue(std::vector<double>& values)
11{
12 size_t size = values.size();
13 std::sort(values.begin(), values.end());
14 switch (size)
15 {
16 case 2:
17 /* Choose biggest value */
18 return values.at(1);
19 case 0:
20 return std::numeric_limits<double>::quiet_NaN();
21 default:
22 /* Choose median value */
23 if (size % 2 == 0)
24 {
25 // Average of the two middle values
26 return (values.at(size / 2) + values.at(size / 2 - 1)) / 2;
27 }
28 else
29 {
30 return values.at((size - 1) / 2);
31 }
32 }
33}
34
35double calculateMaximumValue(std::vector<double>& values)
36{
37 auto maxIt = std::max_element(values.begin(), values.end());
38 if (maxIt == values.end())
39 {
40 return std::numeric_limits<double>::quiet_NaN();
41 }
42 return *maxIt;
43}
44
George Liuc1f822c2024-08-28 17:26:03 +080045double calculateMinimumValue(std::vector<double>& values)
46{
47 auto maxIt = std::min_element(values.begin(), values.end());
48 if (maxIt == values.end())
49 {
50 return std::numeric_limits<double>::quiet_NaN();
51 }
52 return *maxIt;
53}
54
George Liu4e6081b2024-09-19 10:09:04 +080055double calculateSumValue(std::vector<double>& values)
56{
57 if (values.empty())
58 {
59 return std::numeric_limits<double>::quiet_NaN();
60 }
61 return std::accumulate(values.begin(), values.end(), 0.0);
62}
63
George Liu60fab692024-09-19 10:33:15 +080064double calculateAverageValue(std::vector<double>& values)
65{
66 if (values.empty())
67 {
68 return std::numeric_limits<double>::quiet_NaN();
69 }
70 return std::accumulate(values.begin(), values.end(), 0.0) / values.size();
71}
72
George Liu7f41a0d2024-08-28 16:49:06 +080073std::map<Interface, CalculationFunc> calculationIfaces{
George Liu60fab692024-09-19 10:33:15 +080074 {"xyz.openbmc_project.Configuration.Average", calculateAverageValue},
George Liu7f41a0d2024-08-28 16:49:06 +080075 {"xyz.openbmc_project.Configuration.Maximum", calculateMaximumValue},
George Liuc1f822c2024-08-28 17:26:03 +080076 {"xyz.openbmc_project.Configuration.Minimum", calculateMinimumValue},
George Liu4e6081b2024-09-19 10:09:04 +080077 {"xyz.openbmc_project.Configuration.Sum", calculateSumValue},
George Liu7f41a0d2024-08-28 16:49:06 +080078 {"xyz.openbmc_project.Configuration.ModifiedMedian",
79 calculateModifiedMedianValue}};
80
81} // namespace phosphor::virtual_sensor