use alloc::vec::Vec;
use super::Splitting;
use nalgebra::{DMatrix, DVector};
use polyzonotope::{FactorId, Interval, IntervalBox, Reduction, SparsePolyZonotope, Zonotope};
pub(super) fn halves(
piece: &SparsePolyZonotope,
cost: impl Fn(&SparsePolyZonotope) -> f64,
splitting: Splitting,
) -> Option<(SparsePolyZonotope, SparsePolyZonotope)> {
let lifted = lift_independent(&box_independent(piece));
let oriented = match splitting {
Splitting::Factors => None,
_ => Some(SparsePolyZonotope::from_zonotope(
&piece.reduce(1.0, Reduction::Pca).to_zonotope(),
)),
};
let candidates = core::iter::once(&lifted)
.chain(oriented.as_ref())
.flat_map(|set| set.ids().iter().map(move |&id| (set, id)))
.filter(|&(set, id)| set.can_split(id));
let best = candidates
.map(|(set, id)| {
let (lower, upper) = set.split(id);
(cost(&lower).max(cost(&upper)), lower, upper)
})
.min_by(|a, b| a.0.total_cmp(&b.0))?;
(best.0 < cost(piece)).then_some((best.1, best.2))
}
fn box_independent(pz: &SparsePolyZonotope) -> SparsePolyZonotope {
let n = pz.dim();
let independent = Zonotope::new(DVector::zeros(n), pz.independent_generators().clone())
.reduce(1.0, Reduction::Pca);
SparsePolyZonotope::new(
pz.center().clone(),
pz.dependent_generators().clone(),
independent.generators().clone(),
pz.exponents().clone(),
pz.ids().to_vec(),
)
.expect("same shapes")
.translate(independent.center())
}
pub(super) fn lift_independent(pz: &SparsePolyZonotope) -> SparsePolyZonotope {
let (dependent, independent, powers) = (
pz.dependent_generators(),
pz.independent_generators(),
pz.exponents(),
);
let (deps, lifts, factors) = (dependent.ncols(), independent.ncols(), pz.ids().len());
let generators = DMatrix::from_fn(pz.dim(), deps + lifts, |i, j| {
if j < deps {
dependent[(i, j)]
} else {
independent[(i, j - deps)]
}
});
let exponents = DMatrix::from_fn(factors + lifts, deps + lifts, |k, j| {
match (k < factors, j < deps) {
(true, true) => powers[(k, j)],
(false, false) => u32::from(k - factors == j - deps),
_ => 0,
}
});
let mut ids = pz.ids().to_vec();
ids.extend(FactorId::fresh_n(lifts));
SparsePolyZonotope::new(
pz.center().clone(),
generators,
DMatrix::zeros(pz.dim(), 0),
exponents,
ids,
)
.expect("lifted shapes fit")
}
pub(super) fn width(pz: &SparsePolyZonotope) -> f64 {
pz.interval_hull().0.iter().map(Interval::width).sum()
}
pub(super) fn merge(
mut pieces: Vec<SparsePolyZonotope>,
tolerance: f64,
cap: f64,
finish: impl Fn(&SparsePolyZonotope) -> SparsePolyZonotope,
) -> Vec<SparsePolyZonotope> {
while let Some((i, j, merged)) = best_merge(&pieces, tolerance, cap, &finish) {
pieces.swap_remove(j);
pieces[i] = merged;
}
pieces
}
fn best_merge(
pieces: &[SparsePolyZonotope],
tolerance: f64,
cap: f64,
finish: impl Fn(&SparsePolyZonotope) -> SparsePolyZonotope,
) -> Option<(usize, usize, SparsePolyZonotope)> {
let hulls: Vec<_> = pieces
.iter()
.map(SparsePolyZonotope::interval_hull)
.collect();
let mut best: Option<(f64, usize, usize, SparsePolyZonotope)> = None;
for j in 1..pieces.len() {
for i in 0..j {
let merged = hull_of_pair(&pieces[i], &pieces[j]);
let ratio = volume(&merged.interval_hull()) / (volume(&hulls[i]) + volume(&hulls[j]));
let fits = width(&merged) <= cap && ratio <= 1.0 + tolerance;
if !fits || best.as_ref().is_some_and(|b| ratio >= b.0) {
continue;
}
let finished = finish(&merged);
if width(&finished) <= cap {
best = Some((ratio, i, j, finished));
}
}
}
best.map(|(_, i, j, merged)| (i, j, merged))
}
fn volume(hull: &IntervalBox) -> f64 {
hull.0.iter().map(|iv| iv.width().max(1e-12)).product()
}
fn hull_of_pair(a: &SparsePolyZonotope, b: &SparsePolyZonotope) -> SparsePolyZonotope {
let b = pair_factors(a, b);
let n = a.dim();
let half = DMatrix::from_diagonal_element(n, n, 0.5);
let mean = a.linear_map(&half).exact_plus(&b.linear_map(&half));
let difference = a.linear_map(&half).exact_plus(&b.linear_map(&-&half));
mean.exact_plus(&scaled_by_fresh_factor(&difference))
}
fn pair_factors(a: &SparsePolyZonotope, b: &SparsePolyZonotope) -> SparsePolyZonotope {
let mut only_a = a.ids().iter().filter(|id| !b.ids().contains(id));
let ids = b
.ids()
.iter()
.map(|id| {
if a.ids().contains(id) {
*id
} else {
only_a.next().copied().unwrap_or(*id)
}
})
.collect();
SparsePolyZonotope::new(
b.center().clone(),
b.dependent_generators().clone(),
b.independent_generators().clone(),
b.exponents().clone(),
ids,
)
.expect("renamed ids stay distinct")
}
fn scaled_by_fresh_factor(pz: &SparsePolyZonotope) -> SparsePolyZonotope {
let (dependent, powers) = (pz.dependent_generators(), pz.exponents());
let (deps, factors) = (dependent.ncols(), pz.ids().len());
let generators = DMatrix::from_fn(pz.dim(), deps + 1, |i, j| {
if j < deps {
dependent[(i, j)]
} else {
pz.center()[i]
}
});
let exponents = DMatrix::from_fn(factors + 1, deps + 1, |k, j| {
match (k < factors, j < deps) {
(true, true) => powers[(k, j)],
(true, false) => 0,
(false, _) => 1,
}
});
let mut ids = pz.ids().to_vec();
ids.push(FactorId::fresh());
SparsePolyZonotope::new(
DVector::zeros(pz.dim()),
generators,
pz.independent_generators().clone(),
exponents,
ids,
)
.expect("scaled shapes fit")
.compact()
}
#[cfg(test)]
mod tests {
use super::*;
fn mixed() -> SparsePolyZonotope {
SparsePolyZonotope::new(
DVector::from_vec(alloc::vec![1.0, 2.0]),
DMatrix::from_row_slice(2, 1, &[1.0, 0.5]),
DMatrix::from_row_slice(2, 1, &[0.0, 3.0]),
DMatrix::from_element(1, 1, 1),
FactorId::fresh_n(1),
)
.unwrap()
}
#[test]
fn lifting_is_exact() {
let pz = mixed();
let lifted = lift_independent(&pz);
assert_eq!(lifted.independent_generators().ncols(), 0);
for (a, b) in [(-1.0, 0.5), (0.3, -0.7), (1.0, 1.0)] {
let gap = lifted.evaluate(&[a, b], &[]) - pz.evaluate(&[a], &[b]);
assert!(gap.amax() < 1e-12, "{gap}");
}
}
#[test]
fn split_takes_the_widest_factor() {
let pz = mixed();
let (lower, upper) = halves(&pz, width, Splitting::Cheapest).expect("splittable");
assert!(width(&lower) < width(&pz) && width(&upper) < width(&pz));
let hull = lower.interval_hull();
assert!((hull.0[1].width() - 4.0).abs() < 1e-12, "{hull:?}");
}
#[test]
fn a_point_has_no_halves() {
let point = SparsePolyZonotope::from_zonotope(&Zonotope::new(
DVector::from_element(2, 1.0),
DMatrix::zeros(2, 0),
));
assert!(halves(&point, width, Splitting::Cheapest).is_none());
}
#[test]
fn halves_merge_back() {
let pz = mixed();
let (lower, upper) = halves(&pz, width, Splitting::Factors).unwrap();
let merged = merge(
alloc::vec![lower.clone(), upper.clone()],
0.05,
f64::INFINITY,
Clone::clone,
);
assert_eq!(merged.len(), 1);
assert!(width(&merged[0]) <= width(&pz) + 1e-12);
}
#[test]
fn cap_blocks_the_merge() {
let (lower, upper) = halves(&mixed(), width, Splitting::Factors).unwrap();
let cap = width(&lower).max(width(&upper));
assert_eq!(
merge(alloc::vec![lower, upper], 0.05, cap, Clone::clone).len(),
2
);
}
#[test]
fn cap_applies_after_finish() {
let pz = mixed();
let (lower, upper) = halves(&pz, width, Splitting::Factors).unwrap();
let widen = |m: &SparsePolyZonotope| {
m.linear_map(&DMatrix::from_diagonal_element(m.dim(), m.dim(), 2.0))
};
let cap = width(&pz) + 1e-12;
assert_eq!(merge(alloc::vec![lower, upper], 0.05, cap, widen).len(), 2);
}
#[test]
fn distant_pieces_stay_apart() {
let at = |x: f64| {
SparsePolyZonotope::from_zonotope(&Zonotope::new(
DVector::from_vec(alloc::vec![x, 0.0]),
DMatrix::from_diagonal_element(2, 2, 0.1),
))
};
assert_eq!(
merge(
alloc::vec![at(0.0), at(5.0)],
0.1,
f64::INFINITY,
Clone::clone
)
.len(),
2
);
}
}
#[cfg(test)]
mod properties {
use super::*;
use proptest::prelude::*;
fn arb_set() -> impl Strategy<Value = SparsePolyZonotope> {
(
proptest::collection::vec(-2.0..2.0f64, 2),
proptest::collection::vec(-1.0..1.0f64, 6),
proptest::collection::vec(0u32..3, 6),
proptest::collection::vec(-0.5..0.5f64, 2),
)
.prop_map(|(c, g, e, gi)| {
SparsePolyZonotope::new(
DVector::from_vec(c),
DMatrix::from_vec(2, 3, g),
DMatrix::from_vec(2, 1, gi),
DMatrix::from_vec(2, 3, e),
FactorId::fresh_n(2),
)
.unwrap()
})
}
fn near(pz: &SparsePolyZonotope, p: &DVector<f64>) -> bool {
pz.split_pieces(6)
.iter()
.any(|piece| piece.interval_hull().contains(p, 1e-9))
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(64))]
#[test]
fn halves_cover_the_set(pz in arb_set(), a in -1.0..1.0f64, b in -1.0..1.0f64, beta in -1.0..1.0f64) {
let p = pz.evaluate(&[a, b], &[beta]);
if let Some((lower, upper)) = halves(&pz, width, Splitting::Cheapest) {
prop_assert!(near(&lower, &p) || near(&upper, &p));
}
}
#[test]
fn merge_holds_both_pieces(
x in arb_set(),
y in arb_set(),
shared in proptest::bool::ANY,
a in -1.0..1.0f64, b in -1.0..1.0f64, beta in -1.0..1.0f64,
) {
let y = if shared { pair_factors(&x, &y) } else { y };
let merged = hull_of_pair(&x, &y);
prop_assert!(near(&merged, &x.evaluate(&[a, b], &[beta])));
prop_assert!(near(&merged, &y.evaluate(&[a, b], &[beta])));
}
}
}