Dafny verifies insertion sort using swap - swap

I'm working on how to use dafny to verify an insertion sort using "swap" adjacent elements but I can't find a reasonable invariant for the while loop, can anyone help me fix it?
Here is the link: http://rise4fun.com/Dafny/wmYME

There are a few problems here.
First, your inner loop is not correct, because the temp variable is never updated. I recommend removing temp and using the loop condition down >= 0 && a[down+1] < a[down] instead.
Second, you have several issues with the inner loop invariant being ill formed (index out of range, violating precondition of sorted). However, instead of fixing these, I recommend throwing out both inner loop invariants and trying again.
My preferred invariant for the inner loop of insertion sort is "a[0..up+1] is sorted except possibly at down + 1". You can state this as
invariant forall j,k | 0 <= j < k < up+1 && k != down+1 :: a[j]<=a[k]
The resulting file verifies.

Related

Parallel iteration over array with step size greater than 1

I'm working on a practice program for doing belief propagation stereo vision. The relevant aspect of that here is that I have a fairly long array representing every pixel in an image, and want to carry out an operation on every second entry in the array at each iteration of a for loop - first one half of the entries, and then at the next iteration the other half (this comes from an optimisation described by Felzenswalb & Huttenlocher in their 2006 paper 'Efficient belief propagation for early vision'.) So, you could see it as having an outer for loop which runs a number of times, and for each iteration of that loop I iterate over half of the entries in the array.
I would like to parallelise the operation of iterating over the array like this, since I believe it would be thread-safe to do so, and of course potentially faster. The operation involved updates values inside the data structures representing the neighbouring pixels, which are not themselves used in a given iteration of the outer loop. Originally I just iterated over the entire array in one go, which meant that it was fairly trivial to carry this out - all I needed to do was put .Parallel between Array and .iteri. Changing to operating on every second array entry is trickier, however.
To make the change from simply iterating over every entry, I from Array.iteri (fun i p -> ... to using for i in startIndex..2..(ArrayLength - 1) do, where startIndex is either 1 or 0 depending on which one I used last (controlled by toggling a boolean). This means though that I can't simply use the really nice .Parallel to make things run in parallel.
I haven't been able to find anything specific about how to implement a parallel for loop in .NET which has a step size greater than 1. The best I could find was a paragraph in an old MSDN document on parallel programming in .NET, but that paragraph only makes a vague statement about transforming an index inside a loop body. I do not understand what is meant there.
I looked at Parallel.For and Parallel.ForEach, as well as creating a custom partitioner, but none of those seemed to include options for changing the step size.
The other option that occurred to me was to use a sequence expression such as
let getOddOrEvenArrayEntries myarray oddOrEven =
seq {
let startingIndex =
if oddOrEven then
1
else
0
for i in startingIndex..2..(Array.length myarray- 1) do
yield (i, myarray.[i])
}
and then using PSeq.iteri from ParallelSeq, but I'm not sure whether it will work correctly with .NET Core 2.2. (Note that, currently at least, I need to know the index of the given element in the array, as it is used as the index into another array during the processing).
How can I go about iterating over every second element of an array in parallel? I.e. iterating over an array using a step size greater than 1?
You could try PSeq.mapi which provides not only a sequence item as a parameter but also the index of an item.
Here's a small example
let res = nums
|> PSeq.mapi(fun index item -> if index % 2 = 0 then item else item + 1)
You can also have a look over this sampling snippet. Just be sure to substitute Seq with PSeq

How to determine if a vertex has odd or even number of outE()?

I wanna get the vertex that has odd number of edges. Something like these:
g.V().where(out().count() % 2 != 0)
Of course, % can not be used here. Is there a alternative way?
There is no mod operator for sack but there are div, mult and minus.
g.withSack(0).V().as('a').where(outE().count().sack(assign).sack(div).by(constant(2)).sack(mult).by(constant(2)).sack(minus).sack().is(0)) // even
g.withSack(0).V().as('a').where(outE().count().sack(assign).sack(div).by(constant(2)).sack(mult).by(constant(2)).sack(minus).sack().is(neq(0))) // odd
There is no step for a division and to my knowledge also not for modulo, but you can use a lambda for that:
g.V().outE().count().filter{count = it.get(); count % 2 == 1;}
(Note that this query requires a scan of the complete graph in most systems as no index is used.)
This post in the Gremlin-users group contains more information about mathematical operations with Gremlin.

slevel option in value analysis of FramaC

I do not quite understand the slevel option in FramaC. Could anyone please explain more about how the value of slevel relates to user assertions (e.g. //#assert ...;) or states, and what factors cause the number of states go up?
For example, I have a program which does not contain loop, but containing if..else branches, go to statements, and there are also some user assertions in some points of the program, such as:
...
a = Frama_C_unsigned_int_interval(0, 100);
//# assert a == 0 || a == 1 || a == 2 || a == 3 || ... || a == 100;
...
b = Frama_C_unsigned_int_interval(a, 200);
//# assert b == 0 || b == 1 || b == 2 || b == 3 || ... || b == 200;
...
In the output from the analysis (in which I set slevel to ~100000), there may be some like: Semantic level unrolling superposing up to 100 states, then this statement may repeat several times with larger number of states.
Could anyone please explain how is this semantic level unrolling computed and
how can I obtain the optimal slevel for the analysis. Thanks.
Value analysis performs an abstract execution of the program. Instead of testing the program with arbitrary values, it executes it with abstract values encompassing all possible concrete execution. For instance, the abstract state associates x with the interval [0;10]. When arriving at an if statement, for instance if (x<=5) y = 1; else y=2;, the abstract state is split according to the condition. For instance, the then branch will be executed with an interval [0;5] and the else branch with an interval [6;10]. Conversely, at the end of the whole if, you have to join the two abstract states. This means that we will associate to each variable the smallest interval that contain all possible values coming from both (or more in case of a switch for instance) parent states.
For instance, after the if, we have x in [0;10] and y in [1;2]. In addition, note that Value sees a normalized version of the C code, in which you always have to branches for an if ({ if (c) { s }} in the source in seen by Value as if (c) { s } else { }).
Setting -slevel to N means that Value will not join states as above, but instead propagate up to N separate states. In our example, this means that we now have two states, one in which x is in [0;5] and y==1 and one in which x is in [6;10] and y==2. This allows for more precision (for instance it rules out states such as x==0 && y == 2), but at the expense of computation time and memory consumption. In addition, the number of possible distinct states grows exponentially with the number of points of choice in your program. Indeed, if you have a second, unrelated, if, both states coming from the first one will be split, resulting in 4 states afterwards (assuming N>=4). Value gives you an indication of the number of distinct states that it is using so that you can see in the log where the slevel is spent, and possibly adjust it to meet a better precision/computation time ratio.
Finally, if are not the only constructions that will separate states. Any branching statement, in particular loops, will result in a state separation. Similarly, ACSL annotations expressed as disjunctions, as the one shown in your question will have the same effect: you end up with a state per element of the disjunction, provided you have enough slevel.

Proving that reads from an array are initialised in SPARK

Given a very simple SPARK function that sums an array of integers:
function Add (X, Y : in Ints) return Ints is
Sum : Ints;
begin
for i in Ints'Range loop
pragma Loop_Invariant (for all j in Ints'First .. i - 1 => Sum(j) = X(j) + Y(j)); -- line 7
Sum(i) := X(i) + Y(i);
end loop;
return Sum; -- line 11
end Add;
(Where type Ints is array (Integer range 0 .. 9) of Integer_32)
Compiling without the loop invariant works fine (because I have a precondition that bounds the elements of X and Y such that overflow cannot occur). However, I need the invariant in order to show some properties of the post condition, but it results in:
7:69: warning: "Sum" may be referenced before it has a value
Phase 2 of 3: analysis and translation to intermediate language ...
7:10: "Sum" is not initialized
11:7: warning: "Sum" might not be initialized
I'm not sure how the concept of "being initialised" is expressed in the proof language so I don't know how to convince gnatprove that no uninitialised reads are occuring.
I can remove the warnings by explicitly setting all the elements of Sum to zero at the start of the function but I'm hoping that there's a better way.
In SPARK, arrays are considered as entire objects, and a component-by-component initialization like you do is not allowed. However, there is a heuristics in gnatprove which allows a simple for-loop over the range of the array, as you do. This is why without a loop invariant, you don't get the warning. This heuristics breaks down with the loop invariant, that's why you get the warning again.
You will have to accept the warning using pragma Warnings, as described here:
https://gcc.gnu.org/onlinedocs/gnat_rm/Pragma-Warnings.html
And to avoid the error you are getting at line 7, you may move the loop invariant after the assignment (and change the range of the quantificaton accordingly).

One insert kills Recursion in drools

This is related to my previous question. if I don't have the insert, it goes into a recursive loop as expected. But if I do have the insert the program ends. What am I missing here?
rule "Recurse"
when
f : Fibonacci(value == 0)
not Fibonacci(sequence == 0)
then
System.out.println(f.sequence + "/" + f.value);
insert(new Fibonacci(f.sequence - 1));
f.value = 0;
update(f);
end
For the purpose of explaining this example, lets assume:
there is only one rule in the system
that the initial fact set provided to the rule engine meets the criteria of the when in that rule
that sequence is a positive integer value
Firstly, we consider the case where the insert is commented out:
We know that the Working Memory contains at least one object that has value == 0 and there are no objects that have sequence == 0. (I find the more verbose form of not slightly more legible, you can replace not Fibonacci (...) with not ( exists Fibonacci(...))). Note that the rule is valid if there is a single object that meets both criteria.
The consequence sets the object's value to zero and notifies the engine that this object has changed. An infinite loop is then encountered as there is no object in the system with sequence == 0 and we've set the value to be such that this object will trigger the rule to fire.
Now, lets consider the case where the insert is uncommented:
We already know that the initial fact set fires the rule at least once. The consequence is that now an object is placed in working memory which has a decremented sequence and the object referenced by f has its value set to zero (it isn't changed from zero) and updated. There is a mechanism in place by which the end conditions are met, since now, at some point there will be an object inserted that has a zero sequence. That meets the end condition.
In short: the engine will exit when there is a Fibonacci object with sequence zero in it.
I, err.., think that this system might need a little bit of changing before it will output the Fibonacci sequence. You need a way to reference the previous two Fibonacci numbers to evaluate the one being set, the recursive method is much more elegent ;)

Resources