Use medians

This commit is contained in:
Pierre HUBERT 2024-09-26 23:05:10 +02:00
parent 7895b9eca8
commit 3f41269c0b
4 changed files with 20 additions and 9 deletions

View File

@ -1,5 +1,6 @@
use crate::constants; use crate::constants;
use crate::energy::consumption::EnergyConsumption; use crate::energy::consumption::EnergyConsumption;
use crate::utils::math_utils::median;
pub struct ConsumptionCache { pub struct ConsumptionCache {
nb_vals: usize, nb_vals: usize,
@ -27,13 +28,7 @@ impl ConsumptionCache {
return constants::FALLBACK_PRODUCTION_VALUE; return constants::FALLBACK_PRODUCTION_VALUE;
} }
let mut clone = self.values.clone(); median(&self.values)
clone.sort();
let median = clone[clone.len() / 2];
log::info!("Cached consumption: {:?} / Median: {}", self.values, median);
median
} }
} }

View File

@ -1,5 +1,6 @@
use crate::app_config::{AppConfig, ConsumptionHistoryType}; use crate::app_config::{AppConfig, ConsumptionHistoryType};
use crate::energy::consumption::EnergyConsumption; use crate::energy::consumption::EnergyConsumption;
use crate::utils::math_utils::median;
use crate::utils::time_utils::day_number; use crate::utils::time_utils::day_number;
const TIME_INTERVAL: usize = 10; const TIME_INTERVAL: usize = 10;
@ -109,14 +110,20 @@ impl ConsumptionHistoryFile {
let mut file = Self::open(from, r#type)?; let mut file = Self::open(from, r#type)?;
let mut curr_time = from; let mut curr_time = from;
let mut intermediate_values = Vec::new();
while curr_time < to { while curr_time < to {
if !file.contains_time(curr_time) { if !file.contains_time(curr_time) {
file = Self::open(curr_time, r#type)?; 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) Ok(res)

View File

@ -0,0 +1,8 @@
use std::ops::Div;
pub fn median<E: Div + Copy + Ord>(numbers: &[E]) -> E {
let mut numbers = numbers.to_vec();
numbers.sort();
let mid = numbers.len() / 2;
numbers[mid]
}

View File

@ -1,2 +1,3 @@
pub mod files_utils; pub mod files_utils;
pub mod math_utils;
pub mod time_utils; pub mod time_utils;