use time::{Duration, OffsetDateTime};
use crate::domain::{
CarbonIntensity, ForecastPoint, GreenWindow, WindowEstimator, greenest_window,
};
fn estimate(p: &ForecastPoint, estimator: WindowEstimator) -> f64 {
match estimator {
WindowEstimator::Central => p.expected.value(),
WindowEstimator::Prudent => p.upper.value(),
}
}
fn step_of(points: &[ForecastPoint]) -> Option<Duration> {
if points.len() < 2 {
return None;
}
let step = points[1].at - points[0].at;
(step > Duration::ZERO).then_some(step)
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ScheduleSlot {
pub at: OffsetDateTime,
pub intensity: CarbonIntensity,
}
pub fn greenest_window_before(
points: &[ForecastPoint],
duration: Duration,
deadline: OffsetDateTime,
estimator: WindowEstimator,
) -> Option<GreenWindow> {
let step = step_of(points)?;
let cutoff = points
.iter()
.take_while(|p| p.at + step <= deadline)
.count();
if cutoff == 1 {
if duration <= Duration::ZERO || duration > step {
return None;
}
let p = &points[0];
let average = CarbonIntensity::new(estimate(p, estimator))?;
return Some(GreenWindow {
start: p.at,
end: p.at + step,
average,
});
}
greenest_window(&points[..cutoff], duration, estimator)
}
pub fn lowest_slots(
points: &[ForecastPoint],
k: usize,
estimator: WindowEstimator,
) -> Vec<ScheduleSlot> {
if k == 0 {
return Vec::new();
}
let mut slots: Vec<ScheduleSlot> = points
.iter()
.filter_map(|p| {
CarbonIntensity::new(estimate(p, estimator)).map(|intensity| ScheduleSlot {
at: p.at,
intensity,
})
})
.collect();
slots.sort_by(|a, b| {
a.intensity
.value()
.partial_cmp(&b.intensity.value())
.unwrap_or(std::cmp::Ordering::Equal)
});
slots.truncate(k);
slots.sort_by_key(|s| s.at);
slots
}
pub fn slots_below(
points: &[ForecastPoint],
threshold: f64,
estimator: WindowEstimator,
) -> Vec<ScheduleSlot> {
points
.iter()
.filter_map(|p| {
let value = estimate(p, estimator);
if value < threshold {
CarbonIntensity::new(value).map(|intensity| ScheduleSlot {
at: p.at,
intensity,
})
} else {
None
}
})
.collect()
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Savings {
pub now: CarbonIntensity,
pub scheduled: CarbonIntensity,
pub intensity_delta: f64,
pub fraction: f64,
pub absolute_g: Option<f64>,
}
pub fn savings_vs_now(
points: &[ForecastPoint],
scheduled: CarbonIntensity,
energy_kwh: Option<f64>,
estimator: WindowEstimator,
) -> Option<Savings> {
let first = points.first()?;
let now = CarbonIntensity::new(estimate(first, estimator))?;
let intensity_delta = now.value() - scheduled.value();
let fraction = if now.value() > 0.0 {
intensity_delta / now.value()
} else {
0.0
};
let absolute_g = energy_kwh.map(|kwh| intensity_delta * kwh);
Some(Savings {
now,
scheduled,
intensity_delta,
fraction,
absolute_g,
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::domain::{Methodology, ModelVersion, Region};
fn p(at: OffsetDateTime, g: f64) -> ForecastPoint {
ForecastPoint::new(
at,
Region::National,
CarbonIntensity::new(g).unwrap(),
CarbonIntensity::new((g - 5.0).max(0.0)).unwrap(),
CarbonIntensity::new(g + 5.0).unwrap(),
Methodology::rte_direct(),
ModelVersion::new("climatology", 1),
)
}
fn series(values: &[f64]) -> Vec<ForecastPoint> {
let t0 = OffsetDateTime::UNIX_EPOCH;
let step = Duration::minutes(15);
values
.iter()
.enumerate()
.map(|(i, &g)| p(t0 + step * (i as i32), g))
.collect()
}
#[test]
fn deadline_excludes_later_cheaper_window() {
let points = series(&[100.0, 40.0, 50.0, 10.0, 12.0]);
let t0 = OffsetDateTime::UNIX_EPOCH;
let step = Duration::minutes(15);
let deadline = t0 + step * 3;
let w = greenest_window_before(
&points,
Duration::minutes(15),
deadline,
WindowEstimator::Central,
)
.unwrap();
assert_eq!(w.start, t0 + step);
assert!(w.average.value() < 50.0 && w.average.value() >= 40.0);
}
#[test]
fn single_eligible_slot_before_tight_deadline_still_wins() {
let points = series(&[100.0, 10.0, 50.0]);
let t0 = OffsetDateTime::UNIX_EPOCH;
let step = Duration::minutes(15);
let deadline = t0 + step;
let w = greenest_window_before(
&points,
Duration::minutes(15),
deadline,
WindowEstimator::Central,
)
.expect("un créneau unique éligible doit être renvoyé, pas None");
assert_eq!(w.start, t0);
assert_eq!(w.end, t0 + step);
assert_eq!(w.average.value(), 100.0);
}
#[test]
fn single_eligible_slot_too_short_for_duration_stays_none() {
let points = series(&[100.0, 10.0, 50.0]);
let t0 = OffsetDateTime::UNIX_EPOCH;
let step = Duration::minutes(15);
let deadline = t0 + step; let w = greenest_window_before(
&points,
Duration::minutes(30), deadline,
WindowEstimator::Central,
);
assert!(w.is_none());
}
#[test]
fn no_eligible_slot_before_deadline_is_none() {
let points = series(&[100.0, 10.0, 50.0]);
let t0 = OffsetDateTime::UNIX_EPOCH;
let w = greenest_window_before(
&points,
Duration::minutes(15),
t0, WindowEstimator::Central,
);
assert!(w.is_none());
}
#[test]
fn lowest_slots_picks_k_cheapest_in_time_order() {
let points = series(&[100.0, 10.0, 80.0, 20.0, 90.0]);
let t0 = OffsetDateTime::UNIX_EPOCH;
let step = Duration::minutes(15);
let slots = lowest_slots(&points, 2, WindowEstimator::Central);
assert_eq!(slots.len(), 2);
assert_eq!(slots[0].at, t0 + step);
assert_eq!(slots[1].at, t0 + step * 3);
assert!(slots[0].intensity.value() < slots[1].intensity.value());
}
#[test]
fn lowest_slots_caps_at_series_length() {
let points = series(&[30.0, 20.0]);
assert_eq!(lowest_slots(&points, 10, WindowEstimator::Central).len(), 2);
assert!(lowest_slots(&points, 0, WindowEstimator::Central).is_empty());
}
#[test]
fn slots_below_threshold_keeps_time_order() {
let points = series(&[100.0, 40.0, 55.0, 30.0]);
let below = slots_below(&points, 50.0, WindowEstimator::Central);
assert_eq!(below.len(), 2);
assert_eq!(below[0].intensity.value(), 40.0);
assert_eq!(below[1].intensity.value(), 30.0);
}
#[test]
fn savings_absolute_needs_energy() {
let points = series(&[100.0, 20.0]);
let scheduled = CarbonIntensity::new(20.0).unwrap();
let relative = savings_vs_now(&points, scheduled, None, WindowEstimator::Central).unwrap();
assert_eq!(relative.intensity_delta, 80.0);
assert!((relative.fraction - 0.8).abs() < 1e-9);
assert!(relative.absolute_g.is_none());
let absolute =
savings_vs_now(&points, scheduled, Some(10.0), WindowEstimator::Central).unwrap();
assert_eq!(absolute.absolute_g, Some(800.0));
}
}