Whats causing timeout in Promela/SPIN? - verification

I have the following promela code:
chan level = [0] of {int};
proctype Sensor (chan levelChan) {
int x;
do
:: true ->
levelChan ? x;
if
:: (x < 2) -> printf("low %d", x);
:: (x > 8) -> printf("high %d", x);
:: else -> printf("normal %d", x);
fi
od
}
init {
run Sensor(level);
int lvl = 5;
level ! lvl;
lvl = 0;
do
:: true ->
level ! lvl;
lvl++;
(lvl > 9) -> break;
od
}
I am expecting to send level (0-9) information into a channel and have the sensor output low|normal|high depending on this level. Its quite simple. But why SPIN saying its timeout all the time?
0: proc - (:root:) creates proc 0 (:init:)
Starting Sensor with pid 1
1: proc 0 (:init:) creates proc 1 (Sensor)
1: proc 0 (:init:) 1.pml:18 (state 1) [(run Sensor(level))]
2: proc 1 (Sensor) 1.pml:6 (state 11) [(1)]
3: proc 0 (:init:) 1.pml:20 (state 2) [lvl = 5]
4: proc 0 (:init:) 1.pml:20 (state 3) [level!lvl]
4: proc 1 (Sensor) 1.pml:8 (state 2) [levelChan?x]
5: proc 1 (Sensor) 1.pml:9 (state 9) [else]
6: proc 0 (:init:) 1.pml:21 (state 4) [lvl = 0]
normal 5 8: proc 1 (Sensor) 1.pml:12 (state 8) [printf('normal %d',x)]
9: proc 0 (:init:) 1.pml:22 (state 10) [(1)]
12: proc 1 (Sensor) 1.pml:6 (state 11) [(1)]
13: proc 0 (:init:) 1.pml:24 (state 6) [level!lvl]
13: proc 1 (Sensor) 1.pml:8 (state 2) [levelChan?x]
14: proc 1 (Sensor) 1.pml:9 (state 9) [((x<2))]
low 0 15: proc 1 (Sensor) 1.pml:10 (state 4) [printf('low %d',x)]
17: proc 0 (:init:) 1.pml:25 (state 7) [lvl = (lvl+1)]
19: proc 1 (Sensor) 1.pml:6 (state 11) [(1)]
timeout
#processes: 2
19: proc 1 (Sensor) 1.pml:8 (state 2)
19: proc 0 (:init:) 1.pml:26 (state 8)
2 processes created
It seem to only do 1 iteration of the do loop why?

The statements in the init process's do loop are run in sequence.
do
:: true ->
level ! lvl;
lvl++;
(lvl > 9) -> break;
od
The very first time the do loop is run it will send lvl over the level channel, increase the lvl (so it is now 1) and then test (lvl > 9). This is false so will block and causes the timeout.
To have multiple options in a do loop you need :: to define the start of each option:
do
:: true ->
level ! lvl;
lvl++;
:: (lvl > 9) -> break;
od
However this will still not perform as expected. When lvl is greater than 9 both options of the do loop are valid and either one can be chosen, so the loop will not necessarily break when lvl > 9 it could choose to continue to send the lvl over the level channel and increase lvl.
You need to have a condition on the first do option as well as the second:
do
:: (lvl <= 9) ->
level ! lvl;
lvl++;
:: (lvl > 9) -> break;
od
It might be nicer to use the for loop syntax for this example:
init {
run Sensor(level);
int lvl = 5;
level ! lvl;
for (lvl : 0..9){
level ! lvl;
}
}
Note that this example will still have a timeout error caused by Sensor's do loop, when the init process has finished Sensor will still try to read from the level channel and timeout.

Related

How to implement the MapReduce example in Erlang efficiently?

I am trying to compare the performance of concurrent programming languages, such as Haskell, Go and Erlang. The following Go code calculates the sum of squares, ( repeat calculate the sum of squares for R times):
1^2+2^2+3^2....1024^2
package main
import "fmt"
func mapper(in chan int, out chan int) {
for v := range in {out <- v*v}
}
func reducer(in1, in2 chan int, out chan int) {
for i1 := range in1 {i2 := <- in2; out <- i1 + i2}
}
func main() {
const N = 1024 // calculate sum of squares up to N; N must be power of 2
const R = 10 // number of repetitions to fill the "pipe"
var r [N*2]chan int
for i := range r {r[i] = make(chan int)}
var m [N]chan int
for i := range m {m[i] = make(chan int)}
for i := 0; i < N; i++ {go mapper(m[i], r[i + N])}
for i := 1; i < N; i++ {go reducer(r[i * 2], r[i *2 + 1], r[i])}
go func () {
for j := 0; j < R; j++ {
for i := 0; i < N; i++ {m[i] <- i + 1}
}
} ()
for j := 0; j < R; j++ {
<- r[1]
}
}
The following code is the MapReduce solution in Erlang. I am a newbie to Erlang. I would like to compare performance among Go, Haskell and Erlang. My question is how to optimize this Erlang code. I compile this code by using erlc -W mr.erl and run the code by using erl -noshell -s mr start -s init stop -extra 1024 1024. Are there any special compile and execution options available for optimizations? I really appreciate any help you can provide.
-module(mr).
-export([start/0, create/2, doreduce/2, domap/1, repeat/3]).
start()->
[Num_arg|Repeat] = init:get_plain_arguments(),
N = list_to_integer(Num_arg),
[R_arg|_] = Repeat,
R = list_to_integer(R_arg),
create(R, N).
create(R, Num) when is_integer(Num), Num > 0 ->
Reducers = [spawn(?MODULE, doreduce, [Index, self()]) || Index <- lists:seq(1, 2*Num - 1)],
Mappers = [spawn(?MODULE, domap, [In]) || In <- lists:seq(1, Num)],
reducer_connect(Num-1, Reducers, self()),
mapper_connect(Num, Num, Reducers, Mappers),
repeat(R, Num, Mappers).
repeat(0, Num, Mappers)->
send_message(Num, Mappers),
receive
{result, V}->
%io:format("Repeat: ~p ~p ~n", [0, V])
true
end;
repeat(R, Num, Mappers)->
send_message(Num, Mappers),
receive
{result, V}->
%io:format("Got: ~p ~p ~n", [R, V])
true
end,
repeat(R-1, Num, Mappers).
send_message(1, Mappers)->
D = lists:nth (1, Mappers),
D ! {mapper, 1};
send_message(Num, Mappers)->
D = lists:nth (Num, Mappers),
D ! {mapper, Num},
send_message(Num-1, Mappers).
reducer_connect(1, RList, Root)->
Parent = lists:nth(1, RList),
Child1 = lists:nth(2, RList),
Child2 = lists:nth(3, RList),
Child1 ! {connect, Parent},
Child2 ! {connect, Parent},
Parent !{connect, Root};
reducer_connect(Index, RList, Root)->
Parent = lists:nth(Index, RList),
Child1 = lists:nth(Index*2, RList),
Child2 = lists:nth(Index*2+1, RList),
Child1 ! {connect, Parent},
Child2 ! {connect, Parent},
reducer_connect(Index-1, RList, Root).
mapper_connect(1, Num, RList, MList)->
R = lists:nth(Num, RList),
M = lists:nth(1, MList),
M ! {connect, R};
mapper_connect(Index, Num, RList, MList) when is_integer(Index), Index > 0 ->
R = lists:nth(Num + (Index-1), RList),
M = lists:nth(Index, MList),
M ! {connect, R},
mapper_connect(Index-1, Num, RList, MList).
doreduce(Index, CurId)->
receive
{connect, Parent}->
doreduce(Index, Parent, 0, 0, CurId)
end.
doreduce(Index, To, Val1, Val2, Root)->
receive
{map, Val} ->
if Index rem 2 == 0 ->
To ! {reduce1, Val},
doreduce(Index, To, 0, 0, Root);
true->
To ! {reduce2, Val},
doreduce(Index, To, 0, 0, Root)
end;
{reduce1, V1} when Val2 > 0, Val1 == 0 ->
if Index == 1 ->% root node
Root !{result, Val2 + V1},
doreduce(Index, To, 0, 0, Root);
Index rem 2 == 0 ->
To ! {reduce1, V1+Val2},
doreduce(Index, To, 0, 0, Root);
true->
To ! {reduce2, V1+Val2},
doreduce(Index, To, 0, 0, Root)
end;
{reduce2, V2} when Val1 > 0, Val2 == 0 ->
if Index == 1 ->% root node
Root !{result, Val1 + V2},
doreduce(Index, To, 0, 0, Root);
Index rem 2 == 0 ->
To ! {reduce1, V2+Val1},
doreduce(Index, To, 0, 0, Root);
true->
To ! {reduce2, V2+Val1},
doreduce(Index, To, 0, 0, Root)
end;
{reduce1, V1} when Val1 == 0, Val2 == 0 ->
doreduce(Index, To, V1, 0, Root);
{reduce2, V2} when Val1 == 0, Val2 == 0 ->
doreduce(Index, To, 0, V2, Root);
true->
true
end.
domap(Index)->
receive
{connect, ReduceId}->
domap(Index, ReduceId)
end.
domap(Index, To)->
receive
{mapper, V}->
To !{map, V*V},
domap(Index, To);
true->
true
end.
Despite it is not a good task for Erlang at all, there is a quite simple solution:
-module(mr).
-export([start/1, start/2]).
start([R, N]) ->
Result = start(list_to_integer(R), list_to_integer(N)),
io:format("~B x ~B~n", [length(Result), hd(Result)]).
start(R, N) ->
Self = self(),
Reducer = start(Self, R, 1, N),
[ receive {Reducer, Result} -> Result end || _ <- lists:seq(1, R) ].
start(Parent, R, N, N) ->
spawn_link(fun() -> mapper(Parent, R, N) end);
start(Parent, R, From, To) ->
spawn_link(fun() -> reducer(Parent, R, From, To) end).
mapper(Parent, R, N) ->
[ Parent ! {self(), N*N} || _ <- lists:seq(1, R) ].
reducer(Parent, R, From, To) ->
Self = self(),
Middle = ( From + To ) div 2,
A = start(Self, R, From, Middle),
B = start(Self, R, Middle + 1, To),
[ Parent ! {Self, receive {A, X} -> receive {B, Y} -> X+Y end end}
|| _ <- lists:seq(1, R) ].
You can run it using
$ erlc -W mr.erl
$ time erl -noshell -run mr start 1024 1024 -s init stop
1024 x 358438400
real 0m2.162s
user 0m4.177s
sys 0m0.151s
But most of the time is VM start and gracefull stop overhead
$ time erl -noshell -run mr start 1024 1024 -s erlang halt
1024 x 358438400
real 0m1.172s
user 0m4.110s
sys 0m0.150s
$ erl
1> timer:tc(fun() -> mr:start(1024,1024) end).
{978453,
[358438400,358438400,358438400,358438400,358438400,
358438400,358438400,358438400,358438400,358438400,358438400,
358438400,358438400,358438400,358438400,358438400,358438400,
358438400,358438400,358438400,358438400,358438400,358438400,
358438400,358438400,358438400,358438400|...]}
Keep in mind it is more like an elegant solution than an efficient one. An efficient solution should balance reduction tree branching with communication overhead.

Prime numbers in Idris

In idris 0.9.17.1,
with inspiration from https://wiki.haskell.org/Prime_numbers,
I've written the following code for generating prime numbers
module Main
concat: List a -> Stream a -> Stream a
concat [] ys = ys
concat (x :: xs) ys = x :: (concat xs ys)
generate: (Num a, Ord a) => (start:a) -> (step:a) -> (max:a) -> List a
generate start step max = if (start < max) then start :: generate (start + step) step max else []
mutual
sieve: Nat -> Stream Int -> Int -> Stream Int
sieve k (p::ps) x = concat (start) (sieve (k + 1) ps (p * p)) where
fs: List Int
fs = take k (tail primes)
start: List Int
start = [n | n <- (generate (x + 2) 2 (p * p - 2)), (all (\i => (n `mod` i) /= 0) fs)]
primes: Stream Int
primes = 2 :: 3 :: sieve 0 (tail primes) 3
main:IO()
main = do
printLn $ take 10 primes
In the REPL, if I write take 10 primes, the REPL correctly shows [2, 3, 5, 11, 13, 17, 19, 29, 31, 37] : List Int
But if I try :exec, nothing happen and if I try to compile ans execute the program I get Segmentation fault: 11
Can someone help me to debug this problem ?
Your concat function can be made lazy to fix this. Just change its type to
concat : List a -> Lazy (Stream a) -> Stream a
This will do it.
Note:
To get all primes, change the < inside the generate function into <=
(Currently some are missing, e.g. 7 and 23).

SPIN verifier: cannot prove LTL formulae

I have quite simpe sender-receiver protocol:
#define SZ 4
int sent = 0;
int received = 0;
chan ch = [SZ] of {int};
int varch;
init {
do
:: ((len(ch) < SZ) && (received != 1)) ->
d_step {
ch ! 1; sent = 1; printf("sent\n");
}
:: ((len(ch) == SZ) || ((received == 1) && (len(ch) > 0))) ->
d_step {
ch ? varch; received = 1; printf("received\n");
}
:: 1 -> /* simulates ramdomness */
atomic {
printf("timeout1\n");/*break; */
}
od;
}
which sends four packets and then receives them. Then I try to prove property: always send implies eventually receive:
ltl pr { [] ( (sent == 1) -> (<> (received == 1)) ) }
...and nothing happens: SPIN does not find both this property prove and its negation.
Why?
So, upon quick inspection, the LTL property cannot possibly be satisfied. The LTL property includes always but one viable execution is for the do::od statement to take the /* simulates randomness */ option forever. In that case, no queue will be 'received' and the LTL fails.
My SPIN run confirms the above (I put your code into a file 'sr.pml')
$ spin -a sr.pml
$ gcc -o pan pan.c
$ ./pan -a
pan:1: acceptance cycle (at depth 16)
pan: wrote sr.pml.trail
(Spin Version 6.3.2 -- 17 May 2014)
Warning: Search not completed
+ Partial Order Reduction
Full statespace search for:
never claim + (pr)
assertion violations + (if within scope of claim)
acceptance cycles + (fairness disabled)
invalid end states - (disabled by never claim)
State-vector 60 byte, depth reached 20, errors: 1
12 states, stored (14 visited)
0 states, matched
14 transitions (= visited+matched)
0 atomic steps
hash conflicts: 0 (resolved)
Stats on memory usage (in Megabytes):
0.001 equivalent memory usage for states (stored*(State-vector + overhead))
0.290 actual memory usage for states
128.000 memory used for hash table (-w24)
0.534 memory used for DFS stack (-m10000)
128.730 total actual memory usage
pan: elapsed time 0 seconds
And then we can see the path with:
$ spin -p -t sr.pml
ltl pr: [] ((! ((sent==1))) || (<> ((received==1))))
starting claim 1
using statement merging
Never claim moves to line 4 [(1)]
2: proc 0 (:init::1) sr.pml:8 (state 1) [(((len(ch)<4)&&(received!=1)))]
4: proc 0 (:init::1) sr.pml:9 (state 5) [ch!1]
4: proc 0 (:init::1) sr.pml:10 (state 3) [sent = 1]
sent
4: proc 0 (:init::1) sr.pml:10 (state 4) [printf('sent\\n')]
Never claim moves to line 3 [((!(!((sent==1)))&&!((received==1))))]
6: proc 0 (:init::1) sr.pml:8 (state 1) [(((len(ch)<4)&&(received!=1)))]
Never claim moves to line 8 [(!((received==1)))]
8: proc 0 (:init::1) sr.pml:9 (state 5) [ch!1]
8: proc 0 (:init::1) sr.pml:10 (state 3) [sent = 1]
sent
8: proc 0 (:init::1) sr.pml:10 (state 4) [printf('sent\\n')]
10: proc 0 (:init::1) sr.pml:8 (state 1) [(((len(ch)<4)&&(received!=1)))]
12: proc 0 (:init::1) sr.pml:9 (state 5) [ch!1]
12: proc 0 (:init::1) sr.pml:10 (state 3) [sent = 1]
sent
12: proc 0 (:init::1) sr.pml:10 (state 4) [printf('sent\\n')]
14: proc 0 (:init::1) sr.pml:8 (state 1) [(((len(ch)<4)&&(received!=1)))]
16: proc 0 (:init::1) sr.pml:9 (state 5) [ch!1]
16: proc 0 (:init::1) sr.pml:10 (state 3) [sent = 1]
sent
16: proc 0 (:init::1) sr.pml:10 (state 4) [printf('sent\\n')]
<<<<<START OF CYCLE>>>>>
18: proc 0 (:init::1) sr.pml:16 (state 11) [(1)]
timeout1
20: proc 0 (:init::1) sr.pml:18 (state 12) [printf('timeout1\\n')]
spin: trail ends after 20 steps
#processes: 1
sent = 1
received = 0
queue 1 (ch): [1][1][1][1]
varch = 0
20: proc 0 (:init::1) sr.pml:7 (state 14)
20: proc - (pr:1) _spin_nvr.tmp:7 (state 10)
1 processes created
The <<<<<START OF CYCLE>>>> shows sr.pml at line 16 (:: 1 -> ...) executed forever. Also, there are other failures of the LTL. Run the SPIN search with './pan -a -i' to find the shortest trail; it indicates that your LTL isn't finding what you intend to find.

Spin random error, bakery lock

I've created a bakery lock using Spin
1 int n=3;
2 int choosing[4] ; // initially 0
3 int number[4]; // initially 0
4
5 active [3] proctype p()
6 {
7
8 choosing[_pid] = 1;
9 int max = 0;
10 int i=0;
11
12 do
13 ::(number[i] > max) -> max=number[i];
14 ::i++;
15 :: (i == n) -> break;
16 od;
17
18 number[_pid] = max + 1;
19 choosing[_pid] = 0;
20
21 int j=0;
22
23 do
24 ::(j==n) -> break;
25 :: do
26 ::(choosing[j] == 0)-> break;
27 od;
28 :: if
29 ::(number[j] ==0) -> j++;
30 ::(number[j] > number[_pid]) -> j++;
31 ::((number[j] == number[_pid]) && ( j> _pid)) -> j++;
32 fi;
33 od;
34
35 number[_pid]=0
36
37 }
when I test it I get an error: pan:1: assertion violated - invalid array index (at depth 5)
when I run the trail I get this back
1: proc 2 (p) Bakery_lock.pml:8 (state 1) [choosing[_pid] = 1]
2: proc 2 (p) Bakery_lock.pml:10 (state 2) [max = 0]
2: proc 2 (p) Bakery_lock.pml:12 (state 3) [i = 0]
3: proc 2 (p) Bakery_lock.pml:14 (state 6) [i = (i+1)]
4: proc 2 (p) Bakery_lock.pml:14 (state 6) [i = (i+1)]
5: proc 2 (p) Bakery_lock.pml:14 (state 6) [i = (i+1)]
spin: indexing number[3] - size is 3
spin: Bakery_lock.pml:13, Error: indexing array 'number'
6: proc 2 (p) Bakery_lock.pml:13 (state 4) [((number[i]>max))]
Can anyone tell me why it skips this line (i == n) -> break; ?
It doesn't 'skip' that line. Spin executes every line that is executable. In your do the line i++ is always executable and therefore, because Spin explores all possible executions, the i++ line will be executed even when (i == n). The fix is:
do
:: (number[i] > max) -> max=number[i];
:: (i < n) -> i++
:: (i == n) -> break;
od;

Running Time Calculation/Complexity of an Algorithm

I have to calculate the time complexity or theoretical running time of an algorithm (given the psuedocode), line by line as T(n). I've given it a try, but there are a couple things confusing me. For example, what is the time complexity for an "if" statement? And how do I deal with nested loops? The code is below along with my attempt which is commented.
length[A] = n
for i = 0 to length[A] - 1 // n - 1
k = i + 1 // n - 2
for j = 1 + 2 to length[A] // (n - 1)(n - 3)
if A[k] > A[j] // 1(n - 1)(n - 3)
k = j // 1(n - 1)(n - 3)
if k != i + 1 // 1(n - 1)
temp = A[i + 1] // 1(n - 1)
A[i + 1] = A[k] // 1(n - 1)
A[k] = temp // 1(n - 1)
Blender is right, the result is O(n^2): two nested loops that each have an iteration count dependent on n.
A longer explanation:
The if, in this case, does not really matter: Since O-notation only looks at the worst-case execution time of an algorithm, you'd simply choose the execution path that's worse for the overall execution time. Since, in your example, both execution paths (k != i+ 1 is true or false) have no further implication for the runtime, you can disregard it. If there were a third nested loop, also running to n, inside the if, you'd end up with O(n^3).
A line-by-line overview:
for i = 0 to length[A] - 1 // n + 1 [1]
k = i + 1 // n
for j = 1 + 2 to length[A] // (n)(n - 3 + 1) [1]
if A[k] > A[j] // (n)(n - 3)
k = j // (n)(n - 3)*x [2]
if k != i + 1 // n
temp = A[i + 1] // n*y [2]
A[i + 1] = A[k] // n*y
A[k] = temp // n*y
[1] The for loop statement will be executed n+1 times with the following values for i: 0 (true, continue loop), 1 (true, continue loop), ..., length[A] - 1 (true, continue loop), length[A] (false, break loop)
[2] Without knowing the data, you have to guess how often the if's condition is true. This guess can be done mathematically by introducing a variable 0 <= x <= 1. This is in line with what I said before: x is independent of n and therefore influences the overall runtime complexity only as a constant factor: you need to take a look at the execution paths .