Skip to main content

flexpool_telemetry/
sim.rs

1//! The sandbox simulator: telemetry as a pure function of asset, seed, faults and time.
2//!
3//! Values are piecewise constant per minute, so the replay is deterministic and never needs a
4//! store. Every value is computed directly for its minute — a battery's state of charge in closed
5//! form from its daily schedule — so one asset at one instant costs O(1), whatever the time of day. The physics is plausible, not accurate — for demonstrating and
6//! testing, never for forecasting. Weather is shared by every asset (correlated pools); each asset
7//! adds its own small noise.
8
9use std::f64::consts::PI;
10
11use flexpool_core::{AssetId, BusinessDay};
12use flexpool_portfolio::{Asset, AssetKind};
13use time::OffsetDateTime;
14
15use crate::quality::{Flags, Quality, Quantity, Reading, classify};
16use crate::store::{AssetNow, QuarterAggregate, RECENT_SECS, Recent};
17use crate::{QUARTER_SECS, energy_kwh, quarter_start, rated_kw};
18
19/// Simulated values are stale after a minute without a new one.
20pub const STALE_SECS: i64 = 60;
21
22/// What a fault does to an asset.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum FaultKind {
25    /// No value at all.
26    Offline,
27    /// The value and its source time freeze at the fault's start.
28    Stuck,
29    /// Online and reporting, but delivering nothing — a tripped inverter: power 0, state of
30    /// charge held at the fault's start.
31    Tripped,
32}
33
34/// A planned disturbance of one asset over `[from, to)`.
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct Fault {
37    /// The asset.
38    pub asset: AssetId,
39    /// What happens.
40    pub kind: FaultKind,
41    /// Start, Unix seconds (inclusive).
42    pub from: i64,
43    /// End, Unix seconds (exclusive).
44    pub to: i64,
45}
46
47/// A battery's traded schedule for one delivery day: it follows the setpoints instead of its
48/// own daily pattern. The state of charge is closed-form from prefix sums, so it stays O(log n).
49#[derive(Debug, Clone, PartialEq)]
50pub struct Dispatch {
51    /// Unit starts (Unix seconds, ascending) with their setpoint, kW (generator convention: positive
52    /// is discharge).
53    units: Vec<(i64, f64)>,
54    /// Unit length, seconds.
55    unit_secs: i64,
56    /// State of charge (%) at the start of each unit, and after the last.
57    soc: Vec<f64>,
58    /// % per kWh for this battery and the one-way efficiency.
59    pct_per_kwh: f64,
60    efficiency: f64,
61}
62
63impl Dispatch {
64    /// A schedule of `units` (start, kW) of `unit_secs`, starting at `soc_start` % for a battery of
65    /// `energy_kwh` with round-trip efficiency `round_trip`.
66    #[must_use]
67    pub fn new(
68        units: Vec<(i64, f64)>,
69        unit_secs: i64,
70        soc_start: f64,
71        energy_kwh: f64,
72        round_trip: f64,
73    ) -> Self {
74        let pct_per_kwh = if energy_kwh > 0.0 {
75            100.0 / energy_kwh
76        } else {
77            0.0
78        };
79        let efficiency = round_trip.clamp(0.01, 1.0).sqrt();
80        let mut soc = Vec::with_capacity(units.len() + 1);
81        let mut level = soc_start;
82        soc.push(level);
83        #[expect(clippy::cast_precision_loss, reason = "seconds of a quarter hour")]
84        let hours = unit_secs as f64 / 3600.0;
85        for (_, kw) in &units {
86            level = (level + Self::change(*kw, hours, efficiency) * pct_per_kwh).clamp(0.0, 100.0);
87            soc.push(level);
88        }
89        Self {
90            units,
91            unit_secs,
92            soc,
93            pct_per_kwh,
94            efficiency,
95        }
96    }
97
98    /// kWh stored by `kw` over `hours`: discharge draws more than it delivers, charge stores less.
99    fn change(kw: f64, hours: f64, efficiency: f64) -> f64 {
100        if kw > 0.0 {
101            -kw * hours / efficiency
102        } else {
103            -kw * hours * efficiency
104        }
105    }
106
107    /// Power and state of charge at `t`, when the schedule covers it.
108    fn at(&self, t: i64) -> Option<Minute> {
109        let first = self.units.first()?.0;
110        let i = usize::try_from((t - first).div_euclid(self.unit_secs)).ok()?;
111        let (start, kw) = *self.units.get(i)?;
112        #[expect(clippy::cast_precision_loss, reason = "seconds of a quarter hour")]
113        let hours = (t - start) as f64 / 3600.0;
114        let soc = (self.soc[i] + Self::change(kw, hours, self.efficiency) * self.pct_per_kwh)
115            .clamp(0.0, 100.0);
116        Some(Minute {
117            power: kw,
118            soc: Some(soc),
119        })
120    }
121}
122
123/// The simulator for one scenario.
124#[derive(Debug, Clone, Default)]
125pub struct Simulator {
126    seed: u64,
127    faults: Vec<Fault>,
128    dispatch: std::collections::BTreeMap<AssetId, Vec<Dispatch>>,
129}
130
131/// One simulated minute: power (kW, generator convention) and state of charge (%).
132#[derive(Debug, Clone, Copy, PartialEq)]
133struct Minute {
134    power: f64,
135    soc: Option<f64>,
136}
137
138/// What a fault leaves of one instant.
139enum Seen {
140    Offline(i64),
141    Value { at: i64, minute: Minute },
142}
143
144impl Simulator {
145    /// A simulator with a seed and the scenario's faults.
146    #[must_use]
147    pub fn new(seed: u64, faults: Vec<Fault>) -> Self {
148        Self {
149            seed,
150            faults,
151            dispatch: std::collections::BTreeMap::new(),
152        }
153    }
154
155    /// Lets `asset` follow `schedule` over the units it covers (a released, filled day-ahead
156    /// schedule, 010). Adding the same schedule twice changes nothing.
157    pub fn dispatch(&mut self, asset: AssetId, schedule: Dispatch) {
158        let list = self.dispatch.entry(asset).or_default();
159        if !list.contains(&schedule) {
160            list.push(schedule);
161        }
162    }
163
164    /// The minute at `t`: the dispatched schedule where one covers it, else the asset's own pattern.
165    fn minute_of(&self, asset: &AssetId, shape: &Shape, t: i64) -> Minute {
166        self.dispatch
167            .get(asset)
168            .and_then(|list| list.iter().find_map(|d| d.at(t)))
169            .unwrap_or_else(|| shape.minute(t))
170    }
171
172    /// The faults, as declared.
173    #[must_use]
174    pub fn faults(&self) -> &[Fault] {
175        &self.faults
176    }
177
178    fn fault(&self, asset: &AssetId, t: i64) -> Option<&Fault> {
179        self.faults
180            .iter()
181            .find(|f| &f.asset == asset && f.from <= t && t < f.to)
182    }
183
184    /// The asset at instant `now`.
185    #[must_use]
186    pub fn now(&self, asset: &Asset, now: i64) -> AssetNow {
187        let shape = Shape::new(self.seed, asset);
188        match self.seen(&asset.id, &shape, now) {
189            Seen::Offline(since) => AssetNow::offline(Some(since)),
190            Seen::Value { at, minute } => {
191                let rated = rated_kw(asset);
192                let reading = |q, v| Reading {
193                    value: v,
194                    at,
195                    quality: classify(q, v, at, now, STALE_SECS, Flags::default(), rated),
196                };
197                AssetNow::from_readings(
198                    Some(reading(Quantity::Power, minute.power)),
199                    minute.soc.map(|s| reading(Quantity::Soc, s)),
200                )
201            }
202        }
203    }
204
205    fn seen(&self, asset: &AssetId, shape: &Shape, t: i64) -> Seen {
206        match self.fault(asset, t) {
207            Some(f) if f.kind == FaultKind::Offline => Seen::Offline(f.from),
208            Some(f) if f.kind == FaultKind::Tripped => {
209                let at = minute_start(t);
210                let held = self.minute_of(asset, shape, minute_start(f.from)).soc;
211                Seen::Value {
212                    at,
213                    minute: Minute {
214                        power: 0.0,
215                        soc: held,
216                    },
217                }
218            }
219            // A frozen value is the value of its own minute, even across midnight.
220            Some(f) => {
221                let at = minute_start(f.from);
222                Seen::Value {
223                    at,
224                    minute: self.minute_of(asset, shape, at),
225                }
226            }
227            None => {
228                let at = minute_start(t);
229                Seen::Value {
230                    at,
231                    minute: self.minute_of(asset, shape, at),
232                }
233            }
234        }
235    }
236
237    /// Quarter aggregates with a start in `[from, to)`, never past `now`.
238    #[must_use]
239    pub fn quarters(&self, asset: &Asset, from: i64, to: i64, now: i64) -> Vec<QuarterAggregate> {
240        let rated = rated_kw(asset);
241        let mut out = Vec::new();
242        let mut q = quarter_start(from);
243        let shape = Shape::new(self.seed, asset);
244        while q < to && q <= now {
245            let mut energy = 0.0;
246            let mut good_secs = 0_i64;
247            let mut last_soc = None;
248            let mut m = q;
249            while m < q + QUARTER_SECS && m <= now {
250                let held = (m + 60).min(now + 1) - m;
251                if let Seen::Value { at, minute } = self.seen(&asset.id, &shape, m) {
252                    let quality = classify(
253                        Quantity::Power,
254                        minute.power,
255                        at,
256                        m,
257                        STALE_SECS,
258                        Flags::default(),
259                        rated,
260                    );
261                    if quality == Quality::Good {
262                        #[expect(clippy::cast_precision_loss, reason = "at most 60 seconds")]
263                        let secs = held as f64;
264                        energy += minute.power * secs;
265                        good_secs += held;
266                        if minute.soc.is_some() {
267                            last_soc = minute.soc;
268                        }
269                    }
270                }
271                m += 60;
272            }
273            #[expect(clippy::cast_precision_loss, reason = "at most 900 seconds")]
274            out.push(QuarterAggregate {
275                start: q,
276                mean_power_kw: (good_secs > 0).then(|| energy / good_secs as f64),
277                last_soc,
278                good_share: good_secs as f64 / QUARTER_SECS as f64,
279            });
280            q += QUARTER_SECS;
281        }
282        out
283    }
284
285    /// The last 15 minutes, one value per minute, oldest first.
286    #[must_use]
287    pub fn recent(&self, asset: &Asset, now: i64) -> Vec<Recent> {
288        let shape = Shape::new(self.seed, asset);
289        let mut out = Vec::new();
290        let mut m = minute_start(now - RECENT_SECS + 60);
291        while m <= now {
292            if let Seen::Value { at, minute } = self.seen(&asset.id, &shape, m)
293                && out.last().is_none_or(|r: &Recent| r.at != at)
294            {
295                out.push(Recent {
296                    at,
297                    power_kw: Some(minute.power),
298                    soc: minute.soc,
299                });
300            }
301            m += 60;
302        }
303        out
304    }
305}
306
307const fn minute_start(t: i64) -> i64 {
308    t - t.rem_euclid(60)
309}
310
311/// The start of the Berlin business day containing `t` (UTC midnight outside the calendar).
312fn day_start(t: i64) -> i64 {
313    OffsetDateTime::from_unix_timestamp(t)
314        .ok()
315        .and_then(|i| BusinessDay::containing(i).ok())
316        .map_or(t - t.rem_euclid(86_400), |d| d.start().unix_timestamp())
317}
318
319/// The fixed parameters of one asset's behaviour.
320struct Shape {
321    seed: u64,
322    id: u64,
323    kind: AssetKind,
324    rated: f64,
325    energy: Option<f64>,
326}
327
328impl Shape {
329    fn new(seed: u64, asset: &Asset) -> Self {
330        Self {
331            seed,
332            id: fnv(asset.id.as_str()),
333            kind: asset.kind,
334            rated: rated_kw(asset),
335            energy: energy_kwh(asset).filter(|e| *e > 0.0),
336        }
337    }
338
339    fn soc_at_midnight(&self, day_start: i64) -> f64 {
340        #[expect(clippy::cast_sign_loss, reason = "hashing the bits")]
341        let h = unit(mix(self.seed ^ self.id ^ (day_start as u64)));
342        40.0 + 20.0 * h
343    }
344
345    /// Power and state of charge at the minute starting at `t`.
346    fn minute(&self, t: i64) -> Minute {
347        let local = Local::of(t);
348        let soc = self.energy.map(|_| self.soc(local));
349        Minute {
350            power: self.power(t, local, soc),
351            soc,
352        }
353    }
354
355    /// The battery's state of charge (%) at the start of the minute, in closed form: idle until
356    /// the charge window, charging at 0.5 C to at most 95 %, idle, then discharging at 0.6 C to at
357    /// least 5 %.
358    fn soc(&self, local: Local) -> f64 {
359        let Some(kwh) = self.energy else { return 0.0 };
360        let start = self.soc_at_midnight(local.day_start);
361        let mm = local.minute - self.phase();
362        let charge = 0.5 * self.rated / kwh * 100.0 / 60.0; // % per minute
363        let discharge = 0.6 * self.rated / kwh * 100.0 / 60.0;
364        let charged = |m: f64| {
365            if start >= 95.0 {
366                start
367            } else {
368                (start + charge * (m - 600.0).clamp(0.0, 240.0)).min(95.0)
369            }
370        };
371        let full = charged(840.0);
372        let discharged = |m: f64| {
373            if full <= 5.0 {
374                full
375            } else {
376                (full - discharge * (m - 1020.0).clamp(0.0, 240.0)).max(5.0)
377            }
378        };
379        if mm < 1020.0 {
380            charged(mm)
381        } else {
382            discharged(mm)
383        }
384    }
385
386    /// The asset's own shift of its daily schedule, ± 30 minutes.
387    fn phase(&self) -> f64 {
388        (unit(mix(self.id)) - 0.5) * 60.0
389    }
390
391    /// Power at minute `t`, given the state of charge then.
392    fn power(&self, t: i64, local: Local, soc: Option<f64>) -> f64 {
393        let m = local.minute;
394        #[expect(clippy::cast_sign_loss, reason = "hashing the bits")]
395        let noise =
396            1.0 + 0.04 * (unit(mix(self.seed ^ self.id.rotate_left(17) ^ (t as u64))) * 2.0 - 1.0);
397        let phase = self.phase();
398        let r = self.rated;
399        let v = match self.kind {
400            AssetKind::Pv => {
401                r * daylight(m, local.utc_offset_h, local.day_of_year)
402                    * (1.0 - 0.75 * self.cloud(t))
403                    * noise
404            }
405            AssetKind::Wind => r * self.wind(t) * noise,
406            AssetKind::Battery => {
407                let soc = soc.unwrap_or(50.0);
408                let mm = m - phase;
409                if (600.0..840.0).contains(&mm) && soc < 95.0 {
410                    -0.5 * r
411                } else if (1020.0..1260.0).contains(&mm) && soc > 5.0 {
412                    0.6 * r
413                } else {
414                    0.0
415                }
416            }
417            AssetKind::Load => {
418                -r * (0.25
419                    + 0.35 * bump(m - phase, 1140.0, 120.0)
420                    + 0.15 * bump(m - phase, 450.0, 60.0))
421                    * noise
422            }
423            AssetKind::HeatPump => {
424                let cold = if !(420.0..1020.0).contains(&m) {
425                    0.4
426                } else {
427                    0.1
428                };
429                -r * (0.3 + cold) * noise
430            }
431            AssetKind::EvCharger => {
432                let h = mix(self.id ^ 0x00e5);
433                #[expect(clippy::cast_precision_loss, reason = "small values")]
434                let start = 1020.0 + (h % 180) as f64;
435                #[expect(clippy::cast_precision_loss, reason = "small values")]
436                let len = 120.0 + ((h >> 8) % 120) as f64;
437                if (start..start + len).contains(&m) || (start..start + len).contains(&(m + 1440.0))
438                {
439                    -r
440                } else {
441                    0.0
442                }
443            }
444            AssetKind::Chp => {
445                if (360.0..1320.0).contains(&m) {
446                    0.85 * r * noise
447                } else {
448                    0.0
449                }
450            }
451        };
452        // Rounded to watts, as devices report.
453        (v * 1000.0).round() / 1000.0
454    }
455
456    /// Cloud cover 0–1, shared by every asset, interpolated between hours.
457    fn cloud(&self, t: i64) -> f64 {
458        smooth(self.seed ^ 0xc10d, t, 3600)
459    }
460
461    /// Wind capacity factor 0.05–0.8, shared, interpolated over three hours.
462    fn wind(&self, t: i64) -> f64 {
463        0.05 + 0.75 * smooth(self.seed ^ 0x7769_6e64, t, 10_800)
464    }
465}
466
467/// Smoothly interpolated noise in [0, 1] with knots every `period` seconds.
468fn smooth(salt: u64, t: i64, period: i64) -> f64 {
469    let k = t.div_euclid(period);
470    #[expect(clippy::cast_precision_loss, reason = "fraction of one period")]
471    let f = t.rem_euclid(period) as f64 / period as f64;
472    #[expect(clippy::cast_sign_loss, reason = "hashing the bits")]
473    let (a, b) = (unit(mix(salt ^ k as u64)), unit(mix(salt ^ (k + 1) as u64)));
474    let s = (1.0 - (f * PI).cos()) / 2.0;
475    a + (b - a) * s
476}
477
478/// A bell around `centre` minutes with half-width `width`.
479fn bell_shape(x: f64) -> f64 {
480    (-x * x).exp()
481}
482
483fn bump(m: f64, centre: f64, width: f64) -> f64 {
484    bell_shape((m - centre) / width)
485}
486
487/// Clear-sky PV output 0–1 at Berlin minute `m` (latitude 52° N, longitude 10° E).
488fn daylight(m: f64, utc_offset_h: i64, day_of_year: u16) -> f64 {
489    let phi = 52.0_f64.to_radians();
490    let decl = 23.44_f64.to_radians() * (2.0 * PI * (284.0 + f64::from(day_of_year)) / 365.0).sin();
491    let cos_w0 = (-phi.tan() * decl.tan()).clamp(-1.0, 1.0);
492    let day_len = 2.0 * cos_w0.acos() / (2.0 * PI) * 1440.0;
493    #[expect(clippy::cast_precision_loss, reason = "one or two hours")]
494    let noon = 740.0 + (utc_offset_h - 1) as f64 * 60.0;
495    let x = (m - (noon - day_len / 2.0)) / day_len;
496    if (0.0..=1.0).contains(&x) {
497        (PI * x).sin().powf(1.5)
498    } else {
499        0.0
500    }
501}
502
503/// Where an instant falls in its Berlin business day — computed once per value.
504#[derive(Debug, Clone, Copy)]
505struct Local {
506    day_start: i64,
507    minute: f64,
508    utc_offset_h: i64,
509    day_of_year: u16,
510}
511
512impl Local {
513    fn of(t: i64) -> Self {
514        let day_start = day_start(t);
515        #[expect(clippy::cast_precision_loss, reason = "minutes of a day")]
516        let minute = ((t - day_start) / 60) as f64;
517        // Local midnight is 22:00 or 23:00 UTC.
518        let utc_offset_h = (86_400 - day_start.rem_euclid(86_400)) / 3600 % 24;
519        let day_of_year =
520            OffsetDateTime::from_unix_timestamp(day_start + 43_200).map_or(1, |d| d.ordinal());
521        Self {
522            day_start,
523            minute,
524            utc_offset_h,
525            day_of_year,
526        }
527    }
528}
529
530/// SplitMix64.
531const fn mix(mut x: u64) -> u64 {
532    x = x.wrapping_add(0x9e37_79b9_7f4a_7c15);
533    x = (x ^ (x >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
534    x = (x ^ (x >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
535    x ^ (x >> 31)
536}
537
538/// A hash to [0, 1).
539fn unit(x: u64) -> f64 {
540    #[expect(
541        clippy::cast_precision_loss,
542        reason = "53 bits of randomness are plenty"
543    )]
544    let v = (x >> 11) as f64 / (1_u64 << 53) as f64;
545    v
546}
547
548/// FNV-1a.
549fn fnv(s: &str) -> u64 {
550    s.bytes().fold(0xcbf2_9ce4_8422_2325, |h, b| {
551        (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3)
552    })
553}