From 3f41269c0ba31ac16fc9e66f588b3bf5283c204b Mon Sep 17 00:00:00 2001 From: Pierre HUBERT Date: Thu, 26 Sep 2024 23:05:10 +0200 Subject: [PATCH] Use medians --- central_backend/src/energy/consumption_cache.rs | 9 ++------- .../src/energy/consumption_history_file.rs | 11 +++++++++-- central_backend/src/utils/math_utils.rs | 8 ++++++++ central_backend/src/utils/mod.rs | 1 + 4 files changed, 20 insertions(+), 9 deletions(-) create mode 100644 central_backend/src/utils/math_utils.rs diff --git a/central_backend/src/energy/consumption_cache.rs b/central_backend/src/energy/consumption_cache.rs index f9beefe..c702dc7 100644 --- a/central_backend/src/energy/consumption_cache.rs +++ b/central_backend/src/energy/consumption_cache.rs @@ -1,5 +1,6 @@ use crate::constants; use crate::energy::consumption::EnergyConsumption; +use crate::utils::math_utils::median; pub struct ConsumptionCache { nb_vals: usize, @@ -27,13 +28,7 @@ impl ConsumptionCache { return constants::FALLBACK_PRODUCTION_VALUE; } - let mut clone = self.values.clone(); - clone.sort(); - let median = clone[clone.len() / 2]; - - log::info!("Cached consumption: {:?} / Median: {}", self.values, median); - - median + median(&self.values) } } diff --git a/central_backend/src/energy/consumption_history_file.rs b/central_backend/src/energy/consumption_history_file.rs index f4f8757..513c7e8 100644 --- a/central_backend/src/energy/consumption_history_file.rs +++ b/central_backend/src/energy/consumption_history_file.rs @@ -1,5 +1,6 @@ use crate::app_config::{AppConfig, ConsumptionHistoryType}; use crate::energy::consumption::EnergyConsumption; +use crate::utils::math_utils::median; use crate::utils::time_utils::day_number; const TIME_INTERVAL: usize = 10; @@ -109,14 +110,20 @@ impl ConsumptionHistoryFile { let mut file = Self::open(from, r#type)?; let mut curr_time = from; + let mut intermediate_values = Vec::new(); while curr_time < to { if !file.contains_time(curr_time) { file = Self::open(curr_time, r#type)?; } - res.push(file.get_consumption(curr_time)?); + intermediate_values.push(file.get_consumption(curr_time)?); - curr_time += interval; + if curr_time % interval == from % interval { + res.push(median(&intermediate_values)); + intermediate_values = Vec::new(); + } + + curr_time += TIME_INTERVAL as u64; } Ok(res) diff --git a/central_backend/src/utils/math_utils.rs b/central_backend/src/utils/math_utils.rs new file mode 100644 index 0000000..4421ff8 --- /dev/null +++ b/central_backend/src/utils/math_utils.rs @@ -0,0 +1,8 @@ +use std::ops::Div; + +pub fn median(numbers: &[E]) -> E { + let mut numbers = numbers.to_vec(); + numbers.sort(); + let mid = numbers.len() / 2; + numbers[mid] +} diff --git a/central_backend/src/utils/mod.rs b/central_backend/src/utils/mod.rs index 25676ba..5ccc580 100644 --- a/central_backend/src/utils/mod.rs +++ b/central_backend/src/utils/mod.rs @@ -1,2 +1,3 @@ pub mod files_utils; + pub mod math_utils; pub mod time_utils;