| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | // Copyright 2019 Juan Palacios <[email protected]> |
| 3 | |
| 4 | #include "commonutils.h" |
| 5 | |
| 6 | #include "common/mathutils.h" |
| 7 | #include <algorithm> |
| 8 | #include <cstddef> |
| 9 | #include <iterator> |
| 10 | |
| 11 | namespace Utils::Common { |
| 12 | |
| 13 | void normalizePoints( |
| 14 | std::vector<std::pair<units::temperature::celsius_t, |
| 15 | units::concentration::percent_t>> &points, |
| 16 | std::pair<units::temperature::celsius_t, units::temperature::celsius_t> tempRange, |
| 17 | std::pair<units::concentration::percent_t, units::concentration::percent_t> |
| 18 | speedRange) |
| 19 | { |
| 20 | std::vector<double> temps; |
| 21 | |
| 22 | if (std::any_of(points.cbegin(), points.cend(), [&](auto const &point) { |
| 23 | return point.first < tempRange.first || point.first > tempRange.second; |
| 24 | })) { |
| 25 | std::transform( |
| 26 | points.cbegin(), points.cend(), std::back_inserter(temps), |
| 27 | [](auto const &point) { return point.first.template to<double>(); }); |
| 28 | |
| 29 | auto [minTemp, maxTemp] = std::minmax_element(temps.cbegin(), temps.cend()); |
| 30 | |
| 31 | Utils::Math::linearNorm( |
| 32 | temps, std::make_pair(std::min(0.0, *minTemp), std::max(90.0, *maxTemp)), |
| 33 | std::make_pair(tempRange.first.to<double>(), |
| 34 | tempRange.second.to<double>())); |
| 35 | } |
| 36 | |
| 37 | for (size_t i = 0; i < points.size(); ++i) { |
| 38 | auto &[temp, pwm] = points.at(i); |
| 39 | pwm = std::clamp(pwm, speedRange.first, speedRange.second); |
| 40 | |
| 41 | // ensure that point.pwm >= prevPoint.pwm |
| 42 | if (points.size() > 1 && i > 0) { |
| 43 | auto const &[_, prevPwm] = points.at(i - 1); |
| 44 | if (pwm < prevPwm) |
| 45 | pwm = prevPwm; |
| 46 | } |
| 47 | |
| 48 | if (!temps.empty()) |
| 49 | temp = units::temperature::celsius_t(temps[i]); |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | } // namespace Utils::Common |