Skip to main content

polyzonotope_reach/
nonlinear.rs

1//! Reachable sets of nonlinear systems `x' = f(x, u)` by conservative
2//! linearization (Althoff, Stursberg & Buss 2008) or conservative
3//! polynomialization (Althoff 2013), with polynomial zonotopes (Kochdumper &
4//! Althoff 2021).
5//!
6//! Each step linearizes `f` around a point `z* = (x*, u*)` and treats the
7//! rest, the abstraction error, as an extra uncertain input of the linear
8//! system. The error depends on the time-interval set it is meant to
9//! produce, so it is guessed, checked and enlarged until the check passes.
10//! With [`Method::Polynomialization`], the second-order error at the start
11//! set is computed once, as a polynomial zonotope over the set's factors,
12//! and fed in exactly; only the rest is guessed:
13//!
14//! ```mermaid
15//! flowchart LR
16//!     L[linearize at z*] --> P[static error Ψ_s over X, polynomialization only]
17//!     P --> R[linear step with error box Ψ̄]
18//!     R --> E[error Ψ over the time-interval set]
19//!     E -->|Ψ ⊆ Ψ̄| A[accept, reduce]
20//!     E -->|Ψ ⊄ Ψ̄| W[Ψ̄ := widen Ψ̄ ∪ Ψ]
21//!     W --> R
22//!     W -->|too many tries| S[split the set or refuse]
23//! ```
24
25use alloc::vec;
26use alloc::vec::Vec;
27
28use nalgebra::{DMatrix, DVector};
29use polyzonotope::{Interval, IntervalBox, Reduction, SparsePolyZonotope, Zonotope};
30
31use crate::{Dynamics, LinearReach, LinearSystem, ReachError, Step};
32
33mod driver;
34mod error;
35mod polynomialization;
36mod split;
37
38pub use driver::Adaptive;
39
40#[cfg(test)]
41mod ablation;
42
43/// How [`NonlinearReach`] abstracts the dynamics in each step.
44///
45/// Non-exhaustive: more abstractions may be added.
46#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
47#[non_exhaustive]
48pub enum Method {
49    /// Conservative linearization (Althoff, Stursberg & Buss 2008): the
50    /// whole abstraction error `½ Δzᵀ H(ξ) Δz` over the time-interval set is
51    /// one box, guessed and checked. Needs the Hessians only. The default,
52    /// because every [`Dynamics`] supports it.
53    #[default]
54    Linearization,
55    /// Conservative polynomialization (Althoff 2013): the second- and
56    /// third-order error at the start set stays a polynomial zonotope over
57    /// the set's factors and moves with the set; only what changes during
58    /// the step and the Lagrange remainder around the third derivatives at
59    /// `z*` go into the box. Needs [`Dynamics::third_derivatives`]. Tighter
60    /// for large sets, since the box shrinks from `O(w²)` to `O(w r + w² r)`
61    /// plus the spread of `∂³f` times `w³` for a set of width `w`; that spread
62    /// comes from rounding only for fields of degree 3 or less.
63    ///
64    /// # The error decomposition
65    ///
66    /// Let `f` be three times continuously differentiable, `z* = (x*, u*)` the
67    /// linearization point and `[A B]` the center of the enclosure of `J(z*)`,
68    /// with `w ∈ f(z*) − A x* − B u*` the model offset. For a trajectory with
69    /// `x(t_k) = x_k` and any input signal `u(t) ∈ U`, write
70    ///
71    /// - `Δz(t) = z(t) − z*` with `z(t) = (x(t), u(t))`,
72    /// - `s = (x_k − x_m, 0)`, the start of the trajectory relative to the
73    ///   middle `x_m` of the start set's hull, which is constant along the
74    ///   trajectory, and
75    /// - `δ(t) = Δz(t) − s = (x(t) − x_k − c, u(t) − u*)`, what changes, with
76    ///   `c = x* − x_m` the half step from `x_m` to the linearization point.
77    ///
78    /// Any constant split of `Δz` would do; this one centers both parts. With
79    /// `s = (x_k − x*, 0)` instead, `s` would be off-center by the half step and
80    /// `δ` would range over the whole step's drift `[0, r] f`, which made the
81    /// sets of small starts larger than those of linearization in a trial on
82    /// Van der Pol. Centered, `δ` spans about `±½ r f`.
83    ///
84    /// Taylor's theorem with the Lagrange remainder gives, row by row and for
85    /// some `ξ(t)` on the segment from `z*` to `z(t)`,
86    ///
87    /// ```text
88    /// f(z) = f(z*) + J(z*) Δz + ½ Δzᵀ H(z*) Δz + ⅙ Σ_{abc} ∂³f(ξ)_{abc} Δz_a Δz_b Δz_c.
89    /// ```
90    ///
91    /// With `½ H(z*) ∈ Q ± R_Q`, `J(z*) ∈ [A B] ± R_J` and a point tensor
92    /// `P ≈ ⅙ ∂³f(z*)` (the midpoints, divided by 6 and rounded), write
93    /// `T_c` for an enclosure of `6 P` and
94    ///
95    /// ```text
96    /// ⅙ T(ξ) Δz³ = P s³ + ⅙ T_c (Δz³ − s³) + ⅙ (T(ξ) − T_c) Δz³,
97    /// ```
98    ///
99    /// exact for the real `6 P ∈ T_c`. The error of the linear model,
100    /// `e = f(z) − (A x + B u + w)`, then splits into
101    ///
102    /// ```text
103    /// e = ψ_s(x_k) + ψ_d(t),
104    /// ψ_s(x_k) = sᵀ Q s + P s³                                   (static)
105    /// ψ_d(t)  ∈ sᵀ [±R_Q] s + sᵀ (½H) δ + δᵀ (½H) s + δᵀ (½H) δ  (dynamic)
106    ///           + ⅙ T_c (Δz³ − s³) + ⅙ (T(ξ) − T_c) Δz³ + [±R_J] |Δz|.
107    /// ```
108    ///
109    /// The change of the cubic term is bounded through the telescoping
110    /// identity `Δz_a Δz_b Δz_c − s_a s_b s_c = δ_a Δz_b Δz_c + s_a δ_b Δz_c +
111    /// s_a s_b δ_c`, so it is `O(w² r)` instead of the `O(w³)` of the whole
112    /// cube over `□Δz`.
113    ///
114    /// The inputs are never part of `s`: `u(t)` may jump anywhere in `U` during
115    /// the step, so only the state at `t_k` is constant along a trajectory.
116    /// Every term with `u − u*` is dynamic.
117    ///
118    /// # Why the sets enclose every trajectory
119    ///
120    /// The static part is a polynomial of `x_k` alone. The step computes
121    /// `Ψ_s = { sᵀ Q s + P s³ | x_k ∈ X }` with the quadratic and the cubic
122    /// map of the polynomial zonotope `X − x_m`, joined by `exact_plus`, which
123    /// keeps the factors of `X`: the point of `Ψ_s` that belongs to
124    /// `x_k = X(α, β)` uses the same `α`. Degrees above the cap are
125    /// enclosed as independent generators, which only adds points.
126    ///
127    /// The static error acts on the trajectory as a constant input `v = ψ_s(x_k)`.
128    /// The step therefore runs the linear reach on the augmented system
129    /// `x' = A x + v + B u + w + ψ_d`, `v' = 0`, `x₀' = 0`, from
130    /// `{ (x_k, ψ_s(x_k), x_k) | x_k ∈ X }`, built by one linear map of `X`
131    /// and [`SparsePolyZonotope::exact_plus`](polyzonotope::SparsePolyZonotope::exact_plus),
132    /// which keep the shared factors and pair the independent generators of
133    /// both copies of `x_k`. The linear
134    /// reach is sound for any input signal in its input set, so with
135    /// `ψ_d(t) ∈ Ψ̄` for all `t` of the step, the projection of its sets onto
136    /// `x` holds the trajectory at `t_{k+1}` and during the step. The static
137    /// error never needs a guess: it is exact up to the degree cap, and it moves
138    /// with the set rather than being smeared over the whole step as a box.
139    ///
140    /// The dynamic part needs boxes of `s`, `δ` and `Δz`. The step
141    /// takes `s` from the interval hull of `X − x_m`, `Δz` from the hull of the
142    /// time-interval set `R(τ)` and `U`, the input part of `δ` from `U − u*`, and
143    /// the state part, minus `c`, from two enclosures of `x(t) − x_k`,
144    /// intersected: the flow,
145    /// `x(t) − x_k = ∫_{t_k}^t f(z(σ)) dσ ∈ [0, r] · f(□R(τ) × □U)`
146    /// (enclosed in interval arithmetic), and the hull of `x − x₀` over the
147    /// augmented time-interval set, where the factors of `x_k` cancel. Both
148    /// hold as long as the trajectory stays in `R(τ)` up to `t` with its
149    /// error in `Ψ̄`. That is the same hypothesis the
150    /// guess-and-check loop proves for every other term, so the usual argument
151    /// closes: if the dynamic error computed over `R(τ)` lies in the guess `Ψ̄`,
152    /// no trajectory can leave `R(τ)` during the step, because up to the first
153    /// exit its error lies in `Ψ̄` and the linear model with an input in `Ψ̄`
154    /// keeps it in `R(τ)`. The remainder evaluates `∂³f` over a box that holds
155    /// every segment from `z*` into `z* + □Δz`, which holds every `ξ(t)`.
156    ///
157    /// The decomposition is exact algebra, every box encloses its quantity, and
158    /// every product and sum of boxes is interval arithmetic, outward rounded
159    /// with the `sound` feature. Removing any one term makes the claim false;
160    /// the unit tests show that for each term that floating-point rounding does
161    /// not dominate.
162    Polynomialization,
163}
164
165/// How [`NonlinearReach::reach`] splits a piece whose step diverged.
166///
167/// Non-exhaustive: more strategies may be added.
168#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
169#[non_exhaustive]
170pub enum Splitting {
171    /// Factor splits and box splits compete, and the one whose larger half
172    /// has the smaller second-order error bound wins, split by split. The
173    /// default: on the cubic drift `x₀' = x₀³` from radius 0.5, linearization
174    /// with factor splits alone needs 4 pieces where this needs 2.
175    #[default]
176    Cheapest,
177    /// Factor splits only: every piece keeps all dependencies of the start
178    /// set, at the price of more pieces.
179    Factors,
180}
181
182/// What becomes of the generators that order reduction and the linear step
183/// make independent.
184///
185/// Non-exhaustive: more restructurings may be added.
186#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
187#[non_exhaustive]
188pub enum Restructure {
189    /// They stay independent generators. Their products in the next step's
190    /// quadratic error are enclosed one by one, so a wide set loses some of
191    /// its shape step by step. The default: the time-interval hull pairs
192    /// each independent generator with its image, which keeps most of that
193    /// shape, and [`Lift`](Self::Lift) costs more for little gain.
194    #[default]
195    Off,
196    /// After each step's Girard reduction, every independent generator of
197    /// the time-point set becomes a dependent factor of its own. That is
198    /// exact (`g β` with `β ∈ [-1, 1]` is the monomial `g α` of a factor
199    /// nowhere else), and from then on the quadratic maps of later steps
200    /// treat it as a polynomial: `α²` stays non-negative and products
201    /// cancel. Where nothing merges, it costs 1.5 to 1.7 times as much as
202    /// [`Off`](Self::Off) (40 steps of Van der Pol from radius 0.5). The number
203    /// of factors stays at most the number of generators, since
204    /// [`compact`](polyzonotope::SparsePolyZonotope::compact) drops the
205    /// unused ones.
206    ///
207    /// The gain is small: on Van der Pol from radius 0.5, polynomialization
208    /// ends 40 steps 3% narrower than with [`Off`](Self::Off), and from
209    /// radius 1 it proves 26 steps instead of 25. On the damped cubic
210    /// `x₀' = −x₀ − x₀³` from radius 1, both need 6 pieces, and the lifted
211    /// sets end 31% wider; but lifted pieces merge back to 3, where
212    /// unlifted ones stay apart, so that run takes 4.6 s instead of 6.8 s.
213    Lift,
214}
215
216/// How [`NonlinearReach`] steps through time.
217#[derive(Clone, Debug, PartialEq)]
218pub struct NonlinearSettings {
219    /// Time step `r`, positive.
220    pub step: f64,
221    /// Terms of the matrix exponential after the first, see [`LinearReach::new`].
222    pub taylor_terms: usize,
223    /// Order (generators per dimension, at least 1) the sets are reduced to
224    /// after every step and before the error is computed.
225    pub order: f64,
226    /// Most guesses of the error per step, at least 1: the first guess plus
227    /// up to `max_iterations − 1` enlargements before the step is given up.
228    pub max_iterations: usize,
229    /// Relative widening of the error guess on each retry: every bound moves
230    /// outward by this fraction of the interval's magnitude.
231    pub enlarge: f64,
232    /// Most pieces a set may be split into per time step before a failing
233    /// step is refused; 1 never splits.
234    pub max_pieces: usize,
235    /// Which splits [`reach`](NonlinearReach::reach) may use.
236    pub splitting: Splitting,
237    /// The abstraction of each step.
238    pub method: Method,
239    /// How much larger than the two pieces' interval hulls together the
240    /// hull of their merged enclosure may be, by volume, as a fraction (0.1
241    /// allows 10%), for [`reach`](NonlinearReach::reach) to merge them into
242    /// one piece for the next step. Non-negative. A merge is also never
243    /// wider than half the narrowest piece that diverged so far, so splits
244    /// are not undone while the pieces are still too large to step whole.
245    pub merge_tolerance: f64,
246    /// Highest total degree the static error of
247    /// [`Method::Polynomialization`] keeps exact, at least 1. It is cubic
248    /// in the set, so without a cap the degree of the sets would triple
249    /// with every step; higher monomials are enclosed in independent
250    /// generators.
251    pub max_degree: u32,
252    /// Whether the time-point set's independent generators become
253    /// dependent factors before the next step.
254    pub restructure: Restructure,
255    /// Adaptive step lengths for [`reach`](NonlinearReach::reach) and
256    /// [`reach_for`](NonlinearReach::reach_for), starting from `step`; `None`
257    /// keeps every step at `step`.
258    pub adaptive: Option<Adaptive>,
259}
260
261impl NonlinearSettings {
262    /// Defaults for time step `step`: 4 Taylor terms, order 20, 10
263    /// iterations, 10% widening, up to 8 pieces from the cheapest splits,
264    /// merged within 10%, independent generators kept, fixed steps,
265    /// linearization, and degree 4 for polynomialization.
266    #[must_use]
267    pub fn new(step: f64) -> Self {
268        Self {
269            step,
270            taylor_terms: 4,
271            order: 20.0,
272            max_iterations: 10,
273            enlarge: 0.1,
274            max_pieces: 8,
275            splitting: Splitting::Cheapest,
276            method: Method::Linearization,
277            merge_tolerance: 0.1,
278            max_degree: 4,
279            restructure: Restructure::Off,
280            adaptive: None,
281        }
282    }
283}
284
285/// One-step and multi-step reachability of [`Dynamics`].
286///
287/// # Examples
288///
289/// ```
290/// use nalgebra::{DMatrix, DVector};
291/// use polyzonotope_reach::polyzonotope::{SparsePolyZonotope, Zonotope};
292/// use polyzonotope_reach::{NonlinearReach, NonlinearSettings, Polynomial};
293///
294/// // Van der Pol with μ = 1, no inputs.
295/// let vdp = Polynomial::autonomous(2)
296///     .term(0, 1.0, &[0, 1])
297///     .term(1, 1.0, &[0, 1])
298///     .term(1, -1.0, &[2, 1])
299///     .term(1, -1.0, &[1, 0]);
300/// let reach = NonlinearReach::new(vdp, NonlinearSettings::new(0.02));
301/// let start = SparsePolyZonotope::from_zonotope(&Zonotope::new(
302///     DVector::from_vec(vec![1.4, 2.4]),
303///     DMatrix::from_diagonal_element(2, 2, 0.05),
304/// ));
305///
306/// let flowpipe = reach.reach_autonomous(&start, 10)?;
307/// let hull = flowpipe[9][0].time_point.interval_hull();
308/// assert!(hull.0[0].lo > 1.4 && hull.0[1].hi < 2.4);
309/// # Ok::<(), polyzonotope_reach::ReachFailure>(())
310/// ```
311pub struct NonlinearReach<D> {
312    /// The vector field.
313    dynamics: D,
314    /// Step size and limits, checked by [`new`](Self::new).
315    settings: NonlinearSettings,
316}
317
318/// The linear model `x' = A x + B u + w` of one step, with
319/// `w ∈ f(z*) − A x* − B u*`.
320pub(crate) struct Linearization {
321    /// The point `z* = (x*, u*)`.
322    point: Vec<f64>,
323    /// `x_m`, the middle of the interval hull of the start set, from which
324    /// `x*` is half a step along `f`; `n` entries.
325    middle: Vec<f64>,
326    /// `A`, the center of `∂f/∂x` at `z*`.
327    a: DMatrix<f64>,
328    /// `B`, the center of `∂f/∂u` at `z*`.
329    b: DMatrix<f64>,
330    /// An enclosure of `f(z*) − A x* − B u*`.
331    offset: Vec<Interval>,
332    /// The radius of `∂f/∂z` at `z*` around `[A B]`: zero unless rounding
333    /// made the point evaluation an interval.
334    jacobian_radius: DMatrix<f64>,
335}
336
337impl<D: Dynamics> NonlinearReach<D> {
338    /// Reachability of `dynamics` with `settings`.
339    ///
340    /// # Panics
341    ///
342    /// Panics if the step is not positive and finite, the order is below 1,
343    /// `enlarge` or `merge_tolerance` is negative, `max_iterations`,
344    /// `max_pieces` or `max_degree` is zero, or, with [`Adaptive`] steps, `min_step` is not
345    /// positive, `max_step` not finite, `step` not in
346    /// `[min_step, max_step]`, `shrink` not in `(0, 1)` or `grow` below 1.
347    #[must_use]
348    pub fn new(dynamics: D, settings: NonlinearSettings) -> Self {
349        assert!(
350            settings.step > 0.0 && settings.step.is_finite(),
351            "step must be positive"
352        );
353        assert!(settings.order >= 1.0, "order must be at least 1");
354        assert!(settings.enlarge >= 0.0, "enlarge must not be negative");
355        assert!(
356            settings.merge_tolerance >= 0.0,
357            "merge_tolerance must not be negative"
358        );
359        assert!(
360            settings.max_iterations >= 1,
361            "max_iterations must be at least 1"
362        );
363        assert!(settings.max_pieces >= 1, "max_pieces must be at least 1");
364        assert!(settings.max_degree >= 1, "max_degree must be at least 1");
365        if let Some(adaptive) = &settings.adaptive {
366            adaptive.check(settings.step);
367        }
368
369        Self { dynamics, settings }
370    }
371
372    /// The reachable sets one step after `x`, for any integrable input
373    /// signal with values in `u`; for an autonomous system, `u` is the
374    /// zero-dimensional zonotope (or use
375    /// [`step_autonomous`](Self::step_autonomous)).
376    ///
377    /// Both sets are reduced to the configured order, so the time-point set
378    /// can go straight into the next step.
379    ///
380    /// # Errors
381    ///
382    /// - [`ReachError::StepTooLarge`] if the matrix exponential's remainder
383    ///   bound fails for the linearized `A`.
384    /// - [`ReachError::AbstractionDiverged`] if no error guess was confirmed
385    ///   within `max_iterations`, or the model or the error stopped being
386    ///   finite: the set or the step is too large for the abstraction. No
387    ///   set is returned then, since none is proven.
388    /// - [`ReachError::MissingDerivatives`] with
389    ///   [`Method::Polynomialization`] if the dynamics supply no third
390    ///   derivatives.
391    ///
392    /// # Panics
393    ///
394    /// Panics if `x` does not have one row per state or `u` one per input.
395    pub fn step(&self, x: &SparsePolyZonotope, u: &Zonotope) -> Result<Step, ReachError> {
396        let attempt = Attempt {
397            step: self.settings.step,
398            terms: Terms::ALL,
399        };
400        self.step_with(x, u, attempt).map(|(step, _)| step)
401    }
402
403    /// [`step`](Self::step) with the step length and error terms of
404    /// `attempt`, and how many error guesses it took; the tests drop one term
405    /// at a time to show that each is needed.
406    fn step_with(
407        &self,
408        x: &SparsePolyZonotope,
409        u: &Zonotope,
410        attempt: Attempt,
411    ) -> Result<(Step, usize), ReachError> {
412        assert_eq!(x.dim(), self.dynamics.states(), "x needs one row per state");
413        assert_eq!(u.dim(), self.dynamics.inputs(), "u needs one row per input");
414
415        let model = self
416            .linearize(x, u, attempt.step)
417            .ok_or(ReachError::AbstractionDiverged)?;
418        match self.settings.method {
419            Method::Linearization => self.step_linearized(x, u, &model, attempt),
420            Method::Polynomialization => self.step_polynomialized(x, u, &model, attempt),
421        }
422    }
423
424    /// One step of [`Method::Linearization`]: the linear model with the
425    /// whole error as a guessed box.
426    fn step_linearized(
427        &self,
428        x: &SparsePolyZonotope,
429        u: &Zonotope,
430        model: &Linearization,
431        attempt: Attempt,
432    ) -> Result<(Step, usize), ReachError> {
433        let n = self.dynamics.states();
434        let system = LinearSystem {
435            a: model.a.clone(),
436            b: DMatrix::identity(n, n),
437        };
438        let linear = LinearReach::new(system, attempt.step, self.settings.taylor_terms)?;
439        let known = u.linear_map(&model.b);
440
441        self.confirm(n, attempt.step, |assumed| {
442            let step = linear.step(x, &with_error(&known, &model.offset, assumed));
443            let states = step
444                .time_interval
445                .reduce(self.settings.order, Reduction::Girard);
446            let actual =
447                error::abstraction_error(&self.dynamics, model, (&states, u), attempt.terms)
448                    .ok_or(ReachError::AbstractionDiverged)?;
449
450            Ok((step.time_point, states, actual))
451        })
452    }
453
454    /// One step of [`Method::Polynomialization`]: the static error `Ψ_s`
455    /// rides along as the constant input of an augmented linear system, and
456    /// only the dynamic error is a guessed box. The soundness argument is on
457    /// [`Method::Polynomialization`].
458    fn step_polynomialized(
459        &self,
460        x: &SparsePolyZonotope,
461        u: &Zonotope,
462        model: &Linearization,
463        attempt: Attempt,
464    ) -> Result<(Step, usize), ReachError> {
465        let n = self.dynamics.states();
466        let limits = (self.settings.max_degree, self.settings.order);
467        let expansion =
468            polynomialization::static_error(&self.dynamics, model, x, limits, attempt.terms)?;
469        let start = if attempt.terms.has(Term::StaticSet) {
470            polynomialization::augmented_start(x, &expansion.static_set)
471        } else {
472            polynomialization::augmented_start(
473                x,
474                &SparsePolyZonotope::from_zonotope(&Zonotope::new(
475                    DVector::zeros(n),
476                    DMatrix::zeros(n, 0),
477                )),
478            )
479        };
480        let system = polynomialization::augmented_system(&model.a);
481        let linear = LinearReach::new(system, attempt.step, self.settings.taylor_terms)?;
482        let known = u.linear_map(&model.b);
483
484        self.confirm(n, attempt.step, |assumed| {
485            let step = linear.step(&start, &with_error(&known, &model.offset, assumed));
486            let states = polynomialization::project(&step.time_interval, n)
487                .reduce(self.settings.order, Reduction::Girard);
488            let drift = polynomialization::drift(&step.time_interval, n);
489            let actual = polynomialization::dynamic_error(
490                &self.dynamics,
491                (model, &expansion),
492                (&states, &drift, u),
493                attempt.step,
494                attempt.terms,
495            )?;
496
497            Ok((
498                polynomialization::project(&step.time_point, n),
499                states,
500                actual,
501            ))
502        })
503    }
504
505    /// `set` reduced to the configured order, as the start of the next step,
506    /// with its independent generators lifted to factors under
507    /// [`Restructure::Lift`].
508    fn restructure(&self, set: &SparsePolyZonotope) -> SparsePolyZonotope {
509        let reduced = set.reduce(self.settings.order, Reduction::Girard);
510        match self.settings.restructure {
511            Restructure::Off => reduced,
512            Restructure::Lift => split::lift_independent(&reduced),
513        }
514    }
515
516    /// The guess-and-check loop: `attempt` runs the step with the error
517    /// guess `Ψ̄` and returns the time-point set, the reduced time-interval
518    /// set and the error over it. The first attempt whose error lies in its
519    /// guess is accepted, with the number of guesses it took; otherwise the
520    /// guess widens, up to `max_iterations` times. `step` is the length of
521    /// the step, recorded in the result.
522    ///
523    /// # Errors
524    ///
525    /// The first error of `attempt`, or [`ReachError::AbstractionDiverged`]
526    /// if no guess was confirmed or the guess stopped being finite.
527    fn confirm(
528        &self,
529        n: usize,
530        step: f64,
531        mut attempt: impl FnMut(
532            &[Interval],
533        ) -> Result<
534            (SparsePolyZonotope, SparsePolyZonotope, Vec<Interval>),
535            ReachError,
536        >,
537    ) -> Result<(Step, usize), ReachError> {
538        let mut assumed = vec![Interval::point(0.0); n];
539        for guesses in 1..=self.settings.max_iterations {
540            let (time_point, time_interval, actual) = attempt(&assumed)?;
541            if encloses(&assumed, &actual) {
542                let step = Step {
543                    time_point: self.restructure(&time_point),
544                    time_interval,
545                    duration: step,
546                };
547                return Ok((step, guesses));
548            }
549
550            assumed = widen(&assumed, &actual, self.settings.enlarge);
551            if !all_finite(assumed.iter()) {
552                break;
553            }
554        }
555
556        Err(ReachError::AbstractionDiverged)
557    }
558
559    /// The linear model around `z* = (x* , c_u)`, where `x*` is the middle
560    /// of `x`'s interval hull moved half a step along `f` (as CORA does);
561    /// `None` if a value along the way is not finite.
562    fn linearize(&self, x: &SparsePolyZonotope, u: &Zonotope, step: f64) -> Option<Linearization> {
563        let n = self.dynamics.states();
564        let middle: Vec<f64> = x
565            .interval_hull()
566            .0
567            .iter()
568            .map(|iv| f64::midpoint(iv.lo, iv.hi))
569            .collect();
570        let inputs = u.center().iter().copied();
571        let drift = self
572            .dynamics
573            .flow(&points(middle.iter().copied().chain(inputs.clone())));
574        let point: Vec<f64> = middle
575            .iter()
576            .zip(&drift)
577            .map(|(&m, d)| m + 0.5 * step * f64::midpoint(d.lo, d.hi))
578            .chain(inputs)
579            .collect();
580        if !point.iter().all(|v| v.is_finite()) {
581            return None;
582        }
583
584        let at = points(point.iter().copied());
585        let jacobian = self.dynamics.jacobian(&at);
586        let flow = self.dynamics.flow(&at);
587        if !all_finite(jacobian.0.iter()) || !all_finite(flow.iter()) {
588            return None;
589        }
590
591        let (jacobian, jacobian_radius) = jacobian.center_radius();
592        let offset = model_offset(&flow, &jacobian, &point)?;
593        if !all_finite(offset.iter()) {
594            return None;
595        }
596
597        Some(Linearization {
598            a: jacobian.columns(0, n).into_owned(),
599            b: jacobian.columns(n, point.len() - n).into_owned(),
600            point,
601            middle,
602            offset,
603            jacobian_radius,
604        })
605    }
606}
607
608/// The step length and error terms of one step attempt.
609#[derive(Clone, Copy, Debug, PartialEq)]
610pub(crate) struct Attempt {
611    /// The step length `r`, positive and finite.
612    pub(crate) step: f64,
613    /// The error terms to include: all of them outside the tests.
614    pub(crate) terms: Terms,
615}
616
617/// One term of the abstraction error, so that the tests can drop it.
618#[derive(Clone, Copy, Debug, PartialEq, Eq)]
619pub(crate) enum Term {
620    /// Linearization: `Δzᵀ Q Δz` over the time-interval set.
621    Quadratic,
622    /// Linearization: the spread of `½ H` over the segment box.
623    HessianSpread,
624    /// Both: the spread of the Jacobian at `z*`, from rounding only.
625    JacobianSpread,
626    /// Polynomialization: the static polynomial `Ψ_s = sᵀ Q s + P s³`.
627    StaticSet,
628    /// Polynomialization: the spread of `½ H(z*)` around `Q` over `s`, from
629    /// rounding only.
630    StaticRadius,
631    /// Polynomialization: `sᵀ (½H) δ + δᵀ (½H) s`.
632    Cross,
633    /// Polynomialization: `δᵀ (½H) δ`.
634    DynamicQuadratic,
635    /// Polynomialization: the cubic form `P s³` in the static set.
636    CubicStatic,
637    /// Polynomialization: `⅙ T_c (Δz³ − s³)`, the change of the cubic term
638    /// at `z*` during the step.
639    CubicCross,
640    /// Polynomialization: the third-order Lagrange remainder around `T_c`,
641    /// `⅙ (T(ξ) − T_c) Δz³`.
642    Remainder,
643    /// Polynomialization: the input part `u − u*` of `δ`.
644    InputDeviation,
645}
646
647/// A set of [`Term`]s, as a bit mask.
648#[derive(Clone, Copy, Debug, PartialEq, Eq)]
649pub(crate) struct Terms(u16);
650
651impl Terms {
652    /// Every term: what the public API always uses.
653    pub(crate) const ALL: Self = Self(u16::MAX);
654
655    /// Whether `term` is in the set.
656    pub(crate) fn has(self, term: Term) -> bool {
657        self.0 & Self::bit(term) != 0
658    }
659
660    /// The set without `term`.
661    #[cfg(test)]
662    pub(crate) fn without(self, term: Term) -> Self {
663        Self(self.0 & !Self::bit(term))
664    }
665
666    /// The bit of `term`.
667    fn bit(term: Term) -> u16 {
668        1 << term as u16
669    }
670}
671
672/// Whether every bound in `intervals` is finite (and so not NaN either).
673fn all_finite<'a>(mut intervals: impl Iterator<Item = &'a Interval>) -> bool {
674    intervals.all(|iv| iv.lo.is_finite() && iv.hi.is_finite())
675}
676
677/// Point intervals for `values`.
678fn points(values: impl Iterator<Item = f64>) -> Vec<Interval> {
679    values.map(Interval::point).collect()
680}
681
682/// `f(z*) − J z*` row by row in interval arithmetic, `J = [A B]`, or `None`
683/// once a product or partial sum overflows: under `sound`, subtracting an
684/// infinite bound panics instead of giving an infinite result.
685fn model_offset(
686    flow: &[Interval],
687    jacobian: &DMatrix<f64>,
688    point: &[f64],
689) -> Option<Vec<Interval>> {
690    flow.iter()
691        .enumerate()
692        .map(|(i, &f)| {
693            point.iter().enumerate().try_fold(f, |acc, (j, &z)| {
694                let term = Interval::point(jacobian[(i, j)]) * Interval::point(z);
695                all_finite([acc, term].iter()).then(|| acc - term)
696            })
697        })
698        .collect()
699}
700
701/// The input of the linear model: `B U ⊕ (w + Ψ̄)` with the box around its
702/// midpoint, so its center is the constant part.
703fn with_error(known: &Zonotope, offset: &[Interval], assumed: &[Interval]) -> Zonotope {
704    let total = offset.iter().zip(assumed).map(|(&w, &e)| w + e).collect();
705    known.minkowski_sum(&Zonotope::from_box(&IntervalBox(total)))
706}
707
708/// Whether every interval of `actual` lies in the matching one of `assumed`.
709fn encloses(assumed: &[Interval], actual: &[Interval]) -> bool {
710    assumed
711        .iter()
712        .zip(actual)
713        .all(|(a, e)| a.lo <= e.lo && e.hi <= a.hi)
714}
715
716/// The hull of `assumed` and `actual`, every bound moved outward by
717/// `enlarge` times the interval's magnitude.
718fn widen(assumed: &[Interval], actual: &[Interval], enlarge: f64) -> Vec<Interval> {
719    assumed
720        .iter()
721        .zip(actual)
722        .map(|(a, e)| {
723            let hull = Interval::new(a.lo.min(e.lo), a.hi.max(e.hi));
724            let margin = enlarge * hull.mag();
725            Interval::new(hull.lo - margin, hull.hi + margin)
726        })
727        .collect()
728}
729
730#[cfg(test)]
731mod tests {
732    use super::*;
733
734    /// An overflowing `J z*` gives no offset instead of panicking under `sound`.
735    #[test]
736    fn overflowing_offset_is_refused() {
737        let jacobian = DMatrix::from_row_slice(1, 2, &[1e300, 1.0]);
738        let flow = [Interval::point(1.0)];
739        assert_eq!(model_offset(&flow, &jacobian, &[1e10, 1.0]), None);
740        assert_eq!(
741            model_offset(&flow, &jacobian, &[1.0, 1.0]),
742            Some(vec![
743                Interval::point(1.0) - Interval::point(1e300) - Interval::point(1.0)
744            ])
745        );
746    }
747
748    /// Widening covers both boxes and moves out by the relative margin.
749    #[test]
750    fn widening_covers_both() {
751        let w = widen(&[Interval::new(-1.0, 1.0)], &[Interval::new(0.0, 2.0)], 0.5);
752        assert_eq!(w, vec![Interval::new(-2.0, 3.0)]);
753        assert!(encloses(&w, &[Interval::new(-1.0, 2.0)]));
754        assert!(!encloses(&w, &[Interval::new(-1.0, 3.5)]));
755    }
756}