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};
pub const STALE_SECS: i64 = 60;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FaultKind {
Offline,
Stuck,
Tripped,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Fault {
pub asset: AssetId,
pub kind: FaultKind,
pub from: i64,
pub to: i64,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Dispatch {
units: Vec<(i64, f64)>,
unit_secs: i64,
soc: Vec<f64>,
pct_per_kwh: f64,
efficiency: f64,
}
impl Dispatch {
#[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,
}
}
fn change(kw: f64, hours: f64, efficiency: f64) -> f64 {
if kw > 0.0 {
-kw * hours / efficiency
} else {
-kw * hours * efficiency
}
}
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),
})
}
}
#[derive(Debug, Clone, Default)]
pub struct Simulator {
seed: u64,
faults: Vec<Fault>,
dispatch: std::collections::BTreeMap<AssetId, Vec<Dispatch>>,
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct Minute {
power: f64,
soc: Option<f64>,
}
enum Seen {
Offline(i64),
Value { at: i64, minute: Minute },
}
impl Simulator {
#[must_use]
pub fn new(seed: u64, faults: Vec<Fault>) -> Self {
Self {
seed,
faults,
dispatch: std::collections::BTreeMap::new(),
}
}
pub fn dispatch(&mut self, asset: AssetId, schedule: Dispatch) {
let list = self.dispatch.entry(asset).or_default();
if !list.contains(&schedule) {
list.push(schedule);
}
}
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))
}
#[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)
}
#[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,
},
}
}
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),
}
}
}
}
#[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
}
#[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)
}
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())
}
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
}
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,
}
}
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; 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)
}
}
fn phase(&self) -> f64 {
(unit(mix(self.id)) - 0.5) * 60.0
}
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
}
}
};
(v * 1000.0).round() / 1000.0
}
fn cloud(&self, t: i64) -> f64 {
smooth(self.seed ^ 0xc10d, t, 3600)
}
fn wind(&self, t: i64) -> f64 {
0.05 + 0.75 * smooth(self.seed ^ 0x7769_6e64, t, 10_800)
}
}
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
}
fn bell_shape(x: f64) -> f64 {
(-x * x).exp()
}
fn bump(m: f64, centre: f64, width: f64) -> f64 {
bell_shape((m - centre) / width)
}
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
}
}
#[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;
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,
}
}
}
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)
}
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
}
fn fnv(s: &str) -> u64 {
s.bytes().fold(0xcbf2_9ce4_8422_2325, |h, b| {
(h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3)
})
}