Analisi e progetto di sistemi critici Formal Methods Final test, June 9, 2003 Exercise 1 The following fragment of Petri net introduces inhibitor arcs. Intuitively, an inhibitor arc is such that the transition connected through it cannot fire if its place contains one or more token. t1 P1 P2 t2 Thus, transition t2 is enabled if and only if there is at least one token in P1 and no token in P2. By following the same approach used for timed Petri nets without inhibitor arcs, formalize timed Petri nets with inhibitor arcs through suitable TRIO axioms. You may assume the same simplifying assumtpions used for traditional TPNs, i.e.: 1. 1-bounded PNs 2. No conflicts, i.e., no more than one regular arc and no more than one inhibitor arc outcoming from the same place; no more than one regular arc incoming into any place. (Fragments such as those below are excluded; but the fragment of previous figure is allowed) Plus the following one. 3. Lowerbounds greater than 0 and upperbounds less than infinity. -1- Warning The informal timing semantics of inhibitor arcs is subject to the following ambiguous interpretation. One possible semantics, say SEM1 states that a transition is enabled at the moment when a token exists in “positive places” and no token exists in places with inhibitor arcs. Starting from that time the firing can or must occur within the given time bounds. Another possible semantics, say SEM2, starts counting time since the time positive places have tokens therein – without taking into consideration places with inhibitor arcs- and the firing can occur only if, at the time of occurrence, the inhibited place has no token, independently on when it has been emptied. For instance, with reference to the above fragment, suppose that: transition t2 has time bounds [3,6] a token is produced in P1 at time 1 a token is in P2 at time 0 and is consumed at time 8 According to SEM1 t2 could fire at any time between 11 and 14 According to SEM2 t2 could never fire because during the interval 4-7 it would be inhibited by the token in P2. If instead the token in P2 were consumed before time 7, t2 would necessarily fire within time 7. You may choose to formalize either one of SEM1 or SEM2. As an option you may briefly discuss which semantics seems more suitable for practical cases. You may also decide to formalize both of them. -2- Exercise 2 By using the axioms produced for exercise 1 –and the other axioms already introduced for TPNs- prove that in the fragment below, if transition t1 fires at a given instant, then transition t2 fires within 3 time units after t1’s firing . Notice that such a property is true under both semantics SEM1 and SEM2. 0 P0 t1 [x,y] P1 P2 t3 [1,1] t2 [1,2] -3- Solution of Exercise 1.(according to SEM2) As usual, let mtr, Mtr denote the lower and upper tim bounds of a generic trnsition tr. We define the following axioms (1): fire(r) UpToNow(fire(r)) (for every transition) (Mar): marked(P) Sinceii( fire(t2), fire(t1)), (for every triple <t1, P, t2> t1 input of P, t2 output of P. Notice that such an axiom holds even if an inhibitor arc is connected to P) (LB.(t2)) fire(t2) Lastedie (marked(P1) mv) marked(P2), (UB.(t2)) Lastedie (marked(P1), Mv) marked(P2) fire(t2) Solution of Exercise 2.(according to SEM2) Assume by contradiction Lasts ( fire(t2), k) k >= 3.Thus, fire (t1). Lasts ( fire(t2), k) Lasts (marked (P1), k) (by axiom Mar). Lasts (marked (P1), 2) Let us now prove the lemma: Futr ( marked (P2), 2). – Again by contradiction Futr (marked (P2), 2). Futr(Sinceii( fire(t3), fire(t1)), 2), but, since t1 fires at the current instant, this would imply Lastsie ( fire(t3), 2) Lastsii ( fire(t3), 1) and thus Lastsii (marked (P2), 1), which in turn implies Futr(fire(t3), 1) –through a simple translation of axiom (UB.(a)) Lastedii (marked(P), Mv) fire(v) - a contradiction Now, by –a simple translation of- UB(t2) we obtain Futr(fire(t2),2), a contradiction. -4- Analisi e progetto di sistemi critici Formal Methods Final, optional test, June 14, 2004 Exercise Consider the following fragment of timed Petri net. P1 tr2 [2,4] tr1 [1,3] P2 tr3 [0, 5] The axiomatization given during the course does not allow to deal with such a net. In particular, there is no way to prove formally that, if at a given time t0 P1 becomes marked, then, tr3 will fire within the time interval [x?, y?] after t0. Briefly sketch how the axiom system could be extended in such a way as to cope with nets of the above type and how it could be used to prove the related property also stated above. You do not need to go into all details: a clear and succint exposition is enough. However, possible restrictions on the net type should be clearly stated. -5- Analisi e progetto di sistemi critici – Formal Methods (UIC) Mid-term test May 16th, 2005 Test score: 12/10 NB: the final score – expressed in 30ths – for the course will be obtained by adding to this score the points you will get from the homework (expressed in 20ths) and, possibly the score of the final – optional – test. The result will be registered as the Italian course and converted into American grades for UIC. Let x and y be two strings of length < 30. They are stored into two arrays with the same name of 30 characters each. x and y are terminated by the special character ‘#’. Exercise 1 (9/10) Specify, write, and prove the partial correctness (plus, give a few hints about termination) of a program that produces a third string z (stored into a suitable array with the same name and terminated by ‘#’ as well) that is the longest prefix that x and y have in common. Exercise 2 (3/10; to be done only after completion of exercise 1) Briefly sketch, without developing all details, how the previous exercise could be modified so that z is the concatenation of the longest prefix and the longest suffix that x and y have in common. For instance: x = abacccbaa, y = abcbaccbaa z = abccbaa (NB. The special character ‘#’ is not part of the string: it is only used as a terminator) -6- Sketches of possible solutions (not the only ones!) Exercise 1 Let’s assume that x and y are arrays of 30 characters, with index ranging within [1..30] and z is an array of 30 characters, with index ranging within [1..30]. Suitable pre- and post-conditions can be defined as follows PRE: {( h (1 h 30) x[h] = ‘#’ (j (j < h x[j] ‘#’))) ( k (1 k 30) y[k] = ‘#’ (j (j < k y[j] ‘#’)))} POST: { h, k, m ( (1 h 30) x[h] = ‘#’ (j (j < h x[j] ‘#’)) (1 k 30) y[k] = ‘#’ (j (j < k y[j] ‘#’)) (1 m 30) z[m] = ‘#’ (j (1 j < m z[j] ‘#’)) ( p (1 p 30) /* p is the length of the common prefix of x and y + 1*/ (j ((1 j < p (x[j] = y[j] = z[j])) (x[p] y[p] p = h = k = m)) A Pascal-like program that computes z (assuming that x and y are already stored in memory) is the following: begin i := 1; while x[i] = y[i] and x[i] ‘#’ do z[i] := x[i]; i := i+1 od z[i]:= ‘#’ end A fairly natural invariant for a partial corrrectnes proof is the following, whose kernel states that z always stores a common prefix of x and y: I: (j ((1 j < i (x[j] = y[j] = z[j]))) … In order to carry over the proof it should be completed with other –obviously invariant- assertions that are omitted here for simplicity (e.g. the part of the postcondition that defines p as the length of the common prefix of x and y + 1). The proof that I is indeed invariant follows a standard path; as well as the fact that it is obviously implied by initialization. At loop exit either x[i] y[i] which easily leads to i = p = m; or x[i] = ‘#’ which implies i = h and therefore also i = m; which provides the full postcondition after the last statement z[i]:= ‘#’. -7- Exercise 2 Notice that now z is an array of 60 characters. The precondition is the same as in Exercise 1. The postcondition can be modified as follows. POST: { h, k, m ((1 h 30) x[h] = ‘#’ (j (j < h x[j] ‘#’))) (1 k 30) y[k] = ‘#’ (j (j < k y[j] ‘#’))) (1 m 60) z[m] = ‘#’ (j (1 j < m z[j] ‘#’))) ( i, p (1 i, p 30) /* i and p mark the common prefixes and suffixes of x and y, resp.*/ /*the prefix of z is the common prefix of x and y. The suffix of z is the common suffix of x and y. Furthermore z does not contain any other character besides those, i.e., its length is the sum of the two lengths. Notice that, if common prefix and suffix have a common substring, it is repeated.*/ ) (j ((1 j < i (x[j] = y[j] = z[j])) (x[i] y[i] x[i] = y[i] = ‘#’ /* i = h = k*/)) ) (j ((1 j < p) (x[h-j] = y[k-j] = z[m-j])) (p < 30 x[h-p] y[k-p] p = h = k) m = i + p -1 The program, and, consequently, the proof can be split into the following fragments: 1. Compute i and p –and prove the corresponding assertion 2. Write z up to i – 1 by copying x --- and prove assertion ) 3. Write z from i to i + p - 1 by copying y’s elements in reverse order --- and prove assertion ) 4. Write ‘#’ --- and prove m = i + p -1 -8- Analisi e progetto di sistemi critici Formal Methods (Master UIC) Final, optional test, June 15, 2005 Exercise Consider the following timed Petri net. P1 tr2 [1,1] tr1 [1,1] P4 P3 P2 tr4 [2, 2] tr3 [2, 2] Assume that the net is initialized at time t0 with the marking of the figure. 1. Express in TRIO the property that the behavior of the net is such that no place will ever contain more than one token. 2. Briefly sketch a formal proof of the above property, if it holds. Notice that, in order to carry over your job, you may need to slightly modify the axiom system that was provided in the class for highly simplified timed Petri nets. In such a case, you do not have to provide a full axiomatization suitable to cope with any general net and any possible property: it is sufficient that you provide enough definitions, axioms, and rules so that the above property can be proved. You do not need to go into all details: a clear and succint exposition is enough. However, possible restrictions on the net type your axiomatization is able to handle should be clearly stated. -9- Hint for a possible solution The simplified axiomatization assumes a priori that the net is 1-bounded. Here, in principle, we must also formalize the fact that more than one token is stored in a place: this just to express the fact that such a situation does not occur. If we do not strive for full generality, we can formalize this fact by a formula that states that a place is “doubly-marked” iff sometimes in the past –including the current instant- it was singlymarked and its input transition fired and its output transition did not fire since then, –again, including the current instant-. With such a new definition, one can easily express the desired property. The axiom system should be slightly extended to formalize the behavior with multiply marked places. However, since in this case we are only interested in proving that our net will never be doubly marked in any place, it is sufficient to use axioms specifying the behavior of singly marked places and then showing that conditions leading to doubly marking never occur. At this point the proof of the desired property can be carried over along several guidelines. For instance: 1. Proving a –fairly obvious- periodic behavior 2. Proving that during a whole period no place ever get doubly marked. This in turn can be proved, e.g., by showing that the necessary condition that lead to doubly marking would imply some contradiction with te stated hypothesis on initial marking. Such a proff is fostered by the deterministic behavior of this particular net. - 10 - Analisi e progetto di sistemi critici – Formal Methods (UIC) Mid-term test May 10th, 2006 Test score: 13/10ths NB: the final score – expressed in 30ths – for the course will be obtained by adding to this score the points you will get from the homework (probably expressed in 12ths) and the score of the final test (probably expressed in 8ths). The result will be registered as the Italian course and converted into American grades for UIC. Exercise Assume that two arrays a and b, both of n elements – say, integers –, are stored in memory. Give a formal specification in terms of suitable pre- and post-conditions for a program – fragment- that: 1) checks whether a or b have repeated occurrences of the same element and stores the result of such a check in a boolean flag F1 (true if neither a nor b have repeated elements); 2) if neither a nor b have repeated elements, checks whether they are a permutation of each other and stores the result in another boolean flag F2. Write a program fragment – in a suitable “toy subset” of a normal programming language such as Pascal, C, etc.- that satisfies the above specification. Prove the partial correctness of the program you wrote. Suggestion (absolutely not mandatory!) You may split your program –and your specification, accordingly- into two components devoted to requirement 1) and 2), respectively. You can then structure your proof in the same way. In case you feel running short of time we recommend that you first set up the “structure of the exercise”, i.e. pre- and post-conditions, program, assertions in the critical points of the program, invariants; then, you may work out the details of the proof by giving priority to the second part of the proof; only later, if more time is left, you may also detail the first part of the proof. NB. You can get a good score even if you do not fill up all details! - 11 - Sketch of a possible solution (not the only one!) {n>0} begin F1 := true; i := 0; while i < n do j := i+1; while j < n do if a[i] = a[j] or b[i] = b[j] then F1 := false; fi; j := j+1; od; i := i + 1; od; n_eq := 0; i := 0; F2: = true; if F1 then while i < n and F2 do j := 0; F3 := false; while j < n and not F3 do if b[j] = a[i] then F3 := true; else j := j+1; fi; od; F2 := F3; i := i+1; od; fi; F2 := (i = n) and F2; end; { (F1 x,y (0 x < y < n a[x] a[y] b[x] b[y])) F2 F1 x (0 x < n y (0 y < n a[x] = b[y])) } Loop Invariants: Loop invariant for the first outer while: I1 = { (F1 x,y (0 x < i 0 y < n x y a[x] a[y] b[x] b[y])) i n } Loop invariant for the first inner while: J1 = { I1 (F1 y (i < y < j a[i] a[y] b[i] b[y])) i < j n } After the first (outer) while, we are able to prove: K = { (F1 x,y (0 x < y < n a[x] a[y] b[x] b[y])) } Loop invariant for the second outer while: - 12 - I2 = { F2 x (0 x < i y (0 y < n a[x] = b[y])) i n } Loop invariant for the second inner while: J2 = { I2 j n (F3 y (0 y < n a[i] = b[y])) (F3 y (0 y < j a[i] b[y])) } Partial Correctness Proof: We split the proof into: 1. { Pre } F1:=true; i:=0; { I1 } 2. { I1 i < n } first outer loop body { I1} 3. { I1 i n } {K} 4. {K} n_eq:=0; i:=0; {(I2 F1) K} 5. {(I2 F1) K} if … fi; {F1 (I2 i n)}, which is reduced (after trivial case discussion) to: { I2 i < n F2 } second outer loop body { I2 } 6. {(F1 (I2 (i n F2))) K} F2:= (i = n) and F2; {Post} Steps 1, 3, 4, and 6 are trivial. Let us consider step 2, which is: 2. { I1 i < n } j:=i+1; while … od; i:=i+1; {I1} After backward substitution through the last statement, I1 becomes: I1’ = { (F1 x,y (0 x i 0 y < n x y a[x] a[y] b[x] b[y])) i < n } So, we prove: 2.1. { I1 i < n } j:=i+1; { i < n J1 } 2.2. { i < n J1 j < n } if … fi; j:=j+1; { I1 i < n J1 } 2.3. { I1 i < n J1 j n } { I1’ } 2.1. is easy, once we notice that the interval i < y < i+1 is empty. 2.2. is split into then and else branches, that is, respectively: 2.2.1. { i < n J1 j < n (a[i]=a[j] b[i] = b[j]) } - 13 - F1 := false; j:=j+1; { I1 i < n J1 } 2.2.2. { i < n J1 j < n (a[i] a[j] b[i] b[j]) } j:=j+1; { I1 i < n J1 } 2.2.2. is done straightforwardly by backward substitution; for 2.2.1. note that (a[i]=a[j] b[i] = b[j]) i < j implies y (i < y j (a[y] = a[i] b[y] = b[i])), for y = j, as required by the backwardsubstituted expression, as F1 is false in this branch. For 2.3, note that we have j = n, so I1 and J1 imply I1’ (in particular, note that I1 implies that y (0 y < i a[i] a[y] b[i] b[y], by “switching” x and y). Let us finally consider step 5, which is: 5. { I2 i < n F2 } j:=0; F3:=false; while … od; i:=i+1; { I2 } This is split into: 5.1. { I2 i < n F2 } j:=0; F3:=false; { J2 i < n } 5.2. { J2 i < n j <n F3 } if ...fi; { J2 i < n } 5.3. { J2 i < n (j n F3) } F2:=F3; i:=i+1; { I2 } Let us consider 5.3.: by backward substituting I2 we get: { I2’ } = { F3 x (0 x i y (0 y < n a[x] = b[y])) i < n } We have to show { J2 i < n (j n F3) } { I2’ }. If F3 is false, then j n, so j = n, and we have to show that x (0 x i y (0 y < n a[x] b[y])). Notice that F3 false and J2 imply y (0 y < j=n a[i] b[y]), so the goal follows for x = i. If F3 is true, then we have to show that x (0 x i y (0 y < n a[x] = b[y])). From J2, we have y (0 y < n a[i] = b[y])) and from I2 (which is part of J2), we have x (0 x i y (0 y < n a[x] = b[y])): The goal follows by combining the two formulas. Let us move to 5.1., which amounts to proving that { I2 i < n F2 } implies J2 where we substitute 0 for j and false for F3, that is: { I2 j n y (0 y < 0 a[i] b[y]) } { I2 j n } So the implication is immediate (as the interval 0 x < 0 is empty). Let us finally consider the longer step 5.2.; after using the inference rule for the if, it becomes: 5.2.1.{ J2 i < n j <n b[j] = a[i] F3 } F3:=true; { J2 i < n } 5.2.2. { J2 i < n j <n b[j] a[i] F3 } j:=j+1; { J2 i < n } For 5.2.1., let us backward substitute through the assignement, thus reducing to prove that { J 2 i < n j <n b[j] = a[i] F3 } implies: - 14 - { I2 j n y (0 y < n a[i] = b[y])) } I2 is part of J2, and j < n is stronger thhan j n. Moreover, y (0 y < n a[i] = b[y])) is true for y = j < n, since b[j] = a[i]. For 5.2.2., let us backward substitute through the assignement, thus reducing to prove that { J 2 i < n j <n b[j] a[i] F3 } implies: { I2 j < n (F3 y (0 y < n a[i] = b[y])) (F3 y (0 y j a[i] b[y])) } Note that F3 is false, so basically we just have to prove y (0 y j a[i] b[y]), as I2 and j <n are both in the antecedent and the consequent. J2 and F3 imply that y (0 y < j a[i] b[y]); moreover we have b[j] a[i]. So, overall, y (0 y j a[i] b[y]), as required. Comments: Another, faster, solution would have ordered the two arrays, so that both checks can be performed in linear time. The partial correctness proof could have reused the results from the ordering algorithms. - 15 - Analisi e progetto di sistemi critici Formal Methods (UIC) Final test, June 14, 2006 Exercise 1 (points 5/8ths) Consider the following version of timed PNs: A constant time is attached to each place. Its meaning is that, once a token has been produced in place P with associated time k, it can be used to fire an output transition of P only after k time units elapsed since its creation. Formalize the behavior of this type of nets through suitable TRIO axioms. You may assume reasonable simplifying assumptions, if needed (e.g. the same as we adopted to formalize PNs à la Merlin and Farber). Exercise 2 (points 6/8ths; to be done only after Exercise 1!) With reference to Exercise 1, assume now that a pair of constant values is attached to each place P: [mP, MP], whose intuitive meaning is that a token must abide in P at least m P but not longer than MP, if the (an, in the general case) output transition of P can fire within such an interval. Axiomatize this enriched version of TPN with time associated with places. In doing so you may notice that a few ambiguities may arise when interpreting the above intuitive semantics. In particular, what happens if a token has not been consumed within the time associated with the place where it is? Does it stay there forever or is it simply “destroyed”? If it stays there is it possible to deposite another token in the same place still assuming the net as 1-bounded (given that the previous token is definitely lost)? Clearly point out such possible ambiguities; take a choice you deem as reasonable –with appropriate short explanation- and formalize the net behavior accordingly. - 16 - Solution of Exercise 1 Let us adopt the same simplifying assumptions as for M&F TPNs. This means that we should consider only fragments such as those depicted below: s r v P P v mP mP s Q mQ Figure (a) Figure (b) Furthermore each place can store at most one token. Under these assumptions, a suitable set of axioms to formalize the behavior of such nets is the following: (Ist): fire(r) UpToNow(fire(r)) (Mar): marked(P) (Sinceie( fire(v), fire(s)) (fire(s) fire(v)) (LB.(a)) fire(v) Lastedie (marked(P), mP) (LB.(b)) fire(v) Lastedie (marked(P), mP) Lastedie (marked(Q), mQ) Notice that the absence of upperbounds de facto produces a weak time semantics with little difference w.r.t. untimed PNs (only delays in the firing sequences are introduced). Solution of Exercise 2 First, we must decide what happens with “lost tokens”, if any. A reasonable assumption is that they are destroyed if not consumed within the given interval: in such a way they do not hamper the behavior of the net, still allowing it to remain 1-bounded. A different choice would be less “dramatic” if the constraint of 1-boundedness were relaxed. Next, notice that the behavior of the net fragment depicted in Figure (a) now becomes the same as in the M&F nets: it is sufficient to add the axiom: (UB.(a)) Lastedie (marked(P), MP) fire(v) Also, axiom Mar is still valid for this fragment. - 17 - The situation becomes a little more intricate for the fragment of Figure (b). If we assume that, once a token cannot be used to fire its output transition anymore, it “disappears”, the axiom Mar should be rewritten as: (Mar): (Up_to_now ( marked(P) fire(r) Lastsie( fire(v), k) k MP) Lastsie(marked(P), k) (Up_to_now (marked(P) fire(v)) Now_On ( marked(P)) Lastedie (marked(P), MP) Now_On ( marked(P)) marked(P) Lastsie( fire(r), k) Lastsie ( marked(P), k) With a similar axiom for place Q and transition s. Finally the upperbound axiom for fragment (b) can be restated in the following way: (UB.(b)) Lastedie (marked(P), MP) Lastedie (marked(Q), mQ) Lastedie (marked(Q), MQ) Lastedie (marked(P) mP) fire(v) Notice that a different –still strong time- semantics could impose a transition to fire only when both input places have been marked for their maximum time interval. In this case, however, we should allow a token to stay in its place for more than the maximum time and still be usable if it could not be consumed earlier. - 18 - Analisi e progetto di sistemi critici – Formal Methods (UIC) Mid-Term Test: Hoare’s method part May 9th, 2007 The present mid-term test accounts for about 1/3 of the whole exam. Thus, its evaluation will be given in 10ths. However, particularly good solutions could obtain even more than 10/10ths. Consider the following problem: Given an array of n positive integers, determine whether or not there are two elements x, y in the array such as x = y2. Formally specify the requirements for an algorithm to solve such a problem, in terms of pre- and post-condition; then code an algorithm by using a suitable pseudocode (e.g. Pascal- or C-like) and prove its partial correctness. Remarks 1. Any reasonable algorithmic solution –with related proof– will be accepted; however, one that optimizes efficiency in terms of asymptotic time complexity will provide extra benefits in the evaluation. 2. There is no need to develop all details of the proof –and of the algorithm’s code: in particular the use of suitable “library” algorithms, provided they are well and formally specified, does not require their coding and correctness proof. - 19 - Hints for possible solutions The Hoare’s style specification in terms of Pre- and Post- conditions can be formalized as follows: {n >= 1 i(1 <= i <= n a[i] > 0)} P {found j,k(1 <= j <= n 1 <= k <= n j ≠ k a[j] = a[k]2} We outline two possible solutions, with different efficiency. 1. A standard solution would be based on two nested loops that scan the whole array: found is initialized to false for every j, a is scanned with index k to see whether a[k]2 for some k (and k is different than j) if and when such a k is found, variable found is set to true and loops are exited (obviously they are exited at the end of the array if the equality test is failed). = a[j] This solution has an asymptotic worst-case time complexity of (n2). Correctness proof sketch The core of a suitable invariant for the external loop (additional details depend on implementation details), assuming that j is the running index of the external loop and k for the internal one, could be: (found w(1 <= w < j z(1 <= z <= n z ≠ w a[w] = a[z]2))) (found z(1 <= z <= n a[j] = a[z]2 z ≠ j)) Note that we assume that the loop is exited immediately after found is set to true, otherwise the second conjunct of the invariant should include an existential quantification over the range [1..j). Similarly, the core of a suitable invariant for the internal loop could be: I = { (found w(1 <= w < j (z(1 <= z <= n z ≠ w a[w] = a[z]2)) (p(1 <= p < k p ≠ j a[j] = a[p]2)))) (found k ≠ j a[j] = a[k]2) } Also for the internal loop we assume it’s exited immediately after found is set to true. 2. A more efficient solution would consist in: sort the array a - 20 - o sorting should be such as merge-sort performed by means (n.log(n)) of algorithm, for every j, search the array a for an element a[k] such that a[j] = a[k]2 o searching should be performed by by applying a suitable modification of a binary search algorithm of logarithmic complexity; o since this search should be repeated for every j in the worst case, the total complexity of this step is (n.log(n)) Overall, this solution has an asymptotic worst-case time complexity of (n.log(n)). Correctness proof sketch By implicitly assuming that the contents of array a is not altered by the sorting algorithm, but only re-ordered, we can split our job into the following steps: {n >= 1 i(1 <= i <= n a[i] > 0)} SORT {n >= 1 i(1 <= i <= n (a[i] > 0 j(1 <= j < n a[j] <= a[j+1]))) } SEARCH {found j,k(1 <= j <= n 1 <= k <= n j ≠ k a[j] = a[k]2} By skipping the implementation and correctness proof of the SORT part – as it’s already provided in suitable “libraries” (see e.g. the text-book) – the SEARCH part could consist, for each j, in a suitable adaptation of the classsical binary search algorithm, such as the following one. Moreover, a preliminary check should verify whether one of the particular cases a[1] = a[2] = 1 or a[1] = 1 a[2] occurs. If a[1] = a[2] = 1 the search is already finished succesfully; otherwise, the following algorithm is run for each j starting from 2 if a[1] = 1 a[2] and starting from 1 otherwise. l:=1; u:=n+1; while l < u do k := (l+u-1) div 2; if a[k]2 < a[j] then l := k+1 else u := k fi od After dealing separately with the special case a[1] = a[2] = 1, the correctness proof could be centered on a core invariant for the outer loop (the one over j) similar to invariant I under the additional hypothesis (a[1] = a[2] = 1), and on the other following core invariant for the inner loop (i.e., the binary search itself) under the same hypothesis: l<=u p((1 <= p < l a[p]2 < a[j]) (u <= p <= n a[p]2 >= a[j])) h(1 <= h < n a[h] <= a[h +1]) - 21 - Analisi e Progetto di Sistemi Critici: seconda parte Formal Methods: second test June 19th, 2007 Exercise This exercise is worth 12 points if you do not use the hint that is available at your request; if you use the hint you can obtain at most 8 point. You are given one hour for this exercise. In the –simplified- axiomatization of Merlin & Farber timed PNs we used the following axiom to define the fact that a place is marked (in the case of 1-bounded nets): (Mar): marked(P) (Sinceie( fire(v), fire(s)) (fire(s) fire(v)) where s and v are, respectively, the only input and output transitions of P. We also commented that, through this axiomatization marked is a predicate that can hold only in left-closed, right-open intervals. There is however, a particular case where the above axiomatization would be inadequate (in the sense that it would produce behaviors of the net that do not correspond to the intuitive semantics one would like to attach to the net: precisely it would make the presence of the place practically useless). Point out such a particular case and suggest how you could fix the above axiomatizaztion in order to avoid the undesired semantics. Also, briefly discuss the consequences of your choice in terms of the property of the marking condition under the new formal semantics. Warning Notice that, in order to focus our aximomation on the essential aspects of timed PNs semantics, we overlooked formalizing the initial marking of the net. You may do the same here. However, if you feel more comfortable with a more precise problem definition you may assume (as we did in the KRC example) that for an initially marked place P (SomP (marked(P)) holds and the above axiom (Mar) is augmented as: (Mar1): marked(P) (SomP (marked(P) AlwP( fire(v))) (Sinceie( fire(v), fire(s)) (fire(s) fire(v)) - 22 - Hint The exception arises if the input and output transitions of P coincide: - 23 - Solution In the case of the figure above, by applying the normal axiom we would obtain that P is never marked if not initially marked or it becomes unmarked right after the first firing of v and then remains unmarked forever since both Sinceie( fire(v), fire(s)) and (fire(s) fire(v) cannot be satisfied if s = v (notice that Sinceie( fire(v), fire(s)) requires fire(s) in the past and then no firing of v since then: impossible if s = v). Notice also that in any case we do not admit a 0 firing time for s = v since this would be a loop of 0-time transitions. A possible escape is to assume that a marking holds only in open time intervals. This could be achieved by modifying axiom Mar as: (Mar2): marked(P) (Sinceei( fire(v), fire(s)) (and Mar1 similarly for the initialization). I.e., P is marked if and only if its input transition fired in the past and its output transition did not fire yet (including now). Thus, at the instants when a transition fires, its output place is not marked. As a further comment, this assumption would be quite reasonable for dense time models; in the case of discrete time models it would have the consequence that if say, s fires at 0 and v at time 1, then P is marked at 1 and not at 0: acceptable but perhaps not very intuitive. - 24 - Analisi e Progetto di Sistemi Critici Formal Methods July 17th, 2007 NB: the assigned time is 2 hours and 30 minutes. The score obtained will be added to the one obtained in the homework to produce the final score of the whole exam. Some electric car windows behave in the following way: There is a button which can be pushed in two different ways: push up and push down; The user can push the button –in either direction- either “instantaneously” or can he keep it pushed for a while; o If the button is pushed instantaneously the window starts moving in the chosen direction and keeps moving until either it reaches the fully closed (or fully open) position or the button is pushed again in any way. o If the button is kept pushed for a while, the window starts moving in the chosen direction and keeps moving until either it reaches the fully closed (or fully open) position or the button is released. Exercise A (9 points) Formalize the above rules by using TRIO (the use of TRIO+ or ArchiTRIO to describe the “structure of the system” would be welcome but is by no way mandatory). For the sake of simplicity you may assume that the speed of the window is the same and constant (say, k cm/sec) in both directions. Suggestion One possible way of formalizing the notion of “instantaneous push” is to assume that it lasts less than a –small- time quantity (e.g. 1/10 sec). Alternatively, you may assume it is an event in the traditional mathematical meaning of the term and formally distinguish between instantaneous push and lasting push. In this case the former approach seems more realistic, but the latter one would be welcome as well. Exercise B (9 points) - 25 - Give and formalize some sufficient conditions that guarantee that, in whichever position p is the window at any time, it reaches the fully closed position within h seconds (of course, you must state a relation among the speed of the window, the distance between fully closed and fully open positions, and the time h). Then, build a formal proof of such a guarantee. - 26 - Exercise C (6 points: it is highly recommended that you do this exercise only if and after you are confident of a good solution of exercises A and B) Use a timed Petri net to formalize –part of- the rules regulating the movement of the window. You may use the following simplifying assumptions: Consider only one direction of the movement –and, consequently, only one mode of pushing the button (e.g., only upwards); Formalize only the stopping condition given by the pushing or releasing pushing the button and neglect the condition given by the reaching of the fully closed position. Suggestion: You are allowed to enrich the normal syntax of Petri nets by introducing “asynchronous events” modeled by arcs that enter a transition without an input place, as depicted in the figure below. asynchronous “triggering event [n, m] In this case the timed semantics of the transition firing could be defined as: “once a token is in the input place(s) the transition fires if and only if the triggering event occurs within the interval [n , m] (unless disabled in the mean while of course). - 27 - Sketchy solutions Exercise A Define predicates P_U (Push Up) and P_D (Push Down); Stop (the window is stopped); M_U (Moving Up), M_D (moving down). Define also variable P (position); P = 0 meaning window fully open; P = C, meaning window fully closed. Assume that “instantaneous pushing” means that pushing lasts less than 1/10 sec. Then some movement rules are formalized as follows: (Lasts (P_U, r) r < 1/10 (Lasts (P_U, 1/10) Stop) Until (M_U, (P_U P_D P = C)) (Lasts (P_U, r) r ≥ 1/10 Stop) Until (M_U, (P_U P = C)) (P = p Lasts (M_U, s) s (C – p)/k) Futr (P = p + k*s, s) (P = C Lasts ((M_U M_D), s)) Futr (P = C, s) … Exercise B Two sufficient conditions that guarantee Within (P = C, h) (h = C/k) are: Lasts (P_U, h) and (Lasts (P_U, r) 0 < r 1/10 Stop Futr (Lasts ((P_U P_D), h-r), r) Of course proving the goal in the first case is easier, though it is not the most comfortable way of achieving it . Exercise C The following fragment uses two events: Start_push and Stop_push (for symmetry, we consider only one direction): it formalizes the facts that if the user starts pushing the button when the window is stopped and stops pushing immediately, then the window keeps moving (until a next pushing); otherwise, the window stops moving as soon as the user stop pushing. The fragment does not formalize the position of the window. - 28 - Stop Start_push Stop_push Moving Pushing Stop_push [0, 1/10] Not_Pushing - 29 - [1/10, ] Analisi e progetto di sistemi critici – Formal Methods (UIC) Mid-Term Test: Hoare’s method part May 7th, 2008 The present mid-term test accounts for about 1/3 of the whole exam. Thus, its evaluation will be given in 10ths. However, particularly good solutions could obtain even more than 10/10ths. The following program fragment – coded in C (not in Pascal!) – is intended to copy a string of characters – contained in array Input and terminated by the special character ’%’ – into an array Text of length MaxLength. The length of Input is greater than MaxLength which in turn is greater than 0; The string stored in Input does not contain further occurrences of ’%’ besides the one terminating the string; The whole string must be copied into Text, including ’%’; If the input string cannot be fully stored into Text, variable Error must be set to TRUE; otherwise it must be set to FALSE. You are required to: 1. Formally specify the above requirement for the program fragment in terms of Pre and Post conditions. 2. Prove the fragment’s correctness with respect to the specification, or disprove it. 3. If the fragment is incorrect with respect to the specification, fix it and prove the fixed version correct. { Counter = 0; x = Input[0]; Text[Counter] = x; while (x != '%' && Counter < MaxLength) { Counter++; x = Input[Counter]; Text[Counter] = x; } if (Counter == MaxLength && x != '%') Error = TRUE; else Error = FALSE; } - 30 - Sketch of the solution A precondition formalizing the hypotheses is the following: { MaxLength > 0 i (i >=0 Input [i] = ‘%’ j (j < i Input [j] ‘%’) )} Then, a postcondition formalizing fragment’s requirement is the following: { i (i >=0 Input [i] = ‘%’ i > MaxLength –1 Error = TRUE i < MaxLength (Error = False j (j i Text[j] = Input [j])) } Notice: as usual, we implicitly assume that the “input variable Input” is not affected by the program fragment. The proposed fragment is incorrect in a fairly subtle way: in fact, if the input string, including the terminal character %, is longer than MaxLength it produces an attempt to assign a value to Text[MaxLength] which should result into a run-time error (but we know that such errors are not always signaled by the execution!), thus making the final check about the value of counter occurring “too late”. To guarantee freedom for such an error one should prove as a precondition to any assignment to Text[Counter] the invariant assertion {0 Counter MaxLength–1}, which, however, is clearly not guaranteed by the fragment and can be easily disproved (probably in a more apparent way than by testing the program). Once discovered the error we can simply fix the program in the following (or similar) way: { Counter = 0; x = Input[0]; Text[Counter] = x; Counter++; while (x != '%' && Counter < MaxLength) { x = Input[Counter]; Text[Counter] = x; Counter++; } if (Counter == MaxLength && x != '%') Error = TRUE; else Error = FALSE; } - 31 - The new fragment can be proved correct by means of the following “core invariant” (details are omitted): {{0 Counter MaxLength j (j < Counter Text[j] = Input [j])} Notice however that, in order to guarantee freedom from the run-time error consisting of assigning a value to a non-existing array element we should also add a proof that {0 Counter MaxLength–1}always holds before any assignement to variable Text[Counter]: this can be proved in our case thanks to the fact that within the loop body of the fixed version at the point where Text[Counter] is assigned variable Counter has not been changed yet and therefore the loop condition Counter < MaxLength still holds. Important remark on solution evaluation A solution which considered the fragment as correct and prove it vas such without explicitly requiring freedom from the run-time error would be evaluated anyway as “good enough”. - 32 - Analisi e Progetto di Sistemi Critici Formal Methods June 18th, 2008 NB: the assigned time is 2 hours. The score obtained will be added to the ones obtained in the first midterm test and in the homework to produce the final score of the whole exam. A server serves three devices which generate asynchronous requests. Two of them, say D1 and D2, are identical and may generate no more than one request every 10 time units. The third one, say D3, is different and generates at most one request every 20 time units. As soon as it is available the server begins serving any pending request nondeterministically; it takes exactly 2 time units to serve requests from D1 and D2 and 3 time units to serve requests from D3. After serving any request, the server is available again to serve further requests. Formalize the above system by means of a suitable timed PN. Then prove by means of TRIO formulas and deductions that the system behaves in such a way that every request will be served. Optional part (it is strongly recommended that the optional part is taken only after completing the basic part). Modify the previous formalization in such a way that D3 has priority over D1 and D2, without being allowed to preempt them; in other words: if a request comes from D3 before or simultaneously with other requests, D3 is preferred; if it comes while the server is serving another request, the pending request is first finished and then D3’s request is served immediately. If useful/necessary, you may enrich the basic timed PN formalism in such a way that it can better formalize this new policy. Then, prove that in this case not only any request is served but also that any request by D3 is served within k time units (specify the value of k). - 33 - Outline of a possible solution. The following timed PN is a suitable description of the basic system (no priority) t1 [10,] t2 t3 [10,] [20,] S P1 P2 P3 [0,0] [0,0] s1 [2,2] s2 f1 f2 [0,0] s3 [2,2] f3 [3,3] Notice that the above net is not conflict-free. Thus the simplified axiomatization must be extended to deal with conflicts, by stating a mutual exclusion on the firing of s1, s2, s3, e.g. by using a XOR in the UB axioms. Notice also that the net is potentially unbounded but the timing is such that any place will never be more than single-marked. Thus, the axiomatization can be extended only in a way that just the occurrence of a double-marking is formalized and then it is proved that such an event never occurs (see e.g. the exercise proposed in the June 15, 2005 test). Informally, it is clear that in the worst case the three transitions generating the requests fire together; then, there is time to serve the three of them before anyone can fore again. To formalize the above reasoning one should state that: Initially only S is marked If, say, t1 fires when P2 and P3 are not marked, then f1 fires within 2 time units If t1 fires when P2 and/or P3 are marked, then in the worst case s1 fires within 5 time units; at that time P2 and P3 are certainly not marked; therefore s1 fires and f1 fires within 2 more time units. The firing of t2 and t3 is dealt with similarly. Optional part - 34 - A natural way to deal with the optional part is to exploit inhibitor arcs: an inhibitor arc joining P3 with the output transitions of P1 and P2 gives priority to the serving of P3. Then, by exploiting a suitable formalization of the behavior of timed PNs with inhibitor arcs (see e.g. Exercise 1 of the final test of June 2003) the proof proceeds in a similar way as in the basic case. - 35 - Analisi e Progetto di Sistemi Critici: parte Hoare Formal Methods: Hoare part June 17th, 2009 Consider the problem of factorizing a positive integer number as the product of powers of prime numbers: for instance: 99 = 32*11 ( also = 20*32*50*70*111); 250 = 21*53; 3528 = 23*32*72; … We want to build a program (fragment) that, given a positive integer number n, computes the exponents of the prime numbers factorizing n: for instance, the result corresponding to 99 should be [0,2,0,0,1], etc. For the sake of simplicity you may assume that: n is already stored in the core memory (as usual, we may forget about I/O) an array of positive integer, Prime, is also already stored in the memory. Prime contains, in increasing order all prime numbers: 2, 3, 5, 7, 11, 13, … Prime is conceptually infinite: you may neglect its bounds the program fragment must build an array Exp that stores all powers that should be applied to the prime numbers to obtain n, including the 0’s up to the maximum prime number whose exponent is not 0. For instance, in correspondence of 99 Exp should be the above array [0,2,0,0,1]. For Exp too you may neglect the fact that it is conceptually unbounded and build it only up to the last exponent greater than 0. With reference to the above problem, do, in the suggested order, the following actions: 1. Give a formal specification of the problem by means of suitable Pre- and Post-conditions. 2. Write a program fragment (by using a typical Pascal-like or C-like minilanguage) that solves the problem. 3. For each loop of your program write an invariant suitable to prove the partial correctness of your program with respect to the given specification. Briefly sketch how such a proof could be arranged: at this stage you do not have to fully develop the proof: just give a few lines of explanation of how you could build it: e.g. through suitable lemmas. 4. Briefly sketch how you could build a termination proof. Again, you do not have to fully develop the proof: just provide the essential elements thereof, e.g., the chosen well-founded set(s) and an indication of how the loop body (or bodies) transforms the values within such set(s). Optional part to be carried over only after completing the previous items. 5. Complete the missing details in the partial correctness proof 6. Complete the missing details in the termination proof. - 36 - Hints for the solutions 1. Possible pre and post conditions: PRE: {n > 1 i (i 1 prime (Prime(i) (Prime(i) < Prime(i+1)))) x (prime (x) j (x = Prime(j))} /* prime (x) means that x is a prime number; its formal definition is omitted*/ i 1 POST: {n = (Prime(j)Exp(j))} j 1 2. A possible Pascal-like program fragment: begin i := 1; RIS := n; while RIS > 1 do k := Prime(i); c := 0; while (1 < RIS and RIS mod k = 0) do RIS:= RIS div k; c := c +1 end; Exp(i) := c; i := i+1; end end 3 (and part of 5). A possible invariant for the external loop is the following: i 1 IEXT: (n = (Prime(j)Exp(j))* RIS) RIS 1 j 1 In fact IEXT trivially holds after initialization and implies the postcondition at loop exit thanks to the negation of the loop condition. Backwards propagation of IEXT through Exp(i) := c; i := i+1; yelds i IEXT*: (n = (Prime(j) if j = i then c else Exp (j))* RIS) RIS 1 j 1 IEXT* itself, with the addition of k = Prime(i), can be assumed as an invariant for the inner loop. - 37 - In fact, it obviously implies itself, without the addition; furthermore the clause i (n = (Prime(j) if j = i then c else Exp (j))* RIS) is clearly preserved through the body (c is increased j 1 by 1 and RIS is divided by k, i.e. Prime(i)). RIS 1 is maintained through RIS:= RIS div k thanks to the loop condition 1 < RIS and RIS mod k = 0. Finally backwards propogation of IEXT* through k := Prime(i); c := 0; is obviously implied by IEXT itself plus RIS > 1. 4 (and part of 6). Clearly, the essential trace of program execution is driven by the values assumed by RIS: in fact RIS takes value over N (a well founded set); the invariant states that it is always 1; furthermore, at every iteration of the inner loop its value is decreased. Thus, the inner loop certainly terminates. Proving the termination of the external loop is definitely more intricate. The proof can go along the following lines: consider the difference RIS – Prime(i): it takes values over integers; observe however that actually it is always in N (RIS - Prime(i) 0 is invariant): in fact at every loop iteration RIS is either prime, and therefore there must exist a value i such that RIS = Prime(i), or it is not and therefore i, j, h such that RIS = Prime(i)* Prime(j)* h (this is actually an inductive proof that every positive integer can be (uniquely) factorized as the product of powers of prime numbers). At every iteration the difference RIS - Prime(i) is decreased and therefore the loop is eventually exited. - 38 - Analisi e Progetto di Sistemi Critici Formal Methods June 23, 2009 NB: the assigned time is 2 hours. The score obtained will be added to the ones obtained in the first test (on Hoare’s method) and in the homework to produce the final score of the whole exam. Minor adjustments would be possible. Consider the following slight generalization of the KRC problem, say it QRC: Whereas in KRC we consider just one train in one track, we now assume that any number of trains can go through the only track. Trains however are coming at a time distance from each other of at least time units. All trains are obviously running in the same direction; opening and closing the gate takes as usual time units and cannot be interrupted; the time taken by the trains to go through the various region are the usual ones ([dm, dM], [hm, hM]). 1. Formalize the new version QRC as a suitable timed PN. 2. Assume that > dM + hM + . Then prove –or disprove!- by means of a suitable TRIO axiomatization that: a. The net is still 1-bounded. NB: this fact must be proved by means of a suitable extension of the “normal axiomatization”, it cannot be assumed as an a priori hypothesis. b. The safety property, i.e., whenever a train is in the critical region the gate is closed, is still guaranteed. Notice that, in order to prove that a net is 1-bounded you must first formalize the fact that more than one token is stored in a place: this just to express the fact that such a situation does not occur; then the axiom system can be used to prove that such a fact never occurs. You do not have to provide a full axiomatization suitable to cope with any general net and any possible property: it is sufficient that you provide enough definitions, axioms, and rules so that the above property can be proved. Optional part (to be done only after having completed the main part!) Would it be possible to prove properties a. and/or b. even with a value of < dM + hM+ . ? If so, which constraint on should be assumed to prove both properties? Should the “policy” of the gate be arranged accordingly? How? - 39 - Sketch for a solution 1. The TPN below, a slight modification of the one formalizing the KRC, enriches it by adding the possibility the trains arrive at a distance in time of at least between each other. Track QRC TPN Enter_R_Signal Arrived Gate [, ] Enter_R In_R [dm, dM] Go_down Enter_I [dm - , dm - ] Exit_I [] Stop_down Closed Exited_I Stop_up [] Opening Closing In_I [hm, hM] Open Exit_I_Signal Go_up [0, 0] [0, 0] 2. Hints for a possible axiomatization and proof The simplified axiomatization assumes a priori that the net is 1-bounded. Here, in principle, we must also formalize the fact that more than one token is stored in a place: this just to express the fact that such a situation does not occur. If we do not strive for full generality, we can formalize this fact by a formula that states that a place is “doubly-marked” iff sometimes in the past –including the current instant- it was singlymarked and its input transition fired and its output transition did not fire since then, –again, including the current instant-. With such a new definition, one can easily express the desired property. The axiom system should be slightly extended to formalize the behavior with multiply marked places. However, since in this case we are only interested in proving that our net will never be doubly marked in any place, it is sufficient to use axioms specifying the behavior of singly marked places and then showing that conditions leading to doubly marking never occur. At this point the proof of the desired property can be carried over in a fairly similar way as to the normal proof of the KRC. The main difference is that Lemma 3, i.e., - 40 - Every transition of the net of Figure KRC TPN can fire at most once Must be replaced with a different but similar one such as e.g., Every transition of the net of Figure KRC TPN can fire at most once during a time interval < Then, the whole proof of the safety property of the KRC can be arranged for the QRC accordingly (e.g., the sentence “Since, by Lemma 2.B, Go_Down could not fire before a firing of Enter_R, then when Enter_R fired q instants in the past …” becomes “Since, by Lemma 2.B, Go_Down could not fire before a firing of Enter_R within the last time interval, then when Enter_R fired q instants in the past …). Optional part If is > dM and dM > hM , (a reasonable but necessary assumption) then no train “accumulates” in the R and in the I region. However, in this case we could have a token in In_I when the gate is still opening, thus violating the safety property. Instead, if > dM + 2., (or > dM + ,and dM dm > ) and the Go_Down command is issued immediately, i.e. with time bounds [0, 0], then, when a new train is in the critical region there has been enough time to complete the opening and close again the gate. Other more sophisticated options could consist of preventing opening the gate at the arrival of a new train or interrupting the opening. This would require major changes in the PN structure, possibly introducing inhibitor arcs or other changes in the model. - 41 - Analisi e Progetto di Sistemi Critici Formal Methods June 29, 2011 Version 1 NB: the assigned time is 2 hours. The score obtained (expressed in 10ths) will be added to the ones obtained in the first test (on Hoare’s method) and in the homework to produce the final score of the whole exam. Minor adjustments would be possible. Consider the following “timed version” of the dining Philosophers problem. Each philosopher is initially out of the dining room. At some time, within given, finite and non-null bounds, he enters the room, sits at the table and starts thinking. The thinking lasts an unspecified time bounded by a finite interval; after thinking for such a time the philosopher gets hungry and tries to get the forks at his sides, if they are available: he picks up any fork as soon as it is available but cannot grab both forks simultaneously; the time necessary to grab a fork can be neglected w.r.t. other time durations. If and when he gets both forks, he immediately starts eating and eating lasts a time bounded by a fixed finite interval (whose lower bound is > 0). However, if after a fixed time during which he has been holding one fork he did not succeed to get the other one, then he shall release the fork he is holding (and will remain hungry). After eating, if ever, he will release the two forks and start thinking again. Exercise 1 (points 3.5) Formalize the above informal description by means of a suitable timed Petri net (TPN). Exercise 2 (points 3.5) “Axiomatize” the TPN you built by means of suitable TRIO formulas, i.e. provide TRIO axioms that express adequately the semantics of your TPN. Remark: most likely your net will be 1-bounded but not conflict-free: thus you will have to apply some change to the axiomatization given in class. You do not have to achieve full generality, however: it is sufficient that you provide enough axioms to specify the behavior of your particular net. Exercise 3 (points 2.5) Specify in TRIO the property that your net is deadlock-free (perhaps it could be useful to informally premise what exactly means being deadlock-free for a TPN, or for your TPN in particular). Exercise 4 (points 3) Outline a TRIO proof that the net is indeed deadlock-free. You do not have to develop all details of the proof, but give at least a sketch thereof that formalizes the main steps of the proof and provides enough evidence that possible omitted details can be easily completed. - 42 - Hints for the solution(s) Exercise 1 The following fragment of TPN specifies the behavior of the generic Philosopher Ph[i] Rel_F[i+1] [k, k] F_Avail[i+1] 0 Out[i] Enter[i ] Think[i] Th-Hu[i] G_F[i+1] Hungry[i] Hold_F[i+1] Start_E”[i] [0, 0] Eat[i] [0,0] 0 [m1, M1] G_F[i] [m2, M2] Hold_F [i] [0, 0] F_Avail[i] 0 [0,0] [k, k] Rel_F[i] - 43 - Start_E’[i] Exercise 2 With respect to the original axiomatization we must take into account the conflicts for F_Avail and Hold_F. Without aiming at full generality, for Hold_F[i] – F_Avail[i+1] we could state, e.g.: Marked(Hold_F[i]) Sinceii((Fire(Start_E[i] Fire(Rel_F[i]), Fire(G_F[i])) (Fire(G_F[i] (Fire(Start_E[i] Fire(Rel_F[i]) (Lastedie(Marked(Hold_F[i]), k) (Fire(Start_E[i]) Fire(Rel_F[i]) (UpToNow(Marked(Hold_F[i]) (Fire(any-input-tr of_F[i+1])) (Fire(G_F[i] Fire(any-input-tr of_F[i+1])) Lastedie(Marked(Hold_F[i]), k) Lastedie(Marked(Hold_F[i+1]), k) Fire(Start_E’[i]) (Lastedie(Marked(Hold_F[i]), k) Fire(any-input-tr of_F[i+1])) Lastedie(Marked(Hold_F[i+1]), k) /*this is redundant*/ Fire(Start_E’[i]) Fire(Rel_F[i] … and symmetrically; (UpToNow(Marked(Hungry[i]) Marked(F_Avail[i] Marked(F_Avail[i+1])) … Fire(G_F[i]) Fire(G_F[i+1] …. - 44 - Exercise 3 In general, an untimed PN is considered deadlock-free if there is always some enabled transition. For timed PNs with strong time semantics one could consider as a deadlock situation even one where no transition is forced to fire (e.g. if all enabled transitions have an infinite upperbound, so that “nothing happens in the net. In this case, however, given that there are no transitions with infinite upperbound, stating that there exists always at least one enabled transition and that there will always be a transition that will have to fire is actually the same thing. Thus a possible TRIO specification is the following: Alw(SomF(s(Fire(Tr[s])) or Start_E[i], etc. where Tr[s] denotes, for simplicity, any transition, either Enter[i], Exercise 4 The following semi-formal outline of a proof can be easily detailed and formalized in TRIO: Lemma 1: /*after initialization*/ i(Futr (AlwF (Marked(Think[i]) Marked(Hungry[i]) Marked(Eat[i])), M1) /*each philosopher either is thinking or is hungry or is eating*/ Marked(Think[i]) SomF(Fire(Th-Hu[i]) /*similarly for Eat[i]*/ /* thus, let us consider the case Marked(Hungry[i])*/ Marked(Hungry[i]) Marked(Hold_F[i]) Fire(G_F[i+1]) Fire(Start_E[i] /*similarly for other cases*/ (Marked(Hungry[i]) Avail[i]) (Marked(Hold[i-1] Marked(Eat[i-1]) Marked(Hold[i-1] SomF(Fire(Rel[i-1] SomF(Fire(Start_E[i-1])) /* thus, there exists always some transition that will fire in the future*/ - 45 - Analisi e Progetto di Sistemi Critici Formal Methods June 29, 2011 Version 2 NB: the assigned time is 2 hours. The score obtained (expressed in 10ths) will be added to the ones obtained in the first test (on Hoare’s method) and in the homework to produce the final score of the whole exam. Minor adjustments would be possible. Consider the following “timed version” of the dining Philosophers problem. Each philosopher is initially out of the dining room. At some time, within given, finite and non-null bounds, he enters the room, sits at the table and starts thinking. The thinking lasts an unspecified time bounded by a finite interval; after thinking for such a time the philosopher gets hungry and tries to get the forks at his sides, if they are available: he picks up any fork as soon as it is available but cannot grab both forks simultaneously; the time necessary to grab a fork can be neglected w.r.t. other time durations… but perhaps it might be convenient to consider it as non-null, to avoid some subtle “trap”!. If and when he gets both forks, he immediately starts eating and eating lasts a time bounded by a fixed finite interval (whose lower bound is > 0). However, if after a fixed time during which he has been holding one fork he did not succeed to get the other one, then he shall release the fork he is holding (and will remain hungry). After eating, if ever, he will release the two forks and start thinking again. Exercise 1 (points 3.5) Formalize the above informal description by means of a suitable timed Petri net (TPN). Exercise 2 (points 3.5) “Axiomatize” the TPN you built by means of suitable TRIO formulas, i.e. provide TRIO axioms that express adequately the semantics of your TPN. Remark: most likely your net will be 1-bounded but not conflict-free: thus you will have to apply some change to the axiomatization given in class. You do not have to achieve full generality, however: it is sufficient that you provide enough axioms to specify the behavior of your particular net. Exercise 3 (points 2.5) Specify in TRIO the property that your net is deadlock-free (perhaps it could be useful to informally premise what exactly means being deadlock-free for a TPN, or for your TPN in particular). Exercise 4 (points 3) Outline a TRIO proof that the net is indeed deadlock-free. You do not have to develop all details of the proof, but give at least a sketch thereof that formalizes the main steps of the proof and provides enough evidence that possible omitted details can be easily completed. - 46 - Hints for the solution(s) Exercise 1 The following fragment of TPN specifies the behavior of the generic Philosopher Ph[i] Rel_F[i+1] [k, k] F_Avail[i+1] 0 Out[i] Enter[i] Think[i] Th-Hu[i] G_F[i+1] Hungry[i] Hold_F[i+1] [0, 0] Eat[i] [, ] 0 [m1, M1] G_F[i] [m2, M2] Hold_F [i] Start_E[i] F_Avail[i] 0 [, ] [k, k] Rel_F[i] Notice that the time to grab a fork has been set to [,] assuming as a negligible (w.r.t. other time constants) but non-null constant. This will help avoiding a little “trap” in the TRIO axiomatization. - 47 - Exercise 2 With respect to the original axiomatization we must take into account the conflicts for F_Avail and Hold_F. Without aiming at full generality, for Hold_F[i] we could state, e.g.: Marked(Hold_F[i]) Sinceii((Fire(Start_E[i] Fire(Rel_F[i]), Fire(G_F[i])) (Fire(G_F[i] (Fire(Start_E[i] Fire(Rel_F[i]) (Lastedie(Marked(Hold_F[i]), k) (Fire(Start_E[i]) Fire(Rel_F[i]) (UpToNow((Marked(Hold_F[i]) (Marked(Hold_F[i+1]) (Marked(Hungry[i])) Lastedie(Marked(Hold_F[i]), k) Lastedie(Marked(Hold_F[i+1]), k) Fire(Start_E[i]) (UpToNow ((Marked(Hold_F[i]) (Marked(Hold_F[i+1]) (Marked(Hungry[i])) Lastedie(Marked(Hold_F[i]), k) Lastedie(Marked(Hold_F[i+1]), k) Fire(Start_E[i]) Fire(Rel_F[i] …. Similar axioms are stated for F_Avail[i]: Lastedie((Marked(Hungry[i]) …, ) Fire(G_F[i]) Fire(G_F[i+1] Notice however, that, in this case, if the firing time of _F[i] and G_F[i+1] was set to just [0.0], simply stating that G_F[i] and G_F[i+1] cannot fire together would lead to a risk of contradiction since, on the one hand G_G[i] could fire now, excluding the firing of G_G[i+1], but on the other hand, G_G[i+1] could then fire “immediately after”, that would mean … “still now”. Therefore assuming a firing time of [,] for both transitions would be both more “natural” and more consistent in terms of logic deduction: yet another example of the tricky situations that may arise with 0-time actions! - 48 - Exercise 3 In general, an untimed PN is considered deadlock-free if there is always some enabled transition. For timed PNs with strong time semantics one could consider as a deadlock situation even one where no transition is forced to fire (e.g. if all enabled transitions have an infinite upperbound, so that “nothing happens in the net. In this case, however, given that there are no transitions with infinite upperbound, stating that there exists always at least one enabled transition and that there will always be a transition that will have to fire is actually the same thing. Thus a possible TRIO specification is the following: Alw(SomF(s(Fire(Tr[s])) or Start_E[i], etc. where Tr[s] denotes, for simplicity, any transition, either Enter[i], Exercise 4 The following semi-formal outline of a proof can be easily detailed and formalized in TRIO: Lemma 1: /*after initialization*/ i(Futr (AlwF (Marked(Think[i]) Marked(Hungry[i]) Marked(Eat[i])), M1) /*each philosopher either is thinking or is hungry or is eating*/ Marked(Think[i]) SomF(Fire(Th-Hu[i]) /*similarly for Eat[i]*/ /* thus, let us consider the case Marked(Hungry[i])*/ Marked(Hungry[i]) Marked(Hold_F[i]) Fire(G_F[i+1]) Fire(Start_E[i] /*similarly for other cases*/ (Marked(Hungry[i]) Avail[i]) (Marked(Hold[i-1] Marked(Eat[i-1]) Marked(Hold[i-1] SomF(Fire(Rel[i-1] SomF(Fire(Start_E[i-1])) /* thus, there exists always some transition that will fire in the future*/ - 49 - Analisi e Progetto di Sistemi Critici: parte Hoare e dual language Formal Methods: Hoare and dual language parts July 13th, 2011 Exercise 1 (10 points) Consider the following problem: given two arrays of characters, a of length H and b of length K, with H > K, compute how many times the string stored in b occurs as a substring of that stored in a. Formally specify the problem as suitable pre- and post- conditions according to Hoare’s method. Notice that the above defintion of the problem could be interpreted in different wasy, if so, state clearly but informally your own interpretation in such a way that it can be confronted with the formal specification. Write a program in a normal mini-language that solves the problem Prove the correctness of your program with respect to your specification As usual you may neglect I/O assuming that input and output variables are already stored in memory. Exercise 2 Consider a generator of events which generates events, say E, at a distance of no less than M seconds. 1. (4 points) Specify in TRIO the property that, after generating K instances of E the generator must definitely stop and cannot generate anymore other events. 2. (5 points) Build a timed Petri net (TPN) that models the above desired behavior of the instrument, assuming, for simplicity, K = 3. 3. (Optional part) Prove that the TPN you built in point 2 above does guarantee the property specified in point 1 (again assume in this case K = 3). Hint: if the axioms we used in class do not match the TPN you built you should preliminarly reformulate the axioms in such a way that the proof becomes possible (and of course, they are sound). NB, very important: the optional part will be evaluated only if the previous evaluations of Exercise 1 and of points 1, 2, of Exercise 2 will assign at least 9 and 8 points respectively. NB2: the available time is 2 hours and 45 minutes. - 50 - A possible TPN for point 2 of Exercise 2. [M,] [,], 0 < < M [0,0] - 51 - Analisi e Progetto di Sistemi Critici: parte Hoare Formal Methods: Hoare part May 24th, 2012 Assume that two large arrays of exactly n (n could be in the order of G or more) elements are stored in main memory. They store alphabetic characters. Consider the problem of stating whether or not their contents are a permutation of one another. With reference to the above problem, do, in the suggested order, the following actions: 1. Give a formal specification of the problem by means of suitable Pre- and Postconditions. 2. Write a program fragment (by using a typical Pascal-like or C-like minilanguage) that solves the problem. Your algorithm should possibly minimize both space and time complexity; in particular, the two original arrays should remain unaffected by the algorithm execution. 3. Prove the correctness of your program 4. Discuss the complexity of your algorithm. When evaluating –whether informally or formally- the space complexity of your algorithm you should not consider the size of the two arrays as part thereof, since they are considered as pure input. NB If useful, you can extend the basic mini-language by introducing some syntactic construct, preferably chosen among those normally available in standard programming languages; in such a case you should add suitable proof rules to carry over correctness proofs of programs that include the added constructs. - 52 - Hints for the solution 1. It is well-known that a permutaion of the integer interval I = [1 .. n] is a bijection of I into itself, i.e., a function f: I --> I such that f(i) f(j) for i j. Thus the content of array a is a permutation of the content of array b iff there exists such a bijection f such that for every 1 i n, a[f(i)] = b[i]. Formalizinng this original definition in first-order predicate calculus, however, may turn out to be rather cumbersome since it would require to fake the quantification w.r.t. function f, which is syntactically not allowed. Thus, we suggest to adopt the following necessary and sufficient condition that guarantees the desired property as an alternative definition thereof. (the proof of the equivalence between the two’s could be given informally, for instance by induction on the length of the arrays, with a syntax other than first-order-predicate calculus to avoid going back to the original difficulty). The content of a is a permutation of (the content of) b iff for every character ch {a, …, z} {A, …, Z} the number of occurrences of ch in a equals the number of its occurrences in b. As usual, we formalize recurisvely the number of occurrences of ch in the fragment of array z included between indexes [1,…k] as k = 1 #(z, ch, k) = if z[1] = ch then 1 else 0 k > 1 #(z, ch, k) = if z[k] = ch then #(z, ch, k-1) + 1 else #(z, ch, k-1) At this point specifying the above problem–and designing an algorithm for its solution- can follow a fairly standard path. {1 i n a[i] {a, …, z} {A, …, Z} b[i] {a, …, z} {A, …, Z} Program {Permutation ch ((ch {a, …, z} {A, …, Z}) #(a, ch, n) = #(b, ch, n) ) 2., 3., 4. An algorithm to solve the problem with O(n) time complexity and O(1) space complexity (at uniform cost criterion) could use two arrays aCounter[A, …, z] and bCounter[A, …, z] (with a little waste due to the ASCII characters between Z and a) where to store the number of occurrences of each (alphabetic) character in a and in b, respectively. After computing such arrays, it would simply compare their contents. Thus, it would be based on three simple sequential loops: the post conditions of the first two ones would be, respectively ch ((ch {a, …, z} {A, …, Z}) #(a, ch, n) = aCounter[ch] ch ((ch {a, …, z} {A, …, Z}) #(b, ch, n) = bCounter[ch] the third loop checks the identity of aCounter and bCounter. Each one of the three loops would be associated with a fairly natural invariant. For instance, let i be the loop variable: ch ((ch {a, …, z} {A, …, Z}) #(a, ch, i) = aCounter[ch] - 53 - Obviously aCounter should be initialized to 0 for all its elements. Remark If one wished to code the body of the loops counting the number of occurrences of the characters in the arrays by using the pure mini-Pascal, or mini-C language, she would be compelled to write 50 nested if-then-else statements to check the value of a generic a[i] element and to update the corresponding counter. To avoid such a heavy notation, it would be useful to enrich the original mini-lanaguage by a typical case or switch construct; the adaptation of the original if-then-else proof rule to the new construct would be straightforward. As another option, you could design (two) internal loops, one ranging over [A..Z] and one ranging over [a..z], that for every character in those ranges check whether it coincides with a[i], etc. Finally, an even more efficient solution, would consist in adopting a Pascal-like language construct that allows for using the character that is stored in a[i] as the index of the counting array, i.e., using directly a[i] as the index of aCounter. Notice, however, that all above implementation choices, though fairly different in the final code, would not affect the overall asymptotic complexities of the algorithm which would remain O(n) and O(1), respectively, despite some non neglectable differences within the same order of magnitude. - 54 - Analisi e Progetto di Sistemi Critici Formal Methods for Concurrent and Real-time Systems June 27, 2012 NB: the assigned time is 3 hours. The points obtained (expressed in 10ths, but the maximum reachable score could be higher) will be added to the ones obtained in the first test (on Hoare’s method) and in the homework to produce the final score of the whole exam. Minor adjustments would be possible. Major recommendation: the proposed exercise(s) have many degrees of freedom which ask you to take several choices among various options. You are strongly recommended to reflect deeply on the implications of the possible choices before committing to, and beginning to work on, them. The overall goal of this test is to come up with a reasonable axiomatization of untimed PN semantics, so that relevant properties thereof could be proved according to a typical dual-language approach. Somewhat paradoxically, the suggested (but not imposed!) idea is to take inspiration for the axiomatization of timed PNs. This can be pursued in various ways: some of them are proposed here, but, again, not imposed: You could consider untimed PNs as a particular case of the timed ones, where each transition is labeled by [0, ] bounds. You could implicitly assume a “discrete-logic time domain”, in the sense that, as it is often implicit in other discrete state machine, one time unit is associated with the firing of one (or more!) transition. o This approach could be formalized in TRIO, e.g., by assuming that time is discrete and that the effect of transition(s) firing becomes visible at Dist( *, 1) from the current instant. o The use of TRIO as the logic formalism, however, is not mandatory and, if you like, you could resort to the typical temporal logic operator “next” –here denoted as X- where X(P) means that property P holds in the next system state. In this case X(X(P)) would mean that property P is “reached” in two steps …(see also the appendix). Notice that, in one way or another, some “hidden time metric” is nevertheless introduced, as it happens with other abstract machines, where, the time unit is the transition occurrence. Once this is stated, here is what you are asked to do, recommending to stick to the proposed sequence: 1. State clearly which type of PN you are considering: you are free to restrict attention to suitable subclasses of general PN, e.g. by applying the same or other restrictions as those used in our classes. Take into account, however, that generality and suitability to model practical systems are appreciated qualities. In particular, state clearly whether: a. Your nets are (1)-bounded b. Your nets allow or not for conflicts c. … - 55 - Notice also that some of the approaches proposed above could still allow for 0-time transition firings, but this would lead back to a truly timed version of PN and therefore should be excluded. 2. State informally, but precisely, the semantics of your nets. In particular, focus on the two fundamental approaches to untimed PN semantics: a. Interleaving semantics assumes that only one transition fires at time, so that the behavior of the net is described as a set of sequences of transition firings; b. Truly concurrent semantics instead allows for “simultaneous” firings of several enabled transitions, provided they are not in conflict. Notice that in this case still other options are possible: i. A maximum parallelism approach assumes that all enabled, not conflicting transitions fire contemporarily; ii. In a more flexible setting only a subset (nondeterministically chosen) of the enabled transitions fires at any time. c. In general, however, I recommend that your semantics implies at least “a little amount of strength”, i.e., that, if some transition is enabled, then at least one of them fires. 3. Formalize the chosen PN semantics in terms of the logic approach you chose. The logic language should also allow you to formalize meaningful properties of the nets (deadlock, reachability, starvation, …). 4. Apply your axiomatization to prove some meaningful property of a sample net of your (nontrivial) choice. For instance (but again, you are free to take a different choice), it would be interesting to prove that the net of figure below, under the maximum parallelism semantics guarantees that no one of the two processes –represented by the two sides of the net- ever starves; but the same property does not hold for a different semantics or if place P3 initially stores only one token. P1 P2 t1 t2 P3 P4 P5 t3 t4 P6 P7 t5 t6 Appendix, for those who decide to use classical temporal logic but are not fully familiar with it. Here are the standard temporal logic operators: X(P), next: P will hold in the next state G(P), always: P will always hold in the future (usually including now, but the other choice is possible) F(P), sometimes in the future P U Q, until: P will hold until Q (weak and strong versions possible) I also suggest defining recursively Xk(P): P will hold after k steps. - 56 - Hints on one possible solution Main assumptions and choices, among the many possible ones 1. First observe that whichever “untimed semantics” ends up with being based on firing sequences; this actually means assuming an implicit time structure where one firing “step” –which is not necessarily the firing of one transition- corresponds to one time unit. 2. Thus, we can exploit the basic TRIO operator by stating that the effect of one firing step occurs at time distance 1 from the current time: e.g. present marking firing of some transitions Dist(new-marking, 1). 3. Then, we assume some kind of strong time semantics in the sense that if, in given state, some transition is enabled, then some transition among the enabled ones does fire. 4. We do not restrict the number of tokens that can abide in a place, thus we assume unbounded nets, 5. We allow for conflicts, i.e., the same place can be in the postset and in the preset of several transitions; however, for simplicity we assume that at most one arc connects a place to a transition and conversely. Notice that the classical net of the figure above satisfies these conditions. 6. For simplicity we also assume that the same transition cannot fire more than once at any instant even if, say, all places in its preset store more than one token. At this point a “natural axiomatization” of such nets can go along the following lines: 1. For every transition t and place P let their pre- and post-sets be defined in the usual way: pre(P), post(P), … 2. For every place P marked(P,n) with n 0 states that P stores exactly n tokens at the current instant. 3. Then, we define transition enabling trying to formalize the fact that t is enabled iff P in preset(t) marked(P, n) n 1 holds. However, here we have a difficulty due to the possibility of conflicts: for instance in the figure above both t3 and t4 are enabled but if P stores only one token only one of them could fire. a. If we assume a pure interleaving semantics, this difficulty is easily overtaken since the semantics imposes that only one transition can fire at any instant. Thus, we can proceed as follows: i. t(enabled(t) (P (P preset(t) (marked(P,n) n 1)) ii. t (enabled(t)) (t1 (enabled(t1) fire(t1) t2(t2 t1 fire(t2)))) iii. t(fire(t) (P (P preset(P) (marked(P,n) n 1 Dist(marked(P,n-1), 1)) (P (P postset(P) (marked(P,n) Dist(marked(P,n+1), 1)) b. The formalization becomes considerably more complex if we want to deal with a true concurrency semantics, because in this case we must manage the relation between the number of tokens in a place and the number of enabled conflicting transitions. A further complexity arises from the exponential increase in the level of nondeterminism with respect to the number of conflicting transitions and of tokens in the places: think, e.g. to a place with n tokens and m output transitions with m > n. Thus, we assume the simplifying hypothesis, suggested by the figure above, that at most two transitions are in the postset of every place. In this case the axiomatization can proceed with a fairly natural generalization of the above one; we propose here the case of maximum parallelism: i. t(enabled(t) (P (P preset(t) (marked(P,n) n 1 ii. t (enabled(t) (P (P (preset(t) postset(P) = {t})) fire(t) iii. (P,t1, t2(t1t2{t1, t2} = postset(P) (marked(P,1) enabled(t1) enabled(t2)) fire(t1) fire(t2)) iv. (P,t1, t2(t1t2{t1, t2} = postset(P) (marked(P,2) enabled(t1) enabled(t2)) fire(t1) fire(t2)) - 57 - v. …. 4. At this point formalizing and proving net properties can follow a fairly standard path. For instance with reference to the figure above the property that both processes, represented respectively, by transitions [t1, t3, t5] and [t2, t4, t6] never starve can be captured by the formula Alw(Futr(fire(t1) fire(t2))). 5. Proving the above property under the maximum parallelism assumption is fairly easy since it is immediate to realize and to formally prove that the following sequence of concurrent (and therefore parallel) firings is indefinitely repeated: {t1,t2}; {t3,t4};{t5,t6}. Notice however that the property does not hold is the maximum parallelism hypothesis does not hold or if P3 stores only one token instead of two. 6. Non trivial and non requested remark. As usual, in presence of nondeterminism, liveness or reachability properties are much harder to express and prove within this type of logic formalism because they must assess the existence of one possible path that leads to a given –wished or feared- configuration. - 58 - Analisi e Progetto di Sistemi Critici: parte Hoare e dual language Formal Methods: Hoare and dual language parts July 11th, 2012 Exercise 1 (9 points) It is well known that the classical binary search algorithm has a O(log(n)) time complexity (under the uniform cost criterion). Prove this claim by means of Hoare’s method. Hint As usual you may assume that the input data are already stored in an array. For simplicity you may also assume that the array elements are integer numbers. Thus, you should code your algorithm in such a way that it is easy to express its time complexity by means of first-order formulas for pre- and post-condition. Remember that you do not have to prove the functional correctness of the algorithm but its (asymptotic) complexity. Exercise 2 The movement of modern, high speed trains is regulated, among many others, by the following protocol (inspired by, though consideraby simplified w.r.t., the reality). The train can proceed at a given speed only as long as a “movement authority” granted by the ground subsystem, is active. Periodically, with period K, the train sends to the ground subsystem a message containing relevant informations about its state; the message is decomposed into two packets which are sent through two independent channels. Each channel may either deliver the message correctly within H time units or fail: failing means either not delivering the message at all or delivering a corrupted one (within H time units). As soon as the ground subsystem receives the two packets it verifies that they are correct and that the whole message contained in the two packets is such that the train can safely cotinue its trip. o In the positive case it sends back to the train an OK message o In the negative case it sends a NOT OK message This operation takes a constant time M since the time both packets are received. However, if only one packet is received and the other one is not received within N time units, then even the received packet is discarded. Both replies from the ground could fail to be delivered to the train, but if they do not fail they are delivered within P time units. If at least one OK message is not received by the train every time units the movement authority if not granted anymore (and the train must stop or slow down). - 59 - Exercise 2.1 (5 points) Formalize the above rules about granting or not the movement authority by means of a TPN (you may assume that initially the train possesses the movement authority). Exercise 2.2 (4 points) Formalize as a TRIO formula the property that the movement authority is granted as long as (if and only if) none of the steps defined above (sending packets, verifying them, etc.) fail. Exercise 2.3 (Optional part: 4 points) Briefly sketch a proof of the above property. Hint. It is likely that your net exhibits some conflict; in this case, preliminarly you should state at least the main lines of an appropriate axiomatization. You do not have to go in all details neither of the axiom system nor of the proof. NB, very important: the optional part will be evaluated only if the previous evaluations of Exercise 1 and of points 1, 2, of Exercise 2 will assign at least 8, 4 and 3.5 points respectively. NB2: the available time is 2 hours and 45 minutes. - 60 - Sketchy solutions Exercise 1 Whichever program is written to code the binary-search algorithm, it is convenient to add a dummy variable, say t, to measure the –order of magnitude of- algorithm’s complexity, for instance: begin bottom := 1; top := n; found := false; t := 1; while bottom <= top do m := (bottom + top) div 2; if y == a[m] then found := true; bottom := top + 1 else if y < a[m] then top := m -1 else bottom := m + 1 t := t +1 end Since, under the uniform cost criterion, every execution of the loop body takes a constant time (better: takes a time bounded by a constant), at the end of program execution the value of the t variable will be proportional to –and therefore in the same class as- the execution time. Thus, a suitable specification of the desired property is {n >= 1 (and a is sorted)} P {k (t <= k.log(n)} A suitable (core of) invariant to build a proof of the property should state a natural relation between the number of loop iterations, t (-1), and the size of the array portion still to be searched, say I: 2(t-1) <= 2.n /(top – bottom + 2) It clearly holds at initialization and, together with bottom = top + 1, guarantees the postcondition. Its invariance can be proved in the usual way. For instance, in the case y > a[m], backwards propagation of (top – bottom + 2) through bottom := m + 1 yelds top – ((bottom + top)/2 + 1) + 2 = (top – bottom)/2 + 1; since (top – bottom + 2) = 2. ((top – bottom)/2 + 1) 2(t-1+1) <= 2.2.n /(top – bottom + 2) - 61 - A possible TPN for Exercise 2.1 NOT OK Movement authority [] [0P] [H] fail packet1 [0P] fail [P, P] [NN] delivered1 [H] [00] fail [KK] [H] Synthesize-packets [NN] packet2 delivered2 fail fail [H] OK Exercise 2.2 The following formula states (in abbreviated form) that, if no transition labeled “fail” will ever fire, then the movement authority will be granted forever: AlwF ( fail ( fire(fail))) AlwF (marked (movement authority)) Sketch on how to approach Exercise 2.3 The above TPN exhibits some conclicts; thus, we cannot immediately apply the simplified axioms. On the other hand, rather than resorting to a fully general axiom system, we can enrich a little the simple one by formalizing by means of the exclusive OR operator the facts that if a place with a conflict becomes marked, then, within a given time either one of its output transitions will fire; e.g.: Becomes(marked(packet1) t ( t H (Futr(fire(fail1), t) Futr(fire(not-fail1), t))) Becomes(marked(delivered1) (Within (Becomes(marked(delivered2), N) Futr(fail-packet1, N) …. Becomes(marked(delivered1) (marked(delivered2) fire(synthesyze-packets) …. - 62 - At this point the hypothesis that the failing transitions will never fail (of course, the NOT OK case must be considered as a failure) imposes that only the path that leads to the transition that restates the movement authority can happen: thus, if K + H + P , the property easily follows. - 63 - Analisi e Progetto di Sistemi Critici: parte Hoare Formal Methods: Hoare part May 6th, 2013 Exercise Consider the following problem. Two arrays A, of size n, and B of size m < n, store natural numbers. NB: if this may be helpful for your solution you may assume that m < n < 2m. The problem consists in deciding whether the two sets stored in A and B coincide. 1. Write a formal specification of the above problem by means of Hoare’s style pre- and post-conditions. 2. Write a C-like or Pascal-like program to solve the problem. 3. Prove the correctness of your program with respect to the specification. Warning Although the main goal of the problem is to prove the correctness of the algorithm, the algorithm complexity is a factor that affects the quality of your solution… and therefore its evaluation. - 64 - Hint for the solution 1. Specification: Pre: {m < n i (1 i n A[i] N 1 i m B[i] N} P Post: {OK (i (1 i n j (1 j m B[j] = A[i]) (i (1 i m j (1 j n B[i] = A[j])) } 2. Given that n and m are approximately of the same order of magnitude, (n.log(n)) = (m.log(m)) < (n.m) = (n2). This remark suggests to first sort the two arrays, (better, to build sorted versions therefof, say A1, B1, if we do not want the algorithm to change their content), then to apply the following algorithm which, thanks to the sorting hypothesis, has a complexity O(n); as a result we obtain a global algorithm of complexity O(n.log(n)), whereas the “natural one” would require an O(n.m) complexity: {Pre} A1 := Sort(A); B1 := Sort(B) {i (1 i < n A1[i] A1[i+1]) i (1 i < m B1[i] B1[i+1])} P1 {Post} Given that various sorting algorithms with O(n.log(n)) complexity are already well-known with corresponding correctness proofs, let us focus on the design of P1 and its correctness. P1: k := 1; h := 1; OK := True; A1[n+1] := B1[m+1] := /* denotes a value greater than any possible number stored in A and B*/ while (k n h m) OK do if A1[k] = B1[h] then k := k+1; h := h+1 else if A1[k] < B1[h] then {k := k+1; if A1[k] B1[h] A1[k] A1[k-1] then OK := False} else /* A1[k] > B1[h] */ {h := h+1; if A1[k] B1[h] B1[h] B1[h-1] then OK := False} od Clearly the above algorithm has O(n+m) = O(n) complexity. Let us sketch how to prove its correctness. As usual, the core of the proof consists in finding a suitable invariant. In this case the goal of the loop is to keep the OK variable at the True value as far as no element is found in A1 or B1 that does not occur in the other array: if the loop is exited with OK = False, such element has been found; otherwise both k and h will be n+1 and m+1, respectively, and the two arrays contain the same elements. - 65 - Such an invariant is formalized by the following FO formula, which is a fairly obvious restriction of the post condition to the portions of the two arrays examined at the j-th loop iteration: {1 k n+1 1 h m+1 OK (i (1 i < k j (1 j < h B[j] = A[i]) (i (1 i < h j (1 j < k B[i] = A[j])) } Its backwards propogation through the first OK := False is guaranteed by False (i (1 i < k+1 j (1 j < h B[j] = A[i]) (i (1 i < h j (1 j < k B[i] = A[j])) A1[k+1] < B1[h] A1[k+1] B1[h] A1[k+1] A1[k] sorted(A1) sorted(B1) since the subformula following the is clearly a contradiction; similarly for the symmetric case The rest of the proof, i.e., for the backwards propogation through k := k+1; h := h+1 initialization of the invariant, and postcondition, is fairly obvious. - 66 - Analisi e Progetto di Sistemi Critici Formal Methods for Concurrent and Real-time Systems June 26, 2013 NB: the assigned time is 2 hours. The points obtained (expressed in 10ths, but the maximum reachable score could be higher) will be added to the ones obtained in the first test (on Hoare’s method) and in the homework to produce the final score of the whole exam. Minor adjustments could be possible. Among the many versions of timed Petri nets (TPNs) consider the following one: The TPN can store an unbounded number of tokens in its places Time bounds are associated with transitions as in the Merlin & Farber version; however, lower-bounds –and, therefore, upper-bounds as well– must be constants strictly greater than 0. The recharge time semantics is assumed in the case of multiple transition enabling; i.e., if, after a firing the transition is still enabled, a time lower-bound must anyway elapse before the next firing. You may assume that input and output conflicts (i.e. places with multiple pre- and/or post-sets) are excluded. Provide a TRIO axiomatization of the above semantics of this type of TPNs. Is it possible to build such an axiomatization without resorting to the general schema based on the tokenF predicate introduced in the literature? In the positive case, such a solution would be highly preferred; in the negative case, besides providing an appropriate axiomatization, you should briefly explain why simpler solutions are not possible. Optional part What would you change in your axiomatization if, instead of the recharge time semantics, the more traditional one which does not prevent a transition from firing again immediately after the first firing (if the enabling conditions are verified) were adopted? - 67 - Hint for a possible solution The recharge semantics is easier to formalize than the other (and more general) one: in fact, roughly speaking, the firing of a transition depends only on the duration of its enabling (the marking of the input places) and not on which token is produced and which is consumed by transition firing. For instance, consider the fragment below P tr Q [3 – 5] Suppose that a token is produced in P at time 0 and one at time 2; one token is put in Q at 5 and one at 8; then the transition can fire at earliest at time 8; after that, it can fire again only at 11 and must fire at 13…. as it would happen with the original semantics. If instead the second token were put in Q at 6, the earliest first firing would be again at 8 but the earliest second firing could not occur before 11 unlike the original semantics which would allow for a second firing at 9. Thus the axiomatization can be based again on the (duration of the) marking of places without taking care of when tokens are generated. It is necessary, however, to generalize the predicate marking in the natural way: marked(P, n) means that P contains at the current instant exactly n tokens. Then marked(P, n) is defined as a “counter of input and output transition firings” (since 0-time lower-bounds are prohibited it cannot happen that at the same time both the input and the output transition of a single place can fire.) A lower-bound axiom for a transition such as the one in the above fragment could be: fire(tr) n,m (lasted((markedie(P, n) markedie(P, m) fire(tr)), lower-bound) n >0 m >0 nowOn (markedie(P, n-1) marked(P, m-1) /* the marking of the output places is increased by 1/* Correspondingly an upper-bound axiom could be along the following lines: n,m (n >0 m >0 lasted((markedie(P, n) marked(P, m) fire(tr)),upper-bound) fire(tr) The other axioms would follow in a fairly natural way. Optional part With the original semantics, even if forbidding 0-time firings, it would be necessary again to distinguish which token is consumed by which firing since simultaneous firings of the same transition would not be excluded. It would be therefore difficult to avoid resorting to the more general axiomatization based on predicates such as tokenF. As another option, one could still keep the count of number of tokens on the basis of simultaneous firings of input and output transitions (and the duration og their peristency in the places. Which approach should be simpler is a matter of subjective evaluation. - 68 - Analisi e Progetto di Sistemi Critici Formal Methods July 1st, 2014 Exercise 1 Let A be an array of n integers > 0 (A’s index can range between 1 and n, or between 0 and n-1). Consider the problem of finding an index i, if any, such that the sum of A’s elements whose index is < i equals the sum of the remaining upper portion of the array, i.e., those with index i. Write a formal specification in terms of pre- and post- conditions of the above problem. Write an algorithm, by using a suitable pseudocode, to solve the problem. NB: the complexity of the algorithm is a significant parameter of its quality. Prove the correctness of your algorithm w.r.t. to the formal specification by means of Hoare’s method. Exercise 2 The literature proposes many versions of untimed and timed PNs. One of the untimed ones attaches priorities to transitions: if two transitions with different priorities are enabled –whether they are concurrent or in conflict- it cannot happen that the lower priority one fires before the higher priority one. It is well known that, as well as other “enrichments” of the basic PN model, this extension has the computational power of Turing machines. Consider defining a suitable timed version of PNs with priorities attached to transitions. Syntactically the extension is easily defined: to each transition an integer number denoting its priority is attached, besides the usual pair [lower-bound, upper-bound]. Informally discuss, possibly with the help of a few examples, how such a net should behave under the assumption of weak and strong time semantics. Provide an axiomatizazion in terms of TRIO formulas of the informal semantics described above, for at least one of the two semantics (WTS and/or STS: STS is slightly preferred) As usual you may assume reasonable simplifying assumptions, typically but not necessarily, 1bounded nets and exclusion of 0-time lowerbounds; instead it would be preferable (but not mandatory) that conflicts are not excluded. - 69 - Sketchy solutions Exercise 1 1. The following pre and post conditions specify the desired property of the program (assuming a Pascal-like rather than a C-like storage of the arrays): Pre: { i (1 i n) A[i] > 0} sep1 Post: { (found TRUE ) ( Ai i 1 Ai) n i sep k 1 n i 1 i k { (found False ) k ( Ai Ai) } 2. The following O(n) Pascal/C-like program (fragment) should guarantee the above specification. { sep := 2; sum1 := 0; sum2 :=0; {for j:= 1, j++, to n do sum2 := sum2 + A[j]}; while sum1 < sum2 do {sum1 := sum1 + A[sep]; sum2 := sum2 - A[sep]; sep++;}; if sum1 = sum2 then found := TRUE else found := FALSE } 3. The correctness proof can be based on the following invariant: sum1 Inv: sep1 n i 1 i sep Ai sum 2 Ai sum1 Asep sum 2 Asep It is fairly easy to verify that Inv is indeed invariant and that it holds after executing the first initializing line of code. Then Inv ( sum1 < sum2) implies either sum1 = sum2 or sum1 >sum2; in the former case the postcondition immediately follows; in the latter one observe that formulae h sep 1 n n k 1 k 1 k s k sep h sep 1 n k 1 k 1 k s (h (h sep 1) ( Ai Ai)) (s(s sep) ( Ai Ai)) (h (h sep 1) ( Ai Ai)) (s(s sep) ( Ai - 70 - Ai)) n k sep are invariant too (they are an obvious consequence of Inv and of the fact that all elements of A are > 0). Thus, at program exit sum1 Asep sum 2 Asep sum1 sum 2 imply that i((1 i n ) ( i 1 n k 1 k i Ak Ak )) - 71 - Exercise 2 Informal discussion on a timed semantics of Timed, priority,PNs Consider the fragment depicted in figure below P3 P1 P2 [Pr1, lb1, ub1] tr1 tr2 [Pr2, lb2, ub2] Suppose that Pr1 < Pr2 and that the three input places receive a token all at the same time, say 0. In the case of WTS the following situations may arise: 1) ub1 < lb2: in this case the two intervals do not overlap, thus, even if Pr2 > Pr1, tr1 may fire within ub1; if it fires, tr2 is disabled and will not fire until a new token is put in P2; if instead tr1 does not fire within ub1, then tr2 may fire between lb2 and ub2. 2) A symmetric situation occurs if ub2 < lb1. In other words priorities have no effect in these two cases. 3) Suppose instead that the two time intervals overlap, say in [t1-t2]: a) If lb1 < t1, then tr1 may fire before t1, but b) if it does not, then a reasonable assumption is that during [t1-t2] only tr2 can fire, but, according to the WTS it does not have to; c) if tr2 does not fire within t2, then at most one of them can still fire independently on priorities. Thus, priorities have effect only in the intersection of the two intervals. Let us now consider the STS case: 1) ub1 < lb2: in this case the two intervals do not overlap; thus tr1 must fire before tr2 can; tr2 is then disabled and cannot fire until a new token is put in P2. 2) A symmetric situation occurs if ub2 < lb1. In other words priorities have no effect in these two cases. 3) Suppose instead that the two time intervals overlap, say in [t1-t2]: a) If lb1 < t1, then tr1 may fire before t1, but b) if it does not, then a reasonable assumption is that during [t1-t2] only tr2 can fire; c) if furthermore ub2 = t2, then tr2 must fire within t2 and tr1 cannot fire anymore; d) the most intricate situation is the case where ub2 > t2 (therefore ub1 = t2): in this case at t2 tr1 must fire, but it cannot because tr2 has higher priority: the only escape is that tr2 is forced to fire even if its timeout did not expire yet. - 72 - NB: the above semantics is explained with reference to conflicting transitions but can be applied even to the case of concurrent ones, with the difference that in that case concurrent transitions can fire simultaneously without disabling each other. Here below is a sample of relevant TRIO axioms formalizing the above STS, under the following simplifying hyptheses: 1) 1-bounded PN 2) lowerbounds strictly > 0 3) there are no conflicting transitions with the same priority A few preliminary axioms such as those defining a place being marked or not are assumed to be the usual ones. Define the following auxilary predicates (where the meaning of some other predicates is assumed to be intuitively understood) as follows: MayFire(tr) x((Lastedie((P(PInput(tr) Marked(P)), x)(lb(tr) x ub(tr)) TimeOutExpired(tr) ((Lastedie((P(P Input(tr) Marked(P)), ub(tr)) (TimeOutExpired(tr1) tr2((tr2 tr1Pr(tr2 > Pr(tr1))MayFire(tr2)))fire(tr1) /*if tr1 timeout exprie and there is no other transition with higher priority that can fire, then tr1 fires*/ fire(tr1) MayFire(tr1) tr2((tr2 tr1Pr(tr2 > Pr(tr1))MayFire(tr2)) (MayFire(tr1) tr2(tr2 tr1Pr(tr2 < Pr(tr1) TimeOutExpired(tr2))) fire(tr1) /*tr1 must fire if some other transition with lower priority should fire because its timeout expired*/ NB Without the third simplifying hypothesis above, this axioms could be contradictory; thus, removing the hypothesis would require a more detailed axiomatization. - 73 - Formal Methods for Concurrent and Real-time Systems June 30th, 2015 The available time is: 3 hours. Exercise 1 Let A be an array of n positive integers, stored in strictly increasing order (A’s index can range between 1 and n, or between 0 and n-1; A[i] < A[i+1]). Consider the problem of finding two indexes j, h, if any, such that the sum of A’s elements whose indexes are enclosed between j and h included, is a given integer X. Write a formal specification in terms of pre- and post- conditions of the above problem. Write an algorithm, by using a suitable pseudocode, to solve the problem. NB: the complexity of the algorithm is a significant parameter of its quality. Prove the correctness of your algorithm w.r.t. to the formal specification by means of Hoare’s method. Evaluate, not necessarily by applying Hoare’s method, but in a precise way, the asymptotic complexity of your algorithm. NB: it is not necessary that your algorithm is optimal from the point of view of (time) complexity but, of course, better complexity implies better evaluation. Exercise 2 Consider the following problem of delivering a message through unreliable channel(s): to increase reliability the message is sent to the recipient through two independent channels along the following (highly simplified) protocol: The message is duplicated and the two identical copies are sent through two independent and similar (in terms of reliability and timing behavior) channels. Each channel either delivers the message within a time bound 1 or loses it. The recipient waits for both copies: if and as soon as it receives both of them, it gets them from the respective buffers (possibly by comparing them but the chance that one of both of them are corrupted is not contemplated in this exercise) and starts working on the message; however, if after receiving only one copy there is the certainty that the other copy has been lost, then the recipient gets and works on the only received copy. Exercise 2.1 Model the above protocol by means of a suitable timed PN. You may consider the shipping and delivery of just one single message and you may choose the type of TPN you feel most appropriate for this problem but you must define it precisely, even though informally (e.g.: are conflicts admitted; strong or weak time semantics, are 0-time lower and upperbounds admitted, …?). It is preferred, but not imposed, that you do not make use of inhibitor arcs. Exercise 2.2 By means of informal but precise arguments show that your net guarantees that, unless both copies are lost, the receiver eventually gets the message within a given time bound since the message has been sent; which time bound exactly? Exercise 2.3 (Optional: this part will be evaluated only if the previous ones are solved in a satisfactory way!) Sketch a suitable set of axioms formalizing the semantics of your net and hint on how such axioms can support a formal proof of the property required in Exercise 2.2 - 74 - Sketchy solutions Exercise 1 4. The following pre and post conditions specify the desired property of the program (assuming a Pascal-like rather than a C-like storage of the arrays): Pre: { i ((1 i n) A[i] > 0) (1 i < n A[i] < A[i+1]))} h Post: { ( found TRUE ) ( Ai X ) (1 j h n) i j /*j and h could be existentially quantified but in this case they are also the program variables used in the following code*/ h { ( found False ) j, h((1 j h n) Ai X ) } i j 5. The following O(n) Pascal/C-like program (fragment) should guarantee the above specification. { sum := A[1];found := False; j := 1; h := 1; if sum = X then found := True; while h < n and not A[h] > X and not found { while sum < X do {h++; sum := sum + A[h]}; if sum = X then found := True; while not found and sum > X and j < h {sum := sum - A[j]; j++}; if sum = X then found := True; } 6. The correctness proof can be developed along the following milestones (many details are skipped): a. A suitable invariant IEXT for the external loop is: h <= n sum = h Ai i j h ( found TRUE ) ( Ai X ) (1 j h n) i j - 75 - k ( found False ) m, k (1 m k h Ai X ) i m IEXT clearly holds at loop entry. b. A suitable invariant IIN1 for the first internal loop is: h sum = Ai i j h 1 Ai X i j which produces the postcondition PostIN1 sum = h h h 1 i j i j i j Ai Ai X Ai X h Notice that PostIN1 not found implies k (1 k j Ai X ) (more i k h precisely, k (1 k j Ai X ) and this holds at every external loop i k iteration. c. Similarly, a suitable invariant IIN2 for the second internal loop is: sum = h h i j i j 1 Ai Ai X thus, its postcondition PostIN2 not found sum = h h h i j i j i j 1 imply Ai Ai X Ai X h and, therefore, k ( j k h Ai X ) and, again, this holds at every external i k loop iteration. d. This allows to prove the invariance of IEXT. The essence of the proof consists in showing that if k ( found False ) m, k (1 m k h Ai X ) i m holds and the loop body is executed completely, i.e. both internal loops are executed leaving not sum = X, then the same condition holds at the end, i.e. when h is incresed by 1; in fact if at any time it becomes sum = X then the loop is exited and the post condition immediately holds. In other words, we start with the core assumption k ( found False ) m, k (1 m k h 1 Ai X ) i m and we must prove that if we reach the end of the loop with not sum = X still holding, then k ( found False ) m, k (1 m k h Ai X ) i m in fact the first internal loop adds to all previous sums k Ai X with 1 m k h 1 i m h the sum Ai . If at loop exit, not found holds, this means that i j - 76 - k ( found False ) m, k (1 m k h 1 Ai X ) i m h k (1 k j Ai X i k Similarly, at the exit of the second internal loop with not found holding, we have h k ( j k h Ai X ) i k and therefore k ( found False ) m, k (1 m k h Ai X ) i m 7. Finally, the analysis of the three cases of exit from the external loop clearly leads to the global postcondition. Notice also that the case A[h] > X implies immediate exit from the external loop since considering any other value A[k] with k > h would be useless. The above program is clearly O(n) since both indexes j and h take, at most, once and only once all values between 1 and n. Remark A simpler program could solve the program with O(n2) complexity by means of two nested loops that, for each value of a first index build the sum of all elements starting from that index. - 77 - Exercises 2.1 and 2.2 Consider the net depicted in figure below and assume a strong time semantics. The net is clearly 1-bounded but not conflict-free; furthermore lowerbounds are assumed to avoid the tricks of 0-time firing. Message to be deliverd Message duplication [, ] Copy 2 Copy 1 [, 1] [, 1] Copy 2 is lost [, 1] [, 1] Copy 1 is lost Copy 2 stored in its buffer [+ 1, + 1] [, ] [+ 1, + 1] The message is delivered Informal analysis: The message is “immediately” duplicated, both copies within the time interval [, 1] either are stored in the respective receiver’s buffer, or are lost. If both copies are correctly stored in their bufer, the receiver immediately gets them and proceeds successfully; if only one of them is available the receiver waits for a further + 1, since it does not know how long it took to get the token in the corrisponding place; thus it can be sure that the other copy has been lost only after this time and at this point the transition with timeout + 1 fires and a token is stored in the place “The message is received”. At latest this happens, if it happens, after 2*( + 1) since the firing of Message duplication, i.e., + 2*( + 1) after intialization. Clearly the message is not received only if no token is ever deposited in places “Copy 1,2 stored in its buffer”. Hints for a possible TRIO-based axiomatization and formal proof. Given that we excluded strictly 0-time firing, we can aplpy the simplified axiomatization used in the classes, provided that we enrich it with the case of conflicts. This can be done, for a fragment such as the one in the figure below [L1, U1] R P Q tr1 tr2 [L2, U2] adding axioms of the type - 78 - Lasted(Marked(P) Marked(Q), U1) (Lasted(Marked(P) Marked(R), L2)) fire(tr1) Lasted(Marked(P) Marked(R), U2) (Lasted(Marked(P) Marked(Q), L1)) fire(tr2) Lasted(Marked(P) Marked(Q), U1) Lasted(Marked(P) Marked(R), L2) fire(tr1) fire(tr2) …. Simpler axioms are then neede for the other fragment used in the above net and to express the semantics of the lowerbounds. On the basis of these axioms a TRIO proofs formalizing the above informal reasoning can be easily built: it only requires to split the analysis into the various mutually exclusive cases. Of course the proof requires the hypothesis Always( ( (fire(Copy1 is lost) (SomeP(fire(Copy2 is lost)))) ( (fire(Copy2 is lost) (SomeP(fire(Copy1 is lost)))) ) - 79 -