use std::fmt;
use crate::canon::{self, Digest, Value};
use crate::{
Baseline, Energy, Error, IspLabel, MeasurementPoint, Power, Series, Settlement, Window,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ReboundLine {
pub isp: IspLabel,
pub baseline: Power,
pub actual: Power,
pub rebound: Power,
}
impl fmt::Display for ReboundLine {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}: baseline {}, actual {}, rebound {}",
self.isp, self.baseline, self.actual, self.rebound
)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Rebound {
lines: Vec<ReboundLine>,
total: Energy,
settlement: Digest,
baseline: Digest,
actual: Digest,
method: crate::MethodId,
measured_at: MeasurementPoint,
grid: Value,
}
fn mismatch(field: &'static str, ours: impl fmt::Display, theirs: impl fmt::Display) -> Error {
Error::Mismatch {
field,
ours: ours.to_string(),
theirs: theirs.to_string(),
}
}
impl Settlement {
pub fn rebound(
&self,
baseline: &Baseline,
actual: &Series<Power>,
measured_at: MeasurementPoint,
) -> Result<Rebound, Error> {
if &measured_at != self.measured_at() {
return Err(mismatch("measured_at", self.measured_at(), measured_at));
}
if baseline.method() != self.method() {
return Err(mismatch("method", self.method(), baseline.method()));
}
let window = actual.grid();
if window.isp() != self.grid().isp() {
return Err(mismatch("ISP-Duration", self.grid().isp(), window.isp()));
}
if window.start() != self.grid().end() {
return Err(mismatch(
"rebound window start",
self.grid().end(),
window.start(),
));
}
let base = baseline.series();
let covered = Window::new(window.start(), window.end())
.ok()
.and_then(|w| base.over(w).ok())
.filter(|b| b.grid().start() == window.start() && b.grid().count() == window.count())
.ok_or_else(|| mismatch("baseline window", window, base.grid()))?;
for l in self.lines() {
let during = l.isp.window();
match base.over(during) {
Ok(b) if b.grid().start() == during.from() => {
if b.values().first() != Some(&l.baseline) {
return Err(mismatch("baseline during the order", l.isp, l.baseline));
}
}
_ => {
return Err(mismatch(
"baseline during the order",
format!("{} covered", l.isp),
"not covered: compute it over the order and the window together",
));
}
}
}
let sign = self.order_sign()?;
let seconds = i128::from(window.isp().minutes()) * 60;
let mut total = 0i128;
let mut lines = Vec::with_capacity(window.count() as usize);
for ((isp, &a), &b) in actual.iter().zip(covered.values()) {
let back = ((i128::from(a.watts()) - i128::from(b.watts())) * -sign).max(0);
let watts = i64::try_from(back).map_err(|_| Error::Overflow {
quantity: "power",
operation: "rebound",
left: back,
right: None,
})?;
total += back * seconds;
lines.push(ReboundLine {
isp: window.label_total(isp),
baseline: b,
actual: a,
rebound: Power::from_watts(watts),
});
}
let rebound = Rebound {
lines,
total: Energy::from_sum(total)?,
settlement: self.digest(),
baseline: baseline.digest(),
actual: canon::power_input(actual)?,
method: self.method(),
measured_at,
grid: canon::grid(window),
};
rebound.value().exact()?;
Ok(rebound)
}
fn order_sign(&self) -> Result<i128, Error> {
let mut signs = self
.lines()
.iter()
.map(|l| i128::from(l.ordered.watts()).signum())
.filter(|&s| s != 0);
let first = signs.next();
match first {
Some(s) if signs.all(|t| t == s) => Ok(s),
_ => Err(Error::Method {
method: self.method(),
reason: "rebound needs an order in one direction: the ordered power is zero \
or changes sign"
.into(),
}),
}
}
}
impl Rebound {
#[must_use]
pub fn lines(&self) -> &[ReboundLine] {
&self.lines
}
#[must_use]
pub fn total(&self) -> Energy {
self.total
}
#[must_use]
pub fn settlement(&self) -> Digest {
self.settlement
}
#[must_use]
pub fn canonical(&self) -> String {
self.value().text()
}
#[must_use]
pub fn digest(&self) -> Digest {
self.value().digest()
}
fn value(&self) -> Value {
let lines = self
.lines
.iter()
.map(|l| {
Value::obj([
("actual", Value::int(l.actual.watts())),
("baseline", Value::int(l.baseline.watts())),
("isp", Value::int(l.isp.isp())),
("rebound", Value::int(l.rebound.watts())),
])
})
.collect();
Value::obj([
("grid", self.grid.clone()),
(
"inputs",
Value::obj([
("actual", Value::str(self.actual)),
("baseline", Value::str(self.baseline)),
("settlement", Value::str(self.settlement)),
]),
),
("lines", Value::Arr(lines)),
("measured_at", self.measured_at.canonical_value()),
("method", Value::str(self.method)),
("profile", canon::profile("rebound")),
(
"totals",
Value::obj([("rebound_ws", Value::int(self.total.watt_seconds()))]),
),
])
}
}
impl fmt::Display for Rebound {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for line in &self.lines {
writeln!(f, "{line}")?;
}
write!(
f,
"rebound {} after settlement {}, digest {}",
self.total,
self.settlement,
self.digest()
)
}
}