use alloc::vec::Vec;
use crate::mo::coverage::Point;
pub(super) fn prune<const N: usize>(points: &mut Vec<Point<N>>, margin: f64) {
pareto_front(points);
lower_hull(points);
while points.len() > 1 {
let (index, gap) = (0..points.len())
.map(|index| (index, vertex_margin(points, index)))
.min_by(|a, b| a.1.total_cmp(&b.1))
.expect("at least two vertices");
if gap > margin {
break;
}
points.remove(index);
}
}
fn pareto_front<const N: usize>(points: &mut Vec<Point<N>>) {
points.sort_by(|a, b| {
a.vector[0]
.total_cmp(&b.vector[0])
.then(a.vector[1].total_cmp(&b.vector[1]))
});
let mut best = f64::INFINITY;
points.retain(|point| {
let keep = point.vector[1] < best;
if keep {
best = point.vector[1];
}
keep
});
}
fn lower_hull<const N: usize>(points: &mut Vec<Point<N>>) {
let mut kept = 0;
for index in 0..points.len() {
while kept >= 2 && !turns_left(&points[kept - 2], &points[kept - 1], &points[index]) {
kept -= 1;
}
points.swap(kept, index);
kept += 1;
}
points.truncate(kept);
}
fn turns_left<const N: usize>(a: &Point<N>, b: &Point<N>, c: &Point<N>) -> bool {
let (a, b, c) = (&a.vector, &b.vector, &c.vector);
(b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) > 0.0
}
fn vertex_margin<const N: usize>(points: &[Point<N>], index: usize) -> f64 {
let v = &points[index].vector;
let neighbours = [
index.checked_sub(1).map(|left| points[left].vector),
points.get(index + 1).map(|right| right.vector),
];
let lines: Vec<(f64, f64)> = neighbours
.iter()
.flatten()
.map(|u| ((u[0] - v[0]) - (u[1] - v[1]), u[1] - v[1]))
.collect();
let worst = |t: f64| {
lines
.iter()
.map(|&(a, b)| a * t + b)
.fold(f64::INFINITY, f64::min)
};
let mut candidates = [0.0, 1.0, 0.0];
if let [(a1, b1), (a2, b2)] = lines[..] {
let slope = a1 - a2;
if slope != 0.0 {
candidates[2] = ((b2 - b1) / slope).clamp(0.0, 1.0);
}
}
candidates
.into_iter()
.map(worst)
.fold(f64::NEG_INFINITY, f64::max)
}