Skip to content

Commit

Permalink
Make 21 less brittle
Browse files Browse the repository at this point in the history
  • Loading branch information
gt22 committed Aug 8, 2024
1 parent 8f13a4d commit 424c67e
Showing 1 changed file with 26 additions and 12 deletions.
38 changes: 26 additions & 12 deletions 021-rescale_to_unit.dfy
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,16 @@ function affine(x: real, shift: real, scale: real) : (y : real)
(x + shift) / scale
}

lemma affine_zero(x: real, shift: real, scale: real)
requires x == -shift
requires scale > 0.0
ensures affine(x, shift, scale) == 0.0 {}

lemma affine_unit(x: real, shift: real, scale: real)
requires x == scale - shift
requires scale > 0.0
ensures affine(x, shift, scale) == 1.0 {}


predicate affine_seq(s: seq<real>, r: seq<real>, shift: real, scale: real)
requires scale > 0.0
Expand All @@ -24,28 +34,30 @@ method rescale_to_unit(s: seq<real>) returns (r : seq<real>)
requires exists i, j : int :: (0 <= i < j < |s|) && s[i] != s[j]
ensures |r| == |s|
ensures forall i : int :: 0 <= i < |s| ==> 0.0 <= r[i] <= 1.0
ensures exists i, j : int :: 0 <= i < |s| && 0 <= j < |s| && r[i] == 0.0 && r[j] == 1.0
ensures exists i : int :: 0 <= i < |s| && r[i] == 0.0
ensures exists i : int :: 0 <= i < |s| && r[i] == 1.0
ensures exists shift, scale :: scale > 0.0 && affine_seq(s, r, shift, scale)
{
var mn : real := s[if s[0] < s[1] then 0 else 1];
var mx : real := s[if s[0] < s[1] then 1 else 0];
var mni : int := if s[0] < s[1] then 0 else 1;
var mxi : int := if s[0] < s[1] then 1 else 0;
var i : int := 2;
while (i < |s|)
invariant 0 <= i <= |s|
invariant forall j : int :: (0 <= j < i) ==> mn <= s[j] <= mx
invariant exists a, b : int :: (0 <= a < i && 0 <= b < i && a != b) && mn == s[a] && mx == s[b]
invariant mn <= mx
invariant 0 <= mni < |s|
invariant 0 <= mxi < |s|
invariant forall j : int :: (0 <= j < i) ==> s[mni] <= s[j] <= s[mxi]
invariant s[mni] <= s[mxi]
{
if (s[i] < mn) {
mn := s[i];
if (s[i] < s[mni]) {
mni := i;
}
if (s[i] > mx) {
mx := s[i];
if (s[i] > s[mxi]) {
mxi := i;
}
i := i + 1;
}
var shift := -mn;
var scale := mx - mn;
var shift := -s[mni];
var scale := s[mxi] - s[mni];
assert scale > 0.0;
r := [];
var j := 0;
Expand All @@ -62,5 +74,7 @@ method rescale_to_unit(s: seq<real>) returns (r : seq<real>)
j := j + 1;
}
assert s[..|s|] == s;
assert r[mni] == 0.0 by { affine_zero(s[mni], shift, scale); }
assert r[mxi] == 1.0 by { affine_unit(s[mxi], shift, scale); }
return r;
}

0 comments on commit 424c67e

Please sign in to comment.