Skip to main content

clock_dbm/ops/
extra_m.rs

1//! Maximal-constant extrapolation (ExtraM).
2//!
3//! [`MaxBounds`] supplies a ceiling for each clock;
4//! [`Dbm::try_extrapolate_max`](crate::Dbm::try_extrapolate_max) uses these
5//! ceilings to overapproximate a zone. This retains all original valuations,
6//! but may introduce others. Reachability preservation requires additional
7//! assumptions on the timed automaton, including appropriate ceilings and
8//! restrictions on guards, invariants, and resets.
9
10// Source-level implementation and proof notes (not part of public API Rustdoc).
11// ExtraM: maximal-constant extrapolation.
12//
13// Notation: `D[i][j]` bounds the difference between clocks `i` and `j`,
14// with clock zero fixed at zero. `γ(D)` is the set of nonnegative-real
15// valuations represented by `D`, and `∅_d` is the empty zone of matrix
16// dimension `d`. `Le c` means `<= c`, `Lt c` means `< c`, and `∞` means
17// no restriction. The strict order `a ≺ b` means `a` is tighter than `b`;
18// `a ≼ b` also allows equal bounds. The dimension includes the reference
19// clock.
20//
21// For a canonical DBM `D` and ceilings `M(x₁) … M(xₙ)`,
22//
23// ```text
24// ExtraM(D, M) = close(norm(D, k, n)),   k(0) = 0,  k(i) = M(xᵢ)
25// ```
26//
27// where `norm` is the entrywise normalization defined below:
28//
29// ```text
30// norm_upper e t = (if Le t ≺ e then ∞ else e)
31// norm_lower e t = (if e ≺ Lt t then Lt t else e)
32// norm_diag  e   = (if e ≺ Le 0 then Lt 0 else if e = Le 0 then e else ∞)
33// norm D k n i j = let ub = (if i > 0 then k i else 0); lb = (if j > 0 then −k j else 0) in
34//                  if i ≠ j then norm_lower (norm_upper (D i j) ub) lb else norm_diag (D i j)
35// ```
36//
37// An upper bound looser than `Le k(i)` becomes `∞`; then a lower bound
38// tighter than `Lt (−k(j))` becomes `Lt (−k(j))`. Since `k(0) = 0`, the
39// reference row and column use the thresholds `Le 0` and `Lt 0`.
40// On a nonempty public input the diagonal is `Le 0`, which
41// `norm_diag` keeps.
42//
43// # Algorithm
44//
45// 1. Check the dimension of `bounds` (also for empty inputs). An empty
46//    input is returned as `∅_d`.
47// 2. Move the storage into the working matrix and apply `norm` entrywise,
48//    in place. The thresholds `Le k(i)` and `Lt (−k(i))` are representable
49//    because `0 ≤ k(i) ≤ MAX_CONSTANT` and `MIN_CONSTANT = −MAX_CONSTANT`;
50//    `norm` only compares and copies bounds, so it does no range-checked
51//    arithmetic.
52// 3. Recanonicalize:
53//    - **Some entry changed:** a *full* closure, `Matrix::close_pivots`
54//      with every clock selected as a pivot, i.e.
55//      Floyd–Warshall over all pivots with the proved, vectorized
56//      `Matrix::relax_row`. It returns `∅_d`, the canonical form, or
57//      `Err(Range)` when a sum that would tighten an entry is
58//      unrepresentable. With every pivot selected, its precondition
59//      `pivot_ready` asks only for a `Le 0` diagonal and a reference row
60//      `≼ Le 0`. `norm` keeps both on a canonical nonempty input:
61//      `norm_diag` keeps `Le 0`, the reference row's upper threshold `Le 0`
62//      never fires, and its lower rule yields `Lt (−k(j)) ≼ Le 0` because
63//      `k(j) ≥ 0` (by the normalization bounds). It computes the same
64//      closure as the scalar `Matrix::close` (`canonical_unique`), about
65//      2.7× faster at 64 clocks.
66//    - **No entry changed:** the working matrix *is* the canonical,
67//      nonempty input, which is its own closure (`canonical_unique`), so it
68//      is published as is with `Matrix::publish_canonical` (debug builds
69//      re-check canonicity). This shortcut keeps the common case
70//      "no ceiling exceeded" at
71//      `O(d²)` instead of `O(d³)`.
72//
73// `norm` **weakens** entries, so the canonical input's triangle
74// inequalities no longer hold in general: an entry set to `∞` can be
75// re-derived by closure through others. The incremental closure of
76// `ops::constraints`, which repairs a matrix after *tightening*, does not
77// apply, and neither does restricting the pivots to the clocks of changed
78// entries (the argument for intersection, `ops::relations`, needs
79// unchanged entries to be at least as tight as the canonical input's).
80// So every clock is a pivot. `Err(Range)` is genuine: for example,
81// with `k(1) = 5`, `D[1][2] = Le 3`, `D[2][0] = Le (MAX_CONSTANT − 1)` and
82// `D[1][0] = Le 100`, `norm` drops `D[1][0]` to `∞` and the closure
83// re-derives `Le (MAX_CONSTANT + 2)`, which is unrepresentable. Range
84// failure is never reported as emptiness, and no bound is saturated.
85//
86// The `Workspace` holds the pivot flags (all set by
87// `Workspace::select_all`), so repeated calls do not allocate once it has
88// grown to the dimension.
89//
90// # Errors
91//
92// `MaxBounds::new` rejects a vector longer than `MAX_VARIABLES`
93// (`TooManyVariables`), then the first ceiling outside `[0, MAX_CONSTANT]`
94// (`InvalidMaxBounds`). `try_extrapolate_max` returns `DimensionMismatch`
95// when `bounds.variables() ≠ self.variables()`, also for an empty input;
96// then `Ok(∅_d)` for an empty input; then `Err(Range)` if closure (step 3)
97// leaves the representable range. On `Err` the consumed input is dropped
98// (the input is consumed).
99//
100// # Supported abstraction
101//
102// This module implements maximal-constant extrapolation (ExtraM).
103// LU-bound extrapolation and other advanced abstractions are not yet part
104// of the public API and are reserved for future work.
105//
106// # What is (not) claimed
107//
108// ExtraM is extensive (`γ(D) ⊆ γ(ExtraM(D, M))`) and its result is
109// canonical or empty. Idempotence is **not** claimed.
110// ExtraM does not by itself preserve reachability: that needs the
111// automaton-level assumptions (diagonal-free guards
112// and invariants, ceilings covering every compared constant, constant
113// resets). With diagonal constraints it is unsound for reachability.
114//
115// # Verification status
116//
117// Creusot v0.14.0 machine-checks every item of this module on the shipped
118// code, with termination, no panic and no arithmetic overflow. The
119// contracts are stated over nonnegative real valuations (`Dbm::zone`):
120//
121// - `norm_upper`, `norm_lower`, `norm_diag`, `thresholds` and `normalize`
122//   compute the specified `norm` exactly (`proof::norm_entry`, an entrywise
123//   definition over `BoundModel`): `W[i][j] = norm(D, k)[i][j]` for every
124//   entry, upper rule before lower rule, `k(0) = 0`, exact strictness and
125//   `∞`. `normalize` returns `true` iff some entry changed (as a packed
126//   code), so `false` means the matrix is bit-identical to the input;
127// - `MaxBounds`: the type invariant `0 ≤ M(x) ≤ MAX_CONSTANT`, the exact
128//   errors of `new` in their order, `variables`, `get` and `k`;
129// - `try_extrapolate_max`: the errors in their order (`DimensionMismatch`
130//   before emptiness, `Range` only with the provenance
131//   `proof::mrange_failure` of the exact closure of `norm(D, M)`, never as
132//   emptiness), and on success `γ(result) = γ(norm(D, M))` (`∅_d` for an
133//   empty input), `γ(D) ⊆ γ(result)`, and uniqueness: every valid `Dbm` of
134//   that dimension and zone equals the result, so it **is**
135//   `close(norm(D, M))`. Both paths are proved as shipped: the unchanged
136//   path publishes the canonical input without closure; the changed path
137//   runs the all-pivot `Matrix::close_pivots` (`pivot_ready` from
138//   `proof::norm_ready` and `Matrix::full_pivot_ready`, not the
139//   touched-pivot argument of intersection).
140//
141// The lemmas are in `extra_m/proof.rs` (`norm_weakens`, `norm_extensive`,
142// `norm_ready`, `norm_range`). Idempotence, the linear range premise
143// and reachability preservation are **not** proved.
144// See `verification/PROOF_STATUS.md`. The exact-oracle tests in
145// `extra_m/tests.rs` remain as regression tests.
146
147// `?` is not a terminating call for Creusot; keep the style of `dbm.rs`.
148#![allow(clippy::question_mark)]
149
150use crate::bounds::{Bound, MAX_CONSTANT, Variable};
151#[cfg(creusot)]
152use crate::bounds::{BoundModel, order_refines, view_injective};
153#[cfg(creusot)]
154use crate::dbm::proof::{meq, meq_transfer, mrange_failure, mrange_failure_meq};
155use crate::dbm::{Dbm, MAX_VARIABLES, Matrix, Workspace, same, tighter};
156use crate::error::Error;
157#[cfg(creusot)]
158use creusot_std::logic::Mapping;
159use creusot_std::{
160    invariant::Invariant,
161    prelude::{Clone, PartialEq, *},
162};
163
164/// Per-clock maximal constants for [`Dbm::try_extrapolate_max`] (ExtraM).
165///
166/// The slice passed to [`MaxBounds::new`] contains ceilings for actual
167/// clocks 1 through `n` in order. The reference clock's ceiling is
168/// implicitly zero. Values must lie in `[0, MAX_CONSTANT]`.
169///
170/// ExtraM overapproximates a zone. Applying it does **not** alone guarantee
171/// timed-automata reachability preservation: that requires restrictions on
172/// guards, invariants, and clock resets.
173///
174/// # Example
175///
176/// ```
177/// use clock_dbm::{MaxBounds, Variable};
178/// # fn main() -> Result<(), clock_dbm::Error> {
179/// let ceilings = MaxBounds::new(vec![5, 8])?;
180/// assert_eq!(ceilings.variables(), 2);
181/// assert_eq!(ceilings.get(Variable::new(2).unwrap()), Some(8));
182/// # Ok(())
183/// # }
184/// ```
185#[derive(PartialEq, Eq, Debug)]
186// `Hash` is not translated by Creusot (std's `Hasher` has no specs); it is
187// derived from the same field as `Eq`, so it is consistent with it.
188#[cfg_attr(not(creusot), derive(Hash))]
189pub struct MaxBounds {
190    ceilings: Box<[i32]>,
191}
192
193/// A valid ceiling: `0 ≤ c ≤ MAX_CONSTANT`.
194#[logic(open)]
195pub(crate) fn valid_ceiling(c: i32) -> bool {
196    pearlite! { 0 <= c@ && c@ <= MAX_CONSTANT@ }
197}
198
199impl Invariant for MaxBounds {
200    #[logic(open(self))]
201    fn invariant(self) -> bool {
202        pearlite! {
203            self.ceilings@.len() <= MAX_VARIABLES@
204                && forall<p: Int> 0 <= p && p < self.ceilings@.len() ==>
205                    valid_ceiling(self.ceilings@[p])
206        }
207    }
208}
209
210// Written out like `Dbm`'s: `Box<[i32]>::clone` has no creusot-std
211// specification. Not `check(terminates)`, also like `Dbm`'s: `to_vec` is
212// not a terminating call for Creusot.
213impl Clone for MaxBounds {
214    #[ensures(result.ceilings_logic() == self.ceilings_logic())]
215    fn clone(&self) -> MaxBounds {
216        let ceilings = self.ceilings.to_vec().into_boxed_slice();
217        proof_assert!(ceilings@.ext_eq(self.ceilings@));
218        MaxBounds { ceilings }
219    }
220}
221
222impl DeepModel for MaxBounds {
223    type DeepModelTy = Seq<Int>;
224
225    #[logic(open(self))]
226    fn deep_model(self) -> Seq<Int> {
227        pearlite! { *self.ceilings.deep_model() }
228    }
229}
230
231impl MaxBounds {
232    /// Logical ceilings, `M(x_{p+1})` at index `p`.
233    #[logic(open(self))]
234    pub(crate) fn ceilings_logic(self) -> Seq<i32> {
235        pearlite! { self.ceilings@ }
236    }
237
238    /// Logical number of actual clocks.
239    #[logic(open(self))]
240    pub(crate) fn variables_logic(self) -> Int {
241        pearlite! { self.ceilings@.len() }
242    }
243
244    /// `k`: `k(i) = M(xᵢ)` for `1 ≤ i ≤ n`, and `0` elsewhere, in particular
245    /// `k(0) = 0` for the reference clock.
246    #[logic(open(self))]
247    pub(crate) fn kmap(self) -> Mapping<Int, Int> {
248        pearlite! {
249            |i: Int| if 1 <= i && i <= self.ceilings@.len() { self.ceilings@[i - 1]@ } else { 0 }
250        }
251    }
252
253    /// The ceilings are valid and `k` is nonnegative.
254    #[logic]
255    #[requires(inv(self))]
256    #[ensures(self.variables_logic() <= MAX_VARIABLES@)]
257    #[ensures(forall<i: Int> 0 <= self.kmap()[i] && self.kmap()[i] <= MAX_CONSTANT@)]
258    #[ensures(self.kmap()[0] == 0)]
259    pub(crate) fn model(self) {}
260
261    /// Creates maximal constants for actual clocks 1, 2, ..., in the
262    /// order supplied: `ceilings[0]` is the ceiling for clock 1.
263    ///
264    /// # Errors
265    ///
266    /// In this order:
267    ///
268    /// - [`Error::TooManyVariables`] if `ceilings.len() > MAX_VARIABLES`;
269    /// - [`Error::InvalidMaxBounds`] for the first ceiling that is negative
270    /// or greater than [`MAX_CONSTANT`], with its 1-based clock index.
271    ///
272    /// Proved: exactly these errors in this order; on success the
273    /// ceilings are stored as given.
274    ///
275    /// # Complexity
276    ///
277    /// `O(n)` time for `n = ceilings.len()`.
278    #[check(terminates)]
279    #[ensures(match result {
280        Ok(b) => ceilings@.len() <= MAX_VARIABLES@ && b.ceilings_logic() == ceilings@,
281        Err(e) => if ceilings@.len() > MAX_VARIABLES@ {
282            match e {
283                Error::TooManyVariables { requested } => requested@ == ceilings@.len(),
284                _ => false,
285            }
286        } else {
287            exists<p: Int> 0 <= p && p < ceilings@.len() && !valid_ceiling(ceilings@[p])
288                && (forall<q: Int> 0 <= q && q < p ==> valid_ceiling(ceilings@[q]))
289                && match e {
290                    Error::InvalidMaxBounds { variable, value } =>
291                        variable@ == p + 1 && value == ceilings@[p],
292                    _ => false,
293                }
294        },
295    })]
296    #[allow(
297        clippy::manual_range_contains,
298        reason = "`RangeInclusive::contains` is not a terminating call for Creusot"
299    )]
300    pub fn new(ceilings: Vec<i32>) -> Result<MaxBounds, Error> {
301        if ceilings.len() > MAX_VARIABLES {
302            return Err(Error::TooManyVariables {
303                requested: ceilings.len(),
304            });
305        }
306        let mut p: usize = 0;
307        #[invariant(p@ <= ceilings@.len())]
308        #[invariant(forall<q: Int> 0 <= q && q < p@ ==> valid_ceiling(ceilings@[q]))]
309        #[variant(ceilings@.len() - p@)]
310        while p < ceilings.len() {
311            let value = ceilings[p];
312            if value < 0 || value > MAX_CONSTANT {
313                return Err(Error::InvalidMaxBounds {
314                    variable: p + 1,
315                    value,
316                });
317            }
318            p += 1;
319        }
320        Ok(MaxBounds {
321            ceilings: ceilings.into_boxed_slice(),
322        })
323    }
324
325    /// The number of actual clocks.
326    #[check(terminates)]
327    #[ensures(result@ == self.variables_logic())]
328    pub fn variables(&self) -> usize {
329        self.ceilings.len()
330    }
331
332    /// Returns the ceiling for actual clock `x`, or `None` if it is
333    /// outside the range covered by these bounds.
334    ///
335    /// # Complexity
336    ///
337    /// `O(1)` time.
338    #[check(terminates)]
339    #[ensures(match result {
340        Some(c) => x@ <= self.variables_logic() && c == self.ceilings_logic()[x@ - 1],
341        None => x@ > self.variables_logic(),
342    })]
343    pub fn get(&self, x: Variable) -> Option<i32> {
344        let p = x.index() - 1;
345        if p < self.ceilings.len() {
346            Some(self.ceilings[p])
347        } else {
348            None
349        }
350    }
351
352    /// `k(i)`: `0` for the reference clock, `M(xᵢ)` otherwise (`i ≤ n`).
353    #[check(terminates)]
354    #[requires(i@ <= self.variables_logic())]
355    #[ensures(result@ == self.kmap()[i@])]
356    #[ensures(valid_ceiling(result))]
357    fn k(&self, i: usize) -> i32 {
358        if i == 0 { 0 } else { self.ceilings[i - 1] }
359    }
360}
361
362/// `norm_upper e t = (if Le t ≺ e then ∞ else e)`, with `up = Le t`.
363#[check(terminates)]
364#[ensures(forall<t: Int> up@ == BoundModel::Le(t) ==> result@ == proof::norm_upper(e@, t))]
365fn norm_upper(e: Bound, up: Bound) -> Bound {
366    snapshot!(order_refines(up, e));
367    if tighter(up, e) { Bound::INFINITY } else { e }
368}
369
370/// `norm_lower e t = (if e ≺ Lt t then Lt t else e)`, with `low = Lt t`.
371#[check(terminates)]
372#[ensures(forall<t: Int> low@ == BoundModel::Lt(t) ==> result@ == proof::norm_lower(e@, t))]
373fn norm_lower(e: Bound, low: Bound) -> Bound {
374    snapshot!(order_refines(e, low));
375    if tighter(e, low) { low } else { e }
376}
377
378/// `norm_diag e = (if e ≺ Le 0 then Lt 0 else if e = Le 0 then e else ∞)`.
379#[check(terminates)]
380#[ensures(result@ == proof::norm_diag(e@))]
381fn norm_diag(e: Bound) -> Bound {
382    snapshot!(order_refines(e, Bound::LE_ZERO));
383    snapshot!(view_injective(e, Bound::LE_ZERO));
384    if tighter(e, Bound::LE_ZERO) {
385        Bound::LT_ZERO
386    } else if same(e, Bound::LE_ZERO) {
387        e
388    } else {
389        Bound::INFINITY
390    }
391}
392
393/// `(Le k, Lt (−k))` for a validated ceiling `0 ≤ k ≤ MAX_CONSTANT`; both
394/// are representable because `MIN_CONSTANT = −MAX_CONSTANT`.
395#[check(terminates)]
396#[requires(valid_ceiling(k))]
397#[ensures(result.0@ == BoundModel::Le(k@) && result.1@ == BoundModel::Lt(-k@))]
398fn thresholds(k: i32) -> (Bound, Bound) {
399    match (Bound::le(k), Bound::lt(-k)) {
400        (Ok(up), Ok(low)) => (up, low),
401        _ => unreachable!(),
402    }
403}
404
405impl Dbm {
406    /// Computes **ExtraM**, a maximal-constant overapproximation of this zone.
407    ///
408    /// `bounds` supplies a nonnegative integer ceiling for each actual
409    /// clock, in clock-index order. The reference clock (index zero) has
410    /// ceiling zero. The operation relaxes difference bounds using these
411    /// ceilings and returns the canonical zone represented by the result.
412    ///
413    /// More precisely, let `D[i][j]` be the stored bound on
414    /// `clock i - clock j`, and let `k(i)` be clock `i`'s ceiling,
415    /// with `k(0) = 0`. For each off-diagonal entry `e = D[i][j]`:
416    ///
417    /// ```text
418    /// e' = if Le(k(i)) ≺ e then ∞ else e
419    /// normalized[i][j] = if e' ≺ Lt(-k(j)) then Lt(-k(j)) else e'
420    /// ```
421    ///
422    /// `Le(c)` means `<= c`, `Lt(c)` means `< c`, `∞` means no
423    /// restriction, and `a ≺ b` means bound `a` is strictly tighter
424    /// than bound `b`. On a nonempty input the diagonal remains `<= 0`.
425    /// The result is the canonical closure of this normalized matrix.
426    ///
427    /// **Every valuation of the original zone remains in the result**,
428    /// although the result may contain additional valuations. It is always
429    /// canonical or empty on success; an empty input stays empty.
430    ///
431    /// This overapproximation does **not**, by itself, guarantee
432    /// timed-automata reachability preservation. Standard applications
433    /// require suitable ceilings and restrictions on guards, invariants
434    /// and resets; diagonal constraints are not covered. Idempotence is
435    /// not claimed. LU-bound and other advanced abstractions are not
436    /// implemented.
437    ///
438    /// The `ws` parameter does not affect the result.
439    ///
440    /// # Errors
441    ///
442    /// - [`Error::DimensionMismatch`] if `bounds` describes a different
443    ///   number of clocks, including when this zone is empty;
444    /// - [`Error::Range`] if closure of a changed matrix requires a
445    ///   finite bound outside the supported range. This is not an empty
446    ///   result, and no partially updated zone is returned.
447    ///
448    /// # Complexity
449    ///
450    /// Normalization takes `O(d²)` for `d = self.dimension()`. If
451    /// an entry changes, canonicalization can take `O(d³)` in the worst
452    /// case. Otherwise the operation takes `O(d²)`.
453    #[check(terminates)]
454    #[ensures(match result {
455        Ok(r) => bounds.variables_logic() == self.variables_logic()
456            && r.variables_logic() == self.variables_logic()
457            && (self.is_empty_logic() ==> r.is_empty_logic())
458            && (!self.is_empty_logic() ==> forall<u: crate::dbm::proof::Val> r.zone(u) ==
459                crate::dbm::proof::mzone(proof::norm(self.mmat(), bounds.kmap()),
460                    self.variables_logic() + 1, u))
461            && (forall<u: crate::dbm::proof::Val> self.zone(u) ==> r.zone(u))
462            && forall<z: Dbm> inv(z) && z.variables_logic() == r.variables_logic()
463                && (forall<u: crate::dbm::proof::Val> z.zone(u) == r.zone(u))
464                ==> z.deep_model() == r.deep_model(),
465        Err(e) => if bounds.variables_logic() != self.variables_logic() {
466            match e {
467                Error::DimensionMismatch { expected, found } =>
468                    expected@ == self.variables_logic() && found@ == bounds.variables_logic(),
469                _ => false,
470            }
471        } else {
472            e == Error::Range && !self.is_empty_logic()
473                && mrange_failure(proof::norm(self.mmat(), bounds.kmap()),
474                    self.variables_logic() + 1)
475        },
476    })]
477    pub fn try_extrapolate_max(self, bounds: &MaxBounds, ws: &mut Workspace) -> Result<Dbm, Error> {
478        if let Err(e) = self.check_variables(bounds.variables()) {
479            return Err(e);
480        }
481        snapshot!(self.model());
482        snapshot!(bounds.model());
483        let z0 = snapshot!(self);
484        let nf = snapshot!(proof::norm(self.mmat(), bounds.kmap()));
485        snapshot!(proof::norm_extensive(
486            self.mmat(),
487            bounds.kmap(),
488            self.variables_logic() + 1
489        ));
490        let empty = self.empty_like();
491        let mut m = match self.into_matrix() {
492            Some(m) => m,
493            None => {
494                proof_assert!(forall<z: Dbm> inv(z) && z.variables_logic() == empty.variables_logic()
495                && (forall<u: crate::dbm::proof::Val> z.zone(u) == empty.zone(u)) ==> {
496                    Dbm::eq_semantic(z, empty);
497                    z.deep_model() == empty.deep_model()
498                });
499                return Ok(empty);
500            }
501        };
502        let w0 = snapshot!(m);
503        let d = snapshot!(m.dim_logic());
504        snapshot!(w0.model());
505        let changed = normalize(&mut m, bounds);
506        snapshot!(m.model());
507        proof_assert!(meq(m.mmat(), *nf, *d));
508        snapshot!(meq_transfer(m.mmat(), *nf, *d));
509        let r = if changed {
510            // Normalization may break canonicity, so close through every pivot.
511            snapshot!(proof::norm_ready(w0.mmat(), bounds.kmap(), *d));
512            ws.select_all(m.dimension());
513            snapshot!(Matrix::full_pivot_ready(m, ws.touched@));
514            let w1 = snapshot!(m);
515            let r = m.close_pivots(&ws.touched);
516            proof_assert!(match r {
517                Err(_) => {
518                    w1.range_failure_model();
519                    mrange_failure_meq(w1.mmat(), *nf, *d);
520                    true
521                }
522                Ok(_) => true,
523            });
524            r
525        } else {
526            // `norm` changed no entry: the matrix is the canonical input.
527            proof_assert!(forall<a: Int, b: Int> 0 <= a && a < *d && 0 <= b && b < *d ==> {
528                view_injective(m.at(a, b), w0.at(a, b));
529                m.at(a, b)@ == w0.at(a, b)@
530            });
531            proof_assert!(meq(m.mmat(), w0.mmat(), *d));
532            snapshot!(meq_transfer(m.mmat(), w0.mmat(), *d));
533            Ok(m.publish_canonical())
534        };
535        proof_assert!(match r {
536            Ok(y) => forall<z: Dbm> inv(z) && z.variables_logic() == y.variables_logic()
537                && (forall<u: crate::dbm::proof::Val> z.zone(u) == y.zone(u)) ==> {
538                    Dbm::eq_semantic(z, y);
539                    z.deep_model() == y.deep_model()
540                },
541            Err(_) => true,
542        });
543        proof_assert!(forall<u: crate::dbm::proof::Val> z0.zone(u) ==>
544            crate::dbm::proof::mzone(*nf, *d, u));
545        r
546    }
547}
548
549/// `W := norm(W, k, n)` entrywise, in place (`bounds.variables() + 1 =
550/// m.dimension()`). Only compares and copies bounds. Returns whether some
551/// entry changed; if not, `W` is exactly as before.
552///
553/// Proved: every entry becomes `norm_entry` of the old one (upper
554/// rule before lower rule, `k(0) = 0`, `norm_diag` on the diagonal), and
555/// the result is `true` iff some entry differs from before.
556#[check(terminates)]
557#[requires(bounds.variables_logic() + 1 == m.dim_logic())]
558#[ensures((^m).dim_logic() == m.dim_logic())]
559#[ensures(forall<a: Int, b: Int>
560    0 <= a && a < m.dim_logic() && 0 <= b && b < m.dim_logic() ==>
561        (^m).at(a, b)@ == proof::norm_entry(m.at(a, b)@, bounds.kmap(), a, b))]
562#[ensures(result == exists<a: Int, b: Int>
563    0 <= a && a < m.dim_logic() && 0 <= b && b < m.dim_logic() && (^m).at(a, b).deep_model() != m.at(a, b).deep_model())]
564fn normalize(m: &mut Matrix, bounds: &MaxBounds) -> bool {
565    let m0 = snapshot!(*m);
566    let k = snapshot!(bounds.kmap());
567    snapshot!(bounds.model());
568    let mut changed = false;
569    let d = m.dimension();
570    let mut i: usize = 0;
571    #[invariant(i@ <= d@ && m.dim_logic() == d@)]
572    #[invariant(forall<a: Int, b: Int> 0 <= a && a < d@ && 0 <= b && b < d@ ==>
573        if a < i@ {
574            m.at(a, b)@ == proof::norm_entry(m0.at(a, b)@, *k, a, b)
575        } else {
576            m.at(a, b) == m0.at(a, b)
577        })]
578    #[invariant(changed == exists<a: Int, b: Int>
579        0 <= a && a < i@ && 0 <= b && b < d@ && m.at(a, b).deep_model() != m0.at(a, b).deep_model())]
580    #[variant(d@ - i@)]
581    while i < d {
582        let (up, _) = thresholds(bounds.k(i));
583        let mut j: usize = 0;
584        #[invariant(j@ <= d@ && m.dim_logic() == d@)]
585        #[invariant(forall<a: Int, b: Int> 0 <= a && a < d@ && 0 <= b && b < d@ ==>
586            if a < i@ || (a == i@ && b < j@) {
587                m.at(a, b)@ == proof::norm_entry(m0.at(a, b)@, *k, a, b)
588            } else {
589                m.at(a, b) == m0.at(a, b)
590            })]
591        #[invariant(changed == exists<a: Int, b: Int>
592            0 <= a && a < d@ && 0 <= b && b < d@ && (a < i@ || (a == i@ && b < j@))
593                && m.at(a, b).deep_model() != m0.at(a, b).deep_model())]
594        #[variant(d@ - j@)]
595        while j < d {
596            let e = m.get(i, j);
597            let normed = if i == j {
598                norm_diag(e)
599            } else {
600                let (_, low) = thresholds(bounds.k(j));
601                norm_lower(norm_upper(e, up), low)
602            };
603            proof_assert!(normed@ == proof::norm_entry(e@, *k, i@, j@));
604            snapshot!(view_injective(normed, e));
605            if !same(normed, e) {
606                m.set(i, j, normed);
607                changed = true;
608            }
609            j += 1;
610        }
611        i += 1;
612    }
613    changed
614}
615
616#[cfg(creusot)]
617mod proof;
618
619#[cfg(test)]
620mod tests;