mod common;
use flexibility::MeasurementPoint;
use flexibility::jiff::tz::TimeZone;
use flexibility::jiff::{SignedDuration, Timestamp};
use flexibility::{
Bounds, Envelope, Grid, IspDuration, Limit, Power, Provenance, Schedule, Series, Window,
};
use proptest::prelude::*;
const ISPS: u32 = 8;
fn grid() -> Grid {
Grid::new(
Timestamp::UNIX_EPOCH,
IspDuration::FIFTEEN_MINUTES,
ISPS,
TimeZone::UTC,
)
.unwrap()
}
fn bounds() -> impl Strategy<Value = Bounds> {
(
proptest::option::of(-10_000_i64..10_000),
proptest::option::of(-10_000_i64..10_000),
)
.prop_map(|(a, b)| {
let (min, max) = match (a, b) {
(Some(a), Some(b)) => (Some(a.min(b)), Some(a.max(b))),
other => other,
};
Bounds::new(min.map(Power::from_watts), max.map(Power::from_watts)).unwrap()
})
}
fn envelope(tag: &'static str) -> impl Strategy<Value = Option<Envelope>> {
proptest::collection::vec((0_i64..120, 1_i64..120, bounds()), 0..3).prop_map(move |limits| {
let mut env = Envelope::unbounded(grid());
for (i, (from, len, b)) in limits.into_iter().enumerate() {
let from_t = Timestamp::UNIX_EPOCH + SignedDuration::from_mins(from);
let until = from_t + SignedDuration::from_mins(len);
let p = Provenance::new(tag, i.to_string(), Timestamp::UNIX_EPOCH);
env = env
.apply(&Limit::new(Window::new(from_t, until).ok()?, b, p))
.ok()?;
}
Some(env)
})
}
fn all_bounds(e: &Envelope) -> Vec<Bounds> {
(1..=ISPS).map(|i| e.bounds(i).unwrap()).collect()
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(1_000))]
#[test]
fn combine_is_commutative_and_never_widens(a in envelope("a"), b in envelope("b")) {
let (Some(a), Some(b)) = (a, b) else { return Ok(()) };
match (a.combine(&b), b.combine(&a)) {
(Ok(ab), Ok(ba)) => {
prop_assert_eq!(all_bounds(&ab), all_bounds(&ba));
for isp in 1..=ISPS {
let c = ab.bounds(isp).unwrap();
for side in [a.bounds(isp).unwrap(), b.bounds(isp).unwrap()] {
if let Some(m) = side.max() { prop_assert!(c.max().is_some_and(|x| x <= m)); }
if let Some(m) = side.min() { prop_assert!(c.min().is_some_and(|x| x >= m)); }
}
}
}
(Err(x), Err(y)) => prop_assert_eq!(x, y),
_ => prop_assert!(false, "one order failed, the other did not"),
}
}
#[test]
fn combine_is_associative(a in envelope("a"), b in envelope("b"), c in envelope("c")) {
let (Some(a), Some(b), Some(c)) = (a, b, c) else { return Ok(()) };
let left = a.combine(&b).and_then(|ab| ab.combine(&c));
let right = b.combine(&c).and_then(|bc| a.combine(&bc));
match (left, right) {
(Ok(l), Ok(r)) => prop_assert_eq!(all_bounds(&l), all_bounds(&r)),
(Err(_), Err(_)) => {}
_ => prop_assert!(false, "associativity broke on failure"),
}
}
#[test]
fn nothing_panics(
x in any::<i64>(), y in any::<i64>(), m in any::<u64>(),
start in any::<i64>(), minutes in any::<u16>(), count in any::<u32>(),
isp in any::<u32>(), from in any::<i64>(), until in any::<i64>(),
) {
let (p, q) = (Power::from_watts(x), Power::from_watts(y));
let _ = (p.checked_add(q), p.checked_sub(q), p.checked_neg(), p.magnitude(), p.direction());
let _ = (Power::consumption(m), Power::feed_in(m), Bounds::new(Some(p), Some(q)));
let t = |s: i64| Timestamp::from_second(s.rem_euclid(253_402_207_200) - 62_135_596_800).unwrap_or(Timestamp::UNIX_EPOCH);
let _ = IspDuration::from_minutes(minutes);
let isp_len = IspDuration::from_minutes(minutes).unwrap_or(IspDuration::FIFTEEN_MINUTES);
if let Ok(g) = Grid::new(t(start), isp_len, count % 2_000, TimeZone::UTC) {
let _ = (g.interval(isp), g.isp_at(t(from)), Window::new(t(from), t(until)).ok().and_then(|w| g.isps(w)), g.end());
let env = Envelope::unbounded(g.clone());
let prov = Provenance::new("p", "r", t(start));
if let Ok(b) = Bounds::new(Some(p.min(q)), Some(p.max(q)))
&& let Ok(win) = Window::new(t(from), t(until))
&& let l = Limit::new(win, b, prov.clone())
{
let _ = l.isps(&g);
if let Ok(e) = env.apply(&l) {
let _ = (e.bounds(isp), e.max_source(isp), e.min_source(isp));
let plan = Schedule::new(Series::filled(g, p), prov);
let _ = plan.check(&e);
}
}
}
}
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(2_000))]
#[test]
fn power_text_round_trips(watts in any::<i64>()) {
let p = Power::from_watts(watts);
prop_assert_eq!(p.to_string().parse::<Power>().unwrap(), p);
prop_assert_eq!(format!("{p:#}").parse::<Power>().unwrap(), p);
let d = flexibility::Deviation::from_watts(watts);
prop_assert_eq!(d.to_string().parse::<flexibility::Deviation>().unwrap(), d);
}
#[test]
fn deviation_adds_back(a in any::<i64>(), b in any::<i64>()) {
let (a, b) = (Power::from_watts(a), Power::from_watts(b));
if let Ok(d) = a.deviation_from(b) {
prop_assert_eq!(b.checked_add_deviation(d).unwrap(), a);
}
}
#[test]
fn new_operations_never_panic(text in "\\PC{0,80}", x in any::<i64>(), minutes in 1_u16..=1440, isp in any::<u32>()) {
let _ = text.parse::<Power>();
let _ = text.parse::<flexibility::Deviation>();
let p = Power::from_watts(x);
let len = IspDuration::from_minutes(minutes).unwrap_or(IspDuration::FIFTEEN_MINUTES);
let _ = (p.energy(len), p.to_string(), format!("{p:#}"));
let e = flexibility::Energy::from_watt_seconds(x);
let _ = (e.to_string(), Power::average(e, len, flexibility::Rounding::Exact));
let _ = Power::average(e, len, flexibility::Rounding::HalfAwayFromZero);
let g = grid();
let _ = (g.label(isp), g.label(isp).map(|l| l.to_string()));
let env = Envelope::unbounded(g.clone());
let _ = env.explain(isp).map(|e| e.to_string());
let _ = env.headroom(&Schedule::new(Series::filled(g, p), Provenance::new("p", "r", Timestamp::UNIX_EPOCH)));
}
}
mod settlement_properties {
use super::*;
use flexibility::baseline::{self, Adjustment, XofY};
use flexibility::{Deviation, settle};
fn one(base: i64, actual: i64, order: i64) -> (i64, i64) {
let g = Grid::new(
Timestamp::UNIX_EPOCH,
IspDuration::FIFTEEN_MINUTES,
1,
TimeZone::UTC,
)
.unwrap();
let all = Window::new(g.start(), g.end()).unwrap();
let p = Provenance::new("p", "r", Timestamp::UNIX_EPOCH);
let b = baseline::dprognosis(
&Schedule::new(Series::filled(g.clone(), Power::from_watts(base)), p),
all,
)
.unwrap();
let s = settle(
&b,
&Series::filled(g.clone(), Power::from_watts(actual)),
&Series::filled(g, Deviation::from_watts(order)),
MeasurementPoint::ConnectionPoint,
)
.unwrap();
(
s.lines()[0].delivered.watts(),
s.lines()[0].deficiency.watts(),
)
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(2_000))]
#[test]
fn delivered_and_deficiency_conserve_the_order(b in -50_000i64..50_000, a in -50_000i64..50_000, o in -20_000i64..20_000) {
let (delivered, deficiency) = one(b, a, o);
let r = (a - b) * o.signum();
prop_assert_eq!(delivered.abs() + deficiency, o.abs() + (-r).max(0) * i64::from(o != 0));
prop_assert!(delivered.abs() <= o.abs());
prop_assert!(deficiency >= 0);
prop_assert!(delivered == 0 || delivered.signum() == o.signum());
prop_assert_eq!(one(-b, -a, -o), (-delivered, deficiency));
}
#[test]
fn xofy_is_order_independent(levels in proptest::collection::vec(0i64..5, 4), x in 1u32..=4, rotate in 0usize..4) {
let berlin = TimeZone::get("Europe/Berlin").unwrap();
let d = |n: i8| flexibility::jiff::civil::date(2026, 11, n);
let day = Grid::day(d(30), &berlin, IspDuration::FIFTEEN_MINUTES).unwrap();
let history: Vec<_> = levels.iter().enumerate().map(|(i, &l)| {
let g = Grid::day(d(20 + i8::try_from(i).unwrap()), &berlin, IspDuration::FIFTEEN_MINUTES).unwrap();
Series::filled(g, Power::from_watts(l * 1_000))
}).collect();
let mut shuffled = history.clone();
shuffled.rotate_left(rotate);
let event = Window::new(day.start(), day.end()).unwrap();
let p = XofY { x, y: 4, adjustment: Adjustment::None };
let a = baseline::xofy(&day, event, &history, None, p).unwrap();
let b = baseline::xofy(&day, event, &shuffled, None, p).unwrap();
prop_assert_eq!(a.digest(), b.digest());
}
#[test]
fn canonical_text_is_injective_on_strings(a in "\\PC{0,12}", b in "\\PC{0,12}") {
let g = grid();
let all = Window::new(g.start(), g.end()).unwrap();
let s = |issuer: &str| {
let p = Provenance::new(issuer, "r", Timestamp::UNIX_EPOCH);
baseline::schedule(&Schedule::new(Series::filled(g.clone(), Power::ZERO), p), all).unwrap().canonical()
};
prop_assert_eq!(s(&a) == s(&b), a == b);
}
#[test]
fn settlement_never_panics(b in any::<i64>(), a in any::<i64>(), o in any::<i64>()) {
let g = Grid::new(Timestamp::UNIX_EPOCH, IspDuration::FIFTEEN_MINUTES, 1, TimeZone::UTC).unwrap();
let all = Window::new(g.start(), g.end()).unwrap();
let p = Provenance::new("p", "r", Timestamp::UNIX_EPOCH);
let Ok(base) = baseline::dprognosis(&Schedule::new(Series::filled(g.clone(), Power::from_watts(b)), p), all) else {
return Ok(());
};
let _ = settle(&base, &Series::filled(g.clone(), Power::from_watts(a)), &Series::filled(g.clone(), Deviation::from_watts(o)), MeasurementPoint::ConnectionPoint);
let _ = flexibility::accuracy::score([(base.series(), &Series::filled(g, Power::from_watts(a)))]);
}
}
}
mod pools {
use super::*;
use flexibility::pool;
use flexibility::{Deviation, Energy, EnergyEnvelope, Level};
const N: u32 = 3;
fn proportional(total: i64, weights: &[i64]) -> Vec<i64> {
let sum: i64 = weights.iter().sum();
if sum == 0 {
return vec![0; weights.len()];
}
let mut shares: Vec<i64> = weights.iter().map(|w| total * w / sum).collect();
let mut left = total - shares.iter().sum::<i64>();
for (s, w) in shares.iter_mut().zip(weights) {
if left > 0 && *s < *w {
*s += 1;
left -= 1;
}
}
shares
}
fn g() -> Grid {
Grid::new(
Timestamp::UNIX_EPOCH,
IspDuration::FIFTEEN_MINUTES,
N,
TimeZone::UTC,
)
.unwrap()
}
fn who() -> Provenance {
Provenance::new("p", "q", Timestamp::UNIX_EPOCH)
}
fn device() -> impl Strategy<Value = (EnergyEnvelope, Schedule)> {
(
proptest::collection::vec(-4_000_i64..4_000, N as usize),
0_i64..10_000_000,
proptest::collection::vec(
(0_i64..1_000, 0_i64..1_000, any::<bool>(), any::<bool>()),
N as usize,
),
proptest::collection::vec(
(0_i64..900_000, 0_i64..900_000, any::<bool>(), any::<bool>()),
N as usize,
),
)
.prop_map(|(watts, initial, slack, level_slack)| {
let grid = g();
let mut env = Envelope::unbounded(grid.clone());
let mut level = initial;
let mut storage_bounds = Vec::new();
for (i, &w) in watts.iter().enumerate() {
let n = u32::try_from(i).unwrap() + 1;
let (lo, hi, has_lo, has_hi) = slack[i];
let b = Bounds::new(
has_lo.then(|| Power::from_watts(w - lo)),
has_hi.then(|| Power::from_watts(w + hi)),
)
.unwrap();
env = env
.apply(&Limit::new(grid.interval(n).unwrap(), b, who()))
.unwrap();
level += w * 900;
let (lo, hi, has_lo, has_hi) = level_slack[i];
storage_bounds.push((
grid.interval(n).unwrap().until(),
Level::new(
has_lo.then(|| Energy::from_watt_seconds(level - lo)),
has_hi.then(|| Energy::from_watt_seconds(level + hi)),
)
.unwrap(),
));
}
let mut e = EnergyEnvelope::new(env, Energy::from_watt_seconds(initial));
for (at, l) in storage_bounds {
e = e.level_at(at, l, who()).unwrap();
}
let plan = Schedule::new(
Series::new(grid, watts.into_iter().map(Power::from_watts).collect()).unwrap(),
who(),
);
(e, plan)
})
}
proptest! {
#[test]
fn the_aggregate_contains_every_valid_split(devices in proptest::collection::vec(device(), 1..4)) {
let envs: Vec<_> = devices.iter().map(|(e, _)| e.clone()).collect();
let agg = pool::aggregate(&envs, who()).unwrap();
let sum = (0..N as usize)
.map(|k| Power::from_watts(devices.iter().map(|(_, p)| p.series().values()[k].watts()).sum()))
.collect();
let pool_plan = Schedule::new(Series::new(g(), sum).unwrap(), who());
prop_assert!(agg.envelope().check(&pool_plan).unwrap().fits());
let split: Vec<_> = devices.iter().map(|(e, p)| (e, p)).collect();
prop_assert!(pool::check_split(&pool_plan, &split).unwrap().fits());
}
#[test]
fn a_proportional_split_of_the_steady_headroom_fits(
devices in proptest::collection::vec(device(), 1..4),
(first, len) in (1..=N).prop_flat_map(|f| (Just(f), 1..=N - f + 1)),
permille in 0_i64..=1000,
upward in any::<bool>(),
) {
let grid = g();
let window = Window::new(
grid.interval(first).unwrap().from(),
grid.interval(first + len - 1).unwrap().until(),
).unwrap();
let cap = 10_000;
let room: Vec<i64> = devices.iter().map(|(e, p)| {
let h = e.steady_headroom(p, window).unwrap().expect("a fitting plan has 0 W");
let side = if upward { h.up.map(Deviation::watts) } else { h.down.map(|d| -d.watts()) };
let r = side.map_or(cap, |r| r.min(cap));
assert!(r >= 0, "0 W fits a fitting plan");
r
}).collect();
let total = room.iter().sum::<i64>() * permille / 1000;
let sign = if upward { 1 } else { -1 };
let shares = proportional(total, &room);
let moved: Vec<Schedule> = devices.iter().zip(&shares).map(|((_, p), share)| {
let values = p.series().iter().map(|(isp, w)| {
let d = if (first..first + len).contains(&isp) { sign * share } else { 0 };
Power::from_watts(w.watts() + d)
}).collect();
Schedule::new(Series::new(grid.clone(), values).unwrap(), who())
}).collect();
let sum = (0..N as usize)
.map(|k| Power::from_watts(moved.iter().map(|p| p.series().values()[k].watts()).sum()))
.collect();
let pool_plan = Schedule::new(Series::new(grid.clone(), sum).unwrap(), who());
let split: Vec<_> = devices.iter().zip(&moved).map(|((e, _), p)| (e, p)).collect();
prop_assert!(pool::check_split(&pool_plan, &split).unwrap().fits());
for (e, p) in &devices {
let h = e.steady_headroom(p, window).unwrap().unwrap();
let past = if upward { h.up.map(|d| d.watts() + 1) } else { h.down.map(|d| d.watts() - 1) };
if let Some(d) = past {
let values = p.series().iter().map(|(isp, w)| {
Power::from_watts(w.watts() + if (first..first + len).contains(&isp) { d } else { 0 })
}).collect();
let beyond = Schedule::new(Series::new(grid.clone(), values).unwrap(), who());
prop_assert!(!e.check(&beyond).unwrap().fits());
}
}
}
#[test]
fn boxes_aggregate_exactly(
a in (-20_i64..20, 0_i64..20), b in (-20_i64..20, 0_i64..20), p in -60_i64..60,
) {
let grid = Grid::new(Timestamp::UNIX_EPOCH, IspDuration::FIFTEEN_MINUTES, 1, TimeZone::UTC).unwrap();
let all = Window::new(grid.start(), grid.end()).unwrap();
let boxed = |(lo, width): (i64, i64)| {
let b = Bounds::new(Some(Power::from_watts(lo)), Some(Power::from_watts(lo + width))).unwrap();
EnergyEnvelope::new(Envelope::unbounded(grid.clone()).apply(&Limit::new(all, b, who())).unwrap(), Energy::ZERO)
};
let agg = pool::aggregate(&[boxed(a), boxed(b)], who()).unwrap();
prop_assert!(agg.is_exact());
let pool_plan = Schedule::new(Series::filled(grid.clone(), Power::from_watts(p)), who());
let fits = agg.envelope().check(&pool_plan).unwrap().fits();
let some_split = (a.0..=a.0 + a.1).any(|x| (b.0..=b.0 + b.1).contains(&(p - x)));
prop_assert_eq!(fits, some_split);
}
}
}
mod receipts {
use super::*;
use flexibility::{Deviation, Settlement, baseline, settle};
fn settled(base: i64, actual: &[i64], order: i64) -> Settlement {
let g = Grid::new(
Timestamp::UNIX_EPOCH,
IspDuration::FIFTEEN_MINUTES,
u32::try_from(actual.len()).unwrap(),
TimeZone::UTC,
)
.unwrap();
let who = Provenance::new("p", "q", Timestamp::UNIX_EPOCH);
let all = Window::new(g.start(), g.end()).unwrap();
let b = baseline::dprognosis(
&Schedule::new(Series::filled(g.clone(), Power::from_watts(base)), who),
all,
)
.unwrap();
let a = Series::new(
g.clone(),
actual.iter().map(|&w| Power::from_watts(w)).collect(),
)
.unwrap();
settle(
&b,
&a,
&Series::filled(g, Deviation::from_watts(order)),
MeasurementPoint::ConnectionPoint,
)
.unwrap()
}
proptest! {
#[test]
fn every_settlement_reads_back(base in -1_000_000i64..1_000_000, actual in proptest::collection::vec(-1_000_000i64..1_000_000, 1..6), order in -500_000i64..500_000) {
let s = settled(base, &actual, order);
prop_assert_eq!(Settlement::from_canonical(&s.canonical(), TimeZone::UTC).unwrap(), s);
}
#[test]
fn a_changed_byte_never_keeps_the_digest(actual in proptest::collection::vec(-100_000i64..100_000, 1..4), at in any::<prop::sample::Index>(), byte in 0x20u8..0x7f) {
let s = settled(50_000, &actual, -20_000);
let mut bytes = s.canonical().into_bytes();
let i = at.index(bytes.len());
prop_assume!(bytes[i] != byte);
bytes[i] = byte;
if let Ok(text) = String::from_utf8(bytes)
&& let Ok(read) = Settlement::from_canonical(&text, TimeZone::UTC)
{
prop_assert_ne!(read.digest(), s.digest());
}
}
#[test]
fn arbitrary_text_never_panics(text in "\\PC{0,200}", prefix in "[\\[{\"0-9,:-]{0,40}") {
let _ = Settlement::from_canonical(&text, TimeZone::UTC);
let _ = Settlement::from_canonical(&format!("{prefix}{text}"), TimeZone::UTC);
}
}
}