use alloc::vec::Vec;
const PIVOT_TOLERANCE: f64 = 1e-12;
const COVER_TOLERANCE: f64 = 1e-10;
pub(crate) fn best_weight<const N: usize>(
v: &[f64; N],
others: &[[f64; N]],
tableau: &mut Vec<f64>,
) -> ([f64; N], f64) {
if others.is_empty() {
return (uniform(), f64::INFINITY);
}
let lp = Tableau::build(v, others, tableau);
let lp = lp.solve();
let weight = lp.weight::<N>();
let margin = margin(&weight, v, others);
(weight, margin)
}
pub(crate) fn is_covered<const N: usize>(
v: &[f64; N],
others: &[[f64; N]],
margin: f64,
tableau: &mut Vec<f64>,
) -> bool {
if others.is_empty() {
return false;
}
let lp = Tableau::build_covering(v, others, margin, tableau).solve();
lp.objective() >= -COVER_TOLERANCE
}
pub(crate) fn margin<const N: usize>(weight: &[f64; N], v: &[f64; N], others: &[[f64; N]]) -> f64 {
others
.iter()
.map(|u| dot(weight, u) - dot(weight, v))
.fold(f64::INFINITY, f64::min)
}
pub(crate) fn uniform<const N: usize>() -> [f64; N] {
#[expect(
clippy::cast_precision_loss,
reason = "N is a handful of objectives, exact in f64"
)]
let share = 1.0 / N as f64;
[share; N]
}
pub(crate) fn dot<const N: usize>(a: &[f64; N], b: &[f64; N]) -> f64 {
a.iter().zip(b).map(|(x, y)| x * y).sum()
}
struct Tableau<'a> {
cells: &'a mut Vec<f64>,
rows: usize,
columns: usize,
structural: usize,
basis: Vec<usize>,
}
impl<'a> Tableau<'a> {
fn build<const N: usize>(v: &[f64; N], others: &[[f64; N]], cells: &'a mut Vec<f64>) -> Self {
let free = N - 1;
let structural = N;
let rows = others.len() + usize::from(free > 0);
let columns = structural + rows + 1;
let shift = 1.0
+ others
.iter()
.flat_map(|u| u.iter().zip(v).map(|(a, b)| libm::fabs(a - b)))
.fold(0.0, f64::max);
cells.clear();
cells.resize((rows + 1) * columns, 0.0);
for (row, u) in others.iter().enumerate() {
let last = u[free] - v[free];
let line = &mut cells[row * columns..(row + 1) * columns];
for i in 0..free {
line[i] = -((u[i] - v[i]) - last);
}
line[free] = 1.0;
line[structural + row] = 1.0;
line[columns - 1] = last + shift;
}
if free > 0 {
let row = others.len();
let line = &mut cells[row * columns..(row + 1) * columns];
line[..free].fill(1.0);
line[structural + row] = 1.0;
line[columns - 1] = 1.0;
}
cells[rows * columns + free] = -1.0;
let basis = (structural..structural + rows).collect();
Self {
cells,
rows,
columns,
structural,
basis,
}
}
fn build_covering<const N: usize>(
v: &[f64; N],
others: &[[f64; N]],
margin: f64,
cells: &'a mut Vec<f64>,
) -> Self {
let m = others.len();
let rows = N + 1;
let columns = m + N + 2;
cells.clear();
cells.resize((rows + 1) * columns, 0.0);
for objective in 0..N {
let line = &mut cells[objective * columns..(objective + 1) * columns];
for (j, u) in others.iter().enumerate() {
line[j] = u[objective] - v[objective];
}
line[m + objective] = 1.0;
line[columns - 1] = margin;
}
let line = &mut cells[N * columns..(N + 1) * columns];
line[..m].fill(1.0);
line[m + N] = 1.0;
line[columns - 1] = 1.0;
let objective = &mut cells[rows * columns..];
objective[..m].fill(-1.0);
objective[columns - 1] = -1.0;
let basis = (m..=m + N).collect();
Self {
cells,
rows,
columns,
structural: m,
basis,
}
}
fn objective(&self) -> f64 {
self.cells[(self.rows + 1) * self.columns - 1]
}
fn solve(mut self) -> Self {
while let Some(entering) = self.entering() {
let Some(leaving) = self.leaving(entering) else {
break;
};
self.pivot(leaving, entering);
}
self
}
fn entering(&self) -> Option<usize> {
let objective = &self.cells[self.rows * self.columns..];
(0..self.columns - 1).find(|&column| objective[column] < -PIVOT_TOLERANCE)
}
fn leaving(&self, column: usize) -> Option<usize> {
let mut best: Option<(usize, f64)> = None;
for row in 0..self.rows {
let a = self.cells[row * self.columns + column];
if a <= PIVOT_TOLERANCE {
continue;
}
let ratio = self.cells[row * self.columns + self.columns - 1] / a;
let better = best.is_none_or(|(current, best_ratio)| {
ratio < best_ratio - PIVOT_TOLERANCE
|| (ratio <= best_ratio + PIVOT_TOLERANCE
&& self.basis[row] < self.basis[current])
});
if better {
best = Some((row, ratio));
}
}
best.map(|(row, _)| row)
}
fn pivot(&mut self, row: usize, column: usize) {
let columns = self.columns;
let scale = 1.0 / self.cells[row * columns + column];
for cell in &mut self.cells[row * columns..(row + 1) * columns] {
*cell *= scale;
}
for other in 0..=self.rows {
if other == row {
continue;
}
let factor = self.cells[other * columns + column];
if factor == 0.0 {
continue;
}
for index in 0..columns {
let delta = factor * self.cells[row * columns + index];
self.cells[other * columns + index] -= delta;
}
}
self.basis[row] = column;
}
fn weight<const N: usize>(&self) -> [f64; N] {
let mut weight = [0.0; N];
for (row, &variable) in self.basis.iter().enumerate() {
if variable < self.structural - 1 {
weight[variable] = self.cells[row * self.columns + self.columns - 1].max(0.0);
}
}
let rest: f64 = weight[..N - 1].iter().sum();
weight[N - 1] = (1.0 - rest).max(0.0);
weight
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn margin_of_vertices_and_edge_points() {
let mut buffer = Vec::new();
let others = [[2.0, 0.0], [0.0, 2.0]];
let (_, edge) = best_weight(&[1.0, 1.0], &others, &mut buffer);
assert!(edge.abs() < 1e-12, "edge point margin {edge}");
let (weight, vertex) = best_weight(&[0.5, 0.5], &others, &mut buffer);
assert!((vertex - 0.5).abs() < 1e-12, "vertex margin {vertex}");
assert!((weight[0] - 0.5).abs() < 1e-12);
let (_, dominated) = best_weight(&[3.0, 3.0], &others, &mut buffer);
assert!(dominated < 0.0);
}
#[test]
fn covering_agrees_with_the_margin() {
let mut buffer = Vec::new();
let mut state = 11_u64;
let mut next = move || {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
f64::from(u8::try_from(state % 16).unwrap()) / 4.0
};
for _ in 0..500 {
let v = [next(), next(), next()];
let count = if next() < 2.0 { 1 } else { 3 };
let others: Vec<[f64; 3]> = (0..count).map(|_| [next(), next(), next()]).collect();
let (_, gap) = best_weight(&v, &others, &mut buffer);
for margin in [0.0, 0.1, 0.5] {
if (gap - margin).abs() > 1e-9 {
assert_eq!(
is_covered(&v, &others, margin, &mut buffer),
gap <= margin,
"{v:?} {others:?} gap {gap}"
);
}
}
}
}
#[test]
fn single_objective_margin_is_the_gap() {
let mut buffer = Vec::new();
let (weight, gap) = best_weight(&[1.0], &[[4.0], [2.5]], &mut buffer);
assert_eq!(weight, [1.0]);
assert!((gap - 1.5).abs() < 1e-12);
}
#[test]
fn three_objectives() {
let mut buffer = Vec::new();
let others = [[0.0, 5.0, 5.0], [5.0, 5.0, 0.0]];
let (weight, gap) = best_weight(&[5.0, 0.0, 5.0], &others, &mut buffer);
assert!(gap > 1.0, "margin {gap}");
assert!((margin(&weight, &[5.0, 0.0, 5.0], &others) - gap).abs() < 1e-12);
}
}