You are on page 1of 130

Yarmouk Private University

Faculty of Informatics & Communication Eng Software Engineering Department

Declarative Programming
For Computer Science Engineering
YPU - 2013
Moving from the context of purely mathematical applications to gure out how to apply the ideas of theoretical models into computing problems.

By

Tareq Jehad AlJebawi


Supervise

Dr. Adnan Ali

Copyrights Yarmouk Private University 2013 http://www.ypu.edu.sy


Yarmouk Private University

[System Specification Document]


Declarative Programming Tools for Computer Science Engineering By
Tareq Jehad AlJebawi

Supervising
Dr.Adnan Ali

Registration Date: 01 November 2012 Delivering Date: 21 August 2013 Submitted to the
Faculty of Informatics and Communication Engineering Software Engineering Department

In partial fulfillment of the requirements For the award of the degree


Of

Bachelors Degree In Software Engineering


August 2013

2|Page

Table of Contents
Abstract ......................................................................................................................6 Acknowledgements ....................................................................................................6 List of Tables .............................................................................................................7 List of Figures ............................................................................................................7 List of Symbols, Abbreviations or Nomenclature .....................................................9 Chapters....................................................................................................................10 [Chapter 1] Theoretical Models ...............................................................................11
1. Introduction ........................................................................................................... 12 1.1. 1.2. System Approach ......................................................................................... 12 Implemented Models ................................................................................... 13

2. Finite State Automata ............................................................................................ 14 2.1. 2.2. 2.3. 2.4. 2.5. Why Finite Automata .................................................................................. 14 Deterministic Finite Automata .................................................................... 14 Nondeterministic Finite Automata .............................................................. 15 Equivalence of Deterministic & Nondeterministic Finite Automata .......... 16 Finite Automata with Epsilon-Transitions .................................................. 16

3. Finite State Transducer ......................................................................................... 18 3.1. 3.2. 3.3. 3.4. 3.5. 3.6. What are Finite State Transducers? ............................................................. 18 Formal Construction .................................................................................... 18 Ways of looking at a finite state transducers ............................................... 19 Cascading finite state transducers................................................................ 19 Closure properties for regular relations ....................................................... 20 Finite State Automata in action ................................................................... 20

4. Pushdown Automata ............................................................................................. 21 4.1. 4.2. Definition of the pushdown automata ......................................................... 21 The Language of a PDA .............................................................................. 23
3|Page

4.3.

Equivalence of PDAs and CFGs ............................................................... 23

5. Turing Machines ................................................................................................... 25 5.1. 5.2. The Turing Machine .................................................................................... 25 Programming Techniques for Turing Machines.......................................... 27

6. Context Free Grammar .......................................................................................... 28 6.1. 6.2. 6.3. Context Free Grammars............................................................................... 29 Parse Trees ................................................................................................... 30 Ambiguity in Grammars and Languages ..................................................... 31

[Chapter 2] System Development Life Cycle (SDLC) ............................................33


1. Applied Methodology......................................................................................... 34 1.1. 1.2. Introduction ................................................................................................. 34 Agile Methods ............................................................................................. 35

2. Requirements ...................................................................................................... 36 2.1. 2.2. Introduction ................................................................................................. 37 Specific Requirements ................................................................................. 37

3. System Analysis and Design .............................................................................. 42 3.1. 3.2. 3.3. 3.4. Defining a System ....................................................................................... 42 System Life Cycle ....................................................................................... 42 Phases of System Development Life Cycle ................................................. 43 System Behavior .......................................................................................... 54

4. Implementation ................................................................................................... 56 4.1. 4.2. 4.3. 4.4. 4.5. 4.6. Implementing the State class ....................................................................... 58 Implementing the StateInput User Control .................................................. 59 Implementing the Transition class ............................................................... 60 Implementing the TransitionInput User Control ......................................... 62 Implementing the UniversalRecognizer class ............................................. 64 Implementing the FileManager class ........................................................... 71

5. Deployment and Testing .................................................................................... 75 5.1. 5.2. 5.3. Testing Finite State Automata ..................................................................... 77 Testing Finite State Transducer ................................................................... 90 Testing Pushdown Automata ..................................................................... 101
4|Page

5.4. 5.5. 5.6.

Testing Turing Machines ........................................................................... 107 Testing Context Free Grammar ................................................................. 111 Testing the Additional Functionality ......................................................... 116

[Chapter 3] Results.................................................................................................118
1. Discussion and Conclusion .............................................................................. 118 1.1. 1.2. System Functionality ................................................................................. 118 Discussion .................................................................................................. 119

Bibliography...........................................................................................................120 Appendix ................................................................................................................120


1. C#.NET Programming Language ..................................................................... 121 1.1. 1.2. 1.3. 1.4. Classes ....................................................................................................... 121 Converters .................................................................................................. 121 Custom Controls ........................................................................................ 125 Pages .......................................................................................................... 128

2. Prolog: Programming in Logic ......................................................................... 129

5|Page

Abstract
Background Mathematics was always theoretical approach according to a lot of students, really much of mathematics students where uncertainly about mathematics and its applications. With existence of computer software and professional programmers the mathematics reflected to the computer and become the most popular model implemented in the computer. Now days the need for such applications is rapidly growing according to the solutions it gives. Taking a model in mathematics and trying to implements it in software is a very good idea for those how search about such projects. Results formal methods are a very popular mathematics models. What happens is that we tried to automate some of these models with our available ability. We start by taking the following models: a. b. c. d. e. f. g. h. Finite State Automata Finite State Transducer Push Down Automata Turing Machines Context Free Grammar Hidden Markov Model Probabilistic Automata Probabilistic Context Free Grammar

Take each model alone, collect as information as possible about it, analysis it as possible and try to design a good implementation for it, is what we did along the system development life cycle (SDLC) of this system. Conclusion A theoretical analysis, software engineering power, internet and the modern technologies all we employ to serve our goal and achieve constructing this useful system.

Acknowledgements
In the name of Allah the most beneficent the most merciful. No programmer can complete a project or a book without a small army of helpful individuals. We are deeply indebted to Dr.Adnan Ali who draws the line for us. He has an excellent ideas and tactics. He was always reviews our work and gives the best solution for our
6|Page

problems. When we were starting talking about the project idea he explained the general idea of what we will do and the problem behind such systems. And we mustnt forget that this work was to be very excellent if we continue working with doctor Adnan and meet him continuously, but the stage that our country lived with denied us from contacting continuously. We cant say except Thanks for Allah for everything. Finally, wed to point that the good things happen to us are from Allah. And the bad things happen to us from ourselves. No god but Allah.

List of Tables
NO 1 2 3 4 5 6 7 8 Section 1.1 Finite State Automata 2.3 System Analysis & Design 2.3 System Analysis & Design 2.3 System Analysis & Design 2.3 System Analysis & Design 2.3 System Analysis & Design 2.5 Deployment & Testing 2.5 Deployment & Testing Number Table1 Table2 Table3 Table4 Table5 Table6 Table7 Table8 Description Transition Table for Figure 2 Finite State Automata Input Frame Finite State Transducer Input Frame Pushdown Automata Input Frame Turing Machines Input Frame Context Free Grammar Input Frame Transition Table for langue L Transition Table example 5.1.7 Page 17 45 47 47 48 48 85 89

List of Figures
NO 1 2 3 4 Section 1.1 Finite State Automata 1.1 Finite State automata 1.2 Finite State Transducer 1.3 Pushdown Automata Number Figure1 Figure2 Figure3 Figure4 5 1.3 Pushdown Automata Figure5 Description General FA machine example An e-NFA accepting decimal number FSA for rules of the previous example Pushdown Automaton is essentially a finite state automaton with a stack data structure Organization of constructions showing equivalence of three ways of defining the CFLs Turing Machine Architecture A TM viewed as having finite-control storage and multiple tracks. Parse Tree for the given grammar Agile Methodology Use Case Diagram System General Definition Phases of System Development Life Page 14 17 21 22 24

6 7 8 9 10 11 12

1.4 Turing Machines 1.4 Turing Machines 1.5 Context Free Grammar 2.1 Applied Methodology 2.2 Requirements 2.3 System Analysis & Design 2.3 System Analysis & Design

Figure6 Figure7 Figure8 Figure9 Figure10 Figure11 Figure12

26 129 32 36 39 42 43

7|Page

13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53

2.3 System Analysis & Design 2.3 System Analysis & Design 2.3 System Analysis & Design 2.3 System Analysis & Design 2.3 System Analysis & Design 2.3 System Analysis & Design 2.3 System Analysis & Design 2.3 System Analysis & Design 2.3 System Analysis & Design 2.3 System Analysis & Design 2.3 System Analysis & Design 2.3 System Analysis & Design 2.3 System Analysis & Design 2.3 System Analysis & Design 2.3 System Analysis & Design 2.3 System Analysis & Design 2.5 Deployment & Testing 2.5 Deployment & Testing 2.5 Deployment & Testing 2.5 Deployment & Testing 2.5 Deployment & Testing 2.5 Deployment & Testing 2.5 Deployment & Testing 2.5 Deployment & Testing 2.5 Deployment & Testing 2.5 Deployment & Testing 2.5 Deployment & Testing 2.5 Deployment & Testing 2.5 Deployment & Testing 2.5 Deployment & Testing 2.5 Deployment & Testing 2.5 Deployment & Testing 2.5 Deployment & Testing 2.5 Deployment & Testing 2.5 Deployment & Testing 2.5 Deployment & Testing 2.5 Deployment & Testing 2.5 Deployment & Testing 2.5 Deployment & Testing 2.5 Deployment & Testing 2.5 Deployment & Testing

Figure13 Figure14 Figure15 Figure16 Figure17 Figure18 Figure19 Figure20 Figure21 Figure22 Figure23 Figure24 Figure25 Figure26 Figure27 Figure28 Figure29 Figure30 Figure31 Figure32 Figure33 Figure34 Figure35 Figure36 Figure37 Figure38 Figure39 Figure40 Figure41 Figure42 Figure43 Figure44 Figure45 Figure46 Figure47 Figure48 Figure49 Figure50 Figure51 Figure52 Figure53

Cycle Model General Input/Output View Relationship between Input Table and Visual graph Component Diagram State Input Design View Transition Input Design View System Activity Diagram Models' Class Diagram State Input User Control State Input Type Changing State Input Context Menu FSA Transition Input User Control FST Transition Input User Control PDA Transition Input User Control TM Transition Input User Control CFG Transition Input User Control Graphics Library Class Diagram New project user interface User Query builder in two modes Finite automata simple recognizer Transition Table for then string Float signed number Recognizer Identifier Recognizer Even number recognizer Signed even number recognizer Signed odd number recognizer Transition Graph for the language L Transition Graph for accepting string ending with 01 Transition Graph for accepting event number of 0s and 1s A very simple deterministic finitestate transducer Finite State Transducer with Epsilon Transition Simple English - Arabic translator Simple dictionary Transition Table English nouns plural generator English nouns plural more enhancement Simple Encryption / Decryption machine a's and b's counts balancer Pushdown Automata Transition Table an bm cm dn String Recognizer Parenthesis Recognizer Turing Machines Transition Table Binary Addition Machine

46 46 51 52 52 55 57 59 59 60 62 63 63 63 64 74 76 77 78 78 80 82 83 84 84 86 87 89 91 93 93 94 96 97 100 102 103 104 106 108 108

8|Page

54 55 56

2.5 Deployment & Testing 2.5 Deployment & Testing 2.5 Deployment & Testing

Figure54 Figure55 Figure56

an bm String Recognizer Grammar graph tree Context Free Grammar Transition Table

110 111 112

List of Symbols, Abbreviations or Nomenclature


NO 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 Symbol, Abbreviation DPT FSA DFA NFA FST PDA TM CFG HMM PA PCFG SDLC Q q0 F W P D B V T Description Declarative Programming Tools Finite State Automata Deterministic Finite Automata Nondeterministic Finite Automata Finite State Transducer Push Down Automata Turing Machines Context Free Grammar Hidden Markov Model Probabilistic Automata Probabilistic Context Free Grammar System Development Life Cycle Epsilon Empty or null A finite set of states A finite set of input symbols Is the transition function Is the start state Is the set of accepting states A finite set of output symbols Is a function in Q Is a finite stack alphabet Is the remaining input. Is the stack contents Is the next state, in Q Is a direction, either L or R or S The blank symbol Is the set of variables The terminals.

9|Page

Chapters
Chapter 1: Theoretical Models
1. Introduction 2. Finite State Automata 3. Finite State Transducer 4. Push Down Automata 5. Turing Machines 6. Context Free Grammar

Chapter 2: System Development Life Cycle [SDLC]


1. Applied Methodology 2. Requirements 3. System Analysis and Design 4. Implementation 5. Deployment and Testing

Chapter 3: Results
1. Discussion and Conclusion

10 | P a g e

[Chapter 1] Theoretical Models


Chapters Sections:
Introduction Finite State Automata Finite State Transducer Push Down Automata Turing Machines Context Free Grammar

In this chapter we will describe all the theoretical concepts that implemented in our system. The examples and the figures will describe in the chapter 2: Deployment and Testing to give more understanding with the using of our system

11 | P a g e

1. Introduction
Many existing computer systems were unthinkable some years ago and their
complexity is still rapidly growing so that it becomes more and more difficult to detect errors or to predict their incidence. Formal methods play an increasing role during the whole system-design process. The term formal methods covers a wide range of mathematically derived and ideally mechanized approaches to system design and validation. More precisely, research on formal methods attempts to develop mathematical models and algorithms that may contribute to the tasks of modelling, specifying, and verifying software and hardware systems. But students of computer science often study formal methods in the context of purely mathematical applications. They have to gure out how to apply the ideas of theoretical models to computing problems. The logic programming language Prolog is easy to learn and use because its syntax and semantics are similar to that of formal models. The instant feedback provided by Prologs interactive environment can help the process of learning. The Prolog language allows exploring a wide range of topics in computer science engineering. Prologs powerful pattern-matching ability and its computation rule give us the ability to experiment in two directions. For example, a typical experiment might require a test of a definition with a few example computations. Prolog allows this, as do all programming languages. But the Prolog computation rule also allows a definition to be tested in reverse, by specifying a result and then asking for the elements that give the result. From a functional viewpoint this means that we can ask for domain elements that map to a given result. A major aim of this project is to integrate, tightly, the study of formal models with the study of central problems of computer science. Concepts of formal models are illustrated through the solution of problems that arise fundamental domains of computer science engineering.

1.1. System Approach


In our system (Declarative Programming Tools) the idea was not to move the mathematical concepts into computing problems only, but try to find a way that the user can declare and use the system in very easy way especially in the way of entering data and getting outputs. These ways considered as follow: 1. Transition Table 2. Visual Graph

12 | P a g e

Transition Table means enter or declare the data in a user friendly table and maintain a collection of these data to be treated into logic programming code and visualizing them using the Visual Graph. Visual Graph means draw nodes and arcs using simple tools to generate the same graph that can generated using the Transition Table, of course this graph can be converted into the corresponding Transition graph and behave like if we in the Transition Table mode. At the end of declaring our data, the system will be ready to make some processing over these data and add another data to finally generate the desired code we look for, this process described as generative programming. At this point the system able to allows the users to test the generated code using the Logic Programming Interpreter such Prolog and using this interpreter as recognizer or generator.

1.2. Implemented Models


The automata theory contains many models and a lot of theories we try to treat the most important models which are: 1. 2. 3. 4. 5. 6. 7. 8. 9. Finite State Automata. Epsilon Finite State Automata. Finite State Transducer. Push Down Automata. Turing Machine. Context Free Grammar. Hidden Markov Model. Probabilistic Automata. Probabilistic Context Free Grammar.

In addition to these models there are some conversion techniques that helps in convert from one model to another one, really there are three type of conversions that are: 1. Converting from Context Free Grammar to Pushdown Automata 2. Converting from Regular Grammar to Finite State Automata 3. Converting from Finite State Automata to Regular Grammar We will get benefit from these converting operations because we can declare our language simply a model rather than another one. In the next sections we will see the desired models in purely mathematically concepts provided with some examples and figures to make the idea easier. Then in the second chapter of System Development Life Cycle (SDLC) we will demonstrate the way that we extract the similarity between these models and how we planned to employ it.
13 | P a g e

2. Finite State Automata


This section introduces the class of languages known as regular language. These
languages are exactly the ones that can be described by finite automata. We can say that finite automata have a set of states and its Control moves from state to state in response to external inputs. One of the crucial distinctions among classes of finite automata is whether that control is deterministic, meaning that the automata cannot be in more than one state at any one time, or nondeterministic, meaning that it may be in several states at once. In effect, non-determinism allows us to program solutions to problems using a Higher-Level language.

2.1. Why Finite Automata


Finite Automata are used as a model for: a) b) c) d) Software for designing digital circuits. Lexical analyzer of a compiler. Searching for keywords in a file or on the web. Software for verifying finite state system, such as communication protocols.

For example Finite Automaton modeling an ON/OFF switch

Figure 1: General finite automata machine example

2.2. Deterministic Finite Automata


The term Deterministic refers to the fact that on each input there is one and only one state to which the automaton can transition from its current state. The term Finite Automata will refer to the Deterministic variety, although we shall use Deterministic or the abbreviation DFA normally. To remind the reader of which kind of automaton we are talking about.

14 | P a g e

2.2.1. Definition of Deterministic Finite automata A deterministic finite automaton consists of: 1. A finite set of state, often denoted Q. 2. A finite set of input symbols, often denoted . 3. A transition function that takes as arguments a set and an input symbol and returns a state. The transition function will commonly be denoted . In our informal graph representation of automata, was represented by arcs between states and the labels on the arcs If q is a state, and a is an input symbol, then (q, a) is that state p such that there is an arc labeled a from q. 4. A start state, one of the states in Q. 5. A set of final or accepting states F. The set F is a subset of Q. In proofs we often talk about a DFA in Five - tuple notation: A= (Q, , , q0, F) Where: A is the name of the DFA. Q is the set of states. is the input symbols. is the transition function. q0 is the start state. F is the set of accepting states.

2.3. Nondeterministic Finite Automata


Nondeterministic finite automata (NFA) have the power to be in several states at once. This ability is often expressed as an ability to guess something about its input. Like the DFA, an NFA has a finite set of states, a finite set of input symbols, one start state and a set of accepting states. It also has a transition function, which we shall commonly call . The difference between the DFA and NFA is in the type of . For the NFA, is a function that takes a state and input symbol as argument like the DFAs transition function, but returns a set of zero, one, or more states. An NFA is represented essentially like a DFA: A= (Q, , , q0, F) Where: Q: A finite set of states. : A finite set of input symbols. : A transition function from Q x to the power set of Q.
15 | P a g e

q0: A member of Q, is the start state. F: Subset of Q, is the set of final (or accepting) states.

2.4. Equivalence of Deterministic & Nondeterministic Finite Automata


Although there are many languages for which an NFA is easier to construct than a DFA, such as the language of strings that end 01 (that shown in Finite State Automata Testing in chapter 2), it is a surprising fast that every language that can be described by some NFA can also be described by some DFA. Moreover, the DFA in practice has about as many states as the NFA, although it often has more transitions. In the worst case, however, the smallest DFA can have 2n state while the smallest NFA for the same language has only n states.

2.5. Finite Automata with Epsilon-Transitions


We shall now introduce another extension of finite automaton. The new feature is that we allow a transition on , the empty string. In effect, an NFA is allowed to make a transition spontaneously, with receiving an input symbol. This new capability gives us some added Programming convenience. 2.5.1. Use of -Transitions We shall begin with an informal treatment of -NFA, using transition diagrams with allowed as a label. In the examples to follow, think of the automaton as accepting those sequences of labels along paths from the start state to an accepting state. However, each along the path is invisible; it contributes nothing to the string along the path. An -NFA accepting decimal numbers consisting of: 1. 2. 3. 4. An optional + or sign. A string of digits. A decimal point. Another string of digits.

Of particular interest is the transition from q0 to q1 on any of , +, or -. Thus, state q1 represents the situation in which we have seen the sign if there is one, and perhaps some digits, but not the decimal point. State q2 represents the situation where have just seen the decimal point, and may or may not have seen prior digits. In q4 we have definitely seen at least one digit, but not the decimal point. Thus, the interpretation of q3 is that we have seen a decimal point and at least one digit, either before or after the decimal point. We may stay at q3 reading whatever digits there are, and also have the
16 | P a g e

option of guessing the string of digits is complete and going spontaneously to q5, the accepting state.

Figure 2: An -NFA accepting decimal number

2.5.2. The Formal Notation for an -NFA We may represent an -NFA exactly as we do an NFA, with no exception: the transition function must include information about transitions on . formally, we represent an -NFA by: A= (Q, , , q0, F) Where all components have their same interpretation as for an NFA, except that is now a function that takes as arguments: A state in Q. A member of U {}, that is, either an input symbol, or the symbol . Example: The -NFA of previous figure is represented formally as: E= ({q0, q1 q5}, {., +, -, 0, 1 9}, , q0, {q5}) Where is defined by the transition table:
Table 1: Transition Table for Figure 2

q0 q1 q2 q3 q4 q5

{q1} {q5}

+, {q1}

. {q2} {q3}

0, ,9 {q1, q4} {q3} {q3}

17 | P a g e

3. Finite State Transducer


What are finite state transducers and why are they interesting? First what they are.
Start from finite-state automata, and recall that they can be used either as recognizers or generators. Its simply a matter of how we interpret what we do with the symbols on the transition arrows. If we read the symbols from an input tape, then our FSA is an acceptor. Alternatively, if we run the machine non-deterministically, following any legal path from state to state from an initial state to a final state, and output the symbols that are on the transition arrows as we go, then our FSA is a generator. The same machine can be used either way, and defines the same language in either case. From these observations its a small step to a finite-state transducer: we put PAIRS of symbols (or symbol strings) on our transition arrows, viewing one as input and the other as output. One can in principle allow triples and more, but well stick to ones with pairs, and call the members of the pairs inputs and outputs. Which is up to us, and in principle thats a free choice analogous to the choice of viewing a straight FSA as an acceptor or a generator? Well give the exact definition shortly.

3.1. What are Finite State Transducers?


A finite state transducer (FST) is a special type of finite state machine. Specifically, an FST has two tapes, an input string and an output string. Rather than just traversing (and accepting or rejecting) an input string, an FST translates the contents of its input string to its output string. Or put another way, it accepts a string on its input tape and generates another string on its output tape.

3.2. Formal Construction


A finite state transducer is a finite state automaton in which the members of (the symbols labeling the arcs) are pairs, triples, etc., rather than simple symbols. Traditionally the members of S in a transducer are just pairs, of which the left-hand member is the input symbol and the right-hand member is the output symbol. A deterministic finite state transducer (DFST) is defined as a septuple (q0, Q, F, , , , ) Where: q0 Q: The initial state. Q: A finite set of states. F Q: The final states, a subset of Q.
18 | P a g e

: A finite set of input symbols (the input alphabet). : A finite set of output symbols (the output alphabet). : A function in Q Q: is the set of transitions, exactly as for a deterministic FSA, mapping a pair of a state and an input symbol to a state. : A function in Q : the transduction function (emission function), mapping a state and an input symbol to an output symbol. Frequently the transition function and the transduction function are combined into a single transition-transduction function, which may also be called d, in Q x Q, mapping a pair of a state and an input symbol onto a pair of a state and an output symbol. A finite-state transducer is non-deterministic if either the transition mapping or the transduction mapping fails to be a function, i.e. if there is more than one possible transition or more than one possible output symbol for a given pair of a state and an input symbol.

3.3. Ways of looking at a finite state transducers


1. We can think of the input symbols as appearing on one tape (usually called the input tape) and the output symbols on another tape (usually called the output tape.) In that case the transducer is in translating mode, from input tape to output tape, or from the first tape to the second tape. (For the first automaton above, it translates ah to bh and ae to ce.) 2. Reverse translation: We can just as well use the same machine to translate from the second tape to the first. So the first machine in section 2 would then translate bh to ah and ce to ae. 3. Generation mode. The transducer works like a finite state automaton run in generation mode, but writes a pair of output strings rather than just one. (Our automaton generates the pairs of output strings <ah, bh> and <ae, ce>.) 4. Acceptance mode. (Recognition mode). Both tapes are input tapes; the two current input symbols have to match the two symbols on the transition arc in order to make a transition. (Our automaton accepts the pairs of input strings <ah, bh> and <ae, ce>.)

3.4. Cascading finite state transducers


A finite state transducer defines a regular relation. Cascading finite state transducers corresponds to performing a composition of relations to produce a new relation. From Karttunen (2001): As is well-known, phonological rewrite rules and two-level constraints can be implemented as finite-state transducers (Johnson 1972, Kaplan and Kay 1981, Karttunen 1987). The application of a system of rewrite rules to an input string can be
19 | P a g e

modeled as a cascade of transductions, that is, a sequence of compositions that yields a relation mapping the input string to one or more surface realizations.

3.5. Closure properties for regular relations


Regular relations, like regular expressions, are closed under 1. 2. 3. 4. 5. Union Concatenation Iteration A+ (one or more concatenations of members of A) Kleene star A* (union of empty string or relation and A+) Optionality (A) : union of A with the empty string or empty relation

Regular relations, unlike regular expressions, are not in general closed under Complement Intersection Regular relations are closed under composition A B

3.6. Finite State Automata in action


FSTs are particularly useful in the implementation of certain natural language processing tasks. Context-sensitive rewriting rules (ex: ax bx) are adequate for implementing certain computational linguistic tasks such as morphological stemming and part-of-speech tagging. Such rewrite rules are also computationally equivalent to finite-state transducers, providing a unique path for optimizing rule based systems. Example: the following set of ordered context-sensitive rules: 1. change c to b if followed by x: cx bx 2. change a to b if preceded by rs: rsa rsb 3. change b to a if preceded by rs and followed by xy: rsbxy rsaxy The time required to apply a sequence of context-sensitive rules is dependent upon the number of rules, the size of the context window, and the number of characters in the input string. The inefficiencies in such an implementation are highlighted in this example by the multi-step transformation required to translate c to b then b to a by rules 1 and 3, and the redundant transformation of a to b and back to a by rules 2 and 3. Finite State Transducers provide a path to eliminate these inefficiencies. But first we need to convert the rules to State Machines.

20 | P a g e

3.6.1. Converting Rules to FSTs To do this, we simple represent each rule as an FST where each link between states represent the acceptance of an input character and the expression of the corresponding output character. This input / output combination is denoted within an FST by labeling edges with both the input and output character separated by the / character. Following is an FST for each of the above rules.

Figure 3: Finite State Automata for rules of the previous example

4. Pushdown Automata
Push down automata is essentially an -NFA with the addition of a stack. The stack
can be read, pushed, and popped only at the top, just like the Stack data structure. In this section, we define two different versions of the pushdown automaton: One that accepts by entering an accepting state, like finite automata do, and another version that accepts by emptying its stack, regardless of the state it is in. We show that these two variations accept exactly the context-free languages; that is, grammars can be converted to equivalent pushdown automata and vice-versa. We also consider briefly the subclass of pushdown automata that is deterministic.

4.1. Definition of the pushdown automata


In this section we introduce the pushdown automata, first informally, then as a formal construct.
21 | P a g e

4.1.1. Informal Introduction The pushdown automaton is in essence a nondeterministic finite automaton with transitions permitted and one additional capability: a stack on which it can store a string of Stack Symbols The presence of a stack means that, unlike the finite automaton, the pushdown automaton can remember an infinite amount of information. The pushdown automaton can only access the information on its stack in a: (Last In - First Out) way.

Figure 4: Pushdown Automaton is essentially a finite state automaton with a stack data structure

A Finite State Control reads inputs, one symbol at a time. The push down automaton is allowed to observe the symbol at the top of the stack and to base its transition on its current state, the input symbol, and the symbol at the top of stack. Alternatively, it may make a spontaneous transition, using as its input instead of an input symbol. On a transition the PDA: Consumes an input symbol. Goes to a new state (or stays in the old). Replaces the top of the stack by any string. (Does nothing, pops the stack, or pushes a string onto the stack). 4.1.2. The Formal Definition of push down automata Our formal notation for a push down automata (PDA) involves seven components: P= (Q, , , , q0, Z0, F). Where: Q is a finite set of state. is a finite input alphabet. is a finite stack alphabet.
22 | P a g e

: Q x U { } * 2Q** is the transition function. Z0 is the start symbol for the stack. q0 is the start state. F Q is the set of accepting states.

4.1.3. Instantaneous Descriptions of PDA A PDA goes from configuration to configuration when consuming input. To reason about PDA computation, we use instantaneous descriptions of the PDA. An ID is triple (q, w, ) Where: q is the state. w is the remaining input. is the stack contents. Let P= (Q, , , , q0, Z0, F) be a PDA, Then V w *, *: _ (P, ) (q, a, x) (q, aw, x) (P, w , ). We define * to be the reflexivetransitive closure of .

4.2. The Language of a PDA


We have assumed that a PDA accepts its input by consuming it and entering an accepting state. We call this approach acceptance by final state There is a second approach to defining the language of a PDA that has important applications. We may also define for any PDA the language Accepted by empty stack, that is, the set of strings that cause the PDA to empty its stack. String from the initial ID. 4.2.1. Acceptance by Final State Let P= (Q, , , , q0, Z0, F) be a PDA. The language accepted by P by final state is: L (P) = {w: (q0, w, Z0) * (q, , ), q F}. 4.2.2. Acceptance by Empty Stack Let P = (Q, , , , q0, Z0, F) be a PDA. The language accepted by P by empty stack is: N (P) = {w: (q0, w, Z0) * (q, , )}. Note: q can be any state.

4.3. Equivalence of PDAs and CFGs


Now, we shall demonstrate that the language defined by PDAs are exactly the context-free language. The goal is to prove that the following three classes of language:
23 | P a g e

1. The Context-Free Languages, i.e., the languages defined by CFGs. 2. The languages that are accepted by final state by some PDA. 3. The languages that are accepted by empty stack by some PDA. Are all the same class. We have already shown that (2) and (3) are the same. It turns out to be easiest next to show that (1) and (3) are the same, thus implying the equivalence of all three.

Figure 5: Organization of constructions showing equivalence of three ways of defining the CFLs

4.3.1. From Grammars to Pushdown Automata The idea behind the construction of a PDA from a grammar is to have the PDA simulate the sequence of left. Sentential forms that the grammar uses to generate a given terminal string w. The tail of each sentential from xAx appears on the stack, with A at the top. Example: Let us convert the expression grammar to a PDA recall this grammar is: I a | b | Ia | Ib | I0 | I1| E I | E * E | E + E | (E) The set of input symbols for the PDA is {a, b, 0, 1, (,), +, *}. These eight symbols and the symbols I and E form the stack alphabet. The transition function for the PDA is: a. (q, , I) = {(q, a), (q, b), (q, Ib), (q, I0), (q, I1)}. b. (q, , E) = {(q, I), (q, E + E), (q, E * E), (q, (E))}. c. (q, a, a) = {(q, )}; (q, b, b) = {(q, )}; (q, 0, 0) = {(q, )}; (q, 1, 1) = {(q, )}; (q, (, ( ) = {(q, )}; (q, ), ) ) = {(q, )}; (q, +, +) = {(q, )}; (q, *, *) = {(q, )}. Note that (a) and (b) come from rule (1), while the eight transitions of (c) come from rule (2). Also, is empty except as defined by (a) through (c).

24 | P a g e

5. Turing Machines
In this section we change our direction significantly. Until now, we have been
interested primarily in simple classes constrained problems, such as analyzing protocols, searching text, or parsing programs. Now, we shall start looking at the question of what language can be defined by any computational device whatsoever. This question is tantamount to the question of language is a formal way of expressing any problem, and solving a problem is area son able surrogate for what it is that computer do. We begin within an informal argument, using an assumed knowledge of C programming, to show that there are specific problems we cannot solve using a computer. These problems are called Undecidable. We then introduce a venerable formalism for computers, called the Turing Machine. While a truing machine looks nothing like a PC, and would be grossly inefficient should some startup company decide to manufacture and sell them, the Turing machine long has been recognized as an accurate model for what any physical computing device is capable of doing.

5.1. The Turing Machine


The purpose of the theory of undecidable problems is not to establish the existence of such problems an intellectually exciting idea in its own right but to provide guidance to programmers about what they might or might not be able to accomplish through programming. Theory also has great pragmatic impact when we discuss, problems that although decidable, require large amounts of time to solve them. These problems, called intractable problems tend to present greater difficulty to the programmer and system designer than do thee undecidable problems are usually quit obviously so, and their solutions are rarely attempted in practice, the intractable problems are faced every day. 5.1.1. Notation for the Turing Machine We may visualize a Turing Machines as in the following figure, the machine consists a finite controls which can be in any of finite set of states. There is a tape divided into squares or cells each can hold any one of finite number of symbols.

25 | P a g e

Figure 6: Turing Machine Architecture

Initially, the input which is a finite-length string of symbols closen from the input alphabet is placed on the tape. All other tape cells, extending infinitely to the left and right, initially hold a special symbol called the blank is a tape symbol, but not an input symbol and there may be other tape symbols besides the input symbols and the blank, as well. There is a tape head that is always positioned at one of the tape cells. The Turing machine is said to be scanning that cell. Initially, the tape head is at the leftmost cell that holds the input. A more of the Turing machine is a function of the state of the finite control and the tape symbol scanned. In one more, the Truing machine will: Change state. The next state optionally may be the same as the current state. Write a tape symbol in the cell scanned. This tape symbol replaces whatever symbol was in that cell. Optionally, the symbol written may be the same as the symbol currently there. Move the tape head left or right. In our formalism we require a move, and do not allow the head to remain machine stationary. This restriction does not constrain what a Truing machine can computer. Since any sequence of moves with a stationary head could be condensed, along with the next tape-head move, into a single state change, a new tape symbol, and a move left or right. The formal notation we shall use for a Turing machine (TM) is similar to that used for finite automata or PDAs. We describe a TM by the 7.tuple M= (Q, , , , q0, B, F) Whose components have the following meanings: Q: The finite set of states of the finite control. : The finite set of input symbols. : The complete set of tape symbols; is always a subset of .
26 | P a g e

: The transition function. The arguments of (q, X) are a state q and a tape symbol X. The value of (q, X), if it is defined, is a triple (p, , D), where: P is the next state, in Q. is the symbol, in , written in the cell being scanning replacing whatever symbol was there. D is a direction, either L or R, standing for left or right respectively, and telling us the direction in which the head moves. q0: The start state, a member of Q, in which the finite control is found initially. B: The blank symbol. This symbol is in but not in ; i.e. it is not an input symbol. The blank appears initially in all but the finite number of initial cells that hold input symbols. F: The set of final or accepting states, a subset of Q. 5.1.2. Transition Diagrams for Turing Machines We can represent the transitions of a Truing machine pictorially, much as we did for the PDA. A transition diagram consists of a set of nodes corresponding to the states of the form X/Y D, Where X and Y are tape symbols, and D is a direction, either L or R. That is, whenever (q, X) = (P, Y, D), we find the label X/Y D on the are from a top. However, in our diagrams, the direction D is represented pictorially by for left and for right. As for other kinds of transition diagrams, we represent the start state by the word Start and an arrow entering that state Accepting state are indicated by double circles. Thus, the only information about the TM one cannot read directly from the diagrams is the symbol used for the blank. We shall assume that symbol is B unless we state otherwise.

5.2. Programming Techniques for Turing Machines


Our goal is to give you a sense of how a Turing machine can be used to compute in a manner not unlike that of a conventional computer. Eventually, we want to convince you that a TM is exactly as powerful as a conventional computer. In particular, we shall learn that the Turing machine that we saw performed. To make the ability of TM clearer, we shall present a number of examples of how we might think of the tape and finite control of the Turing machine. 5.2.1. Storage in the State We can use the finite control not only to represent a position in the Program of the Turing ma=chine, but to hold a finite amount of data. The following figure suggests this technique. There, we see the finite control consisting of not only a Control state q, but three data elements A, B and C. The technique requires an extension to the TM
27 | P a g e

model; we merely think of the state as a tuple. In the case of the following figure; we should think of the state as {q, A, B , C}. Regarding states this way allows us to describe transitions in a more systematic way, often making the strategy behind the TM program more transparent.

Figure 7: A TM viewed as having finite-control storage and multiple tracks.

5.2.2. Multiple Tracks Another useful trick is to think of the tape of a Turing machine as composed of several tracks. Each track can hold one symbol, and the tape alphabet of the TM consists of tuple, with one component for each track Thus, for instance, the cell scanned by the tape head in the previous figure contains the symbol [X, Y, Z]. Like the technique of storage in finite control, using multiple tracks does not extend what the Turing machine can do. It is simply a way to view tape symbols and to imagine that they have a useful structure. 5.2.3. Subroutines As with programs in general, it helps to think of Turing machine as built from a collection of interaction component, or subroutines. A Turing machine subroutine is a set of states that perform some useful process. This set of states includes a start state and another state that temporarily has no moves, and that serves as the return state to pass control to whatever other set of states called the subroutine.

6. Context Free Grammar


We now turn our attention away from the regular languages to a larger class of
languages, called the Context- Free Grammar. These languages have a natural, recursive notation, called context-free grammars. Context-Free Grammars have played central role in compiler technology since the 1960s. More recently, the
28 | P a g e

context free grammar has been used to describe document formats, via the so-called document-type definition (DTD) that use in the XML (eXtensible Markup Language) community for information exchange on the web. In this section, we introduce the context free grammar notation, and show how grammars define languages. We discuss the parse Tree picture of the structure that a grammar places on the string of its language.

6.1. Context Free Grammars


We shall begin by introduce the context free grammar notation informally. After seeing some of the important capabilities of these grammars, we after formal definitions. We show how to define a grammar formally, and introduce the process of derivation whereby it is determined which strings are in the language of the grammar. 6.1.1. An Informal Example Let us consider the language of palindromes. A palindrome is a string that reads the same forward and backward, such as otto or madamimadam (madam, Im Adam), allegedly the first thing ever heard of the garden of Eden, but another way, string w is a palindrome if and only if w=wR . To make things simple, we shall consider describing only the palindromes with alphabet {0, 1}. This language include is string like 0110, 11011, and , but not 011 or 0101. 6.1.2. Definition of Context-Free Grammars There are four important components in a grammatical description of language. 1. There is a finite set of symbols that form the string of the language begin defined. This set was {0, 1} in the palindrome example we just saw. We call this alphabet the terminal, or terminal symbols. 2. There is a finite set of variables, also called sometimes nonterminals or syntactic categories. Each variable represents a language, a set of string. Our example, above, there was only one variable, P, which we used to represent the class of palindromes over alphabet {0, 1}. 3. One of the variables represents the language being defined; it is called the start symbol. Other variables represent auxiliary classes of string that are used to help define the language of the start symbol. In our example, P the only variable is the start symbol. 4. There is a finite set of productions or rules that represent the recursive definition of a language. Each production consists of : a. A variable that is being (partially) defined by the production. This variable is often called the head of the production. b. The production symbol .
29 | P a g e

c. A string of zero or more terminals and variable. This string called the body of the production represents one way to form strings in the language of variable of the head. IN so doing we leave terminals unchanged and substitute for each variable of the body any string that is known to be in the language of that variable. The four components just described form a context-free grammar, or just grammar, or CFG. We shall represent a CFG G by its four components, that is; G= (V, T, P, S). Where: V is the set of variables. T the terminals. P the set of productions. S the start symbol.

6.1.3. Derivations Using a Grammar The process of deriving string S by applying productions from head to body requires the definition of a new relation Symbol Suppose. G = (V, T, P, S) is a CFG. Notice that one derivation step replaces any variable anywhere in the string by the body of one of its productions. We may extend the relationship to represent zero, one or many derivation steps, much as the transition function of a finite automaton was extended to . For derivations, we use a * to denote zero or more steps. 6.1.4. Left most and Right most Derivations In order to restrict the number of choices we have in deriving a string, it is often useful to require that at each step we replace the leftmost variable by one of its production bodies. Such a derivation is called a leftmost derivation, and we indicate that a derivation is leftmost by using the relations lm and *lm, for one or may steps, respectively. If the grammar G that is being used is not obvious, we can place the name G below the arrow in either of these symbols. Similarly, it is possible to require that at each step the rightmost variable is replaced by one of its bodies. If so, we call the derivation rightmost and use the symbols rm and *rm to indicate one or many rightmost derivation steps, respectively. Again, the most name of the grammar may appear below these symbols if it is not clear which grammar is being used.

6.2. Parse Trees


In this section, we introduce the parse tree and show that existence of parse trees is tied closely to the closely to the existence of derivation and recursive inferences.
30 | P a g e

6.2.1. Constructing Parse Trees Let us fix on a grammar G= (V, T, P, S). The parse trees for G are trees with the following conditions: 1. Each interior node is labeled by a variable in V. 2. Each leaf is labeled by either a variable, a terminal, or . However, if the leaf is labeled . Then it must be the only child of its parent. 3. If an interior node is labeled A, and its children are labeled X1, X2, ..., Xk Respectively, from the left, then A X1, X2, ..., Xk is a production in P.

6.3. Ambiguity in Grammars and Languages


When a grammar fails to provides unique structures, it is sometimes possible to redesign the grammar to make the structure unique for each string in the language. Unfortunately, sometimes we cant do so. That I, there are some CFLs that are inherently ambiguous; every grammar for the language puts more than one structure on some strings in the language. 6.3.1. Ambiguous Grammars. Let us consider a grammar example. This grammar lets us generate expressions with any sequence of * and + operators, and the productions E E + E | E * E allow us to generate these expressions in any order we choose. 6.3.2. Removing ambiguity from grammars Good news: Sometimes we can remove ambiguity by hand Bad news: There is no algorithm to do it. More bad news: Some CFLs ha e only ambiguous CFGs we are studying the grammar. 1. E I | E + E | E * E | (E) 2. I a | b | Ia | Ib | I0| I1 There are two problems: 1. There is no precedence between * and +. 2. There is no grouping of sequences of operators, i.e. is E + E + E mend to be E + (E + E) or (E+E)+E. Solution: We introduce more variables. Each representing expressions of same binding strength A factor is an expression that cannot be broken apart by an adjacent * or +. Our factors are: Identifiers
31 | P a g e

A parenthesized expression. A term is an expression that cannot be broken by +. For instance a*b can be broken by a1* or *a1 is (by precedence rules) same as a1+ (a * b), and a*b + a1 is same as (a*b) +a1. The rest are expressions, i.e. they can be broken apart with * or +. Well let F stand form Factors, T for Terms, and E for expressions. Consider the following grammar: I a | b | Ia | Ib | I0 | I1. F I | (E). T F | T * F. E T | E + T. Now the only parse tree for a + a * a will be

Figure 8: Parse Tree for the given grammar

32 | P a g e

[Chapter 2] System Development Life Cycle (SDLC)

Chapters Sections:
Applied Methodology Requirements System Analysis and Design Implementation Deployment and Testing

In this chapter we will use the software engineering concepts and methodology to implement our system. We will describe each phase of system development life cycle in one section and provide it with figures and diagrams.
33 | P a g e

1. Applied Methodology
The field of software development is not shy of introducing new methodologies. Indeed, in the last 25 years, a large number of different approaches to software development have been introduced, of which only few have survived to be used today. A recent study argues that traditional information system (IS) development methodologies are treated primarily as a necessary fiction to present an image of control or to provide a symbolic status. The same study further claims that these methodologies are too mechanistic to be used in detail. It made similar arguments early on. Another study take an extreme position and state that it is possible that traditional methods are merely unattainable ideals and hypothetical straw men that provide normative guidance to utopian development situations. As a result, industrial software developers have become skeptical about new solutions that are difficult to grasp and thus remain not used. This is the background for the emergence of agile software development methods.

1.1. Introduction
Agility refers to the quality of being agile. Internet software industry and Mobile and wireless application development industry are looking for a very good approach of software development. Conventional software development methods have completely closed the requirements process before analysis and design process. As this approach is not always feasible and compatible with all other projects. In contrast to the conventional approaches, Agile methods allow developers to make late changes in the requirement specification document. The focus of the agile software development as given by Agile Software Development Manifesto is presented in the following: Individuals and interactions over processes and tools Working software over comprehensive documentation. Customer collaboration over contract negotiation Responding to change over following a plan

1. There is vital importance of communication between the individual who are in development team, since development centers are located at different places. The necessity of interaction between Individuals over different tools and different versions and processes is very vital. 2. The only objective of software development team is to continuously deliver the working software for the customers. New releases must be produced for frequent intervals. The developers try to keep the code simple, straight forward and technically as advanced as possible and will try to lessen the documentation.
34 | P a g e

3. The relationship between developers and the stakeholders is most important as the pace and the size of the project grows. The cooperation and negotiation between clients and the developers is the key for the relationship. Agile methods are using in maintaining good relationship with clients. 4. The development team should be well-informed and authorized to consider the possible adjustments and enhancements emerging during the development process.

1.2. Agile Methods


Agile methods are designed to produce the first delivery in weeks, to achieve and early win and rapid feedback. These methods invent simple answers so that change can be less. This also improves design issues and quality as they are based on iteratively incremental method. What makes a method an Agile? When the process is: 1. 2. 3. 4. Incremental: Small releases with rapid iterations Cooperative: Customer and developer relationships Straight: The method which is easy to learn and modify with documentation Adaptive: Able to embrace changes instantly

Software development which can be delivered fast, quick adaptation to requirements and collecting feedback on required information. The agile software methods and development is practices based approach empowered with values, principles and practices which make the software development process easier and in faster time. Agile methods which encompasses individual methods like Extreme programming, Feature Driven Development, Scrum, etc are more coming into the commercial and academic worlds.

35 | P a g e

Figure 9: Agile Methodology

2. Requirements
Declarative Programming Tools for Computer Science Engineering Software Requirements Specification Version 0.1 - 2013 Tareq Jehad AlJebawi Software Engineering Student Prepared for Declarative Programming Tools - Software Engineering / Senior Project Supervisor: Dr. Adnan Ali August 2013
36 | P a g e

2.1. Introduction
Software engineering depending on multiple criteria in order to produce useful applications. Collecting requirements is main step in software production in order to organize the data flow and the user, system interaction. 2.1.1. Purpose In this document SRS (Software Requirement Specification) we will describe all the information needed to implement our system provided with figures and diagrams. In general following such documents is the engineering way to work. It looks like a road map walking through the specification and data to finally get the desired product. 2.1.2. Scope Declarative Programming Tools which are: Finite State Automata. Epsilon Finite State Automata. Finite State Transducer. Push Down Automata. Turing Machines. Context Free Grammar.

Means a collection of tools packed in one system allow the users to make some declaration (Entering some data) with very easy tools to finally get the desired models code. The generated code can be run and tested using Prolog environment. The given models will develop to be used in the same style.

2.2. Specific Requirements


In our system approach we consider that the benefit of Formal Methods in the mathematically concepts need to transformed to computing problems in which it will be more useful and more clearly and fast implementation. To do this job we need to know some concepts and articles. Our system takes about seven models and tries to treat it in the same way in which the user can deal with them all as one model. The main idea was to give the user the ability to enter the data needed in a simple way and provide a mechanism to visualize these data, then he can get the result he want without writing any code, so we can consider the user as a programmer for such models in a declarative manner. We can list the job or goal of our system in the following list: 1. The user can enter the system in an interactive manner in which the system displays its functionality and services to allow the user use it.

37 | P a g e

2. The user can select a model to make a new project, so the system display the provided model in a list and allows the user to select one option and start his new project. 3. The system initializes the environment for the new project. 4. The system allows the user to save his work in the created projects directory with other helped file. And give the user the ability to load this project later. 5. The system allows the user to make a new paper or lecture from a saved model and give him the full control over this document. 6. The system allows the user to make a whole bunch of different management choices or customize the work in other word. With this general introduction it provided us with the systems general idea. Of course later in the Analysis and Design section we will detailed this concepts and we will extends our discussion. The best way to represents the system any system by the way is using the Use Case diagram. 2.2.1. Use Case Diagram: A use case diagram at its simplest is a representation of a user's interaction with the system and depicting the specifications of a use case. A use case diagram can portray the different types of users of a system and the various ways that they interact with the system. This type of diagram is typically used in conjunction with the textual use case and will often be accompanied by other types of diagrams as well. Due to their simplistic nature, use case diagrams can be a good communication tool for stakeholder. The drawings attempt to mimic the real world and provide a view for the stakeholders to understand how the system is going to be designed. We should take care of some concepts when using Use Case diagram: 1. Always structure and organize the use case diagram from the perspective of the actor. 2. Use cases should start off simple and at the highest view possible. Only then can they be refined and detailed further. 3. Use case diagrams are based upon functionality and thus should focus on the "what" and not the "how".

38 | P a g e

Figure 10: Use Case Diagram

39 | P a g e

There are two use cases: 1. Transition Table 2. Visual Graph These use cases are the user interfaces that the user interact with to define his model, The Transition Table is a simple table to interact with, and it convert to the second use case Visual Graph which also can be converted to the corresponding Transition Table. Each use case diagram need to be organized which mean more details and description this process called Use Case Refinement, where we can take the use cases each alone and describe it. Here is the refinement of some use cases, and we should know that the flow of the provided model is made similar. Finite State Automata Use Case: 1. Name: Finite State Automata. Brief specification: The system allows the user to create a new Finite State Automata Model project and manipulate the transitions input, visualize and testing for the output program. 2. Actors: User or Student. 3. Precondition: No precondition here just creates a new project from the Management Panel Use Case. 4. Main Flow: a. The system presents the provided models. b. The Actor selects the suitable project. c. The Finite State Automata Frame appears with the Transition Table for inputs and Graph canvas for visualization. d. Save the inputs (as prolog .pl) e. Test and ability to redefine the inputs is possible here. 5. Conflicts or Errors may happens: a. Asynchronous between Transition Table and Graph that means: if the user made some changes to the graph and didnt reflect it to the transition table or vice versa. b. If the user runs the project without save it, he will get an empty program (no code), and then no testing is available. Transition Table Use Case: 6. Name: Transition Table.

40 | P a g e

Brief specification: After the user select a model to work with the system presents to him a window contains a table to enter some data which represents the declaration process in the system. The table provided with some functionality makes the work easy. 7. Actors: User or Student. 8. Precondition: A new project from the provided models should be created to customize the table according to this model. 9. Main Flow: f. The system presents the Transitions Table inside the Main Model Window. g. The Actor starts to entering or declaring data inside this table. h. The system maintains a collection of data from this table to process and generating the desired code. i. The data converted to a visual graph to more understanding. j. The user saved the work and at this point he able to make tests. 10. Conflicts or Errors may happens: c. The user may enter data and miss some other; the visual graph gives him the visual showing to more understanding and round this conflict. d. Asynchronous between Transition Table and Graph that means: if the user made some changes to the graph and didnt reflect it to the transition table or vice versa. Lecture Use Case: 1. Name: Lecture. 2. Brief specification: The system allows the user to create a new lecture from a previous saved model files. Then the user can use this lecture in education process or learning process. 3. Actors: User or Student. 4. Precondition: The user should has a file that contains a data for a model, then he can use this file to create the desired lecture. 5. Main Flow: a. The system presents the frame in which the user can manage the lecture and ask the user to specify a file path. b. The Actor browses the file path. c. The system analysis the file and create the suitable data such as transition functions, set of states and a set of final or accept states and graph to this model. d. The system allows the user to add articles to this lecture and modify the presented data as the need. e. The system allows the user to print out this lecture to usage.
41 | P a g e

6. Conflicts or Errors may happens: a. The use may select a file that contains invalid data or corrupted file then he cant see what he want.

3. System Analysis and Design


3.1. Defining a System
A system is a collection of components that work together to realize some objectives forms a system. Basically there are three major components in every system, namely input, processing and output.

Figure 11: System General Definition

In a system the different components are connected with each other and they are interdependent. For example, human body represents a complete natural system. We are also bound by many national systems such as political system, economic system, educational system and so forth. The objective of the system demands that some output is produced as a result of processing the suitable inputs. A well-designed system also includes an additional element referred to as control that provides a feedback to achieve desired objectives of the system.

3.2. System Life Cycle


System life cycle is an organizational process of developing and maintaining systems. It helps in establishing a system project plan, because it gives overall list of processes and sub-processes required for developing a system. System development life cycle means combination of various activities. In other words we can say that various activities put together are referred as system development life cycle. In the System Analysis and Design terminology, the system development life cycle also means software development life cycle.
42 | P a g e

Following are the different phases of system development life cycle: Preliminary study Feasibility study Detailed system study System analysis System design Coding Testing Implementation Maintenance

The different phases of system development life cycle are shown in the figure below:

Figure 12: Phases of System Development Life Cycle

3.3. Phases of System Development Life Cycle


Let us now describe the different phases and related activities of system development life cycle in short definitions to take a view over what we will describe later and what we described previously. 1. Preliminary System Study Preliminary system study is the first stage of system development life cycle. This is a brief investigation of the system under consideration and gives a clear picture of what actually the physical system is? In practice, the initial system study involves the preparation of a System Proposal which lists the Problem Definition, Objectives of
43 | P a g e

the Study, Terms of reference for Study, Constraints, Expected benefits of the new system, etc. We saw this in the Introduction section. 2. Feasibility Study In case the system proposal is acceptable to the management, the next phase is to examine the feasibility of the system. The feasibility study is basically the test of the proposed system in the light of its workability, meeting users requirements. We saw this in the Requirements section. 3. Detailed System Study The detailed investigation of the system is carried out in accordance with the objectives of the proposed system. This involves detailed study of various operations performed by a system and their relationships within and outside the system. During this process, data are collected on the available files, decision points and transactions handled by the present system. Interviews, on-site observation and questionnaire are the tools used for detailed system study. Using the following steps it becomes easy to draw the exact boundary of the new system under consideration: Keeping in view the problems and new requirements. Workout the pros and cons including new areas of the system. 4. System Analysis Systems analysis is a process of collecting factual data, understand the processes involved, identifying problems and recommending feasible suggestions for improving the system functioning. This involves studying the business processes, gathering operational data, understand the information flow. The major objectives of systems analysis are to find answers for each business process: What is being done? How is it being done? Who is doing it? When is he doing it? Why is it being done? How can it be improved?

Systems analysis is an iterative process that continues until a preferred and acceptable solution emerges. 4.1. Models Input Output Overview As we talk previously in our vision the models of the system should be work the same, and the best way to collect data is the tables. Tables really is a good data entering tool, each model has its own data types and forms. Now we will take a near look at these tables and how we think it should be. This abstract view gives us a general
44 | P a g e

representation of what we should have to implement our models. In the flowing we will list the input output models for our models showing the main differences between these models will be trivial. We starting with transition table view to show the form of data then we will show the relationship between the transition table and the transition graph. 4.1.1. Finite State Automata Input Output Model The Finite State Automatas transition table will be similar to the following table:
Table 2: Finite State Automata Input Frame

NO

Source State

Target State

Input Symbol

1 2 ...

String String ...

String String ...

String or Symbol String or Symbol ...

Table components: 1. 2. 3. 4. NO: It is normally a serial number for transitions. Source State: It is a representation of the state that the transition starts from. Target State: It is a representation of the state the transition goes to. Input Symbol: It is a Symbol or String that represent the action that makes the transition.

Here we need to mention that the state has a type which is one of the following: 1. 2. 3. 4. Start State Fix State Accept State Start Accept State

The demonstration of these types will be shown in the system design section, we will see that each state provided with image describing the type. This table will give us the ability to enter our data that we need for this model, this data should be take out and processed to get the desired result in specific word to get that prolog (logic programming) code that can run this data and test it.

45 | P a g e

Figure 13: Model General Input/Output View

Form this view we can see there is two files (file or arcs) and (file of situation) these files consist our models and be combine them we get the desired declarative programming goal. What is so important in this process is the graph representation of these table entries. The transition graph in specific word is a very important component in this model and other models, it gives a clearly view to the actual data we provided, so let us take a look to the relationship between this graph and our input table:

Figure 14: Relationship between Input Table and Visual graph

46 | P a g e

From this view it gives us more ideas for the models. In which we need to represent our data in a transition graph the question was why we cant form our data or fill the input table from the transition graph? The answer came there is no problem to do such problem in which it will give the user more easily working and using. Later in this chapter in System Design section we will go through more details about this view and how it designed. 4.1.2. Finite State Transducer Input Output Model The Finite State Transducers transition table will be similar to the following table:
Table 3: Finite State Transducer Input Frame

NO

Source State

Target State

Input Symbol

Output Symbol

1 2 ...

String String ...

String String ...

String or Symbol String or Symbol ...

String or Symbol String or Symbol ...

Table components: 1. 2. 3. 4. NO: It is normally a serial number for transitions. Source State: It is a representation of the state that the transition starts from. Target State: It is a representation of the state the transition goes to. Input Symbol: It is a Symbol or String that represent the action that makes the transition. 5. Output Symbol: It is a Symbol or String that represents the output results from the transition movement. The way to compose the model from the generated arcs and prolog interpreter and the relationship between the transition tables with the transition graph is the same in the Finite State automata model and it will be so for the other models. 4.1.3. Pushdown Automata Input Output Model The pushdown automatas transition table will be similar to the following table:
Table 4: Pushdown Automata Input Frame

NO

Source State

Target State

Input Symbol
String or Symbol String or Symbol ...

Top of Stack
String or Symbol String or Symbol ...

New Top of Stack


String or Symbol String or Symbol ...

1 2 ...

String String ...

String String ...

Table components:

47 | P a g e

1. 2. 3. 4.

NO: It is normally a serial number for transitions. Source State: It is a representation of the state that the transition starts from. Target State: It is a representation of the state the transition goes to. Input Symbol: It is a Symbol or String that represent the action that makes the transition. 5. Top of Stack: It is a Symbol or String that represents the current value of the stack 6. New Top of Stack: It is a Symbol or String that represents the new value of the stack (top of stack) after the operation applied. 4.1.4. Turing Machines Input Output Model The Turing Machines transition table will be similar to the following table:
Table 5: Turing Machines Input Frame

NO

Source State

Target State

1 2 ...

String String ...

String String ...

Input Symbol String or Symbol String or Symbol

Output Symbol String or Symbol String or Symbol

Direction
Left Right Stay L, R or S

...

...

...

Table components: 1. 2. 3. 4. NO: It is normally a serial number for transitions. Source State: It is a representation of the state that the transition starts from. Target State: It is a representation of the state the transition goes to. Input Symbol: It is a Symbol or String that represent the action that makes the transition. 5. Output Symbol: It is a Symbol or String that represents the output results from the transition movement. 6. Direction: It is like a pointer that determines if the pointer should be moved to the left or right or stay at the same location. 4.1.5. Context Free Grammar Input Output Model The Context Free Grammars transition table will be similar to the following table:
Table 6: Context Free Grammar Input Frame

NO

Left Side

Right Side

1 2 ...

String String ...

String String ...


48 | P a g e

Table components: 1. NO: It is normally a serial number for transitions. 2. Left Side: It is a string value that represents the left side of our grammar. 3. Right Side: It is a string value that represents the right side or our grammar. 4.2. Output in More Details In the previous section we see all the input or transition tables. These tables will hold models data; our target from collecting these data is to convert is to another type of data that can be used in generating our codes. In specific word the data we need to obtain is a collection of Facts, these facts is like a database in prolog codes, so be generating such data we can use it directly in the generated code. Types of facts that we want to obtain is listed below: 1. Initial (x). 2. Final (y). 3. Fix (a, b, c... etc). The initial fact represents the start state in our model means where the search should be start. The final fact or facts, because it is a collection of facts means we can have many finals facts represent where the search should be end, in this state the interpreter can determines if the query has been found or not. The fix fact is the main or the core of our model that represents the inner transition values. The search start from the initial state goes through the fix states until it reaches the final states then the interpreter returns the result to use. In the next section system design we will see the actual way that these output treated and how it designed. 5. System Design Based on the user requirements and the detailed analysis of the system should be designed. This is the phase of system designing. It is the most crucial phase in the developments of a system. The logical system design arrived at as a result of systems analysis is converted into physical system design. Normally, the design proceeds in two stages: Preliminary or General Design. Structured or Detailed Design. 5.1. System Components A component: A reusable piece of software that provides some meaningful aggregate of functionality. A cluster of classes that are themselves cohesive but are loosely coupled relative to other clusters. Components may be used to hierarchically
49 | P a g e

decompose a system and represent its logical architecture. The essential elements of a component diagram are components, their interfaces, and their realizations As we describe previously we have transition table for each model, this transition table is the main component in our system. Let us try to decompose this compound component to its primary components: In general the transition table consists of list of transitions and each transition as shown the tables consist of number of fields. The main fields in the transition are the states: Source State and Target State. In the following diagram we will show the component diagram that presents the components and the relationship between them, then we will details them later.

50 | P a g e

Figure 15: Component Diagram

The components presented in the figure are: 1. 2. 3. 4. 5. State Input. Transition Input. Transition Table. Graphics Converter. Transition Graph.

51 | P a g e

The state input is the most important component and the primary one in the system in which it hold the state name and type. Name and Type is really what represent the state and differentiate it from other states. In our design view we consider that putting these two important properties in one component is more useful and easier to use. Let us take a look at the shape that the state should take to achieve our work.

Figure 16: State Input Design View

By this view we can take out the data we want to represent each state. Then we will move to see how the transition input designed with helping of the state input component.

Figure 17: Transition Input Design View

We should note that this transition input take its form depending on the model we select. So what we describe in the analysis section will reflected to form different transition inputs. After we get this transition input designed it is the time to form our transition table which consist of number of transition input that the user can determine it. In the implementation section we will see how the component programmed in see the final view of these components. The Transition Graph component is actually a graph viewer component that works in two modes:
52 | P a g e

1. Visualize the transitions generated by the transition table. 2. Ability to draw the transition then converted to transitions. In the second part which is drawing the graph, it is normally as a painter tools that has some options to draw a transition graph, but what so important in this process is the Graphics Converter component that takes both the transition table input and transition graph and convert it to corresponding transition and vice versa. 5.2. Graphics Design There is an important component in the system and independent one. It is the Graphics Library it provides all the graphical representation to our models. Here are the graphics objects that this library provides: 1. 2. 3. 4. 5. 6. Graphics representation for the Start state. Graphics representation for the Fix state. Graphics representation for the Accept state. Graphics representation for the Start Accept state. Graphics representation for the Transition. Advanced panel to hold and manages graphics objects.

We take in consideration when designing this library some of criteria that makes the graphics more advances and gives more control over the output graph. Below is a list of some consideration taken in graphics designing? 1. 2. 3. 4. 5. 6. 7. Add Graphics. Edit Graphics. Delete Graphics. Select Graphics. Move Graphics. Zooming. Rotating.

And we add some properties that give the graphics more choices and options, these properties will demonstrate in the next section. In the next section we will see the class diagram that shows the classes that form this library and the relationship between these classes. 6. Implementation Implementation means move the theoretical concepts into computing models. In the section 4 (Implementation) in this chapter we will go through this phase in more details.

53 | P a g e

7. Testing Testing means applying examples to the system and takes the results then compare them to the real results to determine the system efficiency and workability. In the section 5 (Deployment and Testing) in this chapter we will go through this phase in more details. 8. Maintenance Maintenance is necessary to eliminate errors in the system during its working life and to tune the system to any variations in its working environments. It has been seen that there are always some errors found in the systems that must be noted and corrected. It also means the review of the system from time to time. The review of the system is done for: Knowing the full capabilities of the system. Knowing the required changes or the additional requirements. Studying the performance. If a major change to a system is needed, a new project may have to be set up to carry out the change. The new project will then proceed through all the above life cycle phases.

3.4. System Behavior


To see the behavior of the system or in other word the flow of the system in which the user can enter the system and deal with it. This approach is describes using the Activity Diagram, in such diagrams it shows the starting point in which the system will starts then what the next step should the user does, flowing these steps will guide the user throw the system data flow, and shows a general view about the system behavior. In the following diagram we will see the different options available to the user and how he can select his model and what are the ways to entering data to get the output at the end and terminate the system.

54 | P a g e

Figure 18: System Activity Diagram

55 | P a g e

4. Implementation
The system design needs to be implemented to make it a workable system. This demands the coding of design into computer understandable language, i.e., programming language. This is also called the programming phase in which the programmer converts the program specifications into computer instructions, which we refer to as programs. It is an important stage where the defined procedures are transformed into control specifications by the help of a computer language. The programs coordinate the data movements and control the entire process in a system. It is generally felt that the programs must be modular in nature. This helps in fast development, maintenance and future changes, if required. Here we will show the class diagram which contains all the classes belong to the models and then we will describe them later. 1. State Class: Holds the data needed to form a state with its name and type and it play an important role in implementing the State Input user control. 2. Transition Class: Holds the needed to form a transition with its source state and target state and input/output values, and it will be wrapped in a user control called Transition Input. 3. UniversalRecognizer Class: Contains the most data and process responsible for handling code and arrange it. 4. FileManager Class: Contains many functions to deal with file system, and directories to save projects and load them later. 5. Graphics Class: Contains many functions that help with graphics operation in our system, the Graphics Library which contains the core of graphics need to interact with our system and models so this class offers this functionality. 6. Graphics Converter Class: This class plays an important role in the process of visualizing and extracts data from visuals. It really converts the data collected by the transition table into visual graph and vice versa. 7. Declarative Programming Model Enumeration: This enumeration defines the models that our system deals with, to hold an instance of our current model. Let us take a look at the class diagram and try to describe the important algorithms in our system in other word the source code that implements these classes.

56 | P a g e

Figure 19: Models' Class Diagram

57 | P a g e

4.1. Implementing the State class


All what we saw in the previous section just needs to convert to the computing environment i.e. implementing with a programming language. The code snippet will presented in this documented based on the C#.NET environment embedded in the Visual Studio 2010. The State class consists mainly of two properties: 1. State name. 2. State Type. State name is normally a simple string, while the state type is a defined value from the enumeration State Type.
public enum StateType { Start, Fix, Accept, StartAccept }

The definition of these two properties in the class will appear like:
public class State { private string m_name = ""; private StateType m_type = StateType.Fix; public string Name { get { return m_name; } set { m_name = value; } } public StateType Type { get { return m_type; } set { m_type = value; } } }

The behavior of changing the state type is the most important one in this class, so we provide a method called ToggleState (); that take the current state type and change it to another type according to the StateType enumeration.
public void ToggleState() { switch (Type) { case StateType.Start: Type = StateType.Fix; break; case StateType.Fix: Type = StateType.Accept;break; case StateType.Accept: Type = StateType.StartAccept;break; case StateType.StartAccept: Type = StateType.Start; break; } }

58 | P a g e

Now we have a good designed class that can hold our data. It is the time to wrap this class inside a User Interface Control that can deal with the user in simple way. The behavior of this control just to change the properties values of the state class we called it StateInput to point that it just an input User Interface to enter our data, and because the Type property is not a string or it has a multi value so we designed a good small control with inside this control that can help in selecting the type value. This control is a small image next to the text area provided to enter the state name.

4.2. Implementing the StateInput User Control

Figure 20: State Input User Control

The figure is so simple. By clicking the type changer icon we can get different types for the state. As shown below:

Figure 21: State Input Type Changing

To make the process of creating states is easier, we provide a context menu with the state input user control. This context menu is contain some functions, but the most important one is the shortcuts for other states means when you creating a states it saved to make you able to use it later. He is a figure shows the context menu of a state input where some states were define such: 1. 2. 3. 4. start: Start State q1: Fix State q2: Fix State accept: Accept State

59 | P a g e

Figure 22: State Input Context Menu

With this additional functionality the inputting is easier and fast.

4.3. Implementing the Transition class


The transition class consists mainly of three properties: 1. Source State. 2. Target State. 3. Input Symbol (may contains other properties for IO). Source and Target states are objects from the previous class State class. The other properties of input and output are simply strings. We should mention that the transition class designed to suitable all models, we provide it with a controlling properties called (Model) that is a value from the enumeration called Declarative Programming Models and the transition change its behavior according to this value.
public enum DeclarativeProgrammingModels { FiniteStateAutomata, EpsilonFiniteStateAutomata, FiniteStateTransducer, PushDownAutomata, TuringMachines, ContextFreeGrammar, HiddenMarkovModel }

Let us take a look at the definition of the transition class with these properties:

60 | P a g e

public class Transition { private private private private State m_source; State m_target; string m_inputSymbol = ""; DeclarativeProgrammingModels m_model;

public State Source { get { return m_source; } set { m_source = value; } } public State Target { get { return m_target; } set { m_target = value; } } public string InputSymbol { get { return m_inputSymbol; } set { m_inputSymbol = value; } } public DeclarativeProgrammingModels Model { get { return m_model; } set { m_model = value; } } }

As we talked previously the Model properties control the behavior of the transition in which the transition responsible for generating the Arcs, so for each model the transition generate suitable arcs as the following: 1. Finite State Automata and Epsilon Finite State:
arc(start state, target state, input symbol).

2. Finite State Transducer:


arc(start state, target state, input symbol, output symbol).

3. Pushdown automata:
arc(start state, input symbol, top of stack, new top of stack, target state).

4. Turing Machines:
arc(start state, input symbol, output symbol, direction, target state).

5. Context Free Grammar:


arc(left side, right side).

The property that generates the arcs inside the transition is:
61 | P a g e

public string Arcs { get { string transition = ""; switch (Model) { case DeclarativeProgrammingModels.FiniteStateAutomata: case DeclarativeProgrammingModels.EpsilonFiniteStateAutomata: transition = string.Format("arc({0}, {1}, {2})", Source.Name, Target.Name, "input"); break; case DeclarativeProgrammingModels.FiniteStateTransducer: transition = string.Format("arc({0}, {1}, {2}:{3})", Source.Name, Target.Name, "input", "output"); break; case DeclarativeProgrammingModels.PushDownAutomata: transition = string.Format("arc({0}, {1}, {2}, {3}, {4})", Source.Name, "input", "top of stack", "new top of stack", Target.Name); break; case DeclarativeProgrammingModels.TuringMachines: transition = string.Format("arc({0}, {1}, {2}, {3}, {4})", Source.Name, "input", "output", "direction", Target.Name); break; case DeclarativeProgrammingModels.ContextFreeGrammar: transition = string.Format("arc({0}, {1})", "left side", "right side"); break; } return transition; } }

Now with this declaration it is the time to wrap this class inside a User Control, this user control has two StateInput and a number of text fields to enter our inputs and outputs.

4.4. Implementing the TransitionInput User Control


For the Finite State Automata and Epsilon Finite State Transducer models we will get the following transition input user control:

Figure 23: FSA Transition Input User Control

62 | P a g e

For the Finite State Transducer transition input is similar to the Finite State Automata one but has additional output field:

Figure 24: FST Transition Input User Control

For the Pushdown Automata transition input is similar to the Finite State Automata one and additional two fields Top of Stack and New Top of Stack:

Figure 25: PDA Transition Input User Control

For the Turing Machines transition input is similar to the Finite State Automata one and additional two fields output symbol and Direction list that allows the user to select one value from the tree value: 1. Left: move the pointer to the left. 2. Right: move the pointer to the right. 3. Stay: stay the pointer in the same location.

Figure 26: TM Transition Input User Control

For the Context Free Grammar transition input it just contains to text fields one to hold the left side value and the other for holding the right side value, here is the figure that shows the CFG transition input which is the last model in our system.

63 | P a g e

Figure 27: CFG Transition Input User Control

4.5. Implementing the UniversalRecognizer class


UniversalRecognizer is a very important class in our system. It contains a bunch of static methods that can be used directly, these methods work many functions, and here is a list of this class general function: 1. 2. 3. 4. 5. 6. 7. Arrange Generated Code: sort and organize the generated code. Hold Finite State Automata Predicates: the prolog code of FSA. Hold Finite State Transducer Predicates: the prolog code of FST. Hold Pushdown Automata Predicates: the prolog code of PDA. Hold Turing Machines Predicates: the prolog code of TM. Hold Context Free Grammar Predicates: the prolog code of CFG. Generate Code: Takes some arguments and generates code according to these arguments and other criteria. 8. Manage the Epsilon Input Output symbols. 4.5.1. Writing the Interpreters Here we will show the interpreters implementation for the prolog programs. These programs will add to our generated arcs file to compose the full prolog program. 1. Finite State Automata Interpreter: To construct the finite state automata interpreter, we should be familiar with the prolog syntax, the function
test1(Symbol).

Is a recursive function that takes the parameter and goes through the facts we provide until it either reach the final state and accept or not then reject.
recognize1(Node,[]) :- final(Node). recognize1(Node1,String) :- arc(Node1,Node2,Label), traverse1(Label,String,NewString), recognize1(Node2,NewString). traverse1(Label,[Label|Symbols],Symbols). test1(Symbols) :- initial(Node), recognize1(Node,Symbols). generate1(X) :- test1(X). recognize2(Node,[]) :- final(Node).

64 | P a g e

recognize2(Node1,String) :- arc(Node1,Node2,Label), traverse2(Label,String,NewString), recognize2(Node2,NewString). traverse2('#',String,String). traverse2(Label,[Label|Symbols],Symbols).

parse1(Node,[],[Node]) :- final(Node). parse1(Node_1,String,[Node_1,Label|Path]) :- arc(Node_1,Node_2,Label), traverse1(Label,String,NewString),parse1(Node_2,NewString,Path). traverse1(Label,[Label|Symbols],Symbols). testparse1(Symbols,Parse) :- initial(Node), parse1(Node,Symbols,Parse). genparse1(Symbols,Parse) parse2(Node,[],[Node]) :- testparse1(Symbols,Parse). :- final(Node).

parse2(Node_1,String,[Node_1,Label|Path]) :- arc(Node_1,Node_2,Label), traverse2(Label,String,NewString), parse2(Node_2,NewString,Path). traverse2('#',String,String). traverse2(Label,[Label|Symbols],Symbols). testparse2(Symbols,Parse) :- initial(Node), parse2(Node,Symbols,Parse). genparse2(Symbols,Parse) parse3(Node,[],[Node]) :- testparse2(Symbols,Parse). :- final(Node).

parse3(Node_1,String,[Node_1,Label|Path]) :- arc(Node_1,Node_2,Label), traverse3(Label,String,NewString), parse3(Node_2,NewString,Path). traverse3('#',String,String). traverse3(Label,[Symbol|Symbols],Symbols) :- lex(Symbol,Label). testparse3(Symbols,Parse) :- initial(Node), parse3(Node,Symbols,Parse). genparse3(Symbols,Parse) :- testparse3(Symbols,Parse).

2. Finite State Transducer Interpreter: In this experiment well construct an interpreter for Finite State Transducer; in this model we should know there are two important parts: 1. Input Tape 2. Output Tape At the end of implementing this interpreter we can ask the model as the following:
testtrans1(?List, ?List).

The Lists represent the two tapes input and output.


transduce1(Node,[],[]) :- final(Node). transduce1(Node_1,String_left,String_right) :- arc(Node_1,Node_2,Label), traverse1(Label,String_left,NewString_left,String_right,NewString_right), transduce1(Node_2,NewString_left,NewString_right). traverse1(Sym_left:Sym_right,[Sym_left|Rest_left],Rest_left, [Sym_right|Rest_right],Rest_right).

65 | P a g e

testtrans1(Left,Right) :- initial(Node), transduce1(Node,Left,Right).

transduce2(Node,[],[]) :- final(Node). transduce2(Node_1,String_left,String_right) :- arc(Node_1,Node_2,Label), traverse2(Label,String_left,NewString_left,String_right,NewString_right), transduce2(Node_2,NewString_left,NewString_right). traverse2('#':'#',String_left,String_left, String_right,String_right). traverse2('#':Sym_right,String_left,String_left, [Sym_right|Rest_right],Rest_right). traverse2(Sym_left:'#',[Sym_left|Rest_left],Rest_left, String_right,String_right). traverse2(Sym_left:Sym_right,[Sym_left|Rest_left],Rest_left, [Sym_right|Rest_right],Rest_right). testtrans2(Left,Right) :- initial(Node), transduce2(Node,Left,Right).

3. Pushdown Automata Interpreter: In this experiment well construct an interpreter for pushdown automata. Suppose we write a pushdown automaton as a set of Prolog facts of the following two forms. a. t(state, letter, top, operation, nextstate). b. start(state). c. final(state). In order to write a simple interpreter for PDAs, well need to make a few assumptions. The input string will be represented as a list. The stack is a list that is initialized with the value [e], which means e is always the starting stack symbol. Well reserve the letters p and n for the operations pop and nop, and well agree to let the push instruction be represented by the symbol that is to be pushed. For example, in the instruction
t(0, a, e, b, 1).

The letter b means push b. For example, a PDA to recognize the language {anbn | n N} can be written as the following set of facts.
start(0). t( 0, a, e, a, 0 ). t( 0, a, a, a, 0 ). t( 0, b, a, p, 1 ). t( 0, [ ], e, n, 2 ). t( 1, b, a, p, 1 ). t( 1, [ ], e, n, 2 ). final(2).

To check whether this PDA accepts the string aabb, we type the following goal:
66 | P a g e

Computability
?- accept([a, a, b, b]).

This action starts the execution of the PDA interpreter, which we will describe next. The interpreter executes a computation sequence, where the path predicate represents an ID containing the current state, the current input string, and the current stack. If the input is empty and the current state is final, then the computation ends successfully. Otherwise, if the input is not empty, the computation continues by looking up an appropriate instruction. The predicate oper(Stack, O, NewStack) means perform stack operation O on Stack, resulting in NewStack. The interpreter can be written as follows, where S is the list representing the input string:
accept(S) :- start(I), path(I, S, [e]). path(K, [ ], Stack) :- final(K). path(K, [A|B], [H|T]) :- t(K, A, H, O, N), oper([H|T], O, NewStack), path(N, B, NewStack). path(K, S, [H|T]) :- t(K, [ ], H, O, N), oper([H|T], O, NewStack), NewStack). oper([H|T], p, T). oper(Stack, n, Stack). oper(Stack, A, [A|Stack]). path(N, S,

In the Deployment and Testing section we will use this interpreter to solve some problem and shows the results coming from the system. 4. Turing Machines Interpreter: Well describe a logic program interpreter for Turing machines. The interpreter will execute any Turing machine with a single two-way infinite tape. Well make the following assumptions about any Turing machine that is to be executed by the interpreter. The read/write head is at the left end of any nonempty input string. The letters l, s, and r represent the moves of the read/write head. The symbol # denotes a blank tape cell. Instructions are represented as facts of the following form.
t(state, letterToRead, letterToWrite, movement, nextState). start(state).

We represent the accept state as halt state. To find the result of adding 1 to the binary number 1011, we type the goal
?- compute([1, 0, 1, 1], Out).

67 | P a g e

This action starts the execution of the Turing machine interpreter, which in turn executes a computation sequence of the given Turing machine. When a halt instruction is executed the variable Out will be returned as a list that represents the tape. The interpreter starts out by placing the input list onto the tape. The tape is represented by the following three items. Cell: is a variable that holds the tape symbol in the current cell pointed at by the read/write head. Left: is a list that holds the information on the tape to the left of the current cell. The head of the list holds the symbol immediately to the left of the current cell. Right: is a list that holds the information on the tape to the right of the current cell. The head of the list holds the symbol immediately to the right of the current cell. For example, the input list [1, 0, 1, 1] is represented on the tape as left = [ ], Cell = 1, Right = [0, 1, 1].

The find predicate tries to find and execute an instruction. Its first argument is the state. The next three arguments are the representation of the tape, and the last argument holds the variable for the output tape. The move predicate makes a move and returns a new representation of the tape in variables A, B, and C. The continue predicate checks for the halt state. If its found, the output tape is constructed and placed in the last variable. Otherwise the execution continues by calling the find predicate to execute another instruction. The clauses for the interpreter are listed as follows:
t(state, letterToRead, letterToWrite, move, nextState). compute([ ], OutTape) :- start(I), find(I, [ ], #, [ ], OutTape). compute([Head|Tail], OutTape) :- start(I), find(I, [ ], Head, Tail, OutTape). find(State, Left, Cell, Right, OutTape) :- t(State, Cell, Write, Move, Next),move(Move, Left, Write, Right, A, B, C), continue(Next, A, B, C, OutTape). continue(halt, Left, Cell, Right, OutTape) :- reverse(Left, R), append(R, [Cell|Right], OutTape). continue(State, Left, Cell, Right, OutTape) :find(State, Left, Cell, Right, OutTape). move(l, [ ], Cell, Right, [ ], #, [Cell|Right]). move(l, [Head|Tail], Cell, Right, Tail, Head, [Cell|Right]). move(s, Left, Cell, Right, Left, Cell, Right). move(r, Left, Cell, [ ], [Cell|Left], #, [ ]). move(r, Left, Cell, [Head|Tail], [Cell|Left], Head, Tail).

68 | P a g e

When the halt state is reached, the tape is reconstructed as a single list with entries in the proper order. To do this we need to reverse the Left part of the tape before concatenating it to the list [Cell|Right]. The predicate reverse(X, Y) sets Y to the reverse of list X. The output tape consists of all cells that were used during the computation. The predicate append(X, Y, Z) sets Z to the concatenation of the two lists X and Y. These predicates can be accessed by including the following statement with the source.
:- use_module(library(lists)).

For the example Turing machine, to add 1 to the binary number 1011, we write the goal;
?- compute([1, 0, 1, 1], Out).

This causes the Turing machine interpreter to execute the instructions of the Turing machine and, upon halting, to return the list
Out = [1, 1, 0, 0, #],

which represents the binary number 1100. Notice in this example that the symbol # is included in the output tape. This is because the computation used that extra cell when it scanned to the right looking for a blank. 5. Context Free Grammar Interpreter: How can we implement a parser for the language of a grammar? If the grammar is context-free and all left recursion has been removed; means the first symbol in the right side should not be the same symbol in the left side then it is quite easy to build a parser in Prolog. Recall that each step in a leftmost derivation of a string consists of replacing the leftmost nonterminal of a sentential form with the right side of a production. So each nonterminal often derives only a proper substring of the given string. For this reason, each nonterminal will be associated with a predicate having two arguments, one for the given string and one to hold the rightmost portion of the string not derived by the nonterminal. Lets do an example to help get the idea. Suppose we start with the following grammar. S aST S T aSb Tc

Let s and t denote the predicates to be associated with nonterminals S and T, respectively. Well represent strings as lists for ease of notation. Now we can give the Prolog definitions of s and t as follows.
s(X, Z) :- X = [a|R], s(R, U), t(U, Z). %% S aST

69 | P a g e

s(X, Z) :- X = Z. %% S t(X, Z) :- X = [a|R], s(R, U), U = [b|Z]. %% T aSb t(X, Z) :- X = [c|Z]. %% T c

A typical goal tests whether a string is in the language. For example, to see whether the string aab is in the language, type the goal
?- s([a, a, b], [ ]).

Notice that the second argument of the goal is always [ ], which represents the empty string L. The reason for this is that the initial call to s asks whether there is a leftmost derivation of the entire input string. In other words, the goal asks whether there is a derivation S aab. These two clauses can also be written as four separate clauses, one for each of the four productions. s a, s, t. s [ ]. t a, s, b. t c. So nonterminals must be lowercase names, terminal letters are strings in quotes, and the empty string is represented by the empty list. The operation is macro operation that transforms the input clauses into other clauses that are used to do the parsing. The nonterminals are converted to predicates with two arguments. For example, to see if the string aab is derived by the grammar we write the following goal.
?- s(aab, [ ]).

If we are going to be doing much testing it can be tedious to always have to type the double quotes and the empty list. We can avoid this tedium by defining our own predicate to parse strings of the grammar. For example, consider the following definition for a predicate p:
p([ ]) :- s([ ], [ ]). p(X) :- name(X, Y), s(Y, [ ]).

The Prolog predicate name is used to transform between a string X and a list Y of ASCII codes for the letters of X. Once weve added this definition to the program, we can find out whether the string aabb is derived by the grammar by writing the following simpler goal.
?- p(aabb).

70 | P a g e

NOTE: Prolog parses in a top-down left-to-right fashion. So if a grammar is left recursive, then make sure to remove the left recursion before you write the Prolog clauses.

4.6. Implementing the FileManager class


FileManager class is the responsible for the operation of creating files and directory and saving and loading the models files. In the following list we will demonstrate the general functions that this class does. 1. 2. 3. 4. Create project directory. Create a valid name for projects. Save model files. Load a pre-saved model.

Let us take a closer look at the implementation of this classs methods. First we will take the project directory that takes a parameter the folder name to be created this method tries to create this folder if not it return false as the folder had been not created.
public bool CreateProjectDirectory(string projectFolder) { try { Directory.CreateDirectory(projectFolder); return true; } catch { return false; } }

Second we will take a look at the create valid name for the project method it just take two arguments one is the folder name to create the projects directory inside it and the second is the model name to specify the name.
public string GetValidProjectName(string folder, string modelName) { int i = 1; while (true) { string tempName = string.Format("{0}{1}", modelName, i); string suggestedName = string.Format("{0}\\{1}", folder, tempName); if (!Directory.Exists(suggestedName)) return tempName; i++; } }

71 | P a g e

This methods start from number 1 and concatenates the model name with this number and check if this name is exist in the projects directory if not it will creates it else it will increment the number and try another name until it reach a suitable name. Save model methods really it consists of three methods. 1. SaveModel (); 2. SaveGraphImage (); 3. SaveModelXMLFormat (); For the first method SaveModel (). It takes two arguments one to hold the file name and the other contains the code to be saved. Let us take a look at the code of it.
public bool SaveModel(string fileName, string code) { try { File.WriteAllText(fileName, code); return true; } catch { return false; } }

The behavior of this method is trivial, if there is a problem in saving the method will returns a false to represent the failure of the process. For the second method SaveGraphImage (). The method takes two arguments also one for the Canvas, which is an element of our Graphics Library that we talked previously and we will talk about its implementation later. The second parameter is the file name that is the name of this image which also consistence with the model name.
public void SaveGraphImage(Canvas canvas, string fileName) { RenderTargetBitmap renderBitmap = new RenderTargetBitmap( (int)canvas.ActualWidth, (int)canvas.ActualHeight, 96d, 96d, System.Windows.Media.PixelFormats.Pbgra32); canvas.Measure(new Size((int)canvas.ActualWidth, (int)canvas.ActualHeight)); canvas.Arrange(new Rect(new Size((int)canvas.ActualWidth, (int)canvas.ActualHeight))); renderBitmap.Render(canvas); PngBitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(renderBitmap));

72 | P a g e

using (FileStream file = File.Create(fileName)) { encoder.Save(file); } }

73 | P a g e

Figure 28: Graphics Library Class Diagram

74 | P a g e

We talked about these classes before, in which it belongs to the Graphics Library that is responsible for the graphics tasks in our system. The hierarchy is simple; we have a parent abstract class call GraphicsBase that holds all the important properties for advance graphics, this class derived into two classes one also abstract called GraphicsStateBase that is the parent for the graphics states and the other for the transition graphics. The other important class is the DrawingCanvas class that responsible for displaying the graphics on its surface. It contains a collection of GraphicsBase objects and it is accessible for more control, the canvas toke these graphics objects and draw them. It also contains the other function we talked about like: selecting, adding, removing...etc.

5. Deployment and Testing


What we said before is the analysis, design and implementation of our system, yet we havent seen any results of the system, it is the time to make some tests and applied some examples over the system. In the chapter 1 Theoretical Models we described the models in purely mathematically approach. Intentionally we didnt support any examples, because it gives no usefulness in the mathematically concepts, but when we provide them in computing models they will be more understood and readably. Let us starting by showing the models examples one by one and showing the system ability to apply them. First we need to briefly show how to make a new project using the system user interface, this process is to specify the model type, project name and project path. 1. 2. 3. 4. 5. 6. Run the system. Click New Project button. You can change the projects path. The system will automatically generate a project name you can change it. The system verify the project name if it already exist or invalid name. Click the Create button to start your model.

The following is what actually appear to perform this process.

75 | P a g e

Figure 29: New project user interface

After clicking the create button, the model user interfaces will appear, this interfaces consist mainly of two parts. 1. Model user interface that contains many functions and in the center contains the graph viewer. 2. Transition Table user interface that linked with the Model user interface and also contains some other functions to make integrated work. Before we start we should pointing to a very important notes when make testing over the system, these notes will be in the behavior and the syntax of the querying and question that we will ask to our programs. 1. The capital letters characters will use variables, means their values not specified yet. These variables will vary through (X, Y, Z ...) and so on. 2. Using the programs as a Recognizer: means ask the program about some inputs if these inputs belong to our language (model) or not. The result will come true if the input belongs to our system and false if not.
76 | P a g e

3. Using the program as a Generator: means provide the system with some variables as we talked previously and ask it to check if there is any result that match our variables, the result will come either the value for each provided variable then our query is answered or false means there is no answer. For more helping in using of the system we provide a small tool that can build the query for the user. The user just type his string to be tested and he can select the type of query means generating or recognizing, in the following figure we will present this tool in these two modes, surely for each model the too has its own shape and fields. Here is for Pushdown Automata model.

Figure 30: User Query builder in two modes

5.1. Testing Finite State Automata


In this section we will show a different bunch of examples from the finite state automata and epsilon finite state automata models.
Example 5.1.1: [then String recognizer | String Matching]

Finite Automaton recognizing the string then.

77 | P a g e

Figure 31: Finite automata simple recognizer

The generated arcs for this model will be like the following:
initial(s1). final(s5). arc(s1, s2, t). arc(s2, s3, h). arc(s3, s4, e). arc(s4, s5, n).

We need to present the shape of the transition table in our system and see how the way of entering data is easy and interesting, and this table as we describe before will take its form depending in the current model and we saw how the different shapes will be in a design view.

Figure 32: Systems Transition Table provided with current example

78 | P a g e

Now we can make some queries over the prolog environment that runs our generated code, let us see some queries that clarify our mission.
%% then 1 ?- test1([t, h, e, n]). true .

%% the? 2 ?- test1([t, h, e, AcceptLetter]). AcceptLetter = n .

%% th?? 3 ?- test1([t, h, Letter1, Letter2]). Letter1 = e, Letter2 = n .

%% j??? 4 ?- test1([j, X, Y, Z]). false.

%% X 5 ?- test1(AcceptString). AcceptString = [t, h, e, n]

Queries discussion: In the first query we ask the system to check if the string (t,h,e,n) is belong to our language or not, the result is (true) means this string is belong to our language. In the second query we give the system a part of our data and provide it with a variable means if the provided data part is match some data in our language and the variable not important what will become, then check these scenario. The result comes (X=n) means if we replace the variable X with the value n, then this input is belong to our language. In the third query we repeat the second query with two variables X and Y. In the fourth query we provide the system with data and variables, and because the first letter (j) is not belong to our language then the result comes soon as (false). In the fifth query we asked the model to generate an accept string and the system go through states and return the [t, h, e, n] string.
Example 5.1.2: [Signed float number | Compiler Design]

Numbers in programming are so important and there are many types for numbers:
79 | P a g e

Short Long Integer Float Double Decimal

Here is an example from Compiler Design that recognizes a float signed float number, means has a decimal part separated by a dot symbol and signed with negative or positive sign.

Figure 33: Float signed number Recognizer

The generated arcs will be similar to follows, note that the (...) means range from the upper arc to lower arc.
initial(q0). final(q2). final(q4). arc(q0, q1, +). arc(q0, q1, -). arc(q1, q2, 0). ... arc(q1, q2, 9). arc(q2, q2, 0). ... arc(q2, q2, 9). arc(q0, q2, 0). ... arc(q0, q2, 9). arc(q2, q3, .). arc(q3, q4, 0). ...

80 | P a g e

arc(q3, q4, 9). arc(q4, q4, 0). ... arc(q4, q4, 9).

Let us make some tests over this recognizer


%% +123.456 1 ?- test1([+, 1, 2, 3, ., 4, 5, 6]). true .

%% -123.456 2 ?- test1([-, 1, 2, 3, ., 4, 5, 6]). true .

%% *123.456 3 ?- test1([*, 1, 2, 3, ., 4, 5, 6]). false.

%% 123 4 ?- test1([1, 2, 3]). true .

%% 123.456 5 ?- test1([1, 2, 3, ., 4, 5, 6]). true .

%% x123.456 6 ?- test1([x, 1, 2, 3, ., 4, 5, 6]). false.

Queries discussion: The queries 1, 2, 4 and 5 are true because it asked for a signed numbers, no sign mean positive also and the dot (.) symbol denote to the decimal part of the number, so they all a correct signed float format. The queries 3 and 6 had false results because they both start with a symbol that is neither a sign nor a number, so the number in invalid format.
Example 5.1.3: [Identifier Recognition | Compiler Design]

Here is an example of Compiler Design in which we need to design automata to recognize identifier declaration. Identifier must start with symbol from the alphabet or underscore, and then it can follow by a mixing of characters and numbers.
81 | P a g e

Figure 34: Identifier Recognizer

Here are the generated arcs the (...) points to ranges of symbols.
initial(start). final(final). arc(start, final, a). arc(start, final, b). ... arc(start, final, z). arc(final, final, a). arc(start, final, A). arc(start, final, B). ... arc(start, final, Z). arc(start, final, _). arc(final, final, a). arc(final, final, b). ... arc(final, final, z). arc(final, final, 0). ... arc(final, final, 9). arc(final, final, A). arc(final, final, B). ... arc(final, final, Z). arc(final, final, _).

Let us make some testing over this language or model.


%% num 1 ?- test1([n, u, m]). true .

%% num1 2 ?- test1([n, u, m, 1]).

82 | P a g e

true .

%% 1num 3 ?- test1([1, n, u, m]). false.

%% firstname 4 ?- test1([f, i, r, s, t, n, a, m, e]). true .

%% first name 5 ?- test1([f, i, r, s, t, ' ', n , a, m, e]). false.

%% 12name 6 ?- test1([1, 2, n, a, m, e]). false.

Queries discussion: The queries 1 and 2 are acceptable, because they start with an alphabet letter then it followed by mixing of letters and numbers, and havent spaces. The queries 3 and 6 are rejected because they start with a number, while the identifier mustnt start with it according to our language. The query 4 is accepted it has not rejected symbol. The query 5 is rejected because it contains a space ( ) inside its definition.
Example 5.1.4: [Signed Even, Odd numbers | Mathematics and Computing]

Even and odd numbers are so used in mathematics and computing in general. Making simple machine that recognizes these numbers from each other is an interesting example, note that event number ends with an even digit.

Figure 35: Even number recognizer

83 | P a g e

If we want to enhance this example and provide signed property we will have additional transition at first to determine the sign symbol.

Figure 36: Signed even number recognizer

The odd numbers will be the same of even numbers, but it ends with odd digit.

Figure 37: Signed odd number recognizer

Now we will describe and test according to the signed even number recognizer the odd will be the same.
initial(start). final(final). arc(start, s1, +). arc(start, s1, -). arc(s1, s1, 0). arc(s1, s1, 1). arc(s1, s1, 2). arc(s1, s1, 3). arc(s1, s1, 4). arc(s1, s1, 5). arc(s1, s1, 6). arc(s1, s1, 7). arc(s1, s1, 8). arc(s1, s1, 9). arc(s1, final, 0). arc(s1, final, 2). arc(s1, final, 4). arc(s1, final, 6). arc(s1, final, 8).

84 | P a g e

Here are some queries on our program and their results.


%% +4 1 ?- test1([+, 4]). true .

%% +100 2 ?- test1([+, 1, 0, 0]). true .

%% -8 3 ?- test1([-, 8]). true .

%% +5 4 ?- test1([+, 5]). false.

%% +? 5 ?- test1([+, AcceptNumber]). AcceptNumber = 0 ; AcceptNumber = 2 ; AcceptNumber = 4 ; AcceptNumber = 6 ; AcceptNumber = 8 ; false.

Queries discussion: The queries 1 to 4 is simple, it just recognize the provided string if it accepted by our language or not. The last query works as generator in which it generates values for the X variables to make a event number.
Example 5.1.5: [Strings contains 01 | String Matching]

An automaton A that accepts L= {x01y: x, y {0, 1}*}. The automaton A= ({q0, q1, q2}, {0, 1}, S, q0, {q1}) as a trans0ition table:
Table 7: Transition Table for the language L

q0 q1 q2

0 q2 q1 q2

1 q0 q1 q1
85 | P a g e

The automaton as transition diagram

Figure 38: Transition Graph for the language L

An FA accepts string w= a1 a2 an, if there is a path in the transition diagram that: 1. Begins at start state. 2. End at an accepting state. 3. Has sequence of labels a1 a2an The generated arcs will be like the following:
initial(q0). final(q1). arc(q0, q0, 1). arc(q0, q2, 0). arc(q2, q2, 0). arc(q2, q1, 1). arc(q1, q1, 0). arc(q1, q1, 1).

This language accepts any string contains (0, 1). The string beginning and ending not matter it a 0 or 1 or a sequence of them. Let us make some queries over this language.
%% 01 1 ?- test1([0, 1]). true .

%% 0011 2 ?- test1([0, 0, 1, 1]). true .

%% 010111100 3 ?- test1([0, 1, 0, 1, 1, 1, 1, 0, 0]). true .

%% 101 4 ?- test1([1, 0, 1]).

86 | P a g e

true .

%% 100 5 ?- test1([1, 0, 0]). false.

Queries discussion: In the queries 1 through 4 the result was (true) because it contains the string (0 1) inside the query While the fifth query return false it doesnt contains the string (0 1) inside the query. Note here we use the program as a recognizer. If we want to use the program as a generator it will return a large number of results according to our extensible language. We can try these queries simple like: test1([X, Y, Z, W]). Then many values will be returned.
Example 5.1.6: [Strings ends with 01 | String Matching]

The FA accepts another strings patterns

Figure 39: Transition Graph for accepting string ending with 01

The generated code will be like the following:


initial(q0). final(q1). arc(q0, q0, 0). arc(q0, q0, 1). arc(q0, q2, 0). arc(q2, q1, 1).

This language accept any string that ends with (0 1). Let us take the string (01101) and test it on the program running with prolog.
%% 01101 1 ?- test1([0, 1, 1, 0, 1]).

87 | P a g e

true .

%% 011010 2 ?- test1([0, 1, 1, 0, 1, 0]). false.

Queries discussion: The first query is what we want, the program return true means this string belongs to our language. In the second query the program returns false means this string no belong to our language because it ends up with (1, 0) which conflict with our model design.
Example 5.1.7: [Even number of 0s and 1s | String Matching]

DFA accepting all and only strings with an even number of 0s and an even number of 1s:

88 | P a g e

Figure 40: Transition Graph for accepting event number of 0s and 1s

The table representation of the automaton:


Table 8: Transition Table

q0 q1 q2 q3
The generated code will look like the following:
initial(q0). final(q0). arc(q0, q1, 1). arc(q0, q2, 0). arc(q1, q0, 1). arc(q1, q3, 0).

0 q2 q3 q0 q1

1 q1 q0 q3 q2

89 | P a g e

arc(q2, q0, 0). arc(q2, q3, 1). arc(q3, q1, 0). arc(q3, q2, 1).

This language accepts only a string with event number of 0s and 1s, we will test this language using the following queries:
%% 01 1 ?- test1([0, 1]). false.

%% 0011 2 ?- test1([0, 0, 1, 1]). true .

%% 0101 3 ?- test1([0, 1, 0, 1]). true .

%% 000011 4 ?- test1([0, 0, 0, 0, 1, 1]). true .

Queries discussion: In the first query there are one 0 and one 1, this conflict with our proposition, so the result comes as false. In the second query there are two 0s and two 1s the result obviously comes true. In the third query we just mix the 0s and 1s which are even, the result comes true. So the language recognizes the number of 0s and 1s and generates the appropriate answer. There is no limit to our examples and testing in this model and other models, we try to present out the common and simple examples and show it in our system applications.

5.2. Testing Finite State Transducer


In this section we will show a different bunch of examples from the finite state transducer model. The queries asked to this model will be also two types: Recognizing and Generating. Finite State Transducer can be summarized by this four-fold way of thinking:

90 | P a g e

FST as recognizer: a transducer that takes a pair of strings as input and outputs accept if the string-pair is in the string-pair language and a reject if it is not. FST as generator: a machine that outputs pairs of strings of the language. Thus the output is a yes or not, and a pair of output strings. FST as translator: a machine that reads a string and outputs another string. FST as set relater: a machine that computes relations between sets.
Example 5.2.1: [Find and Replace Algorithms | General Algorithms]

An Illustration example.

Figure 41: A very simple deterministic finite-state transducer

This very primitive transducer accepts just two input strings, ah and ae, and maps them (transduces them, translates them) onto bh and ce respectively. (One can imagine it as representing the pair of rules a becomes b before h and becomes c before e). The generated code will be like the following:
initial(q0). final(q3).

arc(q0, q1, a:b). arc(q0, q2, a:c). arc(q1, q3, h:h). arc(q2, q3, e:e).

Now we can do some queries over this schema.


%% ah:bh 1 ?- testtrans1([a, h], [b, h]). true .

%% ae:ce

91 | P a g e

2 ?- testtrans1([a, e], [c, e]). true .

%% ah:?? 3 ?- testtrans1([a,h], [Out_a, Out_h]). Out_a = b, Out_h = h .

%% ??:bh 4 ?- testtrans1([Input_b, Input_h], [b, h]). Input_b = a, Input_h = h .

%% a?:h? 5 ?- testtrans1([a, X], [h, Y]). false.

%% ??:?? 6 ?- testtrans1([X, Y], [W, Z]). X = a, Y = h, W = b, Z = h ; X = a, Y = e, W = c, Z = e ; false.

Queries discussion: In the first query we asked the model is the pair [a, h] can translate or transduces to the pair [b, h], the result comes true which support our example, In the second query we asked the model about pair [a, e] with [c, e], the result comes true. In the third query we give the model the inputs and asked it to give us the outputs and what happened is the program assigns the output values to the variables X, Y. In the fourth query we give the model the outputs and asked it to give us the inputs reverse the query 3, and it returns the correct result. The fifth query return false, because the ambiguity in paths in which many result may correct and the path should be bounded.
92 | P a g e

The sixth query we give the models just variables and asked the model to give us each corresponding pairs in our language and the result is clear. This transducer is not deterministic, because there are two paths out of state 0 with input a. Allowing strings of symbols in either input or output (with no loss of generality, Im pretty sure), and using e as the empty string, we can replace the transducer above with the following equivalent deterministic finite state transducer.

Figure 42: Finite State Transducer with Epsilon Transition

Sometimes a deterministic finite state transducer will need many more states than an equivalent non-deterministic one, but they run very fast because the choice of paths is locally deterministic.
Example 5.2.2: [Simple Translator or Dictionary | Natural Language Processing]

Natural language processing is a very interested model to work with; Finite State Transducer allows making many applications in this model, in this example we will construct a simple translator (Dictionary) that converts a limited range of words from English language to Arabic one and vice versa. Here we will provide some English words considering them as input symbols and provide the meaning of them in Arabic words considering them as output symbols.

Figure 43: Simple English - Arabic translator

Here are the generated arcs (transitions) for this simple dictionary
initial(start). final(final).

93 | P a g e

arc(start, final, university:). arc(start, final, faculty:). arc(start, final, teacher:). arc(start, final, teacher:). arc(start, final, student:). arc(start, final, book:).

Let us see the transition table for this dictionary to demonstrate the Finite State Transducer input / output view. Then we will enjoy to making some queries to this dictionary, we will ask it for translation in two ways, meaning translation from English to Arabic and vice versa.

Figure 44: Simple dictionary Transition Table

Here is the testing.


%% university Arabic-> ?

94 | P a g e

1 ?- testtrans1([university], Meaning). Meaning = [ ]. %% teacher Arabic-> ? 2 ?- testtrans1([teacher], Meaning). Meaning = [; ] Meaning = [; ] false.

%%

-English-> ?

3 ?- testtrans1(Meaning, [)]. Meaning = [teacher] .

%%

English-> ?

4 ?- testtrans1(Meaning, [)]. Meaning = [book] .

%% Review the dictionary database 5 ?- testtrans2(EnglishWord, ArabicWord). EnglishWord = [university], ArabicWord = [; ] EnglishWord = [faculty], ArabicWord = [; ] EnglishWord = [teacher], ArabicWord = [; ] EnglishWord = [teacher], ArabicWord = [; ] EnglishWord = [student], ArabicWord = [; ] EnglishWord = [book], ArabicWord = [; ] false.

Queries discussion: In the queries 1 and 2 we asked the program to translate an English words that belong to our database, the result comes in Arabic, when the words provided with more than one meaning we can ask the program to this target using the (;) symbol like the word (teacher) we get two meaning. In the queries 3 and 4 we asked the program to translate Arabic words to English one. Similar to the queries 1 and 2, but in the second direction.

95 | P a g e

In the last query we asked the program to give us each English word with its corresponding Arabic in its database.
Example 5.2.3. [Nouns Pluralizing | Natural Language Processing]

The English language has a large number of words divided in many categories, we need the nouns category for this example in which each noun has a plural format in this example we will try to treat the process of pluralizing a noun from the single noune, we should take in consideration the cases that the noun ends: 1. Nouns that ends with (s, x or z). 2. Nouns that ends with (y). 3. Nouns that ends with other letters. The general rule for generate a plural for the previous states are: 1. Add (es) at the end of the word. 2. Remove the letter (y) and add (ies) at the end of the word. 3. Simply add the (s) letter at the end of the word. Here is simple figure that demonstrate these situations and an enhancement one.

Figure 45: English nouns plural generator

96 | P a g e

Figure 46: English nouns plural more enhancement

The second figure treats the situations that the word may ends with (ss) for example while the first one need just one letter, it is not a problem let us see the arcs generated by the second.
initial(start). final(a1). final(a2). final(a3). arc(start, a1, '#':s). arc(s1, s2, '#':e). arc(s2, a2, '#':s). arc(start, s3, y:'#'). arc(s3, s4, '#':i). arc(s4, s5, '#':e). arc(s5, a3, '#':s). arc(s3, s1, s:s). arc(s3, s1, x:x). arc(s3, s1, z:z). arc(start, s1, s:s). arc(start, s1, x:x). arc(start, s1, z:z). arc(s1, s1, s:s). arc(s1, s1, x:x).

97 | P a g e

arc(s1, s1, z:z). arc(start, start, a:a). arc(start, start, b:b). ... arc(s1, start, r:r). arc(s1, start, t:t). arc(s1, start, u:u). arc(s1, start, v:v). arc(s1, start, w:w). arc(s1, start, a:a). arc(s1, start, b:b). ... arc(s1, start, r:r). arc(s1, start, t:t). arc(s1, start, u:u). arc(s1, start, v:v). arc(s1, start, w:w). arc(s1, start, y:y). arc(s3, start, a:a). arc(s3, start, b:b). ... arc(s3, start, r:r). arc(s3, start, s:s). arc(s3, start, t:t). arc(s3, start, u:u). arc(s3, start, v:v). arc(s3, start, w:w). arc(s3, start, x:x). arc(s3, start, y:y). arc(s3, start, z:z).

Note that the (...) symbol means the range as we talked before, the range varies from the upper arcs to the lower one. Now let us make some queries over this model.
%% book 1 ?- testtrans2([b, o, o, k], Plural). Plural = [b, o, o, k, s] .

%% computer 2 ?- testtrans2([c, o, m, p, u, t, e, r], Plural). Plural = [c, o, m, p, u, t, e, r, s] .

%% box

98 | P a g e

3 ?- testtrans2([b, o, x], Plural). Plural = [b, o, x, e, s] .

%% class 4 ?- testtrans2([c, l, a, s, s], Plural). Plural = [c, l, a, s, s, e, s] .

%% city 5 ?- testtrans2([c, i, t, y], Plural). Plural = [c, i, t, i, e, s] .

Queries discussion: The first query is a noun that can pluralize by adding the (s) letter at the end, we get this result. And the same talking for the query 2. The query 3 is a noun ends with (x), we cant pluralize it directly, instead we should add a letter (e) at the end, then the letter (s). the same for the query 4 that ends with(s). The query 5 ends with (y) to make it plural we should eliminate the (y) letters and replace it by the string (ies), the result comes satisfying our approach.
Example 5.2.4: [Encryption and Decryption | System Security]

Text or message encryption is a very important model in many systems, in order to transfer data in a secure mode. The sender of the message encrypts it in some way then sends it to the receiver who decrypts the message and gets the benefit data. In this example we will present a simple Encryption / Decryption method. This method takes each letter in the message and replaces it with another one in a specific counting system, for example: if we replace each letter by the third letter after it, this will hide the real message content like: a:d b:e c: f .... z:c

Doing it for the numbers also will help in full encryption. The receiver will does the same method in reverse means replace each letter by the third letter before it. Let us take a look at the simple graph generated by this example:

99 | P a g e

Figure 47: Simple Encryption / Decryption machine

Note that the (...) means a range of inputs/ outputs as we talked in previous examples. Now let us take a look at the generated arcs of this machine.
initial(s1). final(s1). arc(s1, s1, a:d). arc(s1, s1, b:e). ... arc(s1, s1, x:a). arc(s1, s1, y:b). arc(s1, s1, z:c). arc(s1, s1, 0:3). arc(s1, s1, 1:4). ... arc(s1, s1, 9:2).

Of course we can do this for any type of inputs and outputs, in the following we will try to make some queries over some messages.
%% Encrypt: ypu 1 ?- testtrans2([y, p, u], Encrypt). Encrypt = [b, s, x] .

%% Encrypt: ypu2013 2 ?- testtrans2([y, p, u, 2, 0, 1, 3], Encrypt). Encrypt = [b, s, x, 5, 3, 4, 6] .

%% Decrypt: bsx 3 ?- testtrans2(Decrypt, [b, s, x]). Decrypt = [y, p, u] .

100 | P a g e

%% Decrypt: bsx5346 4 ?- testtrans2(Decrypt, [b, s, x, 5, 3, 4, 6]). Decrypt = [y, p, u, 2, 0, 1, 3] .

%% Generate the schema 5 ?- testtrans2([Message], [Cipher]). Message = a, Cipher = d ;

Message = b, Cipher = e ;

Message = c, Cipher = f ;

Message = d, Cipher = g ;

Message = e, Cipher = h ;

Message = f, Cipher = i ;

Message = g, Cipher = j ;

Message = h, Cipher ... = k .

Queries discussion: The queries and results are very clear; we work in two directions of encryption and decryption and ask the model to return the schema that it works with. We can built complicated schema more than this as our need, and work it the same like we did previously.

5.3. Testing Pushdown Automata


In the pushdown automata which is similar to finite state automata with additional data structure actually it is a Stack. Pushdown automata can perform more tasks than FA because its stack which work as a memory to store data temporarily, to take in consideration in this section we should list some of interpreter properties: 1. The stack firstly is empty so we denote to this behavior by the letter (e) means empty. 2. The stack can accept an empty string which will represented as [] means empty list. 3. The stack accepts the input when it reaches the final state with empty input.

101 | P a g e

In this section we will show a different bunch of examples from the pushdown automata model. The queries asked to this model will be also two types: Recognizing and Generating.
Example 5.3.1: [Equal Number of as and bs | String Matching]

In this simple example we will present a machine that recognize if the count of letter a in the string left side is equal to that one of b in the string right side: {w | w contains an equal number of as and bs}.

Figure 48: a's and b's counts balancer

As we accustom in each model we present the Transition Table user interface to take a closer look at the form of data entering to this model. Here is the Pushdown Automatas Transition Table which contains more fields than the previous models.

102 | P a g e

Figure 49: Pushdown Automata Transition Table

The arcs generated by this table are the follow:


initial(0). final(2). arc(0, a, e, a, 0). arc(0, a, a, a, 0). arc(0, b, a, p, 1). arc(0, [ ], e, n, 2). arc(1, b, a, p, 1). arc(1, [ ], e, n, 2).

With this simple declaration we can ask for any number of as and bs and check if they are the same length or not, let us do some queries to test this behavior:
%% ab 1 ?- accept([a, b]). true .

103 | P a g e

%% aabb 2 ?- accept([a, a, b, b]). true .

%% aaaaabbbbb 3 ?- accept([a, a, a, a, a, b, b, b, b, b]). true .

%% aabbb 4 ?- accept([a, a, b, b, b]). false.

%% aaabb 5 ?- accept([a, a, a, b, b]). false.

Queries discussion: The queries 1, 2 and 3 have an equal number of as and bs, the machine start from the left when it found the letter (a) it pushes into the stack, initially the stack is empty contains the letter (e), when the machine arrive to the letter (b) if pop a letter (a) from the stack, repeating this process until it arrive to the string ending, if the stack empty then the string accepted else it reject the string. The queries 4 and 5 reject the input string because the process we talked about failed to process the given string.
Example 5.3.2. [Language L = anbmcmdn Recognizer; n, m >=1 | String Matching]

The language l consider all strings that have an equal number of a and d in the string edges and an equal number of b and c inside the string. In this example we will see the powerful of the stack in which we contains many symbols all to be counted and compared with other symbols, the task of counting as we talk done as a pop operation or no operation.

Figure 50: anbmcmdn String Recognizer

104 | P a g e

The generated arcs will be:


initial(s1). final(s4). arc(s1, a, e, a, s1). arc(s1, a, a, a, s1). arc(s1, b, a, b, s1). arc(s1, b, b, b, s1). arc(s1, c, b, p, s2). arc(s2, c, b, p, s2). arc(s2, d, a, p, s3). arc(s3, d, a, p, s3). arc(s3, [], e, n, s4).

Now and generating the pushdown automata prolog code we are ready to make some queries over this model.
%% abcd 1 ?- accept([a, b, c, d]). true .

%% aabcdd 2 ?- accept([a, a, b, c, d, d]). true .

%% abbbcccd 3 ?- accept([a, b, b, b, c, c, c, d]). true .

%% aabcdd 4 ?- accept([a, a, b, c, d, d, d]). false.

%% ???? 5 ?- accept([X1, X2, X3, X4]). X1 = a, X2 = b, X3 = c, X4 = d .

%% a?c? 6 ?- accept([a, X, c, Y]). X = b, Y = d .

105 | P a g e

Queries discussion: The queries are very clear, when the string satisfy our language the result comes true else it comes false, and we can see the generator powerful, when we ask the interpreter about some variables it match the given symbols and return the correct symbols.
Example 5.3.3: [Parenthesis Recognizer | Compiler Design]

When we have an expression inside parenthesis, the parenthesis should be equal in the edges of this expression; means the number of left parenthesis is equal to the right ones. Here is a pushdown automata implementation of this language.

Figure 51: Parenthesis Recognizer

Here we assume that the string inside the parenthesis is the letter (a), surely it could be any other string, and here we show the parenthesis recognizer rather than other things. The generated arcs are:
initial(s1). final(s4). arc(s1, '(', e, '(', s1). arc(s1, '(', '(', '(', s1). arc(s1, a, '(', n, s2). arc(s3, ')', '(', p, s3). arc(s2, ')', '(', p, s3). arc(s3, [], e, n, s4).

Note that we but the parenthesis inside quotes just to make the interpreter recognize them from the arc and query parenthesis. Here are some queries over this language.
%% (a) 1 ?- accept(['(', a, ')']). true .

%% (((a))) 2 ?- accept(['(', '(', '(', a, ')', ')', ')']). true .

106 | P a g e

%% ((a) 3 ?- accept(['(', '(', a, ')']). false.

%% (a? 4 ?- accept(['(', a, X]). X = ')' .

%% ??? 5 ?- accept([X, Y, Z]). X = '(', Y = a, Z = ')' .

Queries discussion: As we saw in the previous example, the queries become obvious to discuss, when the input satisfy our language the result comes true else it comes false and the generator work a nice role in order to generate the missing symbols.

5.4. Testing Turing Machines


Turing Machines is an abstract model in which any model can be built as a Turing Machine, here in the system we focus a little on this model, but it has the full functionality of Turing machines as other models does, In this section we will show a different bunch of examples from the Turing Machines model. The queries asked to this model will be also two types: Recognizing and Generating.
Example 5.4.1: [Binary addition | Computer Organization and Architecture]

The basic CPU operations is the addition one, specifically the binary numbers addition, when we has a binary number and we need to add 1 to it, there are some instructions to do this, here in this example the Turing Machine will do this task automatically just give it the binary number. As in each model we provide an image for the transition table of the system, here is it.

107 | P a g e

Figure 52: Turing Machines Transition Table

The graph generated by the system from this table is:

Figure 53: Binary Addition Machine

The generated arcs will be:


initial(0). arc(0, 0, 0, r, 0). arc(0, 1, 1, r, 0). arc(0, '#', '#', l, 1). arc(1, 0, 1, s, halt).

108 | P a g e

arc(1, 1, 0, l, 1). arc(1, '#', 1, s, halt).

The arcs are simple in which they described previously in this chapter; let us now make some queries over this machine and testing some binary numbers.
%% 1 1 ?- compute([1], Result). Result = [1, 0, #] .

%% 11 2 ?- compute([1, 1], Result). Result = [1, 0, 0, #] .

%% 0 3 ?- compute([0], Result). Result = [1, #] .

%% 01100011 4 ?- compute([0, 1, 1, 0, 0, 0, 1, 1], Result). Result = [0, 1, 1, 0, 0, 1, 0, 0, #] .

%% 145 5 ?- compute([1, 4, 5], Result). False

Queries discussion: When we give the interpreter a binary number it will process it and add number 1 to it then return the result to us via the provided variable, but when we give it decimal number it reject it, it only accepts the 0 and 1 which consist the binary number format.
Example 5.4.2: [Language L = anbm Recognizer; n, m >=1 | String Matching]

In this example we will test the string that starts with one or more (a) then it will be continue with one or more (b), the machine will register this string in a tape an starts from the first index and recognize if the symbol belong to our language or not, doing this task until reach the (halt) state is what determine our result, reaching the (halt) state mean the string is accepted else it will be rejected.

109 | P a g e

Figure 54: anbm String Recognizer

The generated arcs will be:


initial(s1). arc(s1, a, a, r, s2). arc(s2, a, a, r, s2). arc(s2, b, b, r, s3). arc(s3, b, b, r, s3). arc(s3, '#', '#', l, halt).

With this simple transitions we can build our model. Now let us to some queries over this language.
%% ab 1 ?- compute([a, b], Result). Result = [a, b, #] .

%% abb 2 ?- compute([a, b, b], Result). Result = [a, b, b, #] .

%% aaab 3 ?- compute([a, a, a, b], Result). Result = [a, a, a, b, #] .

%% aaa 4 ?- compute([a, a, a], Result). false.

%% bbb 5 ?- compute([b, b, b], Result). false.

%% a? 6 ?- compute([a, X], Result). X = b,

110 | P a g e

Result = [a, b, #] .

%% ?? 7 ?- compute([X, Y], Result). X = a, Y = b, Result = [a, b, #] .

Queries discussion: All the strings starts with number of a then a number of b will accepted in this language, at least we should have one a and one b and the result will come true, else the result is false, the generator also works.

5.5. Testing Context Free Grammar


In this section we will show a different bunch of examples from the Context Free Grammar model. The queries asked to this model will be also two types: Recognizing and Generating.
Example 5.5.1: [Palindrome Recognizer | String Matching]

Almost all we know the palindromes. Palindromes means a string that read from the left or right with the same meaning, here we try to do simple example that check if the given string is palindrome, strings will contains (0, 1) only and we can form any palindrome we want according to these entries. Here is the grammar: 1. 2. 3. 4. 5. P P0 P1 P 0P0 P 1P1

Figure 55: Grammar graph tree

111 | P a g e

For this model we should present the form of the transition table as we did with other models to give more understanding of the way of declaring data:

Figure 56: Context Free Grammar Transition Table

Note that the green circle in the first row represent that this rule is the starting one, where the derivation should be start. The generated code that the system generates from this grammar and depending on the steps we talked about in the context free grammar interpreter will be the following:
p(X, Z):- X = [0| R1], p(R1, R2), R2 = [0| Z]. p(X, Z):- X = [1| R1], p(R1, R2), R2 = [1| Z]. p(X, Z):- X = [0| Z]. p(X, Z):- X = [1| Z]. p(X, Z):- X = Z.

Now we should test this language by making some queries


%% 101 1 ?- p([1, 0, 1], []). true .

112 | P a g e

%% 1101011 2 ?- p([1, 1, 0, 1, 0, 1, 1], []). true .

%% 11111111 3 ?- p([1, 1, 1, 1, 1, 1, 1, 1], []). true .

%% 10100101 4 ?- p([1, 0, 1, 0, 0, 1, 0, 1], []). true .

%% 110010 5 ?- p([1, 1, 0, 0, 1, 0], []). false.

%% 1? 6 ?- p([1, X], []). X = 1 .

Queries discussion: According to our start symbol the query will start with a letter denote to that symbol, from the query 1 to 4 the result was true, because the given string is palindrome and we can check this by seeing, while the query 5 return false because the string is not palindrome, In the query 6 we provide a symbol and ask for the rest of the string that form a palindrome.
Example 5.5.2: [Even and Odd numbers | Mathematics]

Recognizing the number if it an even or odd number is a simple and good examples in simple programs. Here we will present a grammar that defines the even number of 0, and it will be the same for the odd number of 0s. Let us start by showing the grammar of even number of 0. S 1S S 0A0S S A 1A A

113 | P a g e

This grammar will recognize any number that contains mix of 0s and 1s if the count of 0s is even or not. Let us take a look at the prolog generated code from this grammar.
s(X, Z):- X = [1| R1], s(R1, Z). s(X, Z):- X = [0| R1], a(R1, R2), R2 = [0| R3], s(R3, Z). s(X, Z):- X = Z. a(X, Z):- X = [1| R1], a(R1, Z). a(X, Z):- X = Z.

Now the time for some queries


%% 00 1 ?- s([0, 0], []). true .

%% 0000 2 ?- s([0, 0, 0, 0], []). true .

%% 0 3 ?- s([0], []). false.

%% 1010010 4 ?- s([1, 0, 1, 0, 0, 1, 0], []). true .

%% 1111 5 ?- s([1, 1, 1, 1], []). true .

%% 01111 6 ?- s([0, 1, 1, 1, 1], []). false.

Queries discussion: The queries are simple, if the number contains an even number of 0s the result will true else it will be false.
Example 5.5.3: [ancmbmdn Recognizer | String Matching]

We show this example in the pushdown automata testing section, this string consist of combination of a, c, b and d where the number of a and d is equal and the number of c and b is equal too. For context free grammar we can do this example as the context
114 | P a g e

free grammar is equivalent to the pushdown automata, first we should present the grammar for this language. S aSd S SQ Q cQb Q

This grammar will accept all strings that satisfy our language and reject the rest. Let us take a look at the generated prolog code from this grammar.
s(X, Z):- X = [a| R1], s(R1, R2), R2 = [d| Z]. s(X, Z):- X = Z. s(X, Z):- q(X, Z). q(X, Z):- X = [c| R1], q(R1, R2), R2 = [b| Z]. q(X, Z):- X = Z.

Now to do some queries over this code


%% acbd 1 ?- s([a, c, b, d], []). true .

%% aacbdd 2 ?- s([a, a, c, b, d, d], []). true .

%% accbbd 3 ?- s([a, c, c, b, b, d], []). true .

%% aacbddd 4 ?- s([a, a, c, b, d, d, d], []). false.

%% ???? 5 ?- s([X1, X2, X3, X4], []). X1 = X2, X2 = a, X3 = X4, X4 = d ; X1 = X2, X2 = a, X3 = X4, X4 = d ; X1 = a, X2 = c, X3 = b,

115 | P a g e

X4 = d ; X1 = X2, X2 = c, X3 = X4, X4 = b ; false.

Queries discussion: The queries 1, 2 and 3 accept the string that satisfy our language and reject query 4. In the query 5 we use the interpreter as a generator and we can see the result returned and accepted by the interpreter.

5.6. Testing the Additional Functionality


From the previous models and testing and depending on the powerful of conversion from model to another, we can explore different types of conversions like: 1. Converting from Context Free Grammar to Pushdown Automata 2. Converting from Regular Grammar to Finite State Automata 3. Converting from Finite State Automata to Regular Grammar Sometimes defining a problem in a model is easier than other model, with these functions we get the benefit of defining the problem in simple way and get the result as a new desired model. 1. Converting from CFG to PDA If we take the palindrome example of the CFG model we can represent it in a simple way with CFG as we saw, what about converting it to pushdown automata? When we create a CFG project we have the ability to directly convert it to PDA with a simple click, Let us take a look at the graph generated by this conversion process.

Figure 57: Palindrome equivalent PDA

116 | P a g e

2. Converting from RG to FA Another type of conversion is converting the Regular Grammar which is a special case of Context Free Grammar to the equivalent Finite State Automata. We will take the example provided in Goddard CTH book, as our algorithm designed. S 0C S 1A A 1B A1 B 0C B 1A C 0S

Simply we can convert to FA by a simple click, to finally get the equivalent FA as shown in the following graph.

Figure 58: Converting from RG to FA

3. Converting from FA to RG Surely the generated FA in the previous example can be converted also to the equivalence RG this done also be a simple click, if we design a finite automata like the previous example and we need to get the equivalent RG it will be the same. After these examples we can say that infinite number of examples can be implemented and tested on this system. To make sure that the system work correctly in your machine you should understand the two parts of the system: 1. The system UIs which is a User Interfaces implemented using the C sharp programming language under the Microsoft .NET Framework. 2. The SWI Prolog v.5 which is an interpreter for programming language used to interpreter our generated code.

117 | P a g e

[Chapter 3] Results
1. Discussion and Conclusion
1.1. System Functionality
If we want to summarize the systems functionality that described before, and the that one need to be implemented, first we need to show the process of dealing with the system. 1. Declaration Process This step responsible of collecting needed data, it designed to be more easily in which the user can enter the data in two ways, and he has the ability to move from one way to another or work concurrently with it. a. Declaring data using the transition table b. Declaring data using the visual graph c. Moving from transition table to visual graph and vice versa. 2. Generating Process In this step the system ready to handle the entering data and generate the prolog code according to current model. The process of generating the code is. a. Collecting the transitions from the transition table and save them in a list data structure in the memory. b. Filtering the collected transitions; means remove the redundancy and then arrange it to finally generate the file of arcs that represent or model. c. Add the suitable prolog predicates or functions that can work with these arcs to finally give out the full prolog code that represent our problem. 3. Testing Process After declaring data and generating the code the prolog environment will be ready to interact with the user, the prolog really is an interactive environment for the following reason. a. Can be used as a recognizer b. Can be used as a generator
118 | P a g e

c. Open source of the current loaded program, where the user can modify the code it he has knowledge in logic programming within the prolog, and make the testing more and more.

1.2. Discussion
Declarative Programming Tools have a future vision for their service, all the description above is a part of the system complete services. There are some models had not implemented yet like: Hidden Markov Model Probabilistic Automata Probabilistic Context Free Grammar And any model from the formal methods can be implemented also within the system. Our vision for the system after complete these models it to make the process of education and learning more easily. We plan to make a virtual department online with the university website and collect a big bunch of examples into a knowledge base in which the user can enter the website and request the corresponding page, and then he can see the knowledge base examples and create his own examples. Another view for the system is to making an E-Learning system that the user can make his exams online with the system and then the system correct his answers and give him the final result. Really this system has a big view for the education and learning process. As a first stage we make the core of the system with the implemented examples and we look for complete version of the system with previous services. In this document we try to describe approximately all thing matters our system. As we said before our system has a very useful job in which it convert the declarative data into logic programming code, that allows the user to make testing directly and build many models. The formal methods that contain a wide range of mathematically derived and ideally mechanized approaches to system design and validation gives us the ideal to design and implement such system.

119 | P a g e

Bibliography
1. Apress-Pro.C#.WPF.Windows.Presentation.Foundation.with.dot.NET.3.5. 2. Visual.CSharp.2010.Step.by.Step. 3. SWI-Prolog version 5.10.4 Manual by Jan Wielemaker. 4. Foundation of Logic Programming by Floid. 5. Introducing the Computation Theory by Wayne Goddard, Clemson University. 6. Theory of Computation by Aho, Ullman 7. Speech and Language Processing by Jurafsky,Martin. 8. Natural Language Processing Notes by Dr.Adnan Ali. 9. Compiler Construction principles and practice by Kenneth C.Louden 10. Software Engineering Concepts by William Stallings, Stephen R. Schach. 11. Karttunen 1987, 2001 paper. 12. Johnson et al. 1972. 13. Kaplan and Kay 1981. 14. Nandhakumar and Avison 1999. 15. Parnas and Clements 1986. 16. Truex et al. 2000. 17. Wiegers 1998.

Appendix
In this section we will describe some of the main characteristics and functionality that the programming language we used gives. In our system implementation we use two programming languages in which the first one is a complied language which is C#.NET comes from the .NET Framework of Microsoft this language helped us in building the user interfaces and provided the graphics drawing and manipulating, the second one is an interpreted language which is the SWI Prolog v.5 which interprets and runs our generated code.

120 | P a g e

1. C#.NET Programming Language


C# is the programming language designed for .NET. More than 50 languages exist for writing .NET applications, for example, Eiffel, Smalltalk, COBOL, Haskell, Pizza, Pascal, Delphi, Oberon, Prolog, and Ruby. Microsoft alone delivers the languages C#, Visual Basic, C++/CLI, J#, and JScript.NET. The following topics are used in the system development and covered here: 1. 2. 3. 4. 5. Classes Converters Custom Controls Pages Models

1.1. Classes
The folder (namespace) classes in the system contain three classes we described them in previous chapter, they are: Universal Recognizer File Manager Graphics And their implementation is also described.

1.2. Converters
Converters namespace contain many converter classes that helping converting data of an object to another type of data and assign new data to another object, here are the most important converters in the system. Let us first see how to define the converter class:
... using System.Windows.Data; namespace DeclarativeProgrammingTools.Converters { public class MyConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

121 | P a g e

{ throw new NotImplementedException(); } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } }

The IValueConverter interface is including in the System.Windows.Data namespace and it has two unimplemented methods Convert and ConvertBack these two methods give you an object and as to process it and return another object. Now we will describe shortly these converter and supply the code in the Convert method. 1. TypeToImageConverter This take a value from the DeclarativeProgrammingTools enumeration and return a corresponding image to represent this type.
StateType type = (StateType)value; switch (type) { case StateType.Start: return new BitmapImage(new Uri("pack://application:,,,/Images/StartState20.png")); case StateType.Fix: return new BitmapImage(new Uri("pack://application:,,,/Images/FixState20.png")); case StateType.Accept: return new BitmapImage(new Uri("pack://application:,,,/Images/AcceptState20.png")); case StateType.StartAccept: return new BitmapImage(new Uri("pack://application:,,,/Images/StartAcceptState20.png")); default: return null; }

Images.png are images defined in the Image folder. 2. BooleanToVisibilityConverter This converter takes a Boolean value and returns a visibility corresponding object
bool boolValue = (bool)value; if (boolValue) return Visibility.Visible; return Visibility.Collapsed;

122 | P a g e

3. IndexToPageConverter This converter takes an integer number (index in a list) and return a Page.xaml for showing.
int index = (int)value; switch (index) { case 1: return new Uri("pack://application:,,,/Pages/DeclarativeProgrammingPage.xaml"); case 2: return new Uri("pack://application:,,,/Pages/FiniteStateAutomataPage.xaml"); case 3: return new Uri("pack://application:,,,/Pages/FiniteStateTransducerPage.xaml"); case 4: return new Uri("pack://application:,,,/Pages/PushDownAutomataPage.xaml"); case 5: return new Uri("pack://application:,,,/Pages/TuringMachinesPage.xaml"); case 6: return new Uri("pack://application:,,,/Pages/ContextFreeGrammarPage.xaml"); case 7: return new Uri("pack://application:,,,/Pages/HiddenMarkovModelPage.xaml"); case 8: return new Uri("pack://application:,,,/Pages/ProbabilisticAutomataPage.xaml"); case 9: return new Uri("pack://application:,,,/Pages/ProbabilisticCFGPage.xaml"); default: return new Uri("pack://application:,,,/Pages/DeclarativeProgrammingPage.xaml"); }

4. TransitionToGraphicsConverter This is the most important converter in our system, in which it takes a transition and converts it to graphical one and vice versa.
public Transition ToModelTransition(GraphicsTransition graphicsTransition, DeclarativeProgrammingModels model) { GraphicsStateBase graphicsState1 = graphicsTransition.StartState; GraphicsStateBase graphicsState2 = graphicsTransition.EndState; State state1 = new State(graphicsState1.Name, Graphics.GetStateType(graphicsState1));

123 | P a g e

State state2 = new State(graphicsState2.Name, Graphics.GetStateType(graphicsState2)); Transition transition = new Transition(); transition.Name = graphicsTransition.Name; transition.Source = state1; transition.Target = state2; string[] args = UniversalRecognizer.AdjustInputsOutputs(model, graphicsTransition.InputSymbol, graphicsTransition.OutputSymbol, graphicsTransition.Action); transition.InputSymbol = args[0]; transition.OutputSymbol = args[1]; transition.Action = args[2]; return transition; }

public GraphicsTransition ToGraphicsTransition(Transition transition, DeclarativeProgrammingModels model) { State state1 = transition.Source; State state2 = transition.Target; GraphicsStateBase graphicsState1 = Graphics.GetGraphicsType(state1); GraphicsStateBase graphicsState2 = Graphics.GetGraphicsType(state2); graphicsState1.Name = state1.Name; graphicsState2.Name = state2.Name; graphicsState1.Width = 50; graphicsState1.Height = 50; graphicsState2.Width = 50; graphicsState2.Height = 50; string[] args = UniversalRecognizer.AdjustInputsOutputs(model, transition.InputSymbol, transition.OutputSymbol, transition.Action); GraphicsTransition graphicsTransition = new GraphicsTransition(graphicsState1, graphicsState2, args[0], args[1], args[2]); graphicsTransition.Name = transition.Name; return graphicsTransition; }

These converters must be binding to another controls or objects to be workable. First we want to define it in the control resource. And the namespace converters exist in should be declared before also
<Window x:Class="DeclarativeProgrammingTools.MainWindow" ... xmlns:converters="clr-namespace:DeclarativeProgrammingTools.Converters"> <Window.Resources> <converters:IndexToPageConverterx:Key="IndexToPageConverter"/> </Window.Resources>

124 | P a g e

.... </Window>

Now we can bind this object of converter into another control


<Frame Source="{Binding ElementName=listOfModels, Path=SelectedIndex, Converter={StaticResource IndexToPageConverter}}" .... </Frame>

1.3. Custom Controls


Our system contains some custom controls means new developed controls to suit our system which they: GraphViewer ColorSelector DropDownColorSelector PromptTextBox

The Graph Viewer is the most important control in the system and the other are just for user friendly viewing.
<UserControl x:Class="DeclarativeProgrammingTools.CustomControls.GraphViewer"> .... </UserControl>

This controls combine much more controls to make the graphics viewer and constructing more fun. 1. 2. 3. 4. Drawing Canvas Graphics Tool Bar Zoom Control Rotate Control

The drawing canvas is a fully functional canvas created in the graphics library, the other are so simple controls. 1.3.1. Graphics Library The graphics library architecture was described previous in its class diagram; here we will present some of its functionality. The GraphicsBase abstract class is the parent for other graphics classes:
using using using using using using System; System.Collections.Generic; System.Linq; System.Text; System.Windows.Media; System.Windows;

125 | P a g e

namespace GraphicsLibraries { public abstract class GraphicsBase : DrawingVisual { public string Name { get; set; } public double X { get; set; } public double Y { get; set; } public double Width { get; set; } public double Height { get; set; } public double BorderThickness { get; set; } public bool IsSelected { get; set; } public Color BorderColor { get; set; } public Color BorderSelectionColor { get; set; } public Color FillColor { get; set; } public Brush Brush { get; set; } public Pen Pen { get; set; } public Rect Rectangle { get; set; } public Point Center { get; set; } public bool SmoothEdge { get; set; } public bool FillArrowHead { get; set; } public DashStyle DashStyle { get; set; } public virtual void Draw() { } public public public public } } abstract abstract abstract abstract bool bool void void Contains(Point point); IntersectWith(Rect rectangle); Move(double deltaX, double deltaY); MoveTo(double deltaX, double deltaY);

There are two classes derived from GraphicsBase class: GraphicsStateBase GraphicsTransition GrphicsStateBase is an abstract class work as a parent for the derived classes GraphicsStartState GraphicsFixState GraphicsAcceptState GraphicsStartAcceptState

Each one represents a state in type and shape as we discussed previously in this document.
public abstract class GraphicsStateBase : GraphicsBase { public GraphicsStateBase(string name, double x, double y, double width, double height, Color borderColor, Color selectionColor, Color fillColor, double borderThickness, bool isSelected, bool smoothEdges) { // Assign the arguments to the class data member. } public override bool IntersectWith(System.Windows.Rect rectangle) { return rectangle.IntersectsWith(Rectangle); }

126 | P a g e

public override void Move(double deltaX, double deltaY) { X += deltaX; Y += deltaY; } public override void MoveTo(double deltaX, double deltaY) { X = deltaX; Y = deltaY; } public override void Draw() { base.Draw(); // General Drawing for the all states derived classes } }

For the rest of state classes the most important implementation is the Draw() method in which it determines the object shape.
public abstract class GraphicsAcceptState : GraphicsBase { // Other Class Definition // ... public override void Draw() { using (DrawingContext drawingContext = this.RenderOpen()) { base.Draw(); Definition = "Accept State: Graphics Object"; double w; drawingContext.DrawEllipse(new SolidColorBrush(FillColor), Pen, Center, Width / 2, Height / 2); drawingContext.DrawEllipse(new SolidColorBrush(FillColor), Pen, Center, Width / 2.6, Height / 2.6); drawingContext.DrawText(GetFormattedText("Text to render", Brush, out w), new Point()); drawingContext.Close(); } } }

DrawingCanvas class responsible for hold these object render it on its surface and manage their coordinates.
... using using using using GraphicsLibraries; System.Windows.Controls; System.ComponentModel; System.Collections.ObjectModel;

namespace GraphicsLibraries1 { public class DrawingCanvas : Canvas, INotifyPropertyChanged { private ObservableCollection<GraphicsBase> visualGraphics = new ObservableCollection<GraphicsBase>(); protected override Visual GetVisualChild(int index)

127 | P a g e

{ return visualGraphics[index]; } public void AddVisual(GraphicsBase visual) { visualGraphics.Add(visual); base.AddVisualChild(visual); base.AddLogicalChild(visual); } public void RemoveVisual(GraphicsBase visual) { visualGraphics.Remove(visual); base.RemoveVisualChild(visual); base.RemoveLogicalChild(visual); } public GraphicsBase GetVisual(Point point) { HitTestResult hitResult = VisualTreeHelper.HitTest(this, point); return hitResult.VisualHit as GraphicsBase; } public GraphicsBase GetSelectedGraphics() { for (int i = 0; i < visualGraphics.Count; i++) { if (visualGraphics[i].IsSelected) return visualGraphics[i]; } return null; } } }

1.4. Pages
Page is a Resource Dictionary object that can hold many data and objects even UIElements. Pages used in the system to represent a short description for each model in the Main window in which all pages will page presented in a Frame object.
<FlowDocumentScrollViewer xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" VerticalScrollBarVisibility="Hidden"> <FlowDocument ColumnWidth="400" FontSize="14" FontFamily="Tahoma" Background="Transparent"> <Paragraph TextAlignment="Center" FontSize="28" FontWeight="Bold" LineHeight="20" Foreground="CadetBlue"> Declarative Programming Tools <Span FontSize="13"></Span> </Paragraph> <Paragraph FontSize="16">

128 | P a g e

.... </Paragraph> </FlowDocument> </FlowDocumentScrollViewer>

2. Prolog: Programming in Logic


Programming in logic is the core of our system in which the generated code will be written in this language, almost the code we need is described in the Interpreters in the Implementation part. 1. 2. 3. 4. 5. Finite State Automata and Epsilon Finite State Automata Interpreter Finite State Transducer Interpreter Pushdown Automata Interpreter Turing Machines Interpreter Context Free Grammar Interpreter

..............................Done with Allah assistance..............................

129 | P a g e

130 | P a g e

You might also like