use alloc::vec::Vec;
use nalgebra::{DMatrix, DVector};
use polyzonotope::{Interval, IntervalMatrix, SparsePolyZonotope, Zonotope};
use crate::ReachError;
use crate::taylor::Taylor;
#[derive(Clone, Debug, PartialEq)]
pub struct LinearSystem {
pub a: DMatrix<f64>,
pub b: DMatrix<f64>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Step {
pub time_point: SparsePolyZonotope,
pub time_interval: SparsePolyZonotope,
pub duration: f64,
}
pub struct LinearReach {
system: LinearSystem,
taylor: Taylor,
exponential: IntervalMatrix,
input_solution: IntervalMatrix,
state_correction: IntervalMatrix,
input_correction: IntervalMatrix,
}
impl LinearReach {
pub fn new(system: LinearSystem, step: f64, taylor_terms: usize) -> Result<Self, ReachError> {
let n = system.a.nrows();
assert_eq!(system.a.ncols(), n, "A must be square");
assert_eq!(system.b.nrows(), n, "B needs one row per state");
let taylor = Taylor::new(&system.a, step, taylor_terms)?;
Ok(Self {
exponential: taylor.exponential(),
input_solution: taylor.input_solution(),
state_correction: taylor.state_correction(),
input_correction: taylor.input_correction(),
taylor,
system,
})
}
#[must_use]
pub fn step(&self, x: &SparsePolyZonotope, u: &Zonotope) -> Step {
let input = u.linear_map(&self.system.b);
let constant = input.center().clone();
let varying = Zonotope::new(DVector::zeros(input.dim()), input.generators().clone());
let particular = self.varying_input_response(&varying);
let input_effect = point_response(&self.input_solution, &constant);
let time_point = x
.interval_map(&self.exponential)
.minkowski_sum(&input_effect)
.minkowski_sum(&particular);
let time_interval = hull_with_successor(x, &self.exponential, &input_effect)
.minkowski_sum(&x.interval_map(&self.state_correction))
.minkowski_sum(&point_response(&self.input_correction, &constant))
.minkowski_sum(&particular);
Step {
time_point,
time_interval,
duration: self.taylor.step,
}
}
fn varying_input_response(&self, v: &Zonotope) -> SparsePolyZonotope {
let pz = without_factors(v);
(0..=self.taylor.terms())
.map(|i| pz.interval_map(&self.taylor.input_term(i)))
.fold(
pz.interval_map(
&self
.taylor
.remainder
.scale(Interval::point(self.taylor.step)),
),
|acc, term| acc.minkowski_sum(&term),
)
}
}
fn point_response(m: &IntervalMatrix, v: &DVector<f64>) -> SparsePolyZonotope {
let point = Zonotope::new(v.clone(), DMatrix::zeros(v.len(), 0));
without_factors(&point.interval_map(m))
}
pub(crate) fn without_factors(z: &Zonotope) -> SparsePolyZonotope {
SparsePolyZonotope::new(
z.center().clone(),
DMatrix::zeros(z.dim(), 0),
z.generators().clone(),
DMatrix::zeros(0, 0),
Vec::new(),
)
.expect("consistent shapes")
}
fn hull_with_successor(
x: &SparsePolyZonotope,
phi: &IntervalMatrix,
offset: &SparsePolyZonotope,
) -> SparsePolyZonotope {
let n = x.dim();
let (center, radius) = phi.center_radius();
let identity = DMatrix::identity(n, n);
let halved = |sign: f64| {
IntervalMatrix::point(&identity)
.add(&IntervalMatrix::point(&(¢er * sign)))
.scale(Interval::point(0.5))
};
let offset_point = Zonotope::new(offset.center().clone(), DMatrix::zeros(n, 0));
let half_offset = without_factors(&offset_point).linear_map(&(&identity * 0.5));
let mean = x.interval_map(&halved(1.0)).exact_plus(&half_offset);
let difference = x
.interval_map(&halved(-1.0))
.exact_plus(&half_offset.linear_map(&-&identity));
let swing = SparsePolyZonotope::new(
DVector::zeros(n),
DMatrix::zeros(n, 0),
columns(&[
difference.dependent_generators(),
difference.independent_generators(),
&DMatrix::from_column_slice(n, 1, difference.center().as_slice()),
]),
DMatrix::zeros(0, 0),
Vec::new(),
)
.expect("consistent shapes");
let spread = IntervalMatrix(radius.map(|r| Interval::new(-r, r)));
let offset_spread = offset.translate(&-offset.center());
mean.minkowski_sum(&swing)
.minkowski_sum(&x.interval_map(&spread))
.minkowski_sum(&offset_spread)
}
fn columns(parts: &[&DMatrix<f64>]) -> DMatrix<f64> {
let rows = parts[0].nrows();
let all: Vec<f64> = parts.iter().flat_map(|m| m.iter().copied()).collect();
DMatrix::from_vec(rows, all.len() / rows.max(1), all)
}