• No results found

Shunting Example Revisited

N/A
N/A
Protected

Academic year: 2021

Share "Shunting Example Revisited"

Copied!
55
0
0

Loading.... (view fulltext now)

Full text

(1)Shunting Example Revisited.

(2) //The following are constants of the shunting game #define M 7; #define N 6; #define o -1; #define a 1; #define w 0; // col number: 0 1 2 3 4 5 6 var board[N][M] = [o,o,a,a,o,o,o, //0 row number o,o,a,a,o,o,o, //1 a,a,a,w,a,a,a, //2 a,w,a,a,a,w,a, //3 o,o,a,w,o,o,o, //4 o,o,a,a,o,o,o]; //5 // Black position: var r = 3; var c = 0; Game = [r-1>=0]MoveUp [] [r-2>=0]PushUp [] [r+1<N]MoveDown [] [r+2<N]PushDown [] [c-1>=0]MoveLeft [] [c-2>=0]PushLeft [] [c+1<M]MoveRight [] [c+2<M]PushRight; 2.

(3) MoveUp = [board[r-1][c]==a]go_up{r=r-1} -> Game; PushUp = [board[r-2][c]==a && board[r-1][c]==w] push_up{board[r-2][c]=w;board[r-1][c]=a;r=r-1;} -> Game; MoveDown = [board[r+1][c]==a]go_down{r=r+1} -> Game; PushDown = [board[r+2][c]==a && board[r+1][c]==w] push_down{board[r+2][c]=w;board[r+1][c]=a;r=r+1;} -> Game; MoveLeft = [board[r][c-1]==a]go_left{c=c-1} -> Game; PushLeft = [board[r][c-2]==a && board[r][c-1]==w] push_left{board[r][c-2]=w;board[r][c-1]=a;c=c-1;} -> Game; MoveRight = [board[r][c+1]==a]go_right{c=c+1} -> Game; PushRight = [board[r][c+2]==a && board[r][c+1]==w] push_right{board[r][c+2]=w;board[r][c+1]=a;c=c+1;} -> Game;. 3.

(4) //one particular potential trouble position #define trouble board[0][3] == w; //testing if a white can be pushed to ourside #define outside board[4][1] == w; #assert Game reaches trouble; #assert Game reaches outside; #define goal board[2][2] == w && board[2][3] == w && board[3][2] == w && board[3][3] == w; #assert Game reaches goal; #assert Game |= [] (trouble -> !<> goal); //show the trouble position will prevent the goal 4.

(5) Liu Yang School of Computing, NUS. 5.

(6) Outline  How to use PAT and Tips  Editing  Simulation  Verification  How to debug in PAT  Advanced Topics  Using C# Code  Model Based Testing and Verification  Real-Time Module  Summary and Road Map 6.

(7) PAT GUI. 7.

(8) PAT Editing Features  Familiar Environment with tabs.  Similar to Visual Studio, Eclipse  User friendly environment (compared to FDR, Spin and so on)  I18N Support  中文, 繁體中文, English, Deutsch, 日本語 and Việt.  The featured editors.  Syntax Highlighting  Copy/Paste, Find/Replace, Undo/Redo  Goto Line, Uncomment/Comment Selected Code.  More features       . Go to definition Rename a variable automatically Line Number Display Highlight Current Line Tag Navigation Drag and Drop a model into PAT to open it quickly Auto-update 8.

(9) Tips of Using Editor.  Parse the model first, check for the output window for the. correct parsing  P = e  P;.  Look for Error and Warning messages  Better to clear all of them to make sure the input model is correct.. 9.

(10) CSP# Language – Global Definitions  Use Constants and Enumerator  #define N 2;  enum {red, blue, green};.  Variables.  int or bool variable  var knight = 0;  var isCorrect = true;  Array  var board = [3, 5, 6, 0, 2, 7, 8, 4, 1];  var leader[3];  var matrix[3*N][10]; //multi-dimensional array  var matrix[1][6];  Range specification  var knight : {0..} = 0;  var board : {0..10} = [3, 5, 6, 0, 2, 7, 8, 4, 1];  var leader[N] : {..N-1}; //where N is a constant defined.  Array Initialization  var array = [1(2), 3..6, 7(N*2), 12..10]; //#define N 2;  same as: var array = [1, 1, 3, 4, 5, 6, 7, 7, 7, 7, 12, 11, 10];.  Channels.  channel c 5;  channel c 0;.  Propositions.  #define goal x == 0;  P = if(goal) {e -> P}; 10.

(11) CSP# Language - Process  Stop, Skip  Event prefixing  VM() = insertcoin -> coffee -> VM();  Phil(i) = get.i.(i + 1)%N -> Rest();  Data Operation  add{x = x+1;} -> Stop;  Local variable in a data operation . Event{var x = i} -> P.  Tau event  explicit: tau -> P  implicit: {var x = i;} -> P  Channel Communication  c!a.b -> P -- channel output  c?x.y -> P -- channel input  c?1 -> P -- channel input with expected value  c?[x+y+9>10]x.y-> P -- channel input with guard expression 11.

(12) CSP# Language – Process  Sequential composition  P; Q  General/External/Internal choice  P [] Q  P [*] Q  P <> Q  [] x:{1..n}@ P(x) -- which is equivalent to P(1) [] ... [] P(n)  [*] x:{1..n}@ P(x) -- which is equivalent to P(1) [*] ... [*] P(n)  <> x:{1..n}@ P(x) -- which is equivalent to P(1) <> ... <> P(n)  Conditional Choice  if (cond) { P } else { Q }  if (cond1) { P } else if (cond2) { Q } else { M } 12.

(13) CSP# Language – Process  Case  case { cond1: P1 cond2: P2 default: P }  Guarded process  [cond] P  Interleaving  P ||| Q  ||| x:{0..n} @ P(x)  ||| {50} @ P() //50 P() running interleavingly.  ||| {..} @ Q() //infinite number of Q() running in parallel.  Parallel composition  P || Q  #alphabet P {...};  Hiding  Process P \ A where A is a set of events turns events in A to invisible ones.  Hiding is applied when only certain events are interested.  Atomic process  P = atomic { a -> ch!0 -> b -> c -> Skip}; 13.

(14) Tips  if, ifa, ifb or guard condition?  if has two steps: condition checking, followed by true branch execution  ifa has one step: condition checking and true branch execution  ifb has two steps: condition checking, followed by then-branch execution, if the condition is false, the then-branch is blocked.  guard condition has one step: condition checking and then-branch execution, if the condition is false, the then-branch is blocked.  Note: ifb and guard have no else branch..  Example:  var x = 1;  P1 = if (x==1) { a -> Skip} else {b -> Skip};  P2 = ifa (x==1) { a -> Skip} else {b -> Skip};  P3 = ifb (x==1) { a -> Skip};  P4 = [x==1] ( a -> Skip); 14.

(15) Tips.  Precedence of the CSP# operators.  atomic > if > case >  > channel > guard >. ; > hiding > interrupt > [] > || > |||.  E.g.  . a  Skip ||| b  Skip == (a  Skip) ||| (b  Skip) a  (Skip ||| b  Skip).  Using extra () if not sure..  To support process local variables  Promote them into global variables  Make them as process parameters. 15.

(16) Process Parameters vs. Global Variables. Note: Channel input variables behave similarly to process parameters within their valid scope. Local variables behave similarly to global variables within their valid scope. 16.

(17) PAT Type System  The input languages of PAT are weak typing (a.k.a. loose typing). languages and therefore no typing information is required when declaring a variable.  The process parameters and channel input variables can take in. values with different types at different time.  As long as there is no type mismatch (e.g., integer is used as an array or boolean), the execution will proceed. Otherwise, invalid type casting (runtime) exception will be thrown..  Advantage: less effort.  the compiler or interpreter implicitly performs certain kinds of conversions..  Disadvantage: catch fewer errors at compile time and some of these. might still remain after testing has been completed.. 17.

(18) Assertions  Deadlock-freeness  Given P() as a process, the following assertion asks whether P() is deadlock-free or not.  #assert P() deadlockfree;  Reachability  Given P() as a process, the following assertion asks whether P() can reach a state at which some given condition is satisfied.  #assert P() reaches cond; 18.

(19) Optimizations in assertions var x = 0; var weight = 0; P() = if(x <= 14) { coin1{x = x + 1; weight =weight + 1;} -> P() [] coin2{x = x + 2; weight = weight + 1;} -> P() [] coin5{x = x + 5; weight = weight + 1;} -> P() }; #define goal x == 14; #assert P() reaches goal with min(weight); 19.

(20) LTL assertions  Linear Temporal Logic (LTL)  In PAT, we support the full set of LTL syntax. Given a process P(), the following assertion asks whether P() satisfies the LTL formula.  #assert P() |= F;  where F is an LTL formula whose syntax is defined as the following rules,  F = e | prop | [] F | <> F | X F | F1 U F2 | F1 R F2. 20.

(21) Refinement Assertions  Refinement/ Equivalence  In PAT, we support FDR's approach for checking whether an implementation satisfies a specification or not. That is, by the notion of refinement or equivalence. Different from LTL assertions, an assertion for refinement compares the whole behaviors of a given process with another process, e.g., whether there is a subset relationship. There are in total 3 different notions of refinement relationship, which can be written in the following syntax.  #assert P() refines Q() -whether P() refines Q() in the trace semantics;  #assert P() refines<F> Q() -whether P() refines Q() in the stable failures    . semantics; #assert P() refines<FD> Q() -whether P() refines Q() in the failures divergence semantics; #assert P() equals Q() -whether P() equals Q() in the trace semantics; #assert P() equals <F> Q() -whether P() equals Q() in the stable failures semantics; #assert P() equals <FD> Q() -whether P() equals Q() in the failures divergence semantics; 21.

(22) PAT Simulator. 22.

(23) PAT Simulation Features  PAT's simulator allows users to interactively and visually simulate. system behaviors..  Click the Simulate button to do a random simulation of the system.  Double click the event in the "Enabled Events" list to perform the step-by-. step simulation.  Generate Graph button will generate the complete state graph in one click.  Select any state in the "Event Trace" list, then click the Play Trace button to play the trace automatically starting from the selected state. You may go back to any previous states.  Click Reset button to reset the simulator to the initial state of the selected process..  Note: the number of states that can be generated is limited to 300 by. default. You can change this number in the system configurations.. 23.

(24) Tips of Using Simulator  Tips  You can move your mouse over the state and transition in the graph    . to see the detailed information. You can drag the node and edges in the Simulation Graph. You can adjust the simulation speed in the toolbar settings button: very fast, fast, normal, slow, very slow. You can adjust the tooltip popup delay in the toolbar settings button: 5s, 10s, 20s, 40s, 60s. You can hide all the tau transitions in the toolbar settings button. . (Demo using DP example).  Easter Eggs 24.

(25) PAT Verifiers. 25.

(26) PAT Verification Features 1.  System Fairness Settings: PAT will automatically enable the suitable. fairness options for the user according to the model and the property selected.       . No Fairness, Fairness Label Only, Event Level Weak Fairness, Event Level Strong Local Fairness, Process Level Weak Fairness, Process Level Strong Local Fairness, Strong Global Fairness.  Note: all fairness options are disabled except for LTL assertions..  Parallel Verification: This option allows user to make use of the. power of multi-core CPU to speed-up the model checking..  The system will break the model checking problems into smaller problems,. which can run in different CPU cores in parallel. This option is only effective for the verification of LTL assertions (with different fairness event annotations).. 26.

(27) PAT Verification Features 2.  Shortest Witness Trace: For all safety properties, PAT performs. Depth-First-Search to explore the state space for the purpose of fast verification. However, if there is any counterexample, it is desired to have the shortest trace to find the bug quickly. Hence, we provide this option to user such that PAT performs Breadth-First-Search to find the shortest witness trace.  deadlockfree, reachability, refinement relation.  Verbose: This option is by default disabled. Additional verification. information may be printed if this option is enabled. Note that the messages printed will be in a reversed order..  Visualize the witness traces if there one. 27.

(28) Outline  How to use PAT and Tips  Editing  Simulation  Verification  How to debug in PAT  Advanced Topics  Using C# Code  Model Based Testing and Verification  Real-Time Module  Summary and Road Map 28.

(29) How to Debug in PAT 1  PAT does not provide run-time debugger. Nevertheless, you. can easily do the debugging using variable range checking, assertions or simulator..  1) Explicitly providing the range for the global variables, e.g., var. x{1..120};. if the variable's range is out of bound in simulation or verification, PAT will throw runtime exception as the feedback.  However, this may slow down the verification speed a little..  2) Using assert(condition) process inside your program.. assert(condition) will throw a PAT runtime exception during the execution if the condition is evaluated to be false.. 29.

(30) How to Debug in PAT 2  3) Writing simple (safety) assertions on global data to check whether. they are violated or not, e.g., #assert system |= [] invariant; where invariant can be the desired property you want to guarantee..  4) If your model is small, you can quickly using simulator to trace the. behaviors of your model or generate the complete state space..  5) Model difference checking feature (beta version). 30.

(31) Finite Number of States  Model checking only work on finite number of states  But can have infinite executions  Sources of infinite behaviors  Unbounded variables values  . P = e{x=x+1}  P; P(i) = e  P(i+1);.  Unbounded processes   . P = (e  P) ||| P; P = (e  P) [] P; System = {..} P;.  Remove the infinite behaviors  Use simulator to see the patterns  Explicitly providing the range for the global variables, use deadlock assertion to see whether the variables go out of the range 31.

(32) How to speed up the verification  Reduce the range of the variables  Reduce the number of events  Use atomic to group the steps  Reduce the concurrency  Number of parallel or interleave or choices  Shorter names for variables, events, processes  Speed up the hashing process  Use ifa rather than if, when the correctness still holds  For parallel compositions, try to define the alphabets. manually  Use tau events for the events to be hidden. 32.

(33) How to reduce the memory usage  Out of Memory!.  Need to have a smaller model  Same as the previous slide  Usage more memory  Windows XP allocates 2GB memory for each process  Windows Vista/7  64 Bits systems 33.

(34) Outline  How to use PAT and Tips  Editing  Simulation  Verification  How to debug in PAT  Advanced Topics  Using C# Code  Model Based Testing and Verification  Real-Time Module  Summary and Road Map 34.

(35) Using C# Code.  Sometimes, it is difficult and inefficient to write some. functions or advanced data structures using PAT's syntax  Math calculation methods  Array, Stack, Queue and so on.  PAT supports invoking C# code in the models.  C# Library Editor and Compiler  C# classes are built as DLL  Loaded when models import them..  Two types C# code is supported  External Static Methods  Special Classes used as User Defined Data Type.  Integration with Microsoft Contracts 35.

(36) External Static Methods  Some very complicated calculations are difficult to implement in PAT's. modeling language..  algorithms, data operations and computations  It is easier to using programming language like C#..  To import the libraries in your model:.  #import "PAT.Lib.Set"; //to import a library under Lib folder of PAT. installation path #import "C:\Program Files\Intel\Set.dll"; //to import a library using absolute path.  To invoke C# methods in models, please use the following syntax:  x = call(max, 10, 2);  if(call(dominate, 3, 2))...  y = call(ArrayMax, [1,3,5]);. 36.

(37) C# Code Example  using System.Collections.Generic; using PAT.Common.Classes.Expressions.ExpressionClass;  //the namespace must be PAT.Lib, the class and method names can be arbitrary namespace PAT.Lib {  public class PatList {. public static int[] ListAdd(int[] list, int element) { List<int> newList = new List<int>(list); newList.Add(element); return newList.ToArray(); }. . }. }. public static bool ListContains(int[] list, int element) { foreach (int i in list) { if (i == element) { return true; } } return false; }. 37.

(38) Requirements for the C# Code  The namespace must be "PAT.Lib", otherwise it will not be recognized.       . There is no restriction for class names and method names. Importing the PAT Expression name space using "using PAT.Common.Classes.Expressions.ExpressionClass;". All methods should be declared as public static. You can also use (private) static variables and functions to support your methods. The parameters must be of type "bool", "int", "int[]" (int array) or object (object type allow user to pass user defined data type as parameter). The number of parameters can be 0 or many. The return type must be of type "void", "bool", "int", "short", "byte", "int[]" (int array) or user defined data type. The method names are case sensitive. Put the compiled dlls in "Lib" folder of the PAT installation directory to make the linking easy by using #import "DLL_Name"; 38.

(39) User Defined Data Type  PAT only supports integer, Boolean and integer arrays for the. purpose of efficient verification..  Advanced data structures are necessary for some models.  stack, queue, hashtable and so on.  To support arbitrary data structures, PAT provides an interface to create. user defined data type by inheriting an abstract classes ExpressionValue.  To declare the user defined types:.  var<HashTable> table; //use the class name here as the type of the variable..  To invoke the public methods:  table = new HashTable(64);  table.Add(10, 2);  if(table.ContainsKey(10)).... 39.

(40) C# Code Example 1 . using System.Collections; using PAT.Common.Classes.Expressions.ExpressionClass;. . //the namespace must be PAT.Lib, the class and method names can be arbitrary namespace PAT.Lib { public class HashTable : ExpressionValue {.  . public Hashtable table;. . /// Default constructor without any parameter must be implemented public HashTable() { table = new Hashtable(); }. . public HashTable(Hashtable newTable) { table = newTable; }. . public void Add(int key, int value) { if(!table.ContainsKey(key)) { table.Add(key, value); } } public bool ContainsKey(int key) { return table.ContainsKey(key); }.  . }. }. public int GetValue(int key) { return (int)table[key]; } 40.

(41) C# Code Example 2 /// Return the string representation of the hash table. /// This method must be overriden public override string ToString() { string returnString = ""; foreach (DictionaryEntry entry in table) { returnString += entry.Key + "=" + entry.Value + ","; } return returnString; } /// Return a deep clone of the hash table /// This method must be overriden public override ExpressionValue GetClone() { return new HashTable(new Hashtable(table)); }. }. /// Return the compact string representation of the hash table. /// This method must be overriden /// Smart implementation of this method can reduce the state space and speedup verification public override string GetID() { string returnString = ""; foreach (DictionaryEntry entry in table) { returnString += entry.Key + "=" + entry.Value + ","; } return returnString; }. 41.

(42) Using Microsoft Contracts  Run-time Assertions  Debug.Assert(condition).  Methods Contracts (part of .NET framework 4.0).  Preconditions express what program state is required for the method to run. successfully. . Contract.Requires(...);.  Postconditions tell you what you can rely upon at the completion of the. method. . Contract.Ensures(...);.  Object Invariant:guarantees about conditions that will always be true for. an object.   . Contract.Assert(...); [ContractInvariantMethod] private ObjectInvariant() {. }. Contract.Invariant(...);.  Usage:  1 Improve testing via runtime checking  2 enable static contract verification: not-null, array bound  3 documentation generation. 42.

(43) Model Based Testing and Checking  Test cases are difficult to write.  Complete coverage  Tedious to update if code is changed.  A better and simpler way to write test cases: combine. Contracts with CSP#.  Code contracts take the form of object invariants, method. precondition and post-conditions . Write the requirement and effects of the methods.  Testing plan is written using elegant high-level CSP code  Easy to specify the range  Use choices and interleave to capture the alternative executions  Can also check properties of high-level model.  Demo using DBM class. 43.

(44) Outline  How to use PAT and Tips  Editing  Simulation  Verification  How to debug in PAT  Advanced Topics  Using C# Code  Model Based Testing and Verification  Real-Time Module  Summary and Road Map 44.

(45) Real-time Systems  A system dealing with physical environment often has. real-time behaviors..  e.g., a pacemaker must react within certain critical time. frame.  e.g., a session times out after certain time..  The system model must reflect the real-time. behaviors.  Challenge: a real-time system always has infinitely many states!.

(46) Real-time Systems  Real-time system modeling and verification is. dominated by Timed Automata..

(47) Real-time Systems  Real-time system verification is dominated by Uppaal..

(48) RTS Module in PAT  An expressive modeling language which extends CSP#. with the timed constructs..  A method for abstracting and verifying the models.  Zone abstraction which reduces the number of states to finitely many.  LTL and refinement.

(49) Process Expressions Process Expression. Explanation. Wait[d1,d2]. Idle for at least d1 time units and no longer than d2 units. P timeout[d] Q. If P does nothing for d time units, it times out and Q starts. P interrupt[d] Q. P executes exactly for d time units and Q takes over.. P deadline[d]. P must terminate within d time units.. P waituntil[d]. P always take no less than d time units.. P within[d]. P must react within d time units.. 49.

(50) Demonstration  Fischer’s Mutual Exclusion example  Pacemaker. 50.

(51) Outline  How to use PAT and Tips  Editing  Simulation  Verification  How to debug in PAT  Advanced Topics  Using C# Code  Model Based Testing and Verification  Summary and Road Map 51.

(52) The Current Status  PAT is available at  http://www.patroot.com.    . 20 publications in international conferences and journals 6 modules with 60+ build in examples in 2 years time Used as an educational tool in NUS and York University 600+ registered users from100+ organizations.. 52.

(53) PAT Architecture. 53.

(54) PAT Road Map 1  GUI (version 3.0, coming in next one or two months)  . Totally new editors multiple platforms . . Mac OS, Linux, Unix. Intellisense.  Tool Development  . Language Extension Conversion other languages to CSP#  . Promela to CSP# Petri-net to CSP#.  New Modules Development and Applications  . Security Modules Sensor Network Module .  . NesC language/Tiny OS. Bio System Modules Distributed Algorithms . Specialized model checking algorithms for concurrency objects .  . linearizability,. leader election with failure garbage collector 54.

(55) PAT Road Map 2  Model Checking Techniques  Space reduction techniques  Symbolic representation techniques, e.g. BDD  Automatic detection of symmetry relations  Probabilistic model checking techniques  Support for Software Engineering  Verification of UML diagrams . State diagram.  Model Checking Real Codes . Multi-threads C# code.  Testing related . Model Based Testing 55.

(56)

References

Related documents

Therefore, the volume (or porosity) and permeability of the crack should be updated with the effective crack pressure value at each time step.. Then, equations 37

Using Ppatg30D and wild-type cells expressing BFP-SKL (BFP fused to Peroxisome Targeting Signal 1), peroxisomes were induced in methanol medium (in the pres- ence of FM4-64 to stain

These include work requirements, number and duration of exposures, heat exchange components, rest area conditions, and worker clothing (Clayton, 1978). Actions to control heat

To insure that your RockShox fork performs properly, we recommend that you have your fork installed by a qualified bicycle mechanic.. We also urge you to follow our recommendations

As we report in Table 4, the DM test statistic indicates that the reduction in forecast errors achieved by modelling daily exchange rate returns as a function of interdealer order

discharged from the trust, or refuses or becomes, in the opinion of a principal civil court of original jurisdiction, unfit or personally incapable to act in the trust, or accepts

· The study tour gave me insights about how the European Commission works and how CSR can be of positive influence on the growth of companies.

No warranty and no liability: While Givaudan is making great efforts to include accurate and up-to-date information, we make no representations or warranties, expressed or