use std::fmt;
use crate::{Bounds, Deviation, Envelope, Error, Grid, IspLabel, Power, Provenance, Series};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Disposition {
Requested,
Available,
Unstated,
}
impl fmt::Display for Disposition {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Disposition::Requested => "requested",
Disposition::Available => "available",
Disposition::Unstated => "disposition unstated",
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Band {
pub min: Deviation,
pub max: Deviation,
pub disposition: Disposition,
}
impl Band {
pub fn new(min: Deviation, max: Deviation, disposition: Disposition) -> Result<Band, Error> {
if min > max {
return Err(Error::InvertedBand { min, max });
}
Ok(Band {
min,
max,
disposition,
})
}
#[must_use]
pub fn contains(self, deviation: Deviation) -> bool {
self.min <= deviation && deviation <= self.max
}
}
impl fmt::Display for Band {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} to {} ({})", self.min, self.max, self.disposition)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DeviationEnvelope {
bands: Series<Option<Band>>,
provenance: Provenance,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum MisfitKind {
Outside {
offered: Deviation,
band: Band,
},
Unrequested {
offered: Deviation,
},
NotOffered {
band: Band,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Misfit {
pub label: IspLabel,
pub kind: MisfitKind,
pub source: Provenance,
}
impl fmt::Display for Misfit {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let (label, source) = (&self.label, &self.source);
match self.kind {
MisfitKind::Outside { offered, band } => {
write!(
f,
"{label}: offered {offered} outside {band} set by {source}"
)
}
MisfitKind::Unrequested { offered } => {
write!(
f,
"{label}: offered {offered} where {source} requested nothing"
)
}
MisfitKind::NotOffered { band } => {
write!(f, "{label}: not offered, outside {band} set by {source}")
}
}
}
}
impl DeviationEnvelope {
#[must_use]
pub fn new(bands: Series<Option<Band>>, provenance: Provenance) -> DeviationEnvelope {
DeviationEnvelope { bands, provenance }
}
#[must_use]
pub fn grid(&self) -> &Grid {
self.bands.grid()
}
#[must_use]
pub fn band(&self, isp: u32) -> Option<Band> {
self.bands.get(isp).copied().flatten()
}
#[must_use]
pub fn bands(&self) -> &Series<Option<Band>> {
&self.bands
}
#[must_use]
pub fn provenance(&self) -> &Provenance {
&self.provenance
}
pub fn check<T>(&self, offer: &Series<T>) -> Result<Vec<Misfit>, Error>
where
T: Copy + Into<Option<Deviation>>,
{
within(self.grid(), offer.grid())?;
let zero = Deviation::from_watts(0);
Ok(self
.bands
.iter()
.filter_map(|(isp, &band)| {
let offered = offer.get(isp).copied().and_then(Into::into);
let kind = match (offered, band) {
(Some(o), Some(b)) if !b.contains(o) => MisfitKind::Outside {
offered: o,
band: b,
},
(Some(o), None) if o != zero => MisfitKind::Unrequested { offered: o },
(None, Some(b)) if !b.contains(zero) => MisfitKind::NotOffered { band: b },
_ => return None,
};
Some(Misfit {
label: self.grid().label_total(isp),
kind,
source: self.provenance.clone(),
})
})
.collect())
}
pub fn resolve(&self, baseline: &Series<Power>) -> Result<Envelope, Error> {
within(self.grid(), baseline.grid())?;
let bounds = baseline
.iter()
.map(|(isp, &b)| match self.band(isp) {
None => Ok(Bounds::UNBOUNDED),
Some(band) => Bounds::new(
Some(b.checked_add_deviation(band.min)?),
Some(b.checked_add_deviation(band.max)?),
),
})
.collect::<Result<Vec<_>, Error>>()?;
Envelope::from_bounds(baseline.grid().clone(), &bounds, self.provenance.clone())
}
}
fn within(outer: &Grid, inner: &Grid) -> Result<(), Error> {
if outer.slice(inner.numbers()).ok().as_ref() == Some(inner) {
Ok(())
} else {
Err(Error::GridMismatch {
left: outer.clone(),
right: inner.clone(),
})
}
}