6.S057: 6.S057: Verified Software Engineering

Class 19

Slides: class19.pptx

class19.dfy
dfy
// We continue with three more search algorithms.

datatype Option<X> = None | Some(value: X)

// In Slope Search, we're given a 2-dimensional array where values in each dimension
// are ascending (non-decreasing). We're told the matrix contains an element `key`
// and we are to find it.

method SlopeSearch(a: array2<int>, key: int) returns (m: int, n: int)
  requires forall i, j, j' :: 0 <= i < a.Length0 && 0 <= j < j' < a.Length1 ==> a[i, j] <= a[i, j']
  requires forall i, i', j :: 0 <= i < i' < a.Length0 && 0 <= j < a.Length1 ==> a[i, j] <= a[i', j]
  requires exists i, j :: 0 <= i < a.Length0 && 0 <= j < a.Length1 && a[i, j] == key
  ensures 0 <= m < a.Length0 && 0 <= n < a.Length1 && a[m, n] == key
{
  // The crucial design decision about this loop comes from the realization that it's
  // not possible to start from the origin and work toward incrementing `m` and `n`,
  // because we won't know whether to veer left or veer right (see the slides). Instead,
  // we will keep our search close to the "contour lines" of the matrix (see slides).
  // This design gives us
  //   - the initialization (`m` the smallest index and `n` the largest index)
  //   - the termination metric that speaks of incrementing `m` and decreasing `n`
  //   - of the 3 conjuncts in the postcondition, we use two in the invariant and negate
  //     the third to make the loop guard
  //   - we adjust the third precondition (which says the matrix contains `key`) into
  //     a loop invariant that says `key` exists in the quadrant that to the upper left
  //     of (m, n).
  m, n := 0, a.Length1 - 1;
  while a[m, n] != key
    invariant 0 <= m < a.Length0 && 0 <= n < a.Length1
    invariant exists i, j :: m <= i < a.Length0 && 0 <= j <= n && a[i, j] == key
    decreases a.Length0 - m + n
  {
    // We compare the current element with the key.
    if a[m, n] < key {
      // To move to a coordinate with a larger value, increment `m`.
      m := m + 1;
    } else {
      // To move to a coordinate with a smaller value, decrement `n`.
      n := n - 1;
    }
  }
}

// Canyon Search asks us to find the minimum absolute difference between
// pairs of elements drawn from two given arrays. Each of the given arrays is
// nonempty and ascending. The problem bears the name Canyon Search because
// if you make a 2-dimensional plot of `Dist(a[i], b[j])`, you get a landscape
// that looks like a canyon (see the slides).

function Dist(x: int, y: int): nat {
  if x < y then y - x else x - y
}

method CanyonSearch(a: array<int>, b: array<int>) returns (d: int)
  // Computing the minimum requires the arrays to be nonempty.
  requires a.Length != 0 && b.Length != 0
  requires forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j]
  requires forall i, j :: 0 <= i < j < b.Length ==> b[i] <= b[j]
  // The next two lines say, in the usual way, that `d` is the minimum.
  ensures exists i, j :: 0 <= i < a.Length && 0 <= j < b.Length && d == Dist(a[i], b[j])
  ensures forall i, j :: 0 <= i < a.Length && 0 <= j < b.Length ==> d <= Dist(a[i], b[j])
{
  // The design of this algorithm comes from the following decisions:
  //   - We'll start at the origin and will travel along the bottom of the canyon
  //   - (m, n) will mark a portion of the 2-dimensional landscape in such a way
  //     that the minimum may still be affected by what's in the upper right
  //     quadrant from (m, n)
  // See the slides for some diagrams that illustrate this situation.
  d := Dist(a[0], b[0]);
  var m, n := 0, 0;
  while m < a.Length && n < b.Length
    invariant 0 <= m <= a.Length && 0 <= n <= b.Length
    // The following invariant is one of the two postconditions.
    invariant exists i, j :: 0 <= i < a.Length && 0 <= j < b.Length && d == Dist(a[i], b[j])
    // We adjust the other postcondition to obtain the following loop invariant. Essentially,
    // we want to exclude the upper right quadrant (again, see the slides).
    invariant forall i, j ::
      0 <= i < a.Length && 0 <= j < b.Length
      ==> d <= Dist(a[i], b[j]) || (m <= i && n <= j)
    decreases a.Length - m + b.Length - n
  {
    // We get here when the loop guard holds, so (m, n) is a coordinate in our landscape.
    // We adjust our running minimum, `d`, accordingly.
    d := if Dist(a[m], b[n]) < d then Dist(a[m], b[n]) else d;
    // Because `a` and `b` are ascending, we don't have to look at the values in the column
    // above `(m, n)` (if `a[m] <= b[n]`) or in the row to the right of `(m, n)` (if `b[n] <= a[m]`).
    // Hence, a simple increment of either `m` or `n` lets us make progress and maintain the
    // invariant.
    if
    case a[m] <= b[n] => m := m + 1;
    case b[n] <= a[m] => n := n + 1;
  }
}

// As the final algorithm, we'll do Majority Vote. We're given a sequence of votes
// and we're told that more than half of those votes go to a particular candidate.
// We're asked to find that candidate.

// To specify the problem and prove the solution, we need to talk about occurrence
// counts in a slice `[lo..hi]` of a given sequence.
function Count<T(==)>(a: seq<T>, lo: int, hi: int, x: T): nat
  requires 0 <= lo <= hi <= |a|
{
  if lo == hi then
    0
  else
    Count(a, lo, hi - 1, x) + if a[hi - 1] == x then 1 else 0
}

// To count the occurrences of `x` in `a[lo..hi]`, you can count the occurrences
// of `x` in `a[lo..mid]` and `a[mid..hi]` separately and then add the results.
lemma SplitCount<T>(a: seq<T>, lo: int, mid: int, hi: int, x: T)
  requires 0 <= lo <= mid <= hi <= |a|
  ensures Count(a, lo, mid, x) + Count(a, mid, hi, x) == Count(a, lo, hi, x)
{
  // The proof is by automatic induction.
}

// If you count occurrences of different values in `a[lo..hi]` and sum them up,
// you will never get a sum larger than `hi - lo`, since `a[lo..hi]` only has
// `hi - lo` elements. This lemma states that property for two values, `x` and `y`.
lemma DistinctCount<T>(a: seq<T>, lo: int, hi: int, x: T, y: T)
  requires 0 <= lo <= hi <= |a|
  ensures x != y ==>
    Count(a, lo, hi, x) + Count(a, lo, hi, y) <= hi - lo
{
  // Automatic induction closes the proof.
}

// A candidate has a (strict) majority if it has (strictly) more than
// half the votes. We could write
//     (hi - lo) / 2  <  Count(a, lo, hi, x)
// but it's easier to work with multiplication rather than with integer
// division.
predicate HasMajority<T(==)>(a: seq<T>, lo: int, hi: int, x: T)
  requires 0 <= lo <= hi <= |a|
{
  hi - lo < 2 * Count(a, lo, hi, x)
}

// The problem can be stated as follows, where we're told of the existence of a
// majority winner `K`. To prove the algorithm, we frequently talk about that majority
// winner, so it's more convenient to have `K` in an accessible variable or parameter
// (rather than `K` being a variable bound in the existential quantification). So, we'll
// immediately reformulate the problem in method `FindWinner` below, and we show that
// `FindWinner'` can be solved by calling `FindWinner`.
method FindWinner'<Candidate(==)>(a: seq<Candidate>) returns (k: Candidate)
  requires exists K :: HasMajority(a, 0, |a|, K)
  ensures HasMajority(a, 0, |a|, k)
{
  // Since parameter `K` of `FindWinner` is ghost, we use a ghost variable here.
  // So, there is no run-time cost of the `:|` assignment.
  ghost var K :| HasMajority(a, 0, |a|, K);
  k := FindWinner(a, K);
}

method FindWinner<Candidate(==)>(a: seq<Candidate>, ghost K: Candidate) returns (k: Candidate)
  requires HasMajority(a, 0, |a|, K)
  // Since a majority winner is unique (as we will show), our postcondition can elegantly be
  // formulated as the equality `k == K`. (So, ahem... can we implement the algorithm by the
  // assignment `k := K`, then? No, we cannot it. The language does not allow such an assignment,
  // since `K` is ghost and `k` is not.)
  ensures k == K
{
  // Surprisingly, this algorithm, which is due to Boyer and Moore, uses a single scan of the votes.
  // As we go along, we'll store the currently most promising candidate in `k` and we'll use `c`
  // to store the supporting number of votes. However, these will not be the leading candidate
  // and vote count in `a[..hi]`. Rather, it will be for the slice `a[lo..hi]`. Soon, we'll see
  // why having an adjustable lower bound is useful.

  // As we get started, `a[0]` is the leading candidate in `a[0..1]`, where `a[0]` has 1 vote.
  k := a[0];
  var lo, hi, c := 0, 1, 1;
  while hi < |a|
    // These three invariants capture what we said in words above.
    invariant 0 <= lo <= hi <= |a|
    invariant c == Count(a, lo, hi, k)
    invariant HasMajority(a, lo, hi, k)
    // Here's where we make use of an adjustable lower bound. At various times during the
    // course of this loop, we may find that `k` no longer has a strict majority (among the
    // votes in `a[lo..hi]`). The amazing thing is that, if that occurs, we can forget all
    // the votes we've seen so far and start the search anew. This will require proof, of
    // course. The invariant we write is that `K` is known to have a strict majority among
    // the votes `a[lo..]`.
    invariant HasMajority(a, lo, |a|, K)
  {
    var vote := a[hi];
    hi := hi + 1;

    if vote == k {
      // This case is easy. The leading candidate gets yet another vote.
      c := c + 1;
    } else if hi - lo < 2 * c {
      // In this case, after considering the new vote, we've looking at a total of `hi - lo`
      // votes. Candidate `k` is not getting new new vote `vote`, but it has enough votes
      // already to remain in the lead. This happens when `hi - lo < 2 * c`.
    } else {
      // In this remaining case, we've reached a state where candidate `k` has exactly
      // half the votes in `a[lo..hi]`. Not convinced? Well, the following assertion
      // should convince you:
      assert hi - lo == 2 * c;
      // Okay, then. Here are some things that are true:
      calc {
        true;
      ==>
        2 * Count(a, lo, hi, k) == hi - lo;
      ==> { DistinctCount(a, lo, hi, k, K); }
        2 * Count(a, lo, hi, K) <= hi - lo;
      ==> { SplitCount(a, lo, hi, |a|, K); }
        |a| - hi < 2 * Count(a, hi, |a|, K);
      ==
        HasMajority(a, hi, |a|, K);
      }
      // Apparently, `K` has a strict majority among the remaining votes. So, we simply
      // restart our bookkeeping from here.
      k, lo, hi, c := a[hi], hi, hi + 1, 1;
    }
  }

  // We have `hi == |a|` and thus the loop invariant tells as that both `k` and `K`
  // have a majority vote in `a[lo..]`. This can happen only if `k` and `K` are
  // equal, which the following lemma shows.
  DistinctCount(a, lo, |a|, k, K);
}

// That was the Majority Vote algorithm. But let's do two more things. First, we'll
// show that you can run the Majority Vote program (with just a minor tweak)
// even if you don't know if there's a majority winner. Second, as an advanced example
// of the cool things you can do with ghost code, we'll show that you can use
// that program to determine whether or not there is a majority winner.

// For the first thing, we'll add a (ghost) parameter `hasWinner` to the method
// above. This parameter says whether or not `K` is meaningful. (Alternatively,
// we could have changed the type of `K` to be `Option<Candidate>`.)
method FindWinnerMaybe<Candidate(==)>(a: seq<Candidate>,
                                      ghost hasWinner: bool,
                                      ghost K: Candidate) returns (k: Candidate)
  // Previously, the existence of a winner in `a` let us conclude that `a` is
  // nonempty, and the program makes use of that fact. But now, since `hasWinner` may
  // be `false`, we'll have to include the nonemptiness condition as an explicit
  // precondition.
  requires |a| != 0
  // We adjust the pre- and postconditions from `FindWinner` above to say that they
  // apply only if `hasWinner` is `true`. In other words, if `hasWinner` is `false`,
  // then `FindWinnerMaybe` requires nothing (except the nonemptiness of `a`) and
  // promises nothing (except termination).
  requires hasWinner ==> HasMajority(a, 0, |a|, K)
  ensures hasWinner ==> k == K
{
  k := a[0];
  var lo, hi, c := 0, 1, 1;
  while hi < |a|
    invariant 0 <= lo <= hi <= |a|
    invariant c == Count(a, lo, hi, k)
    invariant HasMajority(a, lo, hi, k)
    // The last invariant applies only if `hasWinner` is `true`
    invariant hasWinner ==> HasMajority(a, lo, |a|, K)
  {
    var vote := a[hi];
    hi := hi + 1;

    if vote == k {
      c := c + 1;
    } else if hi - lo < 2 * c {
    } else {
      // For brevity, we replace the `calc` statement from `FindWinner` above with
      // its two salient lemma calls. (This also lets us avoid adjusting the lines in
      // the `calc` statement for `hasWinner`.)
      DistinctCount(a, lo, hi, k, K);
      SplitCount(a, lo, hi, |a|, K);
      // Here's the place where we actually have to change the program from `FindWinner`.
      // If `hasWinner` is `true`, then we know `K` to have a majority in `a[hi..]`, which
      // implies `hi < |a|`. But if `hasWinner` is `false`, then we may have `hi == |a|`.
      // Since we make no promises if `hasWinner` is `false`, we can simply exit the method
      // in this case.
      if hi == |a| {
        return;
      }
      k, lo, hi, c := a[hi], hi, hi + 1, 1;
    }
  }

  DistinctCount(a, lo, |a|, k, K);
}

// For the second thing, here's an advanced use of ghost code that lets us usefully call
// `FindWinnerMaybe` without knowing if there's a majority winner or not.

// (We will restrict the `Candidate` type parameter to types that don't involve references.
// This allows us to avoid the technical issue of having to deal with the possibility of new
// `Candidate` values being created with `new` during the course of the algorithm. This is
// not a central point of the class, so we omit further details of this technicality.)
method DetermineElection<Candidate(==,!new)>(a: seq<Candidate>) returns (result: Option<Candidate>)
  ensures match result
    case Some(k) => HasMajority(a, 0, |a|, k)
    case None => !exists k :: HasMajority(a, 0, |a|, k)
{
  if |a| == 0 {
    return None;
  }

  // To call `FindWinnerMaybe`, we need to have values for `hasWinner` and `K`. It's easy to
  // assign a value to `hasWinner`, since we can just use an existential quantifier.
  // Then, depending on the the value of the ghost variable `hasWinner` (which we are allowed
  // to check in ghost code), we either find a majority winner using a such-that (`:|`)
  // assignment or we set `K` to some arbitrary value.
  ghost var hasWinner := exists k :: HasMajority(a, 0, |a|, k);
  ghost var K: Candidate;
  if hasWinner {
    K :| HasMajority(a, 0, |a|, K);
  } else {
    K := a[0];
  }
  var k := FindWinnerMaybe(a, hasWinner, K);

  // If `hasWinner` is `true`, we now know `k` to be the winner. But we can't use `hasWinner`
  // in a non-ghost `if` statement. Instead, we do a linear scan to see if the number of votes
  // for `k` makes `k` a majority winner.
  if HasMajority(a, 0, |a|, k) {
    // This `if` condition implies that `hasWinner` is true, and that means the call to
    // `FindWinnerMaybe` promises to have found the majority winner.
    return Some(k);
  } else {
    // Just because `k` is not a majority winner does not, by itself, imply that there is
    // no other majority winner. But the fact that `k` was returned by `FindWinnerMaybe` and
    // has now been tested _not_ to be a winner says that `FindWinnerMaybe` must have been
    // called with `hasWinner == false`. Thus, by the value assigned to `hasWinner` above,
    // we have that there is no winner.
    return None;
  }
}

Exercises

class19/slopesearch.dfy
dfy
// Given a 2D matrix where values in both dimensions are non-decreasing
//   and a value `key` that must be in the matrix, find `key`.
//
// a.Length0 ┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┐
//           ├─┼─┼─┼─┼─┼─┼─┼─┼─┼─┼─┤
//           ├─┼─┼─┼─┼─┼─┼─┼─┼─┼─┼─┤
//           ├─┼─┼─┼─┼─┼─┼─┼─┼─┼─┼─┤
//           ├─┼─┼─┼─┼─┼─┼─┼─┼─┼─┼─┤
//           ├─┼─┼─┼─┼─┼─┼─┼─┼─┼─┼─┤↙ start the search at a[0, a.Length1-1]
//         0 ┼─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┤
//           0                     a.Length1

method SlopeSearch(a: array2<int>, key: int) returns (m: int, n: int)
  requires forall i, j, j' :: 0 <= i < a.Length0 && 0 <= j < j' < a.Length1 ==> a[i, j] <= a[i, j']
  requires forall i, i', j :: 0 <= i < i' < a.Length0 && 0 <= j < a.Length1 ==> a[i, j] <= a[i', j]
  requires exists i, j :: 0 <= i < a.Length0 && 0 <= j < a.Length1 && a[i, j] == key
  ensures 0 <= m < a.Length0 && 0 <= n < a.Length1 && a[m, n] == key
{
  m, n := 0, a.Length1 - 1;
  while a[m, n] != key
    invariant 0 <= m < a.Length0 && 0 <= n < a.Length1
    // TODO
  {
    // TODO
  }
}
class19/canyonsearch.dfy
dfy
// Given two non-empty arrays in non-decreasing order,
//   find the minimum absolute difference between pairs of elements.
//
//         b.Length ┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┐
//                  ├─┼─┼─┼─┼─┼─┼─┼─┼─┼─┼─┤
//                  ├─┼─┼─┼─┼─┼─┼─┼─┼─┼─┼─┤
//                  ├─┼─┼─┼─┼─┼─┼─┼─┼─┼─┼─┤
//                  ├─┼─┼─┼─┼─┼─┼─┼─┼─┼─┼─┤
// follow the       ├─┼─┼─┼─┼─┼─┼─┼─┼─┼─┼─┤
//  "canyon" of   0 ┼─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┤
//   minima near  ↗ 0                     a.Length
//    the diagonal

function Dist(x: int, y: int): nat {
  if x < y then y - x else x - y
}

method CanyonSearch(a: array<int>, b: array<int>) returns (d: int)
  requires a.Length != 0 && b.Length != 0
  requires forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j]
  requires forall i, j :: 0 <= i < j < b.Length ==> b[i] <= b[j]
  ensures exists i, j :: 0 <= i < a.Length && 0 <= j < b.Length && d == Dist(a[i], b[j])
  ensures forall i, j :: 0 <= i < a.Length && 0 <= j < b.Length ==> d <= Dist(a[i], b[j])
{
  d := Dist(a[0], b[0]);
  var m, n := 0, 0;
  while m < a.Length && n < b.Length
    invariant 0 <= m <= a.Length && 0 <= n <= b.Length
    invariant exists i, j :: 0 <= i < a.Length && 0 <= j < b.Length && d == Dist(a[i], b[j])
    // TODO
  {
    if Dist(a[m], b[n]) < d {
      d := Dist(a[m], b[n]);
    }
    // TODO
  }
}
class19/majorityvote.dfy
dfy
function Count<T(==)>(a: seq<T>, lo: int, hi: int, x: T): nat
  requires 0 <= lo <= hi <= |a|
{
  if lo == hi then
    0
  else
    Count(a, lo, hi - 1, x) + if a[hi - 1] == x then 1 else 0
}

lemma SplitCount<T>(a: seq<T>, lo: int, mid: int, hi: int, x: T)
  requires 0 <= lo <= mid <= hi <= |a|
  ensures Count(a, lo, hi, x) == Count(a, lo, mid, x) + Count(a, mid, hi, x)
{
}

lemma DistinctCount<T>(a: seq<T>, lo: int, hi: int, x: T, y: T)
  requires 0 <= lo <= hi <= |a|
  ensures x != y ==> Count(a, lo, hi, x) + Count(a, lo, hi, y) <= hi - lo
  ensures hi - lo < Count(a, lo, hi, x) + Count(a, lo, hi, y) ==> x == y
{
}

predicate HasMajority<T(==)>(a: seq<T>, lo: int, hi: int, x: T)
  requires 0 <= lo <= hi <= |a|
{
  (hi - lo) / 2 < Count(a, lo, hi, x)
}

method FindWinner'<Candidate(==)>(a: seq<Candidate>) returns (k: Candidate)
  requires exists w :: HasMajority(a, 0, |a|, w)
  ensures HasMajority(a, 0, |a|, k)
{
  ghost var w :| HasMajority(a, 0, |a|, w);
  k := FindWinner(a, w);
}

// Here is an example where candidate B has the majority vote:
//
//           0    1    2    3    4    5    6
//   a = [   A    A    B    B    C    B    B   ]
//  vote =        A    B    B         B
//           ↓    ↓    ↓      ↙         ↙
//     k =   A    A    A    C         B
//     c =   1    2    2    1         1
// lo,hi =   0,1  0,2  0,3  4,5       6,7

method FindWinner<Candidate(==)>(a: seq<Candidate>,
                                 ghost w: Candidate) returns (k: Candidate)
  requires HasMajority(a, 0, |a|, w)
  ensures k == w
{
  // Start with candidate a[0] in the lead with 1 vote in a[0..1].
  k := a[0];
  var c := 1;
  var lo, hi := 0, 1;
  while hi < |a|
    invariant 0 <= lo <= hi <= |a|
    invariant c == Count(a, lo, hi, k)
    invariant HasMajority(a, lo, hi, k)
    invariant HasMajority(a, lo, |a|, w)
  {
    var vote := a[hi];
    hi := hi + 1;

    if vote == k {
      // Candidate `k` gets another vote.
      c := c + 1;
    } else if (hi - lo) / 2 < c {
      // Candidate `k` still has the majority of the votes in a[lo..hi].
    } else {
      // Candidate `k` has exactly half the votes in a[lo..hi].
      assert (hi - lo) / 2 == c;
      // Amazingly (?), we can show that in this situation,
      //   ghost candidate `w` must have a majority of the votes in a[hi..] (!)

      // TODO

      // And that means we can simply restart our count from scratch at a[hi].
      k, c, lo, hi := a[hi], 1, hi, hi + 1;
    }
  }

  // TODO

}
Copyright 6.S057 course staff.