use alloc::vec::Vec;
use nalgebra::{DMatrix, DVector};
#[cfg(feature = "sound")]
use sound as backend;
#[cfg(not(feature = "sound"))]
use plain as backend;
pub(crate) use backend::{add_down, add_up, mid_rad, residual_bound};
#[cfg(feature = "sound")]
mod sound {
use inari::Interval;
use nalgebra::{DMatrix, DVector};
use super::RowErrors;
fn point(x: f64) -> Interval {
Interval::try_from((x, x)).expect("set coefficients must be finite in sound mode")
}
fn split(x: Interval) -> (f64, f64) {
(x.mid(), x.rad())
}
pub(crate) fn add(a: f64, b: f64) -> (f64, f64) {
split(point(a) + point(b))
}
pub(crate) fn mul(a: f64, b: f64) -> (f64, f64) {
split(point(a) * point(b))
}
fn dot(pairs: impl Iterator<Item = (f64, f64)>) -> (f64, f64) {
split(pairs.fold(point(0.0), |acc, (a, b)| point(a).mul_add(point(b), acc)))
}
pub(crate) fn bilinear(a: &DVector<f64>, q: &DMatrix<f64>, b: &DVector<f64>) -> (f64, f64) {
let mut acc = point(0.0);
for (j, &x) in a.iter().enumerate() {
for (k, &y) in b.iter().enumerate() {
acc = (point(x) * point(q[(j, k)])).mul_add(point(y), acc);
}
}
split(acc)
}
pub(crate) fn residual_bound(u: &DMatrix<f64>, s: &DVector<f64>) -> DVector<f64> {
let n = u.nrows();
DVector::from_fn(n, |i, _| {
let mut acc = point(0.0);
for k in 0..n {
let uut = (0..u.ncols()).fold(point(0.0), |a, j| {
point(u[(i, j)]).mul_add(point(u[(k, j)]), a)
});
let identity = point(if i == k { 1.0 } else { 0.0 });
acc = point((identity - uut).mag()).mul_add(point(s[k]), acc);
}
acc.sup()
})
}
pub(crate) fn add_up(a: f64, b: f64) -> f64 {
(point(a) + point(b)).sup()
}
pub(crate) fn add_down(a: f64, b: f64) -> f64 {
(point(a) + point(b)).inf()
}
pub(crate) fn mid_rad(lo: f64, hi: f64) -> (f64, f64) {
split(Interval::try_from((lo, hi)).expect("interval bounds must be finite in sound mode"))
}
pub(crate) fn mat_mul(
m: &DMatrix<f64>,
x: &DMatrix<f64>,
errs: &mut RowErrors,
) -> DMatrix<f64> {
DMatrix::from_fn(m.nrows(), x.ncols(), |i, j| {
let (v, e) = dot(m.row(i).iter().copied().zip(x.column(j).iter().copied()));
errs.record(i, e);
v
})
}
pub(crate) fn mat_vec(
m: &DMatrix<f64>,
v: &DVector<f64>,
errs: &mut RowErrors,
) -> DVector<f64> {
DVector::from_fn(m.nrows(), |i, _| {
let (r, e) = dot(m.row(i).iter().copied().zip(v.iter().copied()));
errs.record(i, e);
r
})
}
}
#[cfg(not(feature = "sound"))]
mod plain {
use nalgebra::{DMatrix, DVector};
use super::RowErrors;
pub(crate) fn add(a: f64, b: f64) -> (f64, f64) {
(a + b, 0.0)
}
pub(crate) fn mul(a: f64, b: f64) -> (f64, f64) {
(a * b, 0.0)
}
pub(crate) fn bilinear(a: &DVector<f64>, q: &DMatrix<f64>, b: &DVector<f64>) -> (f64, f64) {
(a.dot(&(q * b)), 0.0)
}
pub(crate) fn residual_bound(u: &DMatrix<f64>, _: &DVector<f64>) -> DVector<f64> {
DVector::zeros(u.nrows())
}
pub(crate) fn add_up(a: f64, b: f64) -> f64 {
a + b
}
pub(crate) fn add_down(a: f64, b: f64) -> f64 {
a + b
}
pub(crate) fn mid_rad(lo: f64, hi: f64) -> (f64, f64) {
(f64::midpoint(lo, hi), (hi - lo) / 2.0)
}
pub(crate) fn mat_mul(m: &DMatrix<f64>, x: &DMatrix<f64>, _: &mut RowErrors) -> DMatrix<f64> {
m * x
}
pub(crate) fn mat_vec(m: &DMatrix<f64>, v: &DVector<f64>, _: &mut RowErrors) -> DVector<f64> {
m * v
}
}
pub(crate) struct RowErrors(Vec<f64>);
impl RowErrors {
pub(crate) fn new(n: usize) -> Self {
Self(alloc::vec![0.0; n])
}
pub(crate) fn record(&mut self, row: usize, err: f64) {
if err != 0.0 {
self.0[row] = add_up(self.0[row], err);
}
}
pub(crate) fn bound(&self, row: usize) -> f64 {
self.0[row]
}
pub(crate) fn generators(&self) -> DMatrix<f64> {
let rows: Vec<usize> = (0..self.0.len()).filter(|&i| self.0[i] != 0.0).collect();
DMatrix::from_fn(self.0.len(), rows.len(), |i, j| {
if i == rows[j] { self.0[i] } else { 0.0 }
})
}
}
pub(crate) fn mat_mul(m: &DMatrix<f64>, x: &DMatrix<f64>, errs: &mut RowErrors) -> DMatrix<f64> {
assert_eq!(
m.ncols(),
x.nrows(),
"matrix columns must match the dimension"
);
backend::mat_mul(m, x, errs)
}
pub(crate) fn mat_vec(m: &DMatrix<f64>, v: &DVector<f64>, errs: &mut RowErrors) -> DVector<f64> {
assert_eq!(
m.ncols(),
v.len(),
"matrix columns must match the dimension"
);
backend::mat_vec(m, v, errs)
}
pub(crate) fn vec_add(a: &DVector<f64>, b: &DVector<f64>, errs: &mut RowErrors) -> DVector<f64> {
let mut sum = a.clone();
add_into(&mut sum, b, errs);
sum
}
pub(crate) fn add_into(target: &mut DVector<f64>, v: &DVector<f64>, errs: &mut RowErrors) {
assert_eq!(
target.len(),
v.len(),
"vectors must have the same dimension"
);
for (i, (t, &x)) in target.iter_mut().zip(v.iter()).enumerate() {
let (sum, e) = backend::add(*t, x);
errs.record(i, e);
*t = sum;
}
}
pub(crate) fn scaled(v: &DVector<f64>, s: f64, errs: &mut RowErrors) -> DVector<f64> {
DVector::from_fn(v.len(), |i, _| {
let (p, e) = backend::mul(v[i], s);
errs.record(i, e);
p
})
}
pub(crate) fn bilinear(
left: &DVector<f64>,
matrix: &DMatrix<f64>,
right: &DVector<f64>,
row: usize,
errs: &mut RowErrors,
) -> f64 {
assert_eq!(
matrix.shape(),
(left.len(), right.len()),
"matrix must match both vectors"
);
let (v, e) = backend::bilinear(left, matrix, right);
errs.record(row, e);
v
}
pub(crate) fn add(a: f64, b: f64, row: usize, errs: &mut RowErrors) -> f64 {
let (v, e) = backend::add(a, b);
errs.record(row, e);
v
}
pub(crate) fn halves(v: &DVector<f64>, errs: &mut RowErrors) -> DVector<f64> {
let half = scaled(v, 0.5, errs);
let _ = scaled(v, 0.5, errs);
half
}
pub(crate) fn abs_sum_up<'a>(xs: impl IntoIterator<Item = &'a f64>) -> f64 {
xs.into_iter().fold(0.0, |acc, x| add_up(acc, x.abs()))
}