use polyzonotope::SparsePolyZonotope;
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum Cost {
#[default]
Length,
WidthWeighted {
weight: f64,
},
}
impl Cost {
#[must_use]
pub fn edge(&self, length: f64, end: &SparsePolyZonotope) -> f64 {
match *self {
Self::Length => length,
Self::WidthWeighted { weight } => length + weight * width(end),
}
}
#[must_use]
pub fn is_valid(&self) -> bool {
match *self {
Self::Length => true,
Self::WidthWeighted { weight } => weight.is_finite() && weight >= 0.0,
}
}
}
fn width(set: &SparsePolyZonotope) -> f64 {
set.interval_hull()
.0
.iter()
.map(polyzonotope::Interval::width)
.fold(0.0, f64::max)
}
#[cfg(test)]
mod tests {
use polyzonotope::{Interval, IntervalBox, Zonotope};
use super::*;
fn rect(w: f64, h: f64) -> SparsePolyZonotope {
SparsePolyZonotope::from_zonotope(&Zonotope::from_box(&IntervalBox(vec![
Interval::new(0.0, w),
Interval::new(0.0, h),
])))
}
#[test]
fn length_ignores_the_set() {
assert_eq!(
Cost::Length.edge(0.75, &rect(3.0, 4.0)).to_bits(),
0.75f64.to_bits()
);
}
#[test]
fn width_weighted_adds_the_largest_hull_side() {
let cost = Cost::WidthWeighted { weight: 0.5 };
assert!((cost.edge(1.0, &rect(0.2, 0.6)) - 1.3).abs() < 1e-12);
assert!(
cost.edge(1.0, &rect(0.2, 0.6)) >= 1.0,
"never below the length"
);
}
#[test]
fn only_finite_non_negative_weights_are_valid() {
assert!(Cost::Length.is_valid());
assert!(Cost::WidthWeighted { weight: 0.0 }.is_valid());
assert!(!Cost::WidthWeighted { weight: -1.0 }.is_valid());
assert!(!Cost::WidthWeighted { weight: f64::NAN }.is_valid());
assert!(
!Cost::WidthWeighted {
weight: f64::INFINITY
}
.is_valid()
);
}
}