use std::fmt;
use crate::baseline::{self, Baseline, MethodId};
use crate::canon::{self, Digest, Json, Value};
use jiff::Timestamp;
use jiff::tz::TimeZone;
use crate::{Deviation, Energy, Error, Grid, IspDuration, IspLabel, Power, Series};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Line {
pub isp: IspLabel,
pub baseline: Power,
pub actual: Power,
pub ordered: Deviation,
pub deviation: Deviation,
pub delivered: Deviation,
pub deficiency: Power,
}
impl fmt::Display for Line {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}: baseline {}, actual {}, ordered {}, delivered {}, deficiency {}",
self.isp, self.baseline, self.actual, self.ordered, self.delivered, self.deficiency
)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum MeasurementPoint {
ConnectionPoint,
Device(DeviceId),
}
impl MeasurementPoint {
pub fn device(id: &str) -> Result<MeasurementPoint, Error> {
DeviceId::new(id).map(MeasurementPoint::Device)
}
pub(crate) fn canonical_value(&self) -> Value {
match self {
MeasurementPoint::ConnectionPoint => Value::str("connection-point"),
MeasurementPoint::Device(id) => Value::obj([("device", Value::str(id.as_str()))]),
}
}
}
impl fmt::Display for MeasurementPoint {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
MeasurementPoint::ConnectionPoint => f.write_str("connection point"),
MeasurementPoint::Device(id) => write!(f, "device {}", id.as_str()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct DeviceId(String);
impl DeviceId {
pub fn new(id: &str) -> Result<DeviceId, Error> {
let reason = match id.chars().count() {
0 => Some("is empty"),
n if n > 64 => Some("is longer than 64 characters"),
_ if id.chars().any(char::is_control) => Some("contains a control character"),
_ => None,
};
match reason {
Some(reason) => Err(Error::DeviceId {
id: canon::quote(id),
reason,
}),
None => Ok(DeviceId(id.to_owned())),
}
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Settlement {
method: MethodId,
measured_at: MeasurementPoint,
baseline: Digest,
inputs: Vec<(&'static str, Digest)>,
lines: Vec<Line>,
delivered: Energy,
deficiency: Energy,
grid: Grid,
canonical_grid: Value,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Difference {
Method {
ours: MethodId,
theirs: MethodId,
},
MeasurementPoint {
ours: MeasurementPoint,
theirs: MeasurementPoint,
},
Grid,
Input {
name: &'static str,
ours: Digest,
theirs: Digest,
},
Line {
isp: IspLabel,
field: &'static str,
ours: i64,
theirs: i64,
},
}
impl fmt::Display for Difference {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Difference::Method { ours, theirs } => {
write!(f, "method: ours {ours}, theirs {theirs}")
}
Difference::MeasurementPoint { ours, theirs } => {
write!(f, "measured at: ours {ours}, theirs {theirs}")
}
Difference::Grid => f.write_str("the settlements cover different ISPs"),
Difference::Input { name, ours, theirs } => {
write!(f, "input `{name}` differs: ours {ours}, theirs {theirs}")
}
Difference::Line {
isp,
field,
ours,
theirs,
} => write!(
f,
"{isp}: {field} ours {}, theirs {}",
Power::from_watts(*ours),
Power::from_watts(*theirs)
),
}
}
}
pub fn settle(
baseline: &Baseline,
actual: &Series<Power>,
ordered: &Series<Deviation>,
measured_at: MeasurementPoint,
) -> Result<Settlement, Error> {
let grid = baseline.series().grid();
actual.same_grid(grid)?;
ordered.same_grid(grid)?;
let rows = baseline
.series()
.values()
.iter()
.zip(actual.values())
.zip(ordered.values())
.map(|((&b, &a), &o)| (b, a, o));
build(
baseline.method(),
measured_at,
baseline.digest(),
vec![
("actual", canon::power_input(actual)?),
("ordered", canon::deviation_input(ordered)?),
],
grid,
rows,
)
}
fn build(
method: MethodId,
measured_at: MeasurementPoint,
baseline: Digest,
inputs: Vec<(&'static str, Digest)>,
grid: &Grid,
rows: impl Iterator<Item = (Power, Power, Deviation)>,
) -> Result<Settlement, Error> {
let seconds = i128::from(grid.isp().minutes()) * 60;
let mut lines = Vec::with_capacity(grid.count() as usize);
let (mut delivered_ws, mut deficiency_ws) = (0i128, 0i128);
for (isp, (b, a, o)) in grid.numbers().zip(rows) {
let deviation = a.deviation_from(b)?;
let (delivered, deficiency) =
settle_isp(i128::from(deviation.watts()), i128::from(o.watts()));
delivered_ws += delivered * seconds;
deficiency_ws += deficiency * seconds;
lines.push(Line {
isp: grid.label_total(isp),
baseline: b,
actual: a,
ordered: o,
deviation,
delivered: Deviation::from_watts(to_i64(delivered)?),
deficiency: Power::from_watts(to_i64(deficiency)?),
});
}
let settlement = Settlement {
method,
measured_at,
baseline,
inputs,
lines,
delivered: Energy::from_sum(delivered_ws)?,
deficiency: Energy::from_sum(deficiency_ws)?,
grid: grid.clone(),
canonical_grid: canon::grid(grid),
};
settlement.value().exact()?;
Ok(settlement)
}
pub(crate) fn settle_isp(deviation: i128, ordered: i128) -> (i128, i128) {
let o = ordered;
let u = o.signum();
let r = deviation * u;
let amount = o.abs();
let delivered = r.clamp(0, amount) * u;
let deficiency = (amount - r).max(0);
(delivered, deficiency)
}
fn to_i64(w: i128) -> Result<i64, Error> {
i64::try_from(w).map_err(|_| Error::Overflow {
quantity: "power",
operation: "settle",
left: w,
right: None,
})
}
fn watts(v: &Json, path: &str) -> Result<i64, Error> {
i64::try_from(v.int(path)?).map_err(|_| canon::refuse(path, "outside the range of watts"))
}
fn digest_at(inputs: &Json, name: &str) -> Result<Digest, Error> {
let path = canon::join("inputs", name);
inputs
.get("inputs", name)?
.str(&path)?
.parse()
.map_err(|_| canon::refuse(&path, "not a digest"))
}
const SETTLEMENT_PROFILE: &str = "flexibility.settlement@1";
fn read_header(root: &Json) -> Result<MethodId, Error> {
let profile = root.get("", "profile")?.str("profile")?;
if profile != SETTLEMENT_PROFILE {
return Err(canon::refuse(
"profile",
format!("{} is not {SETTLEMENT_PROFILE}", canon::quote(profile)),
));
}
let id = root.get("", "method")?.str("method")?;
id.parse().map_err(|_| {
canon::refuse(
"method",
format!("{} is not a known method id", canon::quote(id)),
)
})
}
fn read_point(v: &Json) -> Result<MeasurementPoint, Error> {
match v {
Json::Str(s) if s == "connection-point" => Ok(MeasurementPoint::ConnectionPoint),
Json::Obj(_) => {
let id = v.get("measured_at", "device")?.str("measured_at.device")?;
MeasurementPoint::device(id)
.map_err(|e| canon::refuse("measured_at.device", e.to_string()))
}
_ => Err(canon::refuse(
"measured_at",
"neither \"connection-point\" nor {\"device\":…}",
)),
}
}
fn read_grid(g: &Json, zone: TimeZone) -> Result<Grid, Error> {
let number = |name: &str| {
let path = canon::join("grid", name);
u32::try_from(g.get("grid", name)?.int(&path)?)
.map_err(|_| canon::refuse(&path, "out of range"))
};
let (count, first) = (number("count")?, number("first")?);
let isp_text = g.get("grid", "isp")?.str("grid.isp")?;
let isp = IspDuration::from_canonical(isp_text).ok_or_else(|| {
canon::refuse(
"grid.isp",
format!("{} is not an ISP length", canon::quote(isp_text)),
)
})?;
let start_text = g.get("grid", "start")?.str("grid.start")?;
let start: Timestamp = start_text.parse().map_err(|_| {
canon::refuse(
"grid.start",
format!("{} is not an instant", canon::quote(start_text)),
)
})?;
Grid::numbered(start, isp, count, first, zone).map_err(|e| canon::refuse("grid", e.to_string()))
}
fn read_rows(lines: &[Json], grid: &Grid) -> Result<Vec<(Power, Power, Deviation)>, Error> {
if lines.len() != grid.count() as usize {
return Err(canon::refuse(
"lines",
format!("{} lines for a grid of {} ISPs", lines.len(), grid.count()),
));
}
lines
.iter()
.enumerate()
.zip(grid.numbers())
.map(|((k, line), isp)| {
let path = format!("lines[{k}]");
let field = |name: &str| watts(line.get(&path, name)?, &canon::join(&path, name));
if field("isp")? != i64::from(isp) {
return Err(canon::refuse(
&canon::join(&path, "isp"),
format!("expected ISP {isp}"),
));
}
Ok((
Power::from_watts(field("baseline")?),
Power::from_watts(field("actual")?),
Deviation::from_watts(field("ordered")?),
))
})
.collect()
}
fn explain_mismatch(lines: &[Json], totals: &Json, read: &Settlement) -> Result<(), Error> {
for ((k, line), ours) in lines.iter().enumerate().zip(&read.lines) {
let path = format!("lines[{k}]");
for (name, expected) in [
("deviation", ours.deviation.watts()),
("delivered", ours.delivered.watts()),
("deficiency", ours.deficiency.watts()),
] {
let sent = watts(line.get(&path, name)?, &canon::join(&path, name))?;
if sent != expected {
return Err(canon::refuse(
&canon::join(&path, name),
format!("sent {sent}, the rule gives {expected}"),
));
}
}
}
for (name, expected) in [
("delivered_ws", read.delivered.watt_seconds()),
("deficiency_ws", read.deficiency.watt_seconds()),
] {
let path = canon::join("totals", name);
let sent = totals.get("totals", name)?.int(&path)?;
if sent != i128::from(expected) {
return Err(canon::refuse(
&path,
format!("sent {sent}, the lines give {expected}"),
));
}
}
Ok(())
}
impl Settlement {
pub fn from_canonical(text: &str, zone: TimeZone) -> Result<Settlement, Error> {
let root = canon::read(text)?;
let method = read_header(&root)?;
let grid = read_grid(root.get("", "grid")?, zone)?;
let inputs = root.get("", "inputs")?;
let lines = root.get("", "lines")?.arr("lines")?;
let read = build(
method,
read_point(root.get("", "measured_at")?)?,
digest_at(inputs, "baseline")?,
vec![
("actual", digest_at(inputs, "actual")?),
("ordered", digest_at(inputs, "ordered")?),
],
&grid,
read_rows(lines, &grid)?.into_iter(),
)
.map_err(|e| canon::refuse("lines", e.to_string()))?;
explain_mismatch(lines, root.get("", "totals")?, &read)?;
if read.canonical() != text {
return Err(canon::refuse(
"",
"not in canonical form: the bytes differ from the canonical text of the \
settlement they describe (whitespace, key order, an escape or an extra field)",
));
}
Ok(read)
}
#[must_use]
pub fn measured_at(&self) -> &MeasurementPoint {
&self.measured_at
}
#[must_use]
pub fn grid(&self) -> &Grid {
&self.grid
}
#[must_use]
pub fn method(&self) -> MethodId {
self.method
}
#[must_use]
pub fn lines(&self) -> &[Line] {
&self.lines
}
#[must_use]
pub fn delivered(&self) -> Energy {
self.delivered
}
#[must_use]
pub fn deficiency(&self) -> Energy {
self.deficiency
}
#[must_use]
pub fn baseline(&self) -> Digest {
self.baseline
}
#[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()
}
#[must_use]
pub fn diff(&self, theirs: &Settlement) -> Option<Difference> {
if self.method != theirs.method {
return Some(Difference::Method {
ours: self.method,
theirs: theirs.method,
});
}
if self.measured_at != theirs.measured_at {
return Some(Difference::MeasurementPoint {
ours: self.measured_at.clone(),
theirs: theirs.measured_at.clone(),
});
}
if self.canonical_grid != theirs.canonical_grid || self.lines.len() != theirs.lines.len() {
return Some(Difference::Grid);
}
for (a, b) in self.lines.iter().zip(&theirs.lines) {
let fields = [
("baseline", a.baseline.watts(), b.baseline.watts()),
("actual", a.actual.watts(), b.actual.watts()),
("ordered", a.ordered.watts(), b.ordered.watts()),
("delivered", a.delivered.watts(), b.delivered.watts()),
("deficiency", a.deficiency.watts(), b.deficiency.watts()),
];
if let Some((field, ours, theirs)) = fields.into_iter().find(|(_, x, y)| x != y) {
return Some(Difference::Line {
isp: a.isp,
field,
ours,
theirs,
});
}
}
let ours = std::iter::once(("baseline", self.baseline)).chain(self.inputs.iter().copied());
let other =
std::iter::once(("baseline", theirs.baseline)).chain(theirs.inputs.iter().copied());
for ((name, a), (_, b)) in ours.zip(other) {
if a != b {
return Some(Difference::Input {
name,
ours: a,
theirs: b,
});
}
}
None
}
fn value(&self) -> Value {
let mut inputs = self.inputs.clone();
inputs.push(("baseline", self.baseline));
let lines = self
.lines
.iter()
.map(|l| {
Value::obj([
("actual", Value::int(l.actual.watts())),
("baseline", Value::int(l.baseline.watts())),
("deficiency", Value::int(l.deficiency.watts())),
("delivered", Value::int(l.delivered.watts())),
("deviation", Value::int(l.deviation.watts())),
("isp", Value::int(l.isp.isp())),
("ordered", Value::int(l.ordered.watts())),
])
})
.collect();
Value::obj([
("grid", self.canonical_grid.clone()),
("inputs", baseline::inputs(&inputs)),
("lines", Value::Arr(lines)),
("measured_at", self.measured_at.canonical_value()),
("method", Value::str(self.method)),
("profile", Value::str(SETTLEMENT_PROFILE)),
(
"totals",
Value::obj([
("deficiency_ws", Value::int(self.deficiency.watt_seconds())),
("delivered_ws", Value::int(self.delivered.watt_seconds())),
]),
),
])
}
}
impl fmt::Display for Settlement {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for line in &self.lines {
writeln!(f, "{line}")?;
}
write!(
f,
"{}: delivered {}, deficiency {}, digest {}",
self.method,
self.delivered,
self.deficiency,
self.digest()
)
}
}