flexpool-telemetry 0.4.0

flexpool live telemetry: quality, plausibility, a bounded store with quarter-hour aggregation, pool summaries and the sandbox simulator. No I/O; time is an input.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
//! The sandbox simulator: telemetry as a pure function of asset, seed, faults and time.
//!
//! Values are piecewise constant per minute, so the replay is deterministic and never needs a
//! store. Every value is computed directly for its minute — a battery's state of charge in closed
//! 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
//! testing, never for forecasting. Weather is shared by every asset (correlated pools); each asset
//! adds its own small noise.

use std::f64::consts::PI;

use flexpool_core::{AssetId, BusinessDay};
use flexpool_portfolio::{Asset, AssetKind};
use time::OffsetDateTime;

use crate::quality::{Flags, Quality, Quantity, Reading, classify};
use crate::store::{AssetNow, QuarterAggregate, RECENT_SECS, Recent};
use crate::{QUARTER_SECS, energy_kwh, quarter_start, rated_kw};

/// Simulated values are stale after a minute without a new one.
pub const STALE_SECS: i64 = 60;

/// What a fault does to an asset.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FaultKind {
    /// No value at all.
    Offline,
    /// The value and its source time freeze at the fault's start.
    Stuck,
    /// Online and reporting, but delivering nothing — a tripped inverter: power 0, state of
    /// charge held at the fault's start.
    Tripped,
}

/// A planned disturbance of one asset over `[from, to)`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Fault {
    /// The asset.
    pub asset: AssetId,
    /// What happens.
    pub kind: FaultKind,
    /// Start, Unix seconds (inclusive).
    pub from: i64,
    /// End, Unix seconds (exclusive).
    pub to: i64,
}

/// A battery's traded schedule for one delivery day: it follows the setpoints instead of its
/// own daily pattern. The state of charge is closed-form from prefix sums, so it stays O(log n).
#[derive(Debug, Clone, PartialEq)]
pub struct Dispatch {
    /// Unit starts (Unix seconds, ascending) with their setpoint, kW (generator convention: positive
    /// is discharge).
    units: Vec<(i64, f64)>,
    /// Unit length, seconds.
    unit_secs: i64,
    /// State of charge (%) at the start of each unit, and after the last.
    soc: Vec<f64>,
    /// % per kWh for this battery and the one-way efficiency.
    pct_per_kwh: f64,
    efficiency: f64,
}

impl Dispatch {
    /// A schedule of `units` (start, kW) of `unit_secs`, starting at `soc_start` % for a battery of
    /// `energy_kwh` with round-trip efficiency `round_trip`.
    #[must_use]
    pub fn new(
        units: Vec<(i64, f64)>,
        unit_secs: i64,
        soc_start: f64,
        energy_kwh: f64,
        round_trip: f64,
    ) -> Self {
        let pct_per_kwh = if energy_kwh > 0.0 {
            100.0 / energy_kwh
        } else {
            0.0
        };
        let efficiency = round_trip.clamp(0.01, 1.0).sqrt();
        let mut soc = Vec::with_capacity(units.len() + 1);
        let mut level = soc_start;
        soc.push(level);
        #[expect(clippy::cast_precision_loss, reason = "seconds of a quarter hour")]
        let hours = unit_secs as f64 / 3600.0;
        for (_, kw) in &units {
            level = (level + Self::change(*kw, hours, efficiency) * pct_per_kwh).clamp(0.0, 100.0);
            soc.push(level);
        }
        Self {
            units,
            unit_secs,
            soc,
            pct_per_kwh,
            efficiency,
        }
    }

    /// kWh stored by `kw` over `hours`: discharge draws more than it delivers, charge stores less.
    fn change(kw: f64, hours: f64, efficiency: f64) -> f64 {
        if kw > 0.0 {
            -kw * hours / efficiency
        } else {
            -kw * hours * efficiency
        }
    }

    /// Power and state of charge at `t`, when the schedule covers it.
    fn at(&self, t: i64) -> Option<Minute> {
        let first = self.units.first()?.0;
        let i = usize::try_from((t - first).div_euclid(self.unit_secs)).ok()?;
        let (start, kw) = *self.units.get(i)?;
        #[expect(clippy::cast_precision_loss, reason = "seconds of a quarter hour")]
        let hours = (t - start) as f64 / 3600.0;
        let soc = (self.soc[i] + Self::change(kw, hours, self.efficiency) * self.pct_per_kwh)
            .clamp(0.0, 100.0);
        Some(Minute {
            power: kw,
            soc: Some(soc),
        })
    }
}

/// The simulator for one scenario.
#[derive(Debug, Clone, Default)]
pub struct Simulator {
    seed: u64,
    faults: Vec<Fault>,
    dispatch: std::collections::BTreeMap<AssetId, Vec<Dispatch>>,
}

/// One simulated minute: power (kW, generator convention) and state of charge (%).
#[derive(Debug, Clone, Copy, PartialEq)]
struct Minute {
    power: f64,
    soc: Option<f64>,
}

/// What a fault leaves of one instant.
enum Seen {
    Offline(i64),
    Value { at: i64, minute: Minute },
}

impl Simulator {
    /// A simulator with a seed and the scenario's faults.
    #[must_use]
    pub fn new(seed: u64, faults: Vec<Fault>) -> Self {
        Self {
            seed,
            faults,
            dispatch: std::collections::BTreeMap::new(),
        }
    }

    /// Lets `asset` follow `schedule` over the units it covers (a released, filled day-ahead
    /// schedule, 010). Adding the same schedule twice changes nothing.
    pub fn dispatch(&mut self, asset: AssetId, schedule: Dispatch) {
        let list = self.dispatch.entry(asset).or_default();
        if !list.contains(&schedule) {
            list.push(schedule);
        }
    }

    /// The minute at `t`: the dispatched schedule where one covers it, else the asset's own pattern.
    fn minute_of(&self, asset: &AssetId, shape: &Shape, t: i64) -> Minute {
        self.dispatch
            .get(asset)
            .and_then(|list| list.iter().find_map(|d| d.at(t)))
            .unwrap_or_else(|| shape.minute(t))
    }

    /// The faults, as declared.
    #[must_use]
    pub fn faults(&self) -> &[Fault] {
        &self.faults
    }

    fn fault(&self, asset: &AssetId, t: i64) -> Option<&Fault> {
        self.faults
            .iter()
            .find(|f| &f.asset == asset && f.from <= t && t < f.to)
    }

    /// The asset at instant `now`.
    #[must_use]
    pub fn now(&self, asset: &Asset, now: i64) -> AssetNow {
        let shape = Shape::new(self.seed, asset);
        match self.seen(&asset.id, &shape, now) {
            Seen::Offline(since) => AssetNow::offline(Some(since)),
            Seen::Value { at, minute } => {
                let rated = rated_kw(asset);
                let reading = |q, v| Reading {
                    value: v,
                    at,
                    quality: classify(q, v, at, now, STALE_SECS, Flags::default(), rated),
                };
                AssetNow::from_readings(
                    Some(reading(Quantity::Power, minute.power)),
                    minute.soc.map(|s| reading(Quantity::Soc, s)),
                )
            }
        }
    }

    fn seen(&self, asset: &AssetId, shape: &Shape, t: i64) -> Seen {
        match self.fault(asset, t) {
            Some(f) if f.kind == FaultKind::Offline => Seen::Offline(f.from),
            Some(f) if f.kind == FaultKind::Tripped => {
                let at = minute_start(t);
                let held = self.minute_of(asset, shape, minute_start(f.from)).soc;
                Seen::Value {
                    at,
                    minute: Minute {
                        power: 0.0,
                        soc: held,
                    },
                }
            }
            // A frozen value is the value of its own minute, even across midnight.
            Some(f) => {
                let at = minute_start(f.from);
                Seen::Value {
                    at,
                    minute: self.minute_of(asset, shape, at),
                }
            }
            None => {
                let at = minute_start(t);
                Seen::Value {
                    at,
                    minute: self.minute_of(asset, shape, at),
                }
            }
        }
    }

    /// Quarter aggregates with a start in `[from, to)`, never past `now`.
    #[must_use]
    pub fn quarters(&self, asset: &Asset, from: i64, to: i64, now: i64) -> Vec<QuarterAggregate> {
        let rated = rated_kw(asset);
        let mut out = Vec::new();
        let mut q = quarter_start(from);
        let shape = Shape::new(self.seed, asset);
        while q < to && q <= now {
            let mut energy = 0.0;
            let mut good_secs = 0_i64;
            let mut last_soc = None;
            let mut m = q;
            while m < q + QUARTER_SECS && m <= now {
                let held = (m + 60).min(now + 1) - m;
                if let Seen::Value { at, minute } = self.seen(&asset.id, &shape, m) {
                    let quality = classify(
                        Quantity::Power,
                        minute.power,
                        at,
                        m,
                        STALE_SECS,
                        Flags::default(),
                        rated,
                    );
                    if quality == Quality::Good {
                        #[expect(clippy::cast_precision_loss, reason = "at most 60 seconds")]
                        let secs = held as f64;
                        energy += minute.power * secs;
                        good_secs += held;
                        if minute.soc.is_some() {
                            last_soc = minute.soc;
                        }
                    }
                }
                m += 60;
            }
            #[expect(clippy::cast_precision_loss, reason = "at most 900 seconds")]
            out.push(QuarterAggregate {
                start: q,
                mean_power_kw: (good_secs > 0).then(|| energy / good_secs as f64),
                last_soc,
                good_share: good_secs as f64 / QUARTER_SECS as f64,
            });
            q += QUARTER_SECS;
        }
        out
    }

    /// The last 15 minutes, one value per minute, oldest first.
    #[must_use]
    pub fn recent(&self, asset: &Asset, now: i64) -> Vec<Recent> {
        let shape = Shape::new(self.seed, asset);
        let mut out = Vec::new();
        let mut m = minute_start(now - RECENT_SECS + 60);
        while m <= now {
            if let Seen::Value { at, minute } = self.seen(&asset.id, &shape, m)
                && out.last().is_none_or(|r: &Recent| r.at != at)
            {
                out.push(Recent {
                    at,
                    power_kw: Some(minute.power),
                    soc: minute.soc,
                });
            }
            m += 60;
        }
        out
    }
}

const fn minute_start(t: i64) -> i64 {
    t - t.rem_euclid(60)
}

/// The start of the Berlin business day containing `t` (UTC midnight outside the calendar).
fn day_start(t: i64) -> i64 {
    OffsetDateTime::from_unix_timestamp(t)
        .ok()
        .and_then(|i| BusinessDay::containing(i).ok())
        .map_or(t - t.rem_euclid(86_400), |d| d.start().unix_timestamp())
}

/// The fixed parameters of one asset's behaviour.
struct Shape {
    seed: u64,
    id: u64,
    kind: AssetKind,
    rated: f64,
    energy: Option<f64>,
}

impl Shape {
    fn new(seed: u64, asset: &Asset) -> Self {
        Self {
            seed,
            id: fnv(asset.id.as_str()),
            kind: asset.kind,
            rated: rated_kw(asset),
            energy: energy_kwh(asset).filter(|e| *e > 0.0),
        }
    }

    fn soc_at_midnight(&self, day_start: i64) -> f64 {
        #[expect(clippy::cast_sign_loss, reason = "hashing the bits")]
        let h = unit(mix(self.seed ^ self.id ^ (day_start as u64)));
        40.0 + 20.0 * h
    }

    /// Power and state of charge at the minute starting at `t`.
    fn minute(&self, t: i64) -> Minute {
        let local = Local::of(t);
        let soc = self.energy.map(|_| self.soc(local));
        Minute {
            power: self.power(t, local, soc),
            soc,
        }
    }

    /// The battery's state of charge (%) at the start of the minute, in closed form: idle until
    /// the charge window, charging at 0.5 C to at most 95 %, idle, then discharging at 0.6 C to at
    /// least 5 %.
    fn soc(&self, local: Local) -> f64 {
        let Some(kwh) = self.energy else { return 0.0 };
        let start = self.soc_at_midnight(local.day_start);
        let mm = local.minute - self.phase();
        let charge = 0.5 * self.rated / kwh * 100.0 / 60.0; // % per minute
        let discharge = 0.6 * self.rated / kwh * 100.0 / 60.0;
        let charged = |m: f64| {
            if start >= 95.0 {
                start
            } else {
                (start + charge * (m - 600.0).clamp(0.0, 240.0)).min(95.0)
            }
        };
        let full = charged(840.0);
        let discharged = |m: f64| {
            if full <= 5.0 {
                full
            } else {
                (full - discharge * (m - 1020.0).clamp(0.0, 240.0)).max(5.0)
            }
        };
        if mm < 1020.0 {
            charged(mm)
        } else {
            discharged(mm)
        }
    }

    /// The asset's own shift of its daily schedule, ± 30 minutes.
    fn phase(&self) -> f64 {
        (unit(mix(self.id)) - 0.5) * 60.0
    }

    /// Power at minute `t`, given the state of charge then.
    fn power(&self, t: i64, local: Local, soc: Option<f64>) -> f64 {
        let m = local.minute;
        #[expect(clippy::cast_sign_loss, reason = "hashing the bits")]
        let noise =
            1.0 + 0.04 * (unit(mix(self.seed ^ self.id.rotate_left(17) ^ (t as u64))) * 2.0 - 1.0);
        let phase = self.phase();
        let r = self.rated;
        let v = match self.kind {
            AssetKind::Pv => {
                r * daylight(m, local.utc_offset_h, local.day_of_year)
                    * (1.0 - 0.75 * self.cloud(t))
                    * noise
            }
            AssetKind::Wind => r * self.wind(t) * noise,
            AssetKind::Battery => {
                let soc = soc.unwrap_or(50.0);
                let mm = m - phase;
                if (600.0..840.0).contains(&mm) && soc < 95.0 {
                    -0.5 * r
                } else if (1020.0..1260.0).contains(&mm) && soc > 5.0 {
                    0.6 * r
                } else {
                    0.0
                }
            }
            AssetKind::Load => {
                -r * (0.25
                    + 0.35 * bump(m - phase, 1140.0, 120.0)
                    + 0.15 * bump(m - phase, 450.0, 60.0))
                    * noise
            }
            AssetKind::HeatPump => {
                let cold = if !(420.0..1020.0).contains(&m) {
                    0.4
                } else {
                    0.1
                };
                -r * (0.3 + cold) * noise
            }
            AssetKind::EvCharger => {
                let h = mix(self.id ^ 0x00e5);
                #[expect(clippy::cast_precision_loss, reason = "small values")]
                let start = 1020.0 + (h % 180) as f64;
                #[expect(clippy::cast_precision_loss, reason = "small values")]
                let len = 120.0 + ((h >> 8) % 120) as f64;
                if (start..start + len).contains(&m) || (start..start + len).contains(&(m + 1440.0))
                {
                    -r
                } else {
                    0.0
                }
            }
            AssetKind::Chp => {
                if (360.0..1320.0).contains(&m) {
                    0.85 * r * noise
                } else {
                    0.0
                }
            }
        };
        // Rounded to watts, as devices report.
        (v * 1000.0).round() / 1000.0
    }

    /// Cloud cover 0–1, shared by every asset, interpolated between hours.
    fn cloud(&self, t: i64) -> f64 {
        smooth(self.seed ^ 0xc10d, t, 3600)
    }

    /// Wind capacity factor 0.05–0.8, shared, interpolated over three hours.
    fn wind(&self, t: i64) -> f64 {
        0.05 + 0.75 * smooth(self.seed ^ 0x7769_6e64, t, 10_800)
    }
}

/// Smoothly interpolated noise in [0, 1] with knots every `period` seconds.
fn smooth(salt: u64, t: i64, period: i64) -> f64 {
    let k = t.div_euclid(period);
    #[expect(clippy::cast_precision_loss, reason = "fraction of one period")]
    let f = t.rem_euclid(period) as f64 / period as f64;
    #[expect(clippy::cast_sign_loss, reason = "hashing the bits")]
    let (a, b) = (unit(mix(salt ^ k as u64)), unit(mix(salt ^ (k + 1) as u64)));
    let s = (1.0 - (f * PI).cos()) / 2.0;
    a + (b - a) * s
}

/// A bell around `centre` minutes with half-width `width`.
fn bell_shape(x: f64) -> f64 {
    (-x * x).exp()
}

fn bump(m: f64, centre: f64, width: f64) -> f64 {
    bell_shape((m - centre) / width)
}

/// Clear-sky PV output 0–1 at Berlin minute `m` (latitude 52° N, longitude 10° E).
fn daylight(m: f64, utc_offset_h: i64, day_of_year: u16) -> f64 {
    let phi = 52.0_f64.to_radians();
    let decl = 23.44_f64.to_radians() * (2.0 * PI * (284.0 + f64::from(day_of_year)) / 365.0).sin();
    let cos_w0 = (-phi.tan() * decl.tan()).clamp(-1.0, 1.0);
    let day_len = 2.0 * cos_w0.acos() / (2.0 * PI) * 1440.0;
    #[expect(clippy::cast_precision_loss, reason = "one or two hours")]
    let noon = 740.0 + (utc_offset_h - 1) as f64 * 60.0;
    let x = (m - (noon - day_len / 2.0)) / day_len;
    if (0.0..=1.0).contains(&x) {
        (PI * x).sin().powf(1.5)
    } else {
        0.0
    }
}

/// Where an instant falls in its Berlin business day — computed once per value.
#[derive(Debug, Clone, Copy)]
struct Local {
    day_start: i64,
    minute: f64,
    utc_offset_h: i64,
    day_of_year: u16,
}

impl Local {
    fn of(t: i64) -> Self {
        let day_start = day_start(t);
        #[expect(clippy::cast_precision_loss, reason = "minutes of a day")]
        let minute = ((t - day_start) / 60) as f64;
        // Local midnight is 22:00 or 23:00 UTC.
        let utc_offset_h = (86_400 - day_start.rem_euclid(86_400)) / 3600 % 24;
        let day_of_year =
            OffsetDateTime::from_unix_timestamp(day_start + 43_200).map_or(1, |d| d.ordinal());
        Self {
            day_start,
            minute,
            utc_offset_h,
            day_of_year,
        }
    }
}

/// SplitMix64.
const fn mix(mut x: u64) -> u64 {
    x = x.wrapping_add(0x9e37_79b9_7f4a_7c15);
    x = (x ^ (x >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
    x = (x ^ (x >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
    x ^ (x >> 31)
}

/// A hash to [0, 1).
fn unit(x: u64) -> f64 {
    #[expect(
        clippy::cast_precision_loss,
        reason = "53 bits of randomness are plenty"
    )]
    let v = (x >> 11) as f64 / (1_u64 << 53) as f64;
    v
}

/// FNV-1a.
fn fnv(s: &str) -> u64 {
    s.bytes().fold(0xcbf2_9ce4_8422_2325, |h, b| {
        (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3)
    })
}