clock_dbm/ops/temporal.rs
1//! Operations for time elapse and changes to clock values.
2//!
3//! - [`Dbm::future`](crate::Dbm::future) advances **all** clocks by the same
4//! nonnegative delay.
5//! - [`Dbm::past`](crate::Dbm::past) is its backward counterpart: the
6//! valuations from which some common nonnegative delay leads into the zone.
7//! - [`Dbm::try_reset`](crate::Dbm::try_reset) (or
8//! [`Dbm::try_reset_zero`](crate::Dbm::try_reset_zero)) assigns a constant
9//! value to one clock, leaving the others unchanged.
10//! - [`Dbm::try_free`](crate::Dbm::try_free) removes restrictions on one
11//! clock's value while retaining the clock and the values of the others.
12//!
13//! All four transformations preserve the number of actual clocks.
14
15// Source-level implementation and proof notes (not part of public API Rustdoc).
16// Temporal operations: future (delay), past (time predecessors), clock
17// reset and clock free.
18//
19// Notation: `γ(D)` denotes the set of nonnegative-real valuations
20// represented by DBM `D`; `∅_d` denotes the empty zone of matrix
21// dimension `d` (including the reference clock fixed at zero).
22// `Le c` and `Lt c` mean `<= c` and `< c`; `a ≼ b` means
23// bound `a` is at least as tight as bound `b`.
24//
25// Each operation moves the input's storage into a working matrix, rewrites
26// entries in place (`O(d)` of them from the **original** reference row and
27// column; `O(d²)` reads for past, which rewrites row 0 only), and publishes
28// the result with `Matrix::publish_canonical`. There is no closure, no
29// scratch memory and no copy. Empty inputs are returned
30// unchanged (`∅_d` keeps its dimension), after the arguments are validated.
31//
32// Throughout, `D` is the canonical, nonempty input with `d = n + 1`, `k` is
33// the index of the selected actual clock, and `R` is the result.
34//
35// # Future: `γ(R) = { u + t | u ∈ γ(D), t ≥ 0 }`
36//
37// `R[i][0] = ∞` for `i ∈ 1..d`; every other entry is unchanged. All actual
38// clocks advance by the **same** delay, so the differences `xᵢ − xⱼ`
39// (`i, j ≥ 1`) and the lower bounds `D[0][j]` stay; only the upper bounds go.
40//
41// *Canonicity.* Row 0 and the diagonal are unchanged (C2, C3). A triangle
42// `R[i][j] ≼ R[i][l] + R[l][j]` whose left side is a changed entry `(i, 0)`
43// has a right side containing `R[i][0]` (`l = 0`) or `R[l][0]` with `l ≥ 1`
44// (otherwise `l = 0` and `R[0][0] = Le 0` with `R[i][0]` again), and that is
45// `∞`. A triangle whose left side is unchanged only lost tightness on its
46// right side. The corresponding correctness properties are proved below.
47//
48// # Past: `γ(R) = { v ≥ 0 | ∃t ≥ 0. v + t ∈ γ(D) }`
49//
50// ```text
51// R[0][j] = min(Le 0, D[1][j], …, D[n][j]) (every j; R[0][0] = Le 0)
52// ```
53//
54// and every other entry is unchanged. Upper bounds `D[i][0]` and the
55// differences `D[i][j]` (`i, j ≥ 1`) are invariant under a common delay,
56// so they stay. Lower bounds `D[0][j]` disappear, but **not** to `Le 0`:
57// the result must stay canonical, and `xⱼ ≥ 0` together with
58// `xᵢ − xⱼ ≼ D[i][j]` still bounds `−xⱼ` by `D[i][j]` (for example,
59// `x − y ≥ 5` and `y ≥ 0` give `x ≥ 5`). This is row 0 of the closure of
60// "`D` with row 0 relaxed to `Le 0`", and a single step `0 → i → j`
61// suffices: a longer path `0 → i → l → j` is dominated by
62// `D[i][j] ≼ D[i][l] + D[l][j]`.
63//
64// *Why exact.* `v + t ∈ γ(D)` constrains `t` by `t ≼ D[i][0] − vᵢ` and
65// `−t ≼ D[0][j] + vⱼ`. Eliminating `t ≥ 0` (Fourier–Motzkin) leaves
66// `vᵢ ≼ D[i][0]` and `vᵢ − vⱼ ≼ D[i][0] + D[0][j]`, which the canonical
67// `D[i][j]` already implies. So `γ(R)` is "nonnegative, `D`'s upper bounds
68// and differences" (`proof::down_zone`; the hard direction builds `t` with
69// `proof::rewind`).
70//
71// *Canonicity.* Row-0 triangles: `R[0][j] ≼ R[0][l] + D[l][j]` because
72// `R[0][l]` is `Le 0` or some `D[k][l]`, and `D[k][l] + D[l][j] ≽ D[k][j]`.
73// Triangles through `l = 0`: `D[i][j] ≼ D[i][0] + R[0][j]` because
74// `R[0][j]` is `Le 0` or `D[k][j]`, and `D[i][k] ≼ D[i][0] + D[0][k] ≼
75// D[i][0]` (`proof::down_canonical`).
76//
77// *In-place order.* Row 0 `:= Le 0` (`Matrix::fill_row`), then for
78// `i = 1, …, n`: row 0 `:= min(row 0, row i)` (`Matrix::relax_row` through
79// `Le 0`, a contiguous, vectorized pass). Row 0 is never a source, so every
80// row read is the input's. `Le 0 + b = b` is representable for every valid
81// `b`, so the overflow flag of `relax_row` is provably never set. `O(d²)`
82// time, no allocation, cannot fail.
83//
84// # Reset: `γ(R) = { u[xₖ := c] | u ∈ γ(D) }`, `c ≥ 0`
85//
86// ```text
87// R[k][j] = Le c + D[0][j] (j ≠ k)
88// R[i][k] = Le (−c) + D[i][0] (i ≠ k)
89// R[k][k] = Le 0
90// ```
91//
92// and every other entry is unchanged (the canonical reset transformation).
93// The new value of `xₖ` is `c = c + x₀`, so its relation to every other
94// clock is that clock's relation to `x₀`, shifted by `c`. The other clocks
95// keep their values and mutual differences (`R` agrees with `D` off row and
96// column `k`).
97//
98// *In-place order.* Two whole-line updates, each a single pass over the
99// `d` entries: row `k := Le c + row 0` (`Matrix::add_weak_to_row`, a
100// contiguous, vectorized loop), then column `k := Le(−c) + column 0`
101// (`Matrix::add_weak_to_column`), both over **all** indices. The row pass
102// reads row 0, which it does not write. The column pass reads column 0, of
103// which the row pass changed only `D[k][0]`, now `Le c`; the column pass
104// reads it only for `i = k` and writes `R[k][k] = Le c + Le(−c) = Le 0`.
105// It writes `R[0][k] = Le(−c) + D[0][0] = Le(−c)`, the value the row pass
106// read for `j = k` and overwrote. So every other entry is computed from `D`,
107// and the diagonal needs no separate store. (The opposite pass order would
108// be equally correct: then the row pass reads the updated `R[0][k] =
109// Le(−c)`. What matters, and what the proof checks, is that the second pass
110// reads exactly one entry written by the first, and that it yields `Le 0`.)
111//
112// *Range.* `c > MAX_CONSTANT` is rejected with `Err(Range)` before any
113// write (after the argument and emptiness checks). Otherwise every sum is
114// representable, so the kernel adds without range checks
115// (`bounds::add_weak`, whose precondition is this claim):
116//
117// - row `k`: `D[0][j]` is a valid bound `≼ Le 0` (C3), so its constant lies
118// in `[MIN_CONSTANT, 0]` and `c + D[0][j]` in `[MIN_CONSTANT + c, c]`;
119// - column `k`: for `i ≥ 1`, `D[i][0]` is `∞` or `≽ Le 0`, because
120// `D[i][0] + D[0][i] ≽ D[i][i] = Le 0` (C4, C2) and `D[0][i] ≼ Le 0`;
121// so a finite `D[i][0] − c` lies in `[−c, MAX_CONSTANT − c]`.
122//
123// Both facts follow from C2–C4 of the `Dbm` type invariant alone
124// (`proof::reset_representable`), not from the linear range premise of
125// the representability conditions. Hence `Err(Range)` is returned **iff**
126// the input is nonempty and `c > MAX_CONSTANT`, which is exactly when the
127// result (`R[k][0] = Le c`) is unrepresentable. An earlier version added
128// with `Bound::checked_add` and propagated its (unreachable) error; the
129// per-entry range checks made reset about 2× slower than without them in a
130// hot-cache loop.
131//
132// # Free: `γ(R) = { u[xₖ := t] | u ∈ γ(D), t ≥ 0 }`
133//
134// ```text
135// R[k][j] = ∞ (j ≠ k)
136// R[i][k] = D[i][0] (i ≠ k; so R[0][k] = D[0][0] = Le 0)
137// R[k][k] = Le 0
138// ```
139//
140// and every other entry is unchanged. `xₖ` keeps
141// its coordinate and only `xₖ ≥ 0`: free is **not** a reset (a reset pins
142// `xₖ`) and does not remove the clock.
143//
144// *Why.* The projection of a canonical DBM onto the clocks other than `xₖ`
145// is its submatrix (Fourier–Motzkin elimination over a closed system), so
146// the unchanged entries are exactly the constraints on the other clocks.
147// For `xₖ = t ≥ 0` the tightest bounds are `xᵢ − t ≤ xᵢ − 0`, i.e.
148// `R[i][k] = R[i][0]`, and `t` has no upper bound. Canonicity: a triangle
149// through `k` reads `R[i][k] + R[k][j] = D[i][0] + ∞` unless `j = k`, and
150// `R[i][k] = D[i][0] ≼ D[i][l] + D[l][0] = R[i][l] + R[l][k]` for `l ≠ k`.
151// Both facts are proved directly here
152// (`proof::project`, `proof::free_zone`, `proof::free_canonical`).
153//
154// *In-place order.* Column `k := column 0` over all rows
155// (`Matrix::copy_column`), then row `k := ∞` (`Matrix::fill_row`), then
156// `R[k][k] := Le 0`. The copy reads column 0 before the row fill changes
157// `D[k][0]`; the entry it writes in row `k` is overwritten by the fill.
158//
159// # Future, in place
160//
161// Column 0 `:= ∞` over all rows (`Matrix::fill_column`), then
162// `R[0][0] := Le 0`. Future, reset and free are `O(d)`, past is `O(d²)`;
163// none of them runs a closure.
164//
165// # Errors
166//
167// Argument errors come first, also for empty inputs: `ClockOutOfRange`,
168// then (reset) `NegativeConstant`. Then an empty input returns `Ok(∅_d)`.
169// Only then can reset fail with `Range`. Future and past never fail, and
170// free never fails on a valid clock. On `Err` the consumed input is dropped.
171//
172// # Verification status
173//
174// Creusot proves every function of this module on the shipped bodies
175//, with `#[check(terminates)]`; the lemmas are in
176// `temporal/proof.rs`, the primitives in `dbm.rs` and `bounds.rs`. There
177// is no `#[trusted]`, `assume` or admitted lemma.
178//
179// - **Semantics** over nonnegative real valuations: `future` denotes
180// `{ u + t | u ∈ γ(D), t ≥ 0 }` (a common delay, `x₀` stays 0), `try_reset`
181// `{ u[x := c] | u ∈ γ(D) }`, `try_free` `{ u[x := t] | u ∈ γ(D), t ≥ 0 }`
182// (the clock is kept), `past` `{ v ≥ 0 | ∃t ≥ 0. v + t ∈ γ(D) }`. The
183// model of each kernel is `proof::up`, `proof::reset`, `proof::free` and
184// `proof::down`; the proofs show that the in-place updates compute it
185// exactly (including the two-pass order of reset and the loop of past)
186// and that it is canonical, which discharges `publish_canonical`.
187// - **The hard direction** of each set equation constructs a witness with
188// the one-clock extension of `dbm::proof` (`extend`): `proof::project`
189// (the projection of a canonical DBM is its submatrix; free and reset),
190// `proof::unshift` (future) and `proof::rewind` (past).
191// - **Errors and range:** exactly the order above; `Err(Range)` iff the
192// input is nonempty and `c > MAX_CONSTANT`; `∅_d` keeps its dimension; no
193// partially updated matrix escapes (`Range` is decided before any write).
194//
195// The exact-oracle tests (`temporal/tests.rs`) remain as regression tests.
196// See `verification/PROOF_STATUS.md`.
197
198// `?` is not a terminating call for Creusot; keep the style of `dbm.rs`.
199#![allow(clippy::question_mark)]
200
201use crate::bounds::{Bound, Clock, Variable};
202#[cfg(creusot)]
203use crate::bounds::{MAX_CONSTANT, neg_in_range, variable_not_zero, view_representable};
204use crate::dbm::Dbm;
205#[cfg(creusot)]
206use crate::dbm::proof::{meq, meq_transfer};
207use crate::error::Error;
208#[cfg(creusot)]
209use creusot_std::logic::real::Real;
210use creusot_std::prelude::*;
211
212impl Dbm {
213 /// Computes the **future** of this zone by allowing time to elapse.
214 ///
215 /// The result contains exactly those valuations obtained by taking a
216 /// valuation of this zone and advancing **all actual clocks by the same
217 /// nonnegative real delay**. The reference clock remains zero.
218 /// Differences between actual clocks are preserved; individual upper
219 /// bounds on clocks are removed.
220 ///
221 /// The clock count is unchanged. An empty zone remains empty,
222 /// and this operation cannot fail.
223 ///
224 /// # Complexity
225 ///
226 /// `O(d)` time, where `d` is the number of actual clocks plus the
227 /// reference clock. The owned matrix is updated without allocation.
228 #[check(terminates)]
229 #[ensures(result.variables_logic() == self.variables_logic())]
230 #[ensures(result.is_empty_logic() == self.is_empty_logic())]
231 #[ensures(forall<v: crate::dbm::proof::Val> result.zone(v) ==
232 exists<u: crate::dbm::proof::Val, t: Real> Real::from_int(0) <= t && self.zone(u)
233 && proof::shifted(u, t, v, self.variables_logic() + 1))]
234 pub fn future(self) -> Dbm {
235 let z = snapshot!(self);
236 snapshot!(self.model());
237 let empty = self.empty_like();
238 let mut m = match self.into_matrix() {
239 Some(m) => m,
240 None => return empty,
241 };
242 snapshot!(m.dim_pos());
243 let d = snapshot!(m.dim_logic());
244 let f = snapshot!(m.mmat());
245 let m0 = snapshot!(m);
246 snapshot!(m0.model());
247 snapshot!(proof::up_canonical(*f, *d));
248 snapshot!(proof::up_zone(*f, *d));
249 m.fill_column(0, Bound::INFINITY);
250 m.set(0, 0, Bound::LE_ZERO);
251 snapshot!(m.model());
252 proof_assert!(meq(m.mmat(), proof::up(*f), *d));
253 snapshot!(meq_transfer(m.mmat(), proof::up(*f), *d));
254 proof_assert!(forall<v: crate::dbm::proof::Val> m.zone(v) ==
255 exists<u: crate::dbm::proof::Val, t: Real> Real::from_int(0) <= t && z.zone(u)
256 && proof::shifted(u, t, v, *d));
257 m.publish_canonical()
258 }
259
260 /// Computes the **past** of this zone: every valuation from which this
261 /// zone can be reached by letting time elapse.
262 ///
263 /// For a zone `Z` over `n` clocks the result is
264 ///
265 /// ```text
266 /// past(Z) = { v ∈ (ℝ≥0)ⁿ | there is a real t ≥ 0 with v + t ∈ Z },
267 /// ```
268 ///
269 /// where `v + t` advances **all actual clocks by the same delay** `t`
270 /// (the reference clock stays zero). Upper bounds on clocks and all
271 /// differences between actual clocks are kept. Lower bounds on single
272 /// clocks are relaxed, but only as far as nonnegativity and the
273 /// difference constraints allow: the past of `{x − y ≥ 5, y ≥ 3}` is
274 /// `{x − y ≥ 5}`, in which `x ≥ 5` still holds because `y ≥ 0`.
275 ///
276 /// The clock count is unchanged and `Z ⊆ past(Z)`. An empty zone stays
277 /// empty with the same clock count, and this operation cannot fail.
278 ///
279 /// # Complexity
280 ///
281 /// `O(d²)` time, where `d` is the number of actual clocks plus the
282 /// reference clock. The owned matrix is updated without allocation.
283 ///
284 /// # Examples
285 ///
286 /// ```
287 /// use clock_dbm::{Clock, Constraint, Dbm};
288 ///
289 /// let x = Clock::new(1).unwrap();
290 /// let y = Clock::new(2).unwrap();
291 /// // { x − y ≥ 5, 3 ≤ y ≤ 4 }
292 /// let z = Dbm::universe(2)?
293 /// .try_constrain(Constraint::le(y, x, -5)?)?
294 /// .try_constrain(Constraint::le(Clock::ZERO, y, -3)?)?
295 /// .try_constrain(Constraint::le(y, Clock::ZERO, 4)?)?;
296 /// let p = z.clone().past();
297 /// assert!(z.is_subset_of(&p)?);
298 /// // The past keeps x − y ≥ 5 and y ≤ 4, so x ≥ 5 still holds.
299 /// let expected = Dbm::universe(2)?
300 /// .try_constrain(Constraint::le(y, x, -5)?)?
301 /// .try_constrain(Constraint::le(y, Clock::ZERO, 4)?)?;
302 /// assert_eq!(p, expected);
303 /// let x_ge_5 = Dbm::universe(2)?.try_constrain(Constraint::le(Clock::ZERO, x, -5)?)?;
304 /// assert!(p.is_subset_of(&x_ge_5)?);
305 /// # Ok::<(), clock_dbm::Error>(())
306 /// ```
307 #[check(terminates)]
308 #[ensures(result.variables_logic() == self.variables_logic())]
309 #[ensures(result.is_empty_logic() == self.is_empty_logic())]
310 #[ensures(forall<v: crate::dbm::proof::Val> result.zone(v) ==
311 (crate::dbm::proof::valuation(self.variables_logic() + 1, v)
312 && exists<u: crate::dbm::proof::Val, t: Real> Real::from_int(0) <= t && self.zone(u)
313 && proof::shifted(v, t, u, self.variables_logic() + 1)))]
314 pub fn past(self) -> Dbm {
315 let z = snapshot!(self);
316 snapshot!(self.model());
317 let empty = self.empty_like();
318 let mut m = match self.into_matrix() {
319 Some(m) => m,
320 None => return empty,
321 };
322 snapshot!(m.dim_pos());
323 let d = snapshot!(m.dim_logic());
324 let f = snapshot!(m.mmat());
325 let m0 = snapshot!(m);
326 snapshot!(m0.model());
327 proof_assert!(forall<i: Int, j: Int> 0 <= i && i < *d && 0 <= j && j < *d ==> {
328 view_representable(m0.at(i, j)); f[i][j].representable()
329 });
330 snapshot!(proof::down_canonical(*f, *d));
331 snapshot!(proof::down_zone(*f, *d));
332 // Row 0 := Le 0, then row 0 := min(row 0, row i) for every actual
333 // clock i (`relax_row` through `Le 0`). Row 0 is never a source, so
334 // every row i ≥ 1 is still the input's.
335 m.fill_row(0, Bound::LE_ZERO);
336 let dim = m.dimension();
337 let mut i: usize = 1;
338 #[invariant(1 <= i@ && i@ <= *d && m.dim_logic() == *d)]
339 #[invariant(forall<k: Int, l: Int> 1 <= k && k < *d && 0 <= l && l < *d ==>
340 m.at(k, l) == m0.at(k, l))]
341 #[invariant(forall<l: Int> 0 <= l && l < *d ==> m.at(0, l)@ == proof::pmin(*f, i@, l))]
342 #[variant(*d - i@)]
343 while i < dim {
344 let before = snapshot!(m);
345 proof_assert!(forall<l: Int> 0 <= l && l < *d ==>
346 before.at(i@, l)@ == f[i@][l] && f[i@][l].representable());
347 let overflow = m.relax_row(0, i, Bound::LE_ZERO);
348 proof_assert!(forall<l: Int> 0 <= l && l < *d ==> {
349 proof::relax_le_zero(before.at(0, l)@, f[i@][l], m.at(0, l)@);
350 m.at(0, l)@ == proof::pmin(*f, i@ + 1, l)
351 });
352 proof_assert!(!overflow);
353 // Unreachable: `Le 0 + b` is representable for every valid `b`.
354 debug_assert!(!overflow);
355 i += 1;
356 }
357 snapshot!(m.model());
358 proof_assert!(meq(m.mmat(), proof::down(*f, *d), *d));
359 snapshot!(meq_transfer(m.mmat(), proof::down(*f, *d), *d));
360 proof_assert!(forall<v: crate::dbm::proof::Val> m.zone(v) ==
361 (crate::dbm::proof::valuation(*d, v)
362 && exists<u: crate::dbm::proof::Val, t: Real> Real::from_int(0) <= t && z.zone(u)
363 && proof::shifted(v, t, u, *d)));
364 m.publish_canonical()
365 }
366
367 /// Resets actual clock `x` to zero in every valuation of this zone.
368 ///
369 /// All other clock values are preserved. This is equivalent to
370 /// [`Dbm::try_reset`] with `value = 0`. It preserves the clock count
371 /// and leaves an empty zone empty.
372 ///
373 /// # Errors
374 ///
375 /// [`Error::ClockOutOfRange`] if `x` is not one of this zone's actual
376 /// clocks, even when the zone is empty. No arithmetic range error occurs.
377 ///
378 /// # Complexity
379 ///
380 /// `O(d)` time, where `d` includes the reference clock.
381 #[check(terminates)]
382 #[ensures(match result {
383 Ok(r) => x@ <= self.variables_logic()
384 && r.variables_logic() == self.variables_logic()
385 && r.is_empty_logic() == self.is_empty_logic()
386 && forall<v: crate::dbm::proof::Val> r.zone(v) ==
387 exists<u: crate::dbm::proof::Val> self.zone(u) && v[x@] == Real::from_int(0)
388 && proof::agree_except(u, v, self.variables_logic() + 1, x@),
389 Err(e) => x@ > self.variables_logic() && match e {
390 Error::ClockOutOfRange { clock, variables } =>
391 clock@ == x@ && variables@ == self.variables_logic(),
392 _ => false,
393 },
394 })]
395 pub fn try_reset_zero(self, x: Variable) -> Result<Dbm, Error> {
396 self.try_reset(x, 0)
397 }
398
399 /// Resets actual clock `x` to the specified nonnegative integer.
400 ///
401 /// Each valuation of the result is obtained from a valuation of this
402 /// zone by setting `x = value` and leaving every other clock unchanged.
403 /// The clock count is unchanged; an empty zone stays empty after
404 /// argument validation.
405 ///
406 /// # Errors
407 ///
408 /// In the following order:
409 ///
410 /// - [`Error::ClockOutOfRange`] if `x` is not an actual clock of this
411 /// zone;
412 /// - [`Error::NegativeConstant`] if `value` is negative;
413 /// - [`Error::Range`] if the input zone is nonempty and `value`
414 /// exceeds [`crate::MAX_CONSTANT`].
415 ///
416 /// Clock and negativity checks also apply to empty zones, but an
417 /// empty zone accepts an otherwise valid value above `MAX_CONSTANT`
418 /// because no bound needs to be stored.
419 ///
420 /// # Complexity
421 ///
422 /// `O(d)` time, where `d` includes the reference clock.
423 #[check(terminates)]
424 #[ensures(match result {
425 Ok(r) => x@ <= self.variables_logic() && 0 <= value@
426 && (self.is_empty_logic() || value@ <= MAX_CONSTANT@)
427 && r.variables_logic() == self.variables_logic()
428 && r.is_empty_logic() == self.is_empty_logic()
429 && forall<v: crate::dbm::proof::Val> r.zone(v) ==
430 exists<u: crate::dbm::proof::Val> self.zone(u) && v[x@] == Real::from_int(value@)
431 && proof::agree_except(u, v, self.variables_logic() + 1, x@),
432 Err(e) => match e {
433 Error::ClockOutOfRange { clock, variables } => x@ > self.variables_logic()
434 && clock@ == x@ && variables@ == self.variables_logic(),
435 Error::NegativeConstant { value: v } =>
436 x@ <= self.variables_logic() && value@ < 0 && v == value,
437 Error::Range => x@ <= self.variables_logic() && 0 <= value@
438 && !self.is_empty_logic() && MAX_CONSTANT@ < value@,
439 _ => false,
440 },
441 })]
442 pub fn try_reset(self, x: Variable, value: i32) -> Result<Dbm, Error> {
443 let z = snapshot!(self);
444 snapshot!(self.model());
445 snapshot!(variable_not_zero(x));
446 let k = match self.check_clock(Clock::from(x)) {
447 Ok(k) => k,
448 Err(e) => return Err(e),
449 };
450 if value < 0 {
451 return Err(Error::NegativeConstant { value });
452 }
453 let empty = self.empty_like();
454 let mut m = match self.into_matrix() {
455 Some(m) => m,
456 None => return Ok(empty),
457 };
458 snapshot!(if crate::bounds::BoundModel::in_range(value@) { neg_in_range(value@) });
459 let (up, down) = match (Bound::le(value), Bound::le(-value)) {
460 (Ok(up), Ok(down)) => (up, down),
461 _ => return Err(Error::Range),
462 };
463 proof_assert!(value@ <= MAX_CONSTANT@);
464 snapshot!(m.dim_pos());
465 let d = snapshot!(m.dim_logic());
466 let f = snapshot!(m.mmat());
467 let m0 = snapshot!(m);
468 snapshot!(m0.model());
469 proof_assert!(forall<i: Int, j: Int> 0 <= i && i < *d && 0 <= j && j < *d ==> {
470 view_representable(m0.at(i, j)); f[i][j].representable()
471 });
472 snapshot!(proof::reset_representable(*f, *d, value@));
473 snapshot!(proof::cancel(value@));
474 snapshot!(proof::reset_canonical(*f, *d, k@, value@));
475 snapshot!(proof::reset_zone(*f, *d, k@, value@));
476 // Row k from row 0, then column k from column 0 (which by then
477 // reads R[k][0] = Le c, so R[k][k] = Le c + Le(−c) = Le 0). Every
478 // sum is representable by proof::reset_representable.
479 m.add_weak_to_row(k, 0, up);
480 let m1 = snapshot!(m);
481 proof_assert!(forall<i: Int, j: Int> 0 <= i && i < *d && 0 <= j && j < *d ==>
482 m1.at(i, j)@ == if i == k@ {
483 crate::bounds::BoundModel::Le(value@).add(f[0][j])
484 } else {
485 f[i][j]
486 });
487 proof_assert!(forall<i: Int> 0 <= i && i < *d ==>
488 down@.add_in_range(m1.at(i, 0)@));
489 m.add_weak_to_column(k, 0, down);
490 let m2 = snapshot!(m);
491 proof_assert!(forall<i: Int, j: Int> 0 <= i && i < *d && 0 <= j && j < *d ==>
492 m2.at(i, j)@ == if j == k@ {
493 crate::bounds::BoundModel::Le(-value@).add(m1.at(i, 0)@)
494 } else {
495 m1.at(i, j)@
496 });
497 snapshot!(m.model());
498 proof_assert!(forall<i: Int, j: Int> 0 <= i && i < *d && 0 <= j && j < *d ==>
499 m.mmat()[i][j] == m2.at(i, j)@);
500 proof_assert!(meq(m.mmat(), proof::reset(*f, k@, value@), *d));
501 snapshot!(meq_transfer(m.mmat(), proof::reset(*f, k@, value@), *d));
502 proof_assert!(forall<v: crate::dbm::proof::Val> m.zone(v) ==
503 exists<u: crate::dbm::proof::Val> z.zone(u) && v[k@] == Real::from_int(value@)
504 && proof::agree_except(u, v, *d, k@));
505 Ok(m.publish_canonical())
506 }
507
508 /// Forgets the constraints on actual clock `x` while retaining it.
509 ///
510 /// The result contains exactly those valuations obtained by taking a
511 /// valuation of this zone, leaving the other clocks unchanged, and
512 /// choosing **any nonnegative real value** for `x`. Unlike resetting,
513 /// this does not fix `x` to a constant or remove it from the zone.
514 /// The clock count is unchanged, and an empty zone stays empty.
515 ///
516 /// # Errors
517 ///
518 /// [`Error::ClockOutOfRange`] if `x` is not an actual clock of this
519 /// zone, even when the zone is empty.
520 ///
521 /// # Complexity
522 ///
523 /// `O(d)` time, where `d` includes the reference clock.
524 #[check(terminates)]
525 #[ensures(match result {
526 Ok(r) => x@ <= self.variables_logic()
527 && r.variables_logic() == self.variables_logic()
528 && r.is_empty_logic() == self.is_empty_logic()
529 && forall<v: crate::dbm::proof::Val> r.zone(v) ==
530 exists<u: crate::dbm::proof::Val> self.zone(u) && Real::from_int(0) <= v[x@]
531 && proof::agree_except(u, v, self.variables_logic() + 1, x@),
532 Err(e) => x@ > self.variables_logic() && match e {
533 Error::ClockOutOfRange { clock, variables } =>
534 clock@ == x@ && variables@ == self.variables_logic(),
535 _ => false,
536 },
537 })]
538 pub fn try_free(self, x: Variable) -> Result<Dbm, Error> {
539 snapshot!(self.model());
540 snapshot!(variable_not_zero(x));
541 let k = match self.check_clock(Clock::from(x)) {
542 Ok(k) => k,
543 Err(e) => return Err(e),
544 };
545 let empty = self.empty_like();
546 let mut m = match self.into_matrix() {
547 Some(m) => m,
548 None => return Ok(empty),
549 };
550 snapshot!(m.dim_pos());
551 let d = snapshot!(m.dim_logic());
552 let f = snapshot!(m.mmat());
553 let m0 = snapshot!(m);
554 snapshot!(m0.model());
555 snapshot!(proof::free_canonical(*f, *d, k@));
556 snapshot!(proof::free_zone(*f, *d, k@));
557 m.copy_column(k, 0);
558 m.fill_row(k, Bound::INFINITY);
559 m.set(k, k, Bound::LE_ZERO);
560 snapshot!(m.model());
561 proof_assert!(meq(m.mmat(), proof::free(*f, k@), *d));
562 snapshot!(meq_transfer(m.mmat(), proof::free(*f, k@), *d));
563 Ok(m.publish_canonical())
564 }
565}
566
567#[cfg(creusot)]
568mod proof;
569
570#[cfg(test)]
571mod tests;