use std::fmt;
use std::ops::RangeInclusive;
use jiff::Timestamp;
use crate::error::Breach;
use crate::{Deviation, Error, Grid, IspLabel, Power, Series, Window};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Provenance {
issuer: String,
reference: String,
issued_at: Timestamp,
}
impl Provenance {
#[must_use]
pub fn new(
issuer: impl Into<String>,
reference: impl Into<String>,
issued_at: Timestamp,
) -> Provenance {
Provenance {
issuer: issuer.into(),
reference: reference.into(),
issued_at,
}
}
#[must_use]
pub fn issuer(&self) -> &str {
&self.issuer
}
#[must_use]
pub fn reference(&self) -> &str {
&self.reference
}
#[must_use]
pub fn issued_at(&self) -> Timestamp {
self.issued_at
}
}
impl fmt::Display for Provenance {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} {}", self.issuer, self.reference)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Bounds {
min: Option<Power>,
max: Option<Power>,
}
impl Bounds {
pub const UNBOUNDED: Bounds = Bounds {
min: None,
max: None,
};
pub fn new(min: Option<Power>, max: Option<Power>) -> Result<Bounds, Error> {
if let (Some(min), Some(max)) = (min, max)
&& min > max
{
return Err(Error::InvertedBounds { min, max });
}
Ok(Bounds { min, max })
}
#[must_use]
pub const fn at_most(max: Power) -> Bounds {
Bounds {
min: None,
max: Some(max),
}
}
#[must_use]
pub const fn at_least(min: Power) -> Bounds {
Bounds {
min: Some(min),
max: None,
}
}
#[must_use]
pub const fn min(self) -> Option<Power> {
self.min
}
#[must_use]
pub const fn max(self) -> Option<Power> {
self.max
}
#[must_use]
pub fn contains(self, power: Power) -> bool {
self.min.is_none_or(|m| power >= m) && self.max.is_none_or(|m| power <= m)
}
}
impl fmt::Display for Bounds {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match (self.min, self.max) {
(None, None) => f.write_str("unbounded"),
(None, Some(max)) => write!(f, "max {max}"),
(Some(min), None) => write!(f, "min {min}"),
(Some(min), Some(max)) => write!(f, "{min} to {max}"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Limit {
window: Window,
bounds: Bounds,
provenance: Provenance,
}
impl Limit {
#[must_use]
pub fn new(window: Window, bounds: Bounds, provenance: Provenance) -> Limit {
Limit {
window,
bounds,
provenance,
}
}
#[must_use]
pub fn consumption_cap(window: Window, max: Power, provenance: Provenance) -> Limit {
Limit::new(window, Bounds::at_most(max), provenance)
}
pub fn feed_in_cap(
window: Window,
amount: Power,
provenance: Provenance,
) -> Result<Limit, Error> {
let min = negated_amount(amount)?;
Ok(Limit::new(window, Bounds::at_least(min), provenance))
}
#[must_use]
pub fn consumption_floor(window: Window, min: Power, provenance: Provenance) -> Limit {
Limit::new(window, Bounds::at_least(min), provenance)
}
pub fn feed_in_floor(
window: Window,
amount: Power,
provenance: Provenance,
) -> Result<Limit, Error> {
let max = negated_amount(amount)?;
Ok(Limit::new(window, Bounds::at_most(max), provenance))
}
pub fn band(
window: Window,
min: Power,
max: Power,
provenance: Provenance,
) -> Result<Limit, Error> {
Ok(Limit::new(
window,
Bounds::new(Some(min), Some(max))?,
provenance,
))
}
#[must_use]
pub fn window(&self) -> Window {
self.window
}
#[must_use]
pub fn bounds(&self) -> Bounds {
self.bounds
}
#[must_use]
pub fn provenance(&self) -> &Provenance {
&self.provenance
}
#[must_use]
pub fn isps(&self, grid: &Grid) -> Option<RangeInclusive<u32>> {
grid.isps(self.window)
}
}
fn negated_amount(amount: Power) -> Result<Power, Error> {
if amount < Power::ZERO {
return Err(Error::NegativeAmount { power: amount });
}
amount.checked_neg()
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Guarantee {
window: Window,
kind: Kind,
provenance: Provenance,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum Kind {
Consumption(Power),
FeedIn(Power),
}
impl fmt::Display for Guarantee {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.kind {
Kind::Consumption(p) => {
write!(f, "consumption of {p} stays allowed ({})", self.provenance)
}
Kind::FeedIn(p) => write!(
f,
"feed-in of {} stays allowed ({})",
Power::from_watts(-p.watts()),
self.provenance
),
}
}
}
impl Guarantee {
pub fn consumption(
window: Window,
amount: Power,
provenance: Provenance,
) -> Result<Guarantee, Error> {
if amount < Power::ZERO {
return Err(Error::NegativeAmount { power: amount });
}
Ok(Guarantee {
window,
kind: Kind::Consumption(amount),
provenance,
})
}
pub fn feed_in(
window: Window,
amount: Power,
provenance: Provenance,
) -> Result<Guarantee, Error> {
let min = negated_amount(amount)?;
Ok(Guarantee {
window,
kind: Kind::FeedIn(min),
provenance,
})
}
#[must_use]
pub fn window(&self) -> Window {
self.window
}
#[must_use]
pub fn power(&self) -> Power {
match self.kind {
Kind::Consumption(p) | Kind::FeedIn(p) => p,
}
}
#[must_use]
pub fn provenance(&self) -> &Provenance {
&self.provenance
}
fn broken_by(&self, slot: Slot) -> Option<(Power, usize)> {
match self.kind {
Kind::Consumption(p) => slot.max.filter(|&(max, _)| max < p),
Kind::FeedIn(p) => slot.min.filter(|&(min, _)| min > p),
}
}
}
type Sourced = Option<(Power, usize)>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
struct Slot {
min: Sourced,
max: Sourced,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct Layer {
first: u32,
last: u32,
bounds: Bounds,
source: usize,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Envelope {
slots: Series<Slot>,
provenances: Vec<Provenance>,
layers: Vec<Layer>,
guarantees: Vec<Guarantee>,
}
impl Envelope {
#[must_use]
pub fn unbounded(grid: Grid) -> Envelope {
Envelope {
slots: Series::filled(grid, Slot::default()),
provenances: Vec::new(),
layers: Vec::new(),
guarantees: Vec::new(),
}
}
pub(crate) fn from_bounds(
grid: Grid,
bounds: &[Bounds],
provenance: Provenance,
) -> Result<Envelope, Error> {
let slots = Series::new(
grid,
bounds
.iter()
.map(|b| Slot {
min: b.min.map(|p| (p, 0)),
max: b.max.map(|p| (p, 0)),
})
.collect(),
)?;
let mut layers: Vec<Layer> = Vec::new();
for (isp, &b) in slots.grid().numbers().zip(bounds) {
if b == Bounds::UNBOUNDED {
continue;
}
match layers.last_mut() {
Some(l) if l.bounds == b && l.last + 1 == isp => l.last = isp,
_ => layers.push(Layer {
first: isp,
last: isp,
bounds: b,
source: 0,
}),
}
}
Ok(Envelope {
slots,
provenances: vec![provenance],
layers,
guarantees: Vec::new(),
})
}
pub fn apply(&self, limit: &Limit) -> Result<Envelope, Error> {
let Some(range) = limit.isps(self.grid()) else {
return Ok(self.clone());
};
let set = Slot {
min: limit.bounds.min.map(|p| (p, 0)),
max: limit.bounds.max.map(|p| (p, 0)),
};
let values = self
.grid()
.numbers()
.map(|isp| {
if range.contains(&isp) {
set
} else {
Slot::default()
}
})
.collect();
let other = Envelope {
slots: Series::new(self.grid().clone(), values)?,
provenances: vec![limit.provenance.clone()],
layers: vec![Layer {
first: *range.start(),
last: *range.end(),
bounds: limit.bounds,
source: 0,
}],
guarantees: Vec::new(),
};
self.combine(&other)
}
pub fn combine(&self, other: &Envelope) -> Result<Envelope, Error> {
self.slots.same_grid(other.grid())?;
let mut provenances = self.provenances.clone();
let remap: Vec<usize> = other
.provenances
.iter()
.map(|p| {
provenances.iter().position(|q| q == p).unwrap_or_else(|| {
provenances.push(p.clone());
provenances.len() - 1
})
})
.collect();
let mut values = Vec::with_capacity(self.slots.values().len());
for (isp, (a, b)) in self
.grid()
.numbers()
.zip(self.slots.values().iter().zip(other.slots.values()))
{
let b_min = b.min.and_then(|(p, i)| Some((p, *remap.get(i)?)));
let b_max = b.max.and_then(|(p, i)| Some((p, *remap.get(i)?)));
let min = stricter(a.min, b_min, |left, right| right > left);
let max = stricter(a.max, b_max, |left, right| right < left);
if let (Some((min, _)), Some((max, _))) = (min, max)
&& min > max
{
return Err(Error::EmptyRange {
isp: self.label(isp),
min,
max,
});
}
values.push(Slot { min, max });
}
let mut layers = self.layers.clone();
layers.extend(other.layers.iter().filter_map(|l| {
Some(Layer {
source: *remap.get(l.source)?,
..*l
})
}));
let mut guarantees = self.guarantees.clone();
for g in &other.guarantees {
if !guarantees.contains(g) {
guarantees.push(g.clone());
}
}
let combined = Envelope {
slots: Series::new(self.grid().clone(), values)?,
provenances,
layers,
guarantees,
};
for g in &combined.guarantees {
combined.check_guarantee(g)?;
}
Ok(combined)
}
pub fn guarantee(&self, guarantee: &Guarantee) -> Result<Envelope, Error> {
self.check_guarantee(guarantee)?;
let mut next = self.clone();
if !next.guarantees.contains(guarantee) {
next.guarantees.push(guarantee.clone());
}
Ok(next)
}
#[must_use]
pub fn guarantees(&self) -> &[Guarantee] {
&self.guarantees
}
fn check_guarantee(&self, g: &Guarantee) -> Result<(), Error> {
let Some(range) = self.grid().isps(g.window) else {
return Ok(());
};
for isp in range {
let Some(&slot) = self.slots.get(isp) else {
continue;
};
if let Some((bound, source)) = g.broken_by(slot)
&& let Some(limit) = self.provenances.get(source)
{
return Err(Error::GuaranteeBreached(Box::new(Breach {
isp: self.label(isp),
bound,
guaranteed: g.power(),
limit: limit.clone(),
guarantee: g.provenance.clone(),
})));
}
}
Ok(())
}
#[must_use]
pub fn grid(&self) -> &Grid {
self.slots.grid()
}
#[must_use]
pub fn bounds(&self, isp: u32) -> Option<Bounds> {
self.slots.get(isp).map(|s| Bounds {
min: s.min.map(|(p, _)| p),
max: s.max.map(|(p, _)| p),
})
}
#[must_use]
pub fn max_source(&self, isp: u32) -> Option<&Provenance> {
let (_, i) = self.slots.get(isp)?.max?;
self.provenances.get(i)
}
#[must_use]
pub fn min_source(&self, isp: u32) -> Option<&Provenance> {
let (_, i) = self.slots.get(isp)?.min?;
self.provenances.get(i)
}
#[must_use]
pub fn provenances(&self) -> &[Provenance] {
&self.provenances
}
#[must_use]
pub fn explain(&self, isp: u32) -> Option<Explanation> {
let slot = *self.slots.get(isp)?;
let label = self.grid().label(isp)?;
let shadowed_part = |l: &Layer| Bounds {
max: l
.bounds
.max
.filter(|&p| !matches!(slot.max, Some((q, s)) if s == l.source && q == p)),
min: l
.bounds
.min
.filter(|&p| !matches!(slot.min, Some((q, s)) if s == l.source && q == p)),
};
let shadowed = self
.layers
.iter()
.filter(|l| (l.first..=l.last).contains(&isp))
.map(|l| (shadowed_part(l), l.source))
.filter(|(b, _)| *b != Bounds::UNBOUNDED)
.filter_map(|(b, i)| Some((b, self.provenances.get(i)?.clone())))
.collect();
Some(Explanation {
label,
bounds: self.bounds(isp)?,
max_source: self.max_source(isp).cloned(),
min_source: self.min_source(isp).cloned(),
shadowed,
guaranteed: self
.guarantees
.iter()
.filter(|g| self.grid().isps(g.window).is_some_and(|r| r.contains(&isp)))
.cloned()
.collect(),
})
}
pub fn headroom(&self, schedule: &Schedule) -> Result<Series<Headroom>, Error> {
let series = schedule.series.zip_with(&self.slots, |planned, slot| {
let up = slot
.max
.map(|(max, _)| max.deviation_from(*planned))
.transpose()?;
let down = slot
.min
.map(|(min, _)| min.deviation_from(*planned))
.transpose()?;
Ok::<_, Error>(Headroom { up, down })
})?;
series.try_map(Clone::clone)
}
fn label(&self, isp: u32) -> IspLabel {
self.grid().label_total(isp)
}
}
fn stricter(left: Sourced, right: Sourced, right_wins: impl Fn(Power, Power) -> bool) -> Sourced {
match (left, right) {
(Some(l), Some(r)) => Some(if right_wins(l.0, r.0) { r } else { l }),
(l, None) => l,
(None, r) => r,
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Explanation {
pub label: IspLabel,
pub bounds: Bounds,
pub max_source: Option<Provenance>,
pub min_source: Option<Provenance>,
pub shadowed: Vec<(Bounds, Provenance)>,
pub guaranteed: Vec<Guarantee>,
}
impl fmt::Display for Explanation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}: ", self.label)?;
match (
self.bounds.min,
&self.min_source,
self.bounds.max,
&self.max_source,
) {
(None, _, None, _) => f.write_str("unbounded")?,
(min, min_src, max, max_src) => {
let mut first = true;
if let (Some(min), Some(src)) = (min, min_src) {
write!(f, "min {min} ({src})")?;
first = false;
}
if let (Some(max), Some(src)) = (max, max_src) {
if !first {
f.write_str(", ")?;
}
write!(f, "max {max} ({src})")?;
}
}
}
for (bounds, src) in &self.shadowed {
write!(f, "\n shadowed: {bounds} ({src})")?;
}
for g in &self.guaranteed {
write!(f, "\n guaranteed: {g}")?;
}
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Headroom {
pub up: Option<Deviation>,
pub down: Option<Deviation>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Schedule {
series: Series<Power>,
provenance: Provenance,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Broken {
AboveMax(Power),
BelowMin(Power),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Violation {
pub label: IspLabel,
pub planned: Power,
pub broken: Broken,
pub source: Provenance,
}
impl fmt::Display for Violation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let (side, bound) = match self.broken {
Broken::AboveMax(p) => ("above max", p),
Broken::BelowMin(p) => ("below min", p),
};
write!(
f,
"{}: planned {} {side} {bound} set by {}",
self.label, self.planned, self.source
)
}
}
impl Schedule {
#[must_use]
pub fn new(series: Series<Power>, provenance: Provenance) -> Schedule {
Schedule { series, provenance }
}
#[must_use]
pub fn series(&self) -> &Series<Power> {
&self.series
}
#[must_use]
pub fn provenance(&self) -> &Provenance {
&self.provenance
}
pub fn check(&self, envelope: &Envelope) -> Result<Vec<Violation>, Error> {
self.series.same_grid(envelope.grid())?;
let mut violations = Vec::new();
for ((isp, &planned), slot) in self.series.iter().zip(envelope.slots.values()) {
let broken = match (slot.min, slot.max) {
(_, Some((max, i))) if planned > max => Some((Broken::AboveMax(max), i)),
(Some((min, i)), _) if planned < min => Some((Broken::BelowMin(min), i)),
_ => None,
};
if let Some((broken, i)) = broken
&& let Some(source) = envelope.provenances.get(i)
{
violations.push(Violation {
label: envelope.label(isp),
planned,
broken,
source: source.clone(),
});
}
}
Ok(violations)
}
}