blob: 63e348860f434b67019a349ea3fb6eb8322c42aa [file] [log] [blame]
George Liu7f41a0d2024-08-28 16:49:06 +08001#include "calculate.hpp"
2
3#include <limits>
George Liu4e6081b2024-09-19 10:09:04 +08004#include <numeric>
George Liu7f41a0d2024-08-28 16:49:06 +08005
6namespace phosphor::virtual_sensor
7{
8
9double calculateModifiedMedianValue(std::vector<double>& values)
10{
11 size_t size = values.size();
12 std::sort(values.begin(), values.end());
13 switch (size)
14 {
15 case 2:
16 /* Choose biggest value */
17 return values.at(1);
18 case 0:
19 return std::numeric_limits<double>::quiet_NaN();
20 default:
21 /* Choose median value */
22 if (size % 2 == 0)
23 {
24 // Average of the two middle values
25 return (values.at(size / 2) + values.at(size / 2 - 1)) / 2;
26 }
27 else
28 {
29 return values.at((size - 1) / 2);
30 }
31 }
32}
33
34double calculateMaximumValue(std::vector<double>& values)
35{
36 auto maxIt = std::max_element(values.begin(), values.end());
37 if (maxIt == values.end())
38 {
39 return std::numeric_limits<double>::quiet_NaN();
40 }
41 return *maxIt;
42}
43
George Liuc1f822c2024-08-28 17:26:03 +080044double calculateMinimumValue(std::vector<double>& values)
45{
46 auto maxIt = std::min_element(values.begin(), values.end());
47 if (maxIt == values.end())
48 {
49 return std::numeric_limits<double>::quiet_NaN();
50 }
51 return *maxIt;
52}
53
George Liu4e6081b2024-09-19 10:09:04 +080054double calculateSumValue(std::vector<double>& values)
55{
56 if (values.empty())
57 {
58 return std::numeric_limits<double>::quiet_NaN();
59 }
60 return std::accumulate(values.begin(), values.end(), 0.0);
61}
62
George Liu7f41a0d2024-08-28 16:49:06 +080063std::map<Interface, CalculationFunc> calculationIfaces{
64 {"xyz.openbmc_project.Configuration.Maximum", calculateMaximumValue},
George Liuc1f822c2024-08-28 17:26:03 +080065 {"xyz.openbmc_project.Configuration.Minimum", calculateMinimumValue},
George Liu4e6081b2024-09-19 10:09:04 +080066 {"xyz.openbmc_project.Configuration.Sum", calculateSumValue},
George Liu7f41a0d2024-08-28 16:49:06 +080067 {"xyz.openbmc_project.Configuration.ModifiedMedian",
68 calculateModifiedMedianValue}};
69
70} // namespace phosphor::virtual_sensor