use std::fmt;
use std::ops::RangeInclusive;
use std::str::FromStr;
use jiff::civil::Date;
use crate::canon::{self, Digest, Value};
use crate::power::div_round;
use crate::{Deviation, Error, Grid, Power, Provenance, Rounding, Schedule, Series, Window};
pub const MAX_DAYS: u32 = 366;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum MethodId {
DPrognosis1,
Schedule1,
Mbma1,
XofY1,
}
impl MethodId {
pub const ALL: [MethodId; 4] = [
MethodId::DPrognosis1,
MethodId::Mbma1,
MethodId::Schedule1,
MethodId::XofY1,
];
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
MethodId::DPrognosis1 => "dprognosis@1",
MethodId::Schedule1 => "schedule@1",
MethodId::Mbma1 => "mbma@1",
MethodId::XofY1 => "xofy@1",
}
}
#[must_use]
pub fn card(self) -> &'static MethodCard {
CARDS.iter().find(|c| c.id == self).unwrap_or(&CARDS[0])
}
fn refuse(self, reason: impl Into<String>) -> Error {
Error::Method {
method: self,
reason: reason.into(),
}
}
}
impl fmt::Display for MethodId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl FromStr for MethodId {
type Err = Error;
fn from_str(text: &str) -> Result<MethodId, Error> {
MethodId::ALL
.into_iter()
.find(|m| m.as_str() == text)
.ok_or_else(|| Error::ParseMethod {
text: text.chars().take(80).collect(),
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MethodCard {
pub id: MethodId,
pub summary: &'static str,
pub formula: &'static str,
pub parameters: &'static [(&'static str, &'static str)],
pub rounding: &'static str,
pub fits: &'static str,
pub gaming: &'static [(&'static str, &'static str)],
}
const ROUNDING: &str = "one division per ISP after summing, half away from zero to the watt";
static CARDS: [MethodCard; 4] = [
MethodCard {
id: MethodId::DPrognosis1,
summary: "The aggregator's D-Prognosis for the day is the baseline, as sent.",
formula: "baseline(isp) = prognosis(isp) for every ISP of the event",
parameters: &[(
"prognosis",
"the D-Prognosis schedule, with who sent it and when",
)],
rounding: "none: the prognosis is taken as sent",
fits: "UFTP's default method; any asset whose aggregator sends a D-Prognosis",
gaming: &[(
"the seller writes a high prognosis",
"nothing in the method; the DSO compares prognoses with metered days (accuracy::score)",
)],
},
MethodCard {
id: MethodId::Mbma1,
summary: "Meter before / meter after: the mean of the last n ISPs before the event, held flat.",
formula: "baseline(isp) = round(Σ measured(i) / n) for the n ISPs i ending gap ISPs before the event's first ISP",
parameters: &[
(
"n",
"how many ISPs before the event are averaged; at least 1",
),
(
"gap",
"ISPs skipped between the averaged ISPs and the event, so a notification cannot move the window",
),
],
rounding: ROUNDING,
fits: "short activations, heat pumps, curtailment; fails on ramps (the accuracy score shows it)",
gaming: &[(
"raise consumption just before the event",
"gap: the averaged ISPs end before the notification",
)],
},
MethodCard {
id: MethodId::Schedule1,
summary: "A schedule the asset declared before the event is the baseline.",
formula: "baseline(isp) = declared(isp) for every ISP of the event",
parameters: &[(
"declared",
"the committed schedule (an S2 plan, a Fahrplan), with who declared it and when",
)],
rounding: "none: the schedule is taken as declared",
fits: "batteries and scheduled assets; a declarative baseline",
gaming: &[(
"declare a schedule after the notification",
"the contract's cut-off: the schedule's provenance carries its issue instant",
)],
},
MethodCard {
id: MethodId::XofY1,
summary: "The mean of the X highest of Y comparable days, optionally adjusted to the day.",
formula: "rank the Y days by total consumption over the event ISPs (ties: later date first); baseline(isp) = round(Σ over the X highest days of day(isp) / X); then the adjustment",
parameters: &[
("x", "how many of the highest days are averaged; 1 ≤ x ≤ y"),
(
"y",
"how many comparable days are given, already filtered by the caller (day type, no event, no holiday); at most 366",
),
(
"adjustment",
"none; additive {window, gap, cap}: shift by round(Σ(actual − baseline) / window) over the window ISPs ending gap ISPs before the event, within ±cap; ratio {window, gap, cap_percent}: scale by Σ actual / Σ baseline over that window, within 1 ± cap_percent %",
),
],
rounding: ROUNDING,
fits: "household and commercial loads; PJM, CAISO, NYISO and Elia run variants",
gaming: &[
(
"pick high days",
"the caller filters the Y days by rule before the event; ranking is fixed",
),
(
"inflate the adjustment window",
"the window ends gap ISPs before the event, and the cap bounds the shift",
),
],
},
];
#[must_use]
pub fn cards() -> &'static [MethodCard] {
&CARDS
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Mbma {
pub n: u32,
pub gap: u32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct XofY {
pub x: u32,
pub y: u32,
pub adjustment: Adjustment,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Adjustment {
None,
Additive {
window: u32,
gap: u32,
cap: Option<Power>,
},
Ratio {
window: u32,
gap: u32,
cap_percent: u32,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Derivation {
Declared {
provenance: Provenance,
},
Mbma {
isps: RangeInclusive<u32>,
},
XofY {
days: Vec<Date>,
adjustment: Option<Applied>,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Applied {
Additive(Deviation),
Ratio {
numerator: i128,
denominator: i128,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Baseline {
method: MethodId,
parameters: Value,
series: Series<Power>,
inputs: Vec<(&'static str, Digest)>,
derivation: Derivation,
}
impl Baseline {
#[must_use]
pub fn method(&self) -> MethodId {
self.method
}
#[must_use]
pub fn series(&self) -> &Series<Power> {
&self.series
}
#[must_use]
pub fn derivation(&self) -> &Derivation {
&self.derivation
}
#[must_use]
pub fn inputs(&self) -> &[(&'static str, Digest)] {
&self.inputs
}
#[must_use]
pub fn canonical(&self) -> String {
self.value().text()
}
#[must_use]
pub fn digest(&self) -> Digest {
self.value().digest()
}
pub(crate) fn value(&self) -> Value {
Value::obj([
("derivation", derivation(&self.derivation)),
("inputs", inputs(&self.inputs)),
("method", Value::str(self.method)),
("parameters", self.parameters.clone()),
("profile", canon::profile("baseline")),
("series", canon::powers(&self.series)),
])
}
}
fn history_digest(days: &[(Date, &Series<Power>)]) -> Result<Digest, Error> {
Ok(Value::obj([
(
"days",
Value::Arr(days.iter().map(|(_, s)| canon::powers(s)).collect()),
),
("profile", canon::profile("history")),
])
.exact()?
.digest())
}
fn history_days<'a>(
method: MethodId,
day: &Grid,
history: &'a [Series<Power>],
) -> Result<Vec<(Date, &'a Series<Power>)>, Error> {
let target = day.date();
let mut days: Vec<(Date, &Series<Power>)> = Vec::with_capacity(history.len());
for h in history {
let d = day.zone().to_datetime(h.grid().start()).date();
if !same_local_times(day, h.grid()) {
return Err(method.refuse(format!(
"the history series starting {} does not cover the target's local times {} ({} ISPs of {}): on a day that skips or repeats an hour, give the event's hours only",
h.grid().start(),
day,
h.grid().count(),
h.grid().isp()
)));
}
if d >= target {
return Err(method.refuse(format!("{d} is not before the target day {target}")));
}
days.push((d, h));
}
days.sort_by_key(|(d, _)| *d);
if let Some(w) = days.windows(2).find(|w| w[0].0 == w[1].0) {
return Err(method.refuse(format!("{} is given twice", w[0].0)));
}
Ok(days)
}
fn same_local_times(day: &Grid, history: &Grid) -> bool {
let zone = day.zone();
history.isp() == day.isp()
&& history.count() == day.count()
&& day.numbers().zip(history.numbers()).all(|(a, b)| {
match (day.interval(a), history.interval(b)) {
(Some(x), Some(y)) => {
zone.to_datetime(x.from()).time() == zone.to_datetime(y.from()).time()
}
_ => false,
}
})
}
fn checked(b: Baseline) -> Result<Baseline, Error> {
b.value().exact()?;
Ok(b)
}
pub(crate) fn inputs(list: &[(&'static str, Digest)]) -> Value {
Value::Obj(list.iter().map(|(k, d)| (*k, Value::str(d))).collect())
}
fn derivation(d: &Derivation) -> Value {
match d {
Derivation::Declared { provenance } => {
Value::obj([("declared", canon::provenance(provenance))])
}
Derivation::Mbma { isps } => Value::obj([(
"isps",
Value::Arr(vec![Value::int(*isps.start()), Value::int(*isps.end())]),
)]),
Derivation::XofY { days, adjustment } => {
let mut v = vec![("days", Value::Arr(days.iter().map(Value::str).collect()))];
match adjustment {
Some(Applied::Additive(d)) => v.push(("additive", Value::int(d.watts()))),
Some(Applied::Ratio {
numerator,
denominator,
}) => v.push((
"ratio",
Value::Arr(vec![Value::Int(*numerator), Value::Int(*denominator)]),
)),
None => {}
}
Value::Obj(v.into_iter().collect())
}
}
}
fn event_isps(method: MethodId, grid: &Grid, event: Window) -> Result<RangeInclusive<u32>, Error> {
grid.isps(event)
.ok_or_else(|| method.refuse(format!("the event {event} overlaps no ISP of {grid}")))
}
fn declared(method: MethodId, schedule: &Schedule, event: Window) -> Result<Baseline, Error> {
let isps = event_isps(method, schedule.series().grid(), event)?;
let series = schedule.series().slice(isps)?;
let declared = Value::obj([
("profile", canon::profile("schedule")),
("provenance", canon::provenance(schedule.provenance())),
("series", canon::powers(schedule.series())),
])
.exact()?;
checked(Baseline {
method,
parameters: Value::obj([("event", canon::window(event))]),
series,
inputs: vec![("declared", declared.digest())],
derivation: Derivation::Declared {
provenance: schedule.provenance().clone(),
},
})
}
pub fn dprognosis(prognosis: &Schedule, event: Window) -> Result<Baseline, Error> {
declared(MethodId::DPrognosis1, prognosis, event)
}
pub fn schedule(declared_schedule: &Schedule, event: Window) -> Result<Baseline, Error> {
declared(MethodId::Schedule1, declared_schedule, event)
}
fn window_before(
method: MethodId,
grid: &Grid,
first: u32,
n: u32,
gap: u32,
) -> Result<RangeInclusive<u32>, Error> {
if n == 0 {
return Err(method.refuse("the window must have at least one ISP"));
}
let start = u64::from(first)
.checked_sub(u64::from(gap) + u64::from(n))
.filter(|&s| s >= u64::from(grid.first()))
.ok_or_else(|| {
method.refuse(format!(
"needs {n} ISPs ending {gap} ISPs before ISP {first}, but the series starts too late"
))
})?;
let start = u32::try_from(start).map_err(|_| method.refuse("ISP out of range"))?;
Ok(start..=start + (n - 1))
}
fn mean(method: MethodId, sum: i128, count: u32) -> Result<Power, Error> {
let w = div_round(sum, i128::from(count), Rounding::HalfAwayFromZero)?;
i64::try_from(w)
.map(Power::from_watts)
.map_err(|_| method.refuse("the mean is outside the representable range"))
}
fn sum(
method: MethodId,
series: &Series<Power>,
isps: &RangeInclusive<u32>,
) -> Result<i128, Error> {
isps.clone().try_fold(0i128, |acc, i| {
series
.get(i)
.map(|p| acc + i128::from(p.watts()))
.ok_or_else(|| method.refuse(format!("ISP {i} is not in {}", series.grid())))
})
}
pub fn mbma(measured: &Series<Power>, event: Window, params: Mbma) -> Result<Baseline, Error> {
let method = MethodId::Mbma1;
let isps = event_isps(method, measured.grid(), event)?;
let window = window_before(method, measured.grid(), *isps.start(), params.n, params.gap)?;
let level = mean(method, sum(method, measured, &window)?, params.n)?;
let grid = measured.grid().slice(isps)?;
checked(Baseline {
method,
parameters: Value::obj([
("event", canon::window(event)),
("gap", Value::int(params.gap)),
("n", Value::int(params.n)),
]),
series: Series::filled(grid, level),
inputs: vec![("measured", canon::power_input(measured)?)],
derivation: Derivation::Mbma { isps: window },
})
}
pub fn xofy(
day: &Grid,
event: Window,
history: &[Series<Power>],
same_day: Option<&Series<Power>>,
params: XofY,
) -> Result<Baseline, Error> {
let method = MethodId::XofY1;
let XofY { x, y, adjustment } = params;
if y > MAX_DAYS {
return Err(method.refuse(format!("y = {y} is above {MAX_DAYS} days")));
}
if x == 0 || x > y {
return Err(method.refuse(format!("x = {x} must be within 1..={y}")));
}
if history.len() != y as usize {
return Err(method.refuse(format!(
"needs y = {y} comparable days, got {}",
history.len()
)));
}
let days = history_days(method, day, history)?;
let history_digest = history_digest(&days)?;
let event_range = event_isps(method, day, event)?;
let aligned: Vec<(Date, Series<Power>)> = days
.iter()
.map(|(d, s)| {
let g = s.grid();
let grid = Grid::numbered(
g.start(),
g.isp(),
g.count(),
day.first(),
day.zone().clone(),
)?;
Ok((*d, Series::new(grid, s.values().to_vec())?))
})
.collect::<Result<_, Error>>()?;
let mut ranked: Vec<(i128, Date, &Series<Power>)> = aligned
.iter()
.map(|(d, s)| Ok((sum(method, s, &event_range)?, *d, s)))
.collect::<Result<_, Error>>()?;
ranked.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)));
ranked.truncate(x as usize);
let chosen: Vec<&Series<Power>> = ranked.iter().map(|(_, _, s)| *s).collect();
let unadjusted = |isp: u32| -> Result<Power, Error> {
let total = chosen
.iter()
.try_fold(0i128, |acc, s| Ok(acc + sum(method, s, &(isp..=isp))?))?;
mean(method, total, x)
};
let mut parameters = vec![
("event", canon::window(event)),
("x", Value::int(x)),
("y", Value::int(y)),
];
let mut inputs = vec![("history", history_digest)];
let (applied, adjustment_value) = if adjustment == Adjustment::None {
(None, Value::str("none"))
} else {
let actual = same_day_series(method, day, same_day)?;
inputs.push(("same_day", canon::power_input(actual)?));
adjust(
method,
day,
*event_range.start(),
actual,
&unadjusted,
adjustment,
)?
};
parameters.push(("adjustment", adjustment_value));
let values = event_range
.clone()
.map(|isp| {
let b = unadjusted(isp)?;
applied.map_or(Ok(b), |a| a.apply(b))
})
.collect::<Result<Vec<_>, _>>()?;
let grid = day.slice(event_range)?;
checked(Baseline {
method,
parameters: Value::Obj(parameters.into_iter().collect()),
series: Series::new(grid, values)?,
inputs,
derivation: Derivation::XofY {
days: ranked.iter().map(|(_, d, _)| *d).collect(),
adjustment: applied,
},
})
}
fn same_day_series<'a>(
method: MethodId,
day: &Grid,
same_day: Option<&'a Series<Power>>,
) -> Result<&'a Series<Power>, Error> {
let s = same_day
.ok_or_else(|| method.refuse("an adjustment needs the day's own measurement (same_day)"))?;
s.same_grid(day)?;
Ok(s)
}
fn adjust(
method: MethodId,
day: &Grid,
first: u32,
actual: &Series<Power>,
unadjusted: &dyn Fn(u32) -> Result<Power, Error>,
adjustment: Adjustment,
) -> Result<(Option<Applied>, Value), Error> {
let measured = |isp| sum(method, actual, &(isp..=isp));
match adjustment {
Adjustment::None => Ok((None, Value::str("none"))),
Adjustment::Additive { window, gap, cap } => {
let w = window_before(method, day, first, window, gap)?;
let mut diff: i128 = 0;
for isp in w {
diff += measured(isp)? - i128::from(unadjusted(isp)?.watts());
}
let mut delta = div_round(diff, i128::from(window), Rounding::HalfAwayFromZero)?;
if let Some(cap) = cap {
if cap < Power::ZERO {
return Err(
method.refuse(format!("the additive cap {cap} must not be negative"))
);
}
let c = i128::from(cap.watts());
delta = delta.clamp(-c, c);
}
let delta = i64::try_from(delta)
.map(Deviation::from_watts)
.map_err(|_| method.refuse("the adjustment is outside the representable range"))?;
let value = Value::obj([
(
"cap",
cap.map_or(Value::str("none"), |c| Value::int(c.watts())),
),
("gap", Value::int(gap)),
("kind", Value::str("additive")),
("window", Value::int(window)),
]);
Ok((Some(Applied::Additive(delta)), value))
}
Adjustment::Ratio {
window,
gap,
cap_percent,
} => {
let w = window_before(method, day, first, window, gap)?;
let (mut num, mut den) = (0i128, 0i128);
for isp in w.clone() {
num += measured(isp)?;
den += i128::from(unadjusted(isp)?.watts());
}
if den <= 0 {
return Err(method.refuse(format!(
"the ratio window ISPs {}..={} have no positive baseline consumption",
w.start(),
w.end()
)));
}
let c = i128::from(cap_percent);
let (low, high) = ((100 - c).max(0), 100 + c);
if num * 100 < low * den {
(num, den) = (low, 100);
} else if num * 100 > high * den {
(num, den) = (high, 100);
}
let value = Value::obj([
("cap_percent", Value::int(cap_percent)),
("gap", Value::int(gap)),
("kind", Value::str("ratio")),
("window", Value::int(window)),
]);
Ok((
Some(Applied::Ratio {
numerator: num,
denominator: den,
}),
value,
))
}
}
}
impl Applied {
pub fn apply(self, baseline: Power) -> Result<Power, Error> {
match self {
Applied::Additive(delta) => baseline.checked_add_deviation(delta),
Applied::Ratio {
numerator,
denominator,
} => {
let product =
i128::from(baseline.watts())
.checked_mul(numerator)
.ok_or(Error::Overflow {
quantity: "power",
operation: "ratio adjustment",
left: i128::from(baseline.watts()),
right: Some(numerator),
})?;
let w = div_round(product, denominator, Rounding::HalfAwayFromZero)?;
i64::try_from(w).map(Power::from_watts).map_err(|_| {
MethodId::XofY1
.refuse("the adjusted baseline is outside the representable range")
})
}
}
}
}