Skip to main content

polyzonotope_reach/
linear.rs

1//! Reachable sets of linear systems `x' = A x + B u` with `u ∈ U`
2//! (Althoff 2010, Sec. 3.2; Girard 2005 for the time-interval hull).
3
4use alloc::vec::Vec;
5
6use nalgebra::{DMatrix, DVector};
7use polyzonotope::{Interval, IntervalMatrix, SparsePolyZonotope, Zonotope};
8
9use crate::ReachError;
10use crate::taylor::Taylor;
11
12/// `x' = A x + B u`.
13#[derive(Clone, Debug, PartialEq)]
14pub struct LinearSystem {
15    /// State matrix `A`, `n × n`.
16    pub a: DMatrix<f64>,
17    /// Input matrix `B`, `n × m`.
18    pub b: DMatrix<f64>,
19}
20
21/// The reachable sets of one step `[t_k, t_k + r]`.
22#[derive(Clone, Debug, PartialEq)]
23pub struct Step {
24    /// Every state the system can be in at `t_k + r`.
25    pub time_point: SparsePolyZonotope,
26    /// Every state the system can be in at some `t ∈ [t_k, t_k + r]`.
27    pub time_interval: SparsePolyZonotope,
28    /// The step length `r`: the configured step, unless adaptive steps
29    /// (see [`Adaptive`](crate::Adaptive)) chose another.
30    pub duration: f64,
31}
32
33/// Precomputed one-step propagation of a [`LinearSystem`] with time step `r`.
34pub struct LinearReach {
35    /// The system.
36    system: LinearSystem,
37    /// Taylor series of `e^{A r}` with its remainder.
38    taylor: Taylor,
39    /// `e^{A r}`, enclosed.
40    exponential: IntervalMatrix,
41    /// `Γ(r)`, the response to a constant input after one step.
42    input_solution: IntervalMatrix,
43    /// `F`, the time-interval correction of the state.
44    state_correction: IntervalMatrix,
45    /// `F̃`, the time-interval correction of a constant input.
46    input_correction: IntervalMatrix,
47}
48
49impl LinearReach {
50    /// Propagation of `system` in steps of `step`, with `taylor_terms` terms
51    /// of the matrix exponential after the first.
52    ///
53    /// # Errors
54    ///
55    /// [`ReachError::InvalidStep`] if `step` is negative, infinite or NaN.
56    /// [`ReachError::StepTooLarge`] if the Taylor remainder bound does not
57    /// hold for this step and term count.
58    ///
59    /// # Panics
60    ///
61    /// Panics if `A` is not square or `B` does not have one row per state.
62    pub fn new(system: LinearSystem, step: f64, taylor_terms: usize) -> Result<Self, ReachError> {
63        let n = system.a.nrows();
64        assert_eq!(system.a.ncols(), n, "A must be square");
65        assert_eq!(system.b.nrows(), n, "B needs one row per state");
66        let taylor = Taylor::new(&system.a, step, taylor_terms)?;
67
68        Ok(Self {
69            exponential: taylor.exponential(),
70            input_solution: taylor.input_solution(),
71            state_correction: taylor.state_correction(),
72            input_correction: taylor.input_correction(),
73            taylor,
74            system,
75        })
76    }
77
78    /// The reachable sets one step after `x`, for inputs in `u`: any
79    /// integrable signal with values in `u`, the zonotope's center being the
80    /// constant part.
81    ///
82    /// Time point: `e^{Ar} X ⊕ Γ(r) B c_u ⊕ R_p(B U_Δ)`. Time interval: the
83    /// hull of `X` and `e^{Ar} X + Γ(r) B c_u`, plus `F X ⊕ F̃ B c_u ⊕ R_p(B U_Δ)`, where
84    /// `R_p(V) = ⊕_{i=0}^{η} A^i r^{i+1} / (i+1)! V ⊕ E(r) r V` encloses the
85    /// response to the varying part `U_Δ` of the input.
86    ///
87    /// # Panics
88    ///
89    /// Panics if `x` does not have one row per state or `u` one per input.
90    #[must_use]
91    pub fn step(&self, x: &SparsePolyZonotope, u: &Zonotope) -> Step {
92        // `B U` with its rounding errors as generators: a constant is one of
93        // the signals the varying part covers, so they may go there.
94        let input = u.linear_map(&self.system.b);
95        let constant = input.center().clone();
96        let varying = Zonotope::new(DVector::zeros(input.dim()), input.generators().clone());
97        let particular = self.varying_input_response(&varying);
98
99        let input_effect = point_response(&self.input_solution, &constant);
100        let time_point = x
101            .interval_map(&self.exponential)
102            .minkowski_sum(&input_effect)
103            .minkowski_sum(&particular);
104        let time_interval = hull_with_successor(x, &self.exponential, &input_effect)
105            .minkowski_sum(&x.interval_map(&self.state_correction))
106            .minkowski_sum(&point_response(&self.input_correction, &constant))
107            .minkowski_sum(&particular);
108
109        Step {
110            time_point,
111            time_interval,
112            duration: self.taylor.step,
113        }
114    }
115
116    /// `R_p(V) = ⊕_{i=0}^{η} A^i r^{i+1} / (i+1)! V ⊕ E(r) r V`.
117    fn varying_input_response(&self, v: &Zonotope) -> SparsePolyZonotope {
118        let pz = without_factors(v);
119        (0..=self.taylor.terms())
120            .map(|i| pz.interval_map(&self.taylor.input_term(i)))
121            .fold(
122                pz.interval_map(
123                    &self
124                        .taylor
125                        .remainder
126                        .scale(Interval::point(self.taylor.step)),
127                ),
128                |acc, term| acc.minkowski_sum(&term),
129            )
130    }
131}
132
133/// `{ M v | M ∈ m }` for a fixed vector `v`, as a set without factors.
134fn point_response(m: &IntervalMatrix, v: &DVector<f64>) -> SparsePolyZonotope {
135    let point = Zonotope::new(v.clone(), DMatrix::zeros(v.len(), 0));
136    without_factors(&point.interval_map(m))
137}
138
139/// A zonotope as a polynomial zonotope with independent generators only, so
140/// that its parts never correlate with anything else.
141pub(crate) fn without_factors(z: &Zonotope) -> SparsePolyZonotope {
142    SparsePolyZonotope::new(
143        z.center().clone(),
144        DMatrix::zeros(z.dim(), 0),
145        z.generators().clone(),
146        DMatrix::zeros(0, 0),
147        Vec::new(),
148    )
149    .expect("consistent shapes")
150}
151
152/// An enclosure of `{ λ x + (1 − λ) (e^{Ar} x + w) | x ∈ X, λ ∈ [0, 1] }`
153/// (Girard 2005), with `Φ = Φ_c ± R` the interval matrix `phi` and `w` from
154/// `offset`, a point `w_c` plus independent generators:
155///
156/// `λ x + (1 − λ)(Φ_c x + w_c) = ½ (I + Φ_c) x + ½ w_c + (λ − ½)((I − Φ_c) x − w_c)`.
157/// Both parts are linear maps of the one point `x`, so the first keeps the
158/// factors of `X` and pairs each independent generator of `x` with its image
159/// under `Φ_c`, as CORA's `enclose` does. In the second, `2λ − 1 ∈ [-1, 1]`
160/// multiplies every term, so each generator of `½ (X − Φ_c X − w_c)`, its
161/// center included, becomes an independent generator: even monomials lose
162/// their sign there. `(Φ − Φ_c) x ∈ [-R, R] X` covers the spread of `phi`,
163/// and the generators of `offset` cover the spread of `w`.
164fn hull_with_successor(
165    x: &SparsePolyZonotope,
166    phi: &IntervalMatrix,
167    offset: &SparsePolyZonotope,
168) -> SparsePolyZonotope {
169    let n = x.dim();
170    let (center, radius) = phi.center_radius();
171    let identity = DMatrix::identity(n, n);
172    // ½ (I ± Φ_c) in interval arithmetic, so that the rounding of the sums
173    // is enclosed; interval_map still maps every generator in place.
174    let halved = |sign: f64| {
175        IntervalMatrix::point(&identity)
176            .add(&IntervalMatrix::point(&(&center * sign)))
177            .scale(Interval::point(0.5))
178    };
179    let offset_point = Zonotope::new(offset.center().clone(), DMatrix::zeros(n, 0));
180    let half_offset = without_factors(&offset_point).linear_map(&(&identity * 0.5));
181
182    let mean = x.interval_map(&halved(1.0)).exact_plus(&half_offset);
183    let difference = x
184        .interval_map(&halved(-1.0))
185        .exact_plus(&half_offset.linear_map(&-&identity));
186    let swing = SparsePolyZonotope::new(
187        DVector::zeros(n),
188        DMatrix::zeros(n, 0),
189        columns(&[
190            difference.dependent_generators(),
191            difference.independent_generators(),
192            &DMatrix::from_column_slice(n, 1, difference.center().as_slice()),
193        ]),
194        DMatrix::zeros(0, 0),
195        Vec::new(),
196    )
197    .expect("consistent shapes");
198    let spread = IntervalMatrix(radius.map(|r| Interval::new(-r, r)));
199    let offset_spread = offset.translate(&-offset.center());
200
201    mean.minkowski_sum(&swing)
202        .minkowski_sum(&x.interval_map(&spread))
203        .minkowski_sum(&offset_spread)
204}
205
206/// The columns of all `parts`, side by side; all have the same row count.
207fn columns(parts: &[&DMatrix<f64>]) -> DMatrix<f64> {
208    let rows = parts[0].nrows();
209    let all: Vec<f64> = parts.iter().flat_map(|m| m.iter().copied()).collect();
210    DMatrix::from_vec(rows, all.len() / rows.max(1), all)
211}