Skip to main content

flexpool_sim/
synthetic.rs

1//! A deterministic, plausible German day-ahead day.
2//!
3//! Morning and evening peaks, a midday solar dip whose depth depends on a seeded "sunniness"
4//! (deep enough for negative prices on sunny days), and noise. Computed in `f64`, quantised to the
5//! day's price granularity through `flexpool_core::quantize`, clamped to the price limits in force.
6//! The same seed gives the same day on every platform and version (own SplitMix64, no `rand`).
7
8use flexpool_core::{BusinessDay, EurPerMwh, Granularity, quantize};
9use time::{Duration, OffsetDateTime};
10
11/// SplitMix64 — tiny, deterministic, good enough for synthetic data.
12#[derive(Debug, Clone)]
13pub struct SplitMix64(u64);
14
15impl SplitMix64 {
16    /// A generator for `seed`.
17    #[must_use]
18    pub const fn new(seed: u64) -> Self {
19        Self(seed)
20    }
21
22    /// The next 64 random bits.
23    pub fn next_u64(&mut self) -> u64 {
24        self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
25        let mut z = self.0;
26        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
27        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
28        z ^ (z >> 31)
29    }
30
31    /// A uniform value in `[0, 1)`.
32    pub fn unit(&mut self) -> f64 {
33        // 53 random mantissa bits.
34        (self.next_u64() >> 11) as f64 / (1_u64 << 53) as f64
35    }
36}
37
38fn bump(hour: f64, centre: f64, width: f64) -> f64 {
39    let x = (hour - centre) / width;
40    (-x * x).exp()
41}
42
43/// The price of each interval of `day` at `minutes` resolution, deterministic for `seed`.
44///
45/// Returns `(start, price)` pairs in time order.
46#[must_use]
47pub fn day_ahead(
48    day: &BusinessDay,
49    minutes: u16,
50    seed: u64,
51    price_step: Granularity,
52    limits: (EurPerMwh, EurPerMwh),
53) -> Vec<(OffsetDateTime, EurPerMwh)> {
54    let mut rng = SplitMix64::new(seed ^ u64::from(day.date().to_julian_day().unsigned_abs()));
55    let sunniness = rng.unit();
56    let base = 70.0 + 40.0 * rng.unit();
57    let step = Duration::minutes(i64::from(minutes));
58    let mut out = Vec::new();
59    let mut start = day.start();
60    while start < day.end() {
61        let local = flexpool_core::calendar::to_berlin(start);
62        let hour = f64::from(local.hour()) + f64::from(local.minute()) / 60.0;
63        let shape = 38.0 * bump(hour, 8.0, 1.6) + 55.0 * bump(hour, 19.0, 1.8)
64            - (40.0 + 130.0 * sunniness * sunniness) * bump(hour, 13.0, 2.4)
65            - 18.0 * bump(hour, 3.5, 2.0);
66        let noise = (rng.unit() - 0.5) * 12.0;
67        let price = quantize(base + shape + noise, price_step)
68            .map(|q| EurPerMwh::new(q.value))
69            .unwrap_or(EurPerMwh::ZERO)
70            .clamp(limits.0, limits.1);
71        out.push((start, price));
72        start += step;
73    }
74    out
75}