Fundamentals of Programming

Similar documents
Informatics 2A: Language Complexity and the. Inf2A: Chomsky Hierarchy

Proof Theory for Syntacticians

Language properties and Grammar of Parallel and Series Parallel Languages

Erkki Mäkinen State change languages as homomorphic images of Szilard languages

Syntax Parsing 1. Grammars and parsing 2. Top-down and bottom-up parsing 3. Chart parsers 4. Bottom-up chart parsing 5. The Earley Algorithm

Lecture 10: Reinforcement Learning

A General Class of Noncontext Free Grammars Generating Context Free Languages

ISFA2008U_120 A SCHEDULING REINFORCEMENT LEARNING ALGORITHM

GACE Computer Science Assessment Test at a Glance

Refining the Design of a Contracting Finite-State Dependency Parser

Continual Curiosity-Driven Skill Acquisition from High-Dimensional Video Inputs for Humanoid Robots

Entrepreneurial Discovery and the Demmert/Klein Experiment: Additional Evidence from Germany

COMPUTATIONAL COMPLEXITY OF LEFT-ASSOCIATIVE GRAMMAR

MinE 382 Mine Power Systems Fall Semester, 2014

ReinForest: Multi-Domain Dialogue Management Using Hierarchical Policies and Knowledge Ontology

Parsing of part-of-speech tagged Assamese Texts

A R "! I,,, !~ii ii! A ow ' r.-ii ' i ' JA' V5, 9. MiN, ;

Learning to Think Mathematically With the Rekenrek

Grammars & Parsing, Part 1:

Evolution of Collective Commitment during Teamwork

Software Maintenance

New Features & Functionality in Q Release Version 3.2 June 2016

Controlled vocabulary

On the Polynomial Degree of Minterm-Cyclic Functions

Numeracy Medium term plan: Summer Term Level 2C/2B Year 2 Level 2A/3C

CS 598 Natural Language Processing

Seminar - Organic Computing

A Version Space Approach to Learning Context-free Grammars

Liquid Narrative Group Technical Report Number

University of Groningen. Systemen, planning, netwerken Bosman, Aart

Are You Ready? Simplify Fractions

Introduction to Simulation

Spring 2016 Stony Brook University Instructor: Dr. Paul Fodor

PowerTeacher Gradebook User Guide PowerSchool Student Information System

Modeling user preferences and norms in context-aware systems

RANKING AND UNRANKING LEFT SZILARD LANGUAGES. Erkki Mäkinen DEPARTMENT OF COMPUTER SCIENCE UNIVERSITY OF TAMPERE REPORT A ER E P S I M S

On-Line Data Analytics

Many instructors use a weighted total to calculate their grades. This lesson explains how to set up a weighted total using categories.

WiggleWorks Software Manual PDF0049 (PDF) Houghton Mifflin Harcourt Publishing Company

LEGO MINDSTORMS Education EV3 Coding Activities

CS 101 Computer Science I Fall Instructor Muller. Syllabus

School of Innovative Technologies and Engineering

TABLE OF CONTENTS TABLE OF CONTENTS COVER PAGE HALAMAN PENGESAHAN PERNYATAAN NASKAH SOAL TUGAS AKHIR ACKNOWLEDGEMENT FOREWORD

Artificial Neural Networks written examination

Constraining X-Bar: Theta Theory

Rule-based Expert Systems

PH.D. IN COMPUTER SCIENCE PROGRAM (POST M.S.)

IBM Software Group. Mastering Requirements Management with Use Cases Module 6: Define the System

Infrared Paper Dryer Control Scheme

IVY TECH COMMUNITY COLLEGE

ARNE - A tool for Namend Entity Recognition from Arabic Text

Using dialogue context to improve parsing performance in dialogue systems

Chinese Language Parsing with Maximum-Entropy-Inspired Parser

A Comparison of Charter Schools and Traditional Public Schools in Idaho

Specification and Evaluation of Machine Translation Toy Systems - Criteria for laboratory assignments

Abstractions and the Brain

Text Compression for Dynamic Document Databases

A Context-Driven Use Case Creation Process for Specifying Automotive Driver Assistance Systems

Lecture 1: Basic Concepts of Machine Learning

Lecture 2: Quantifiers and Approximation

Discriminative Learning of Beam-Search Heuristics for Planning

The Strong Minimalist Thesis and Bounded Optimality

Using SAM Central With iread

Stacks Teacher notes. Activity description. Suitability. Time. AMP resources. Equipment. Key mathematical language. Key processes

A Minimalist Approach to Code-Switching. In the field of linguistics, the topic of bilingualism is a broad one. There are many

ECE-492 SENIOR ADVANCED DESIGN PROJECT

Carter M. Mast. Participants: Peter Mackenzie-Helnwein, Pedro Arduino, and Greg Miller. 6 th MPM Workshop Albuquerque, New Mexico August 9-10, 2010

Developing a TT-MCTAG for German with an RCG-based Parser

Chapter 2 Rule Learning in a Nutshell

Hentai High School A Game Guide

Objectives. Chapter 2: The Representation of Knowledge. Expert Systems: Principles and Programming, Fourth Edition

Visual CP Representation of Knowledge

Introduction to HPSG. Introduction. Historical Overview. The HPSG architecture. Signature. Linguistic Objects. Descriptions.

CAN PICTORIAL REPRESENTATIONS SUPPORT PROPORTIONAL REASONING? THE CASE OF A MIXING PAINT PROBLEM

Axiom 2013 Team Description Paper

Learning Structural Correspondences Across Different Linguistic Domains with Synchronous Neural Language Models

Preparing for the School Census Autumn 2017 Return preparation guide. English Primary, Nursery and Special Phase Schools Applicable to 7.

Notes on The Sciences of the Artificial Adapted from a shorter document written for course (Deciding What to Design) 1

The Indices Investigations Teacher s Notes

(Sub)Gradient Descent

Learning goal-oriented strategies in problem solving

Setting Up Tuition Controls, Criteria, Equations, and Waivers

Ohio s Learning Standards-Clear Learning Targets

Fragment Analysis and Test Case Generation using F- Measure for Adaptive Random Testing and Partitioned Block based Adaptive Random Testing

Probabilistic Latent Semantic Analysis

Designing a Computer to Play Nim: A Mini-Capstone Project in Digital Design I

CPS122 Lecture: Identifying Responsibilities; CRC Cards. 1. To show how to use CRC cards to identify objects and find responsibilities

Linking Task: Identifying authors and book titles in verbose queries

Probability and Game Theory Course Syllabus

Using Blackboard.com Software to Reach Beyond the Classroom: Intermediate

PRODUCT PLATFORM DESIGN: A GRAPH GRAMMAR APPROACH

STUDENT MOODLE ORIENTATION

have to be modeled) or isolated words. Output of the system is a grapheme-tophoneme conversion system which takes as its input the spelling of words,

Lecture 1: Machine Learning Basics

Your School and You. Guide for Administrators

Study Guide for Right of Way Equipment Operator 1

Generating Test Cases From Use Cases

Implementing a tool to Support KAOS-Beta Process Model Using EPF

SYSTEM ENTITY STRUCTUURE ONTOLOGICAL DATA FUSION PROCESS INTEGRAGTED WITH C2 SYSTEMS

Algebra 2- Semester 2 Review

Transcription:

Fundamentals of Programming Finite State Machines Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa April 12, 2012 G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 1 / 66

Outline 1 Finite State Machines (FSMs) Introduction Moore and Mealy machines State Diagrams Mealy machines 2 Non deterministic FSMs Non determinism Exercise 3 Implementing FSM in C 4 Regular Expressions 5 Hierarchical Finite State Machines H-FSM specification 6 The Elevator Example Simple FSM Improved design G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 2 / 66

Outline 1 Finite State Machines (FSMs) Introduction Moore and Mealy machines State Diagrams Mealy machines 2 Non deterministic FSMs Non determinism Exercise 3 Implementing FSM in C 4 Regular Expressions 5 Hierarchical Finite State Machines H-FSM specification 6 The Elevator Example Simple FSM Improved design G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 3 / 66

Outline 1 Finite State Machines (FSMs) Introduction Moore and Mealy machines State Diagrams Mealy machines 2 Non deterministic FSMs Non determinism Exercise 3 Implementing FSM in C 4 Regular Expressions 5 Hierarchical Finite State Machines H-FSM specification 6 The Elevator Example Simple FSM Improved design G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 4 / 66

Introduction State machines are basic building blocks for computing theory. very important in theoretical computer science many applications in practical systems There are many slightly different definitions, depending on the application area A state machine is a Discrete Event Discrete State system transitions from one state to another only happen on specific events events do not need to occur at specific times we only need a temporal order between events (events occur one after the other), not the exact time at which they occur G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 5 / 66

Definition A deterministic finite state machine (DFSM) is a 5-tuple: S (finite) set of states I set of possible input symbols (also called input alphabet) s 0 initial state φ transitions: a function from (state,input) to a new state ω output function (see later) φ : S I S An event is a new input symbol presented to the machine. In response, the machine will react by updating its state and possibly producing an output. This reaction is istantaneous (synchronous assumption). G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 6 / 66

Outline 1 Finite State Machines (FSMs) Introduction Moore and Mealy machines State Diagrams Mealy machines 2 Non deterministic FSMs Non determinism Exercise 3 Implementing FSM in C 4 Regular Expressions 5 Hierarchical Finite State Machines H-FSM specification 6 The Elevator Example Simple FSM Improved design G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 7 / 66

Output function Two types of machines: Moore output only depends on state: ω mr : S Ω Where Ω is the set of output symbols. In this case, the output only depends on the state, and it is produced upon entrance on a new state. Mealy output depends on state and input: ω ml : S I Ω In this case, the output is produced upon occurrence of a certain transaction. G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 8 / 66

Moore machines Moore machines are the simplest ones If Ω = {yes, no}, the machine is a recognizer A recognizer is able to accept or reject sequences of input symbols The set of sequences accepted by a recognizer is a regular language G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 9 / 66

Outline 1 Finite State Machines (FSMs) Introduction Moore and Mealy machines State Diagrams Mealy machines 2 Non deterministic FSMs Non determinism Exercise 3 Implementing FSM in C 4 Regular Expressions 5 Hierarchical Finite State Machines H-FSM specification 6 The Elevator Example Simple FSM Improved design G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 10 / 66

State diagrams FSM can be represented by State Diagrams S0 S1 S2 a final states are identified by a double circle G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 11 / 66

Example: recognizer In this example I = {a, b}. The following state machine recognizes string aba a b a S0 S1 S2 S3 a b b S4 a,b G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 12 / 66

b Example: recognizer II Recognize string a n b m with n even and m odd (i.e. aabbb, b, aab are all legal sequences, while a, aabb, are non legal) a b S0 S2 b a a a S1 S4 b S4 is an error state. It is not possible to go out from an error state (for every input, no transaction out of the state) S2 is an accepting state, however we do not know the length of the input string, so it is possible to exit from the accepting state if the input continues If we want to present a new string we have to reset the machine to its initial state S3 G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 13 / 66

Non regular language FSM are not so powerful. They can only recognize simple languages Example: strings of the form a n b n for all n 0 cannot be recognized by a FSM (because they only have a finite number of states) they could if we put a limit on n. For example, 0 n 10. G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 14 / 66

Outline 1 Finite State Machines (FSMs) Introduction Moore and Mealy machines State Diagrams Mealy machines 2 Non deterministic FSMs Non determinism Exercise 3 Implementing FSM in C 4 Regular Expressions 5 Hierarchical Finite State Machines H-FSM specification 6 The Elevator Example Simple FSM Improved design G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 15 / 66

Mealy machines In Mealy machines, output is related to both state and input. In practice, output can be associated to a transition Given the synchronous assumption, the Moore s model is equivalent to the Mealy s model: for every Moore machine, it is possible to derive an equivalent Mealy machine, and viceversa G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 16 / 66

Example: parity check In this example, we have a Mealy machine that outputs 1 if the number of symbols 1 in input so far is odd; it outputs 0 otherwise. 1 / 1 0 / 0 S0 S1 0 / 0 1 / 0 Usually, Mealy machines have a more compact representation than Moore machines (i.e. they perform the same task with a number of states that is no less than the equivalent Moore machine). G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 17 / 66

Table representation A FSM can be represented through a table The table shown below corresponds to the parity-check Mealy FSM shown just before. 0 1 S 0 S 0 / 0 S 1 / 1 S 1 S 1 / 1 S 0 / 0 G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 18 / 66

Stuttering symbol Input and output alphabets include the absent symbol ǫ It correspond to a null input or output When the input is absent, the state remains the same, and the output is absent Any sequence of inputs can be interleaved or extended with an arbitrary number of absent symbols without changing the behavior of the machine the absent symbol is also called the stuttering symbol G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 19 / 66

Abbreviations If no guard is specified for a transition, the transition is taken for every possible input (except the absent symbol ǫ) If no output is specified for a transition, the output is ǫ given a state S 0, if a symbol α is not used as guard of any transition going out of S 0, then an implicit transition from S 0 to itself is defined with α as guard and ǫ as output α / 0 α / 0 S0 S1 β / ǫ S0 S1 α / ǫ β / 1 β / 1 G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 20 / 66

Exercise Draw the state diagram of a FSM with I = {0, 1}, Ω = {0, 1}, with the following specification: let x(k) be the sequence of inputs the output ω(k) = 1 iff x(k 2) = x(k 1) = x(k) = 1 G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 21 / 66

Solution three states: S0 is the initial state, S1 if last input was 1, S2 if last two inputs were 1 0 / 0 1 / 0 1 / 0 S0 S1 S2 0 / 0 0 / 0 1 / 1 G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 22 / 66

Outline 1 Finite State Machines (FSMs) Introduction Moore and Mealy machines State Diagrams Mealy machines 2 Non deterministic FSMs Non determinism Exercise 3 Implementing FSM in C 4 Regular Expressions 5 Hierarchical Finite State Machines H-FSM specification 6 The Elevator Example Simple FSM Improved design G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 23 / 66

Outline 1 Finite State Machines (FSMs) Introduction Moore and Mealy machines State Diagrams Mealy machines 2 Non deterministic FSMs Non determinism Exercise 3 Implementing FSM in C 4 Regular Expressions 5 Hierarchical Finite State Machines H-FSM specification 6 The Elevator Example Simple FSM Improved design G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 24 / 66

Deterministic machines Transitions are associated with a source state a guard (i.e. a input value) a destination state a output in deterministic FSM, a transition is uniquely identified by the first two. in other words, given a source state and a input, the destination and the output are uniquely defined G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 25 / 66

Non deterministic FSMs A non deterministic finite state machine is identified by a 5-tuple: I set of input symbols Ω set of output symbols S set of states S 0 set of initial states φ transition function: φ : S I (S Ω) where S denotes the power set of S, i.e. the set of all possible subsets of S. In other words, given a state and an input, the transition returns a set of possible pairs (new state, output). G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 26 / 66

Non determinism Non determinism is used in many cases: to model randomness to build more compact automata G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 27 / 66

Non determinism Non determinism is used in many cases: to model randomness to build more compact automata Randomness is when there is more than one possible behaviour and the system follows one specific behavior at random G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 27 / 66

Non determinism Non determinism is used in many cases: to model randomness to build more compact automata Randomness is when there is more than one possible behaviour and the system follows one specific behavior at random Randomness has nothing to do with probability! we do not know the probability of occurrence of every behavior, we only know that they are possible G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 27 / 66

Non determinism Non determinism is used in many cases: to model randomness to build more compact automata Randomness is when there is more than one possible behaviour and the system follows one specific behavior at random Randomness has nothing to do with probability! we do not know the probability of occurrence of every behavior, we only know that they are possible A more abstract model of a system hides unnecessary details, and it is more compact (less states) G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 27 / 66

Example of non deterministic state machine We now build an automata to recognize all input strings (of any lenght) that end with a 01 0,1 0 1 S0 S1 S2 G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 28 / 66

Equivalence between D-FSM and N-FSM It is possible to show that Deterministic FSMs (D-FSMs) are equivalent to non deterministic ones(n-fsms) Proof sketch Given a N-FSM A, we build an equivalent D-FSM B (i.e. that recognizes the same strings recognized by the N-FSM. For every subset of states of the A, we make a state of B. Therefore, the maximum number of states of B is 2 S. The start state of B is the one corresponding to the A. For every subset of states that are reachable from the start state of state of A with a certain symbol, we make one transition in B to the state corresponding to the sub-set. The procedure is iterated until all transitions have been covered. G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 29 / 66

Outline 1 Finite State Machines (FSMs) Introduction Moore and Mealy machines State Diagrams Mealy machines 2 Non deterministic FSMs Non determinism Exercise 3 Implementing FSM in C 4 Regular Expressions 5 Hierarchical Finite State Machines H-FSM specification 6 The Elevator Example Simple FSM Improved design G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 30 / 66

Exercise As an exercise, build the D-FSM equivalent to the previous example of N-FSM 0,1 0 1 S0 S1 S2 Figure: The N-FSM G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 31 / 66

Solution 0,1 0 1 S0 S1 S2 Figure: The N-FSM Initial state: {S0} state name subset 0 1 q0 {S0} {S0, S1} {S0} q1 {S0,S1} {S0, S1} {S0, S2} q2 {S0,S2} {S0, S1} {S0} G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 32 / 66

Solution 1 0 0 q0 q1 q2 1 0 1 Figure: The equivalent D-FSM G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 33 / 66

Outline 1 Finite State Machines (FSMs) Introduction Moore and Mealy machines State Diagrams Mealy machines 2 Non deterministic FSMs Non determinism Exercise 3 Implementing FSM in C 4 Regular Expressions 5 Hierarchical Finite State Machines H-FSM specification 6 The Elevator Example Simple FSM Improved design G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 34 / 66

Encoding states and symbols The first thing to do is to encode states and event symbols in the state machine. States can be simply and enumerated, so they can be represented by an integer variable #define STATE_1 1 #define STATE_2 2 #define STATE_3 3... int current_state;... Same thing can be done for the events #define EVENT_1 1 #define EVENT_2 2 #define EVENT_3 3... int event;... G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 35 / 66

Enum in C In C, an enumerated type can also be defined with the keyword enum enum states { STATE_1, STATE_2, STATE_3, MAX_STATES } current_state; enum events { EVENT_1, EVENT_2, MAX_EVENTS } new_event; The C compiler maps those variables into int Therefore, it is just a notation, no new added feature G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 36 / 66

Actions The main cycle is the following: When an even arrives check the current state depending on the event, perform an action and change state A simple way to perform this is through a sequence of if-then-else or switch-case switch(current_state) { case STATE_1 : if (new_event == EVENT_1) { // action for EVENT_1 // change state } else if (new_event == EVENT_2) { // new action for EVENT_2 // change state }... case STATE_2 : if (new_event == EVENT_1) { // action for EVENT_1 // change state }... } G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 37 / 66

Functions The previous implementation does not scale for large number of states and events A more modular implementation consists in having one separate function per action void action_s1_e1 (); void action_s1_e2 (); void action_s2_e1 (); void action_s2_e2 (); void action_s3_e1 (); void action_s3_e2 (); In this way, functions can go in separate files void action_s1_e1 () { /* do some processing here */ current_state = STATE_2; /* set new state, if necessary */ } G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 38 / 66

Function Table All functions can be stores in a table of states-events typedef void (*ACTION)(); ACTION [MAX_STATES][MAX_EVENTS] = { { action_s1_e1, action_s1_e2 }, /* procedures for state 1 */ { action_s2_e1, action_s2_e2 }, /* procedures for state 2 */ { action_s3_e1, action_s3_e2 } /* procedures for state 3 */ }; Of course, not all transitions are possible In this case, you can define empty functions, or functions that return an error G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 39 / 66

Main cycle The main program cycle is then: new_event = get_new_event (); /* get the next event to process */ if (((new_event >= 0) && (new_event < MAX_EVENTS)) && ((current_state >= 0) && (current_state < MAX_STATES))) { /* call the action procedure */ state_table[current_state][new_event] (); } else { /* invalid event/state - handle appropriately */ } G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 40 / 66

Consideration In the previous implementation, all functions act on a global variable current_state to modify the state To make the implementation less dependent on a global variable, it is possible to pass the state and event, and return the new state variable; typedef int (*ACTION)(int, int); int action_s1_e1(int state, int event) { /* do something */ return STATE_2; /* returns the new state */ } In this way, it is also possible to write more functions that can be reused for different states and events G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 41 / 66

Outline 1 Finite State Machines (FSMs) Introduction Moore and Mealy machines State Diagrams Mealy machines 2 Non deterministic FSMs Non determinism Exercise 3 Implementing FSM in C 4 Regular Expressions 5 Hierarchical Finite State Machines H-FSM specification 6 The Elevator Example Simple FSM Improved design G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 42 / 66

Regular expressions and automata Regular expressions are equivalent to Finite State Automata In fact, a regular expression can be translated to an automaton, by means of an appropriate parser This is exactly what the grep program does Regular expression syntax (POSIX) Symbol meaning. matches any single character [abc] matches any of the characters within the brackets. [a-z] specifies a range which matches any lowercase letter from a to z [ˆ abc] matches any of the characters not within the brackets ˆ matches the starting position of the input line $ matches the ending position of the input line * matches the preceding character or expression any number of times (including 0) + matches the preceding character or expression one or more number of times? matches the preceding character or expression zero or one times Or between two expressions G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 43 / 66

Examples *cat* any string containing the substring cat * c a t q0 q1 q2 q3 [a-z]*=[1-9][0-9]* An assignment (for example x = 50) a-z = 1-9 0-9 q0 q1 q2 q3 0-9 (Here I am assuming that characters not in the event list will abort the machine) G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 44 / 66

Outline 1 Finite State Machines (FSMs) Introduction Moore and Mealy machines State Diagrams Mealy machines 2 Non deterministic FSMs Non determinism Exercise 3 Implementing FSM in C 4 Regular Expressions 5 Hierarchical Finite State Machines H-FSM specification 6 The Elevator Example Simple FSM Improved design G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 45 / 66

Problems with FSMs FSM are flat and global All states stay on the same level, and a transition can go from one state to another It is not possible to group states and transitions Replicated transition problem: α α α S0 S1 S2 S3 β β β G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 46 / 66

Product of two FSM Another problem is related to the cartesian product of two FSM Suppose we have two distinct FSMs that we want to combine into a single one S1 Q1 δ α β γ δ Q2 S0 Q0 γ Figure: FSM 1 Figure: FSM 2 G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 47 / 66

Product result The result is a state machine where each state corresponds to a pair of states of the original machines Also, each transition in corresponds to one transition in either of the two original state machines γ δ γ S0-Q0 S0-Q1 S0-Q2 δ β α α β β α γ γ S1-Q0 S1-Q1 S1-Q2 δ δ G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 48 / 66

Complexity handling All these problems have to do with complexity of dealing with states In particular, the latter problem is very important, because we often need to combine different simple state machines However, the resulting diagram (or table specification) can become very large We need a different specification mechanism to deal with such complexity In this course, we will study Statecharts (similar to Matlab StateFlow), first proposed by Harel G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 49 / 66

Outline 1 Finite State Machines (FSMs) Introduction Moore and Mealy machines State Diagrams Mealy machines 2 Non deterministic FSMs Non determinism Exercise 3 Implementing FSM in C 4 Regular Expressions 5 Hierarchical Finite State Machines H-FSM specification 6 The Elevator Example Simple FSM Improved design G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 50 / 66

States In H-FSMs, a state can be final or composite my_state_machine <<top>> simple_state a comp_state <<submachine>> A a B b C a G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 51 / 66

State specification A state consist of: An entry action, executed once when the system enters the state An exit action, executed once before leaving the state A do action, executed while in the state (the semantic is not very clear) They are all optional MyState entry / onentry() exit / beforeexit() do / whileinside() Figure: Entry, exit and do behaviors G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 52 / 66

Transitions A transition can have: A triggering event, which activates the transition A guard, a boolean expression that enables the transition. If not specified, the transition is always enabled An action to be performed if the transition is activated and enabled, just after the exit operation of the leaving state, and before the entry operation of the entering state Only the triggering event specification is mandatory, the other two are optional First State myevent [temp>0] / turnonheater() Second State Figure: Transition, with event, guard and action specified G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 53 / 66

Or composition A state can be decomposed into substates When the machine enters state Composite, it goes into state Comp1 Then, if event e2 it goes in Comp2, if event e3 it goes in Comp3, else if event e4 it exits from Composite. extstate e1 Composite <<submachine>> e2 Comp2 anotherstate e4 Comp1 e3 Comp3 G. Lipari (Scuola Superiore Sant Anna) Figure: ATree composite and Heap state April 12, 2012 54 / 66

History When the machine exits from a composite state, normally it forgets in which states it was, and when it enters again, it starts from the starting state To remember the state, so that when entering again it will go in the same state it had before exiting, we must use the history symbol extstate e1 Composite <<submachine>> anotherstate e4 e2 Comp2 Comp1 e5 e3 Comp3 G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 55 / 66

AND decomposition A state can be decomposed in orthogonal regions, each one contains a different sub-machine When entering the state, the machine goes into one substate for each sub-machine Compound <<submachine>> capslock uppercase lowercase extstate capslock numlock numbers arrows numlock Figure: Orthogonal states for a keyboard G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 56 / 66

Outline 1 Finite State Machines (FSMs) Introduction Moore and Mealy machines State Diagrams Mealy machines 2 Non deterministic FSMs Non determinism Exercise 3 Implementing FSM in C 4 Regular Expressions 5 Hierarchical Finite State Machines H-FSM specification 6 The Elevator Example Simple FSM Improved design G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 57 / 66

Outline 1 Finite State Machines (FSMs) Introduction Moore and Mealy machines State Diagrams Mealy machines 2 Non deterministic FSMs Non determinism Exercise 3 Implementing FSM in C 4 Regular Expressions 5 Hierarchical Finite State Machines H-FSM specification 6 The Elevator Example Simple FSM Improved design G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 58 / 66

Elevator Let s define an intelligent elevator For a 5-stores building (ground floor, and four additional floors) Users can reserve the elevator The elevator serves all people in order of reservation We assume at most one user (or group of users) per each trip, and they all need to go to the same floor G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 59 / 66

Design considerations How do you encode at which floor the elevator is? 1 One different state per each floor Does not scale well; for 100 floors bulding, we need 100 states! 2 The floor is encoded as an extended state, i.e. a variable cf It scales, but more difficult to design 3 It always depends on what we want to describe! Which events do we have? An user press a button to reserve the elevator, setting variable rf An user inside the elevator presses the button to change floor, setting variable df G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 60 / 66

First design elevator_machine <<machine>> Idle timeout Destination reached reserve [cf!= rf] reserve [cf == rf] timeout motor stop Move To Reserve Move to destination motor stop Ready to Load press button G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 61 / 66

Outline 1 Finite State Machines (FSMs) Introduction Moore and Mealy machines State Diagrams Mealy machines 2 Non deterministic FSMs Non determinism Exercise 3 Implementing FSM in C 4 Regular Expressions 5 Hierarchical Finite State Machines H-FSM specification 6 The Elevator Example Simple FSM Improved design G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 62 / 66

Doors The previous design does not capture all aspects of our systems Let s start to add details by adding the description of how the doors behave Abstraction level The level of details of a design depends on what the designer is more interested in describing with the specification In the previous design, we were not interested in describing all aspects, but only on giving a few high-level details The design can be refined by adding details when needed G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 63 / 66

The doors submachine door_machine <<machine>> doors_closed close_end closing open doors close doors opening open_end doors_open G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 64 / 66

The elevator, second design elevator_machine <<machine>> Idle entry / close doors timeout timeout Destination reached entry / open doors reserve [cf!= rf] Move To Reserve reserve [cf == rf] motor stop Move to destination entry / close doors motor stop go Ready to Load entry / open doors G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 65 / 66

Putting everything together Global Elevator <<machine>> Idle entry / close doors timeout Destination reached entry / open doors reserve [cf!= rf] reserve [cf == rf] timeout motor stop Move To Reserve motor stop Ready to Load entry / open doors go Move to destination entry / close doors doors_closed close_end closing open doors close doors opening open_end doors_open G. Lipari (Scuola Superiore Sant Anna) Tree and Heap April 12, 2012 66 / 66