1use 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
19pub const STALE_SECS: i64 = 60;
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum FaultKind {
25 Offline,
27 Stuck,
29 Tripped,
32}
33
34#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct Fault {
37 pub asset: AssetId,
39 pub kind: FaultKind,
41 pub from: i64,
43 pub to: i64,
45}
46
47#[derive(Debug, Clone, PartialEq)]
50pub struct Dispatch {
51 units: Vec<(i64, f64)>,
54 unit_secs: i64,
56 soc: Vec<f64>,
58 pct_per_kwh: f64,
60 efficiency: f64,
61}
62
63impl Dispatch {
64 #[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 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 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#[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#[derive(Debug, Clone, Copy, PartialEq)]
133struct Minute {
134 power: f64,
135 soc: Option<f64>,
136}
137
138enum Seen {
140 Offline(i64),
141 Value { at: i64, minute: Minute },
142}
143
144impl Simulator {
145 #[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 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 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 #[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 #[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 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 #[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 #[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
311fn 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
319struct 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 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 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; 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 fn phase(&self) -> f64 {
388 (unit(mix(self.id)) - 0.5) * 60.0
389 }
390
391 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 (v * 1000.0).round() / 1000.0
454 }
455
456 fn cloud(&self, t: i64) -> f64 {
458 smooth(self.seed ^ 0xc10d, t, 3600)
459 }
460
461 fn wind(&self, t: i64) -> f64 {
463 0.05 + 0.75 * smooth(self.seed ^ 0x7769_6e64, t, 10_800)
464 }
465}
466
467fn 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
478fn 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
487fn 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#[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 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
530const 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
538fn 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
548fn 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}