Download presentation
Presentation is loading. Please wait.
Published byDerek Bradford Modified over 9 years ago
1
Programming Techniques Lecture 16 Formal Methods Based on: Software Engineering, A Practitioner’s Approach, 6/e, R.S. Pressman, Model-based Specification, Ian Sommerville, and Chapter 2, Formal Specification Using Z, David Lightfoot Software Engineering Fall 2005
2
Programming Techniques Problems in the creation of computer systems There are long-standing problems in the development of computer systems: often they take too much time to produce, cost more than estimated and fail to satisfy the customer. Central to the problem is the fact that errors and inadequacies are more expensive to correct the later in the development process they are discovered. Furthermore, it is extremely difficult to clarify exactly what is required of a very complex system.
3
Programming Techniques Problems with Conventional Specification Contradictions - statements do not agree with one another. Ambiguities - statements have more than one interpretation. Vagueness - specifications in large documents are often not written precisely enough. Incompleteness (e.g., failing to list limitations and error handling required of a function). Mixed levels of abstraction - occurs when very abstract statements are intermixed randomly with statements written at lower levels of detail).
4
Programming Techniques Formal Specification Properties Unambiguous - formal syntax used by formal methods has only one interpretation (unlike natural language statements). Consistency - ensuring through mathematical proof that initial facts can be mapped (using inference rules) into later statements within the specification. Completeness - difficult to achieve in a large system even using formal methods.
5
Programming Techniques Use of formal methods The principal benefits of formal methods are in reducing the number of faults in systems. Consequently, their main area of applicability is in critical systems engineering. There have been several successful projects where formal methods have been used in this area. In this area, the use of formal methods is most likely to be cost-effective because high system failure costs must be avoided.
6
Programming Techniques Critical Systems Safety-critical systems –Failure results in loss of life, injury or damage to the environment; –Example : Chemical plant protection system; Mission-critical systems –Failure results in failure of some goal-directed activity; –Example : Spacecraft navigation system; Business-critical systems –Failure results in high economic losses; –Example : Customer accounting system in a bank.
7
Programming Techniques Development Costs with Formal Specification
8
Programming Techniques Formal Methods Advantages – Practical View To explain the advantages of formal specification to practising software engineers, it is important to focus on what it brings to the practice of software development rather than on more abstract advantages such as the ability to mathematically analyse the specification. Advantages that might be stressed are: - The detailed analysis of the requirements that is necessary to produce a formal specification. This results in the discovery and resolution of ambiguities and errors at an early stage in the process. - The unambiguous specification of interfaces. Interface problems are one of the major problems in system integration and a reduction in such problems can significantly reduce software costs. - The ability to mix formal and informal specifications. The whole system need not be formally specified but only those parts where most benefit can be gained.
9
Programming Techniques Ten Commandments of Formal Methods 1.Choose the appropriate notation 2.Do not over-formalize 3.Estimate costs 4.Have a formal methods guru on call 5.Do not abandon traditional development methods 6.Document sufficiently 7.Do not compromise quality standards 8.Do not be dogmatic in assuming formal specifications are flawless 9.Use of formal methods does not eliminate the need to test products 10.Reuse is still important
10
Programming Techniques 1. Formal Methods Concepts data invariant - a condition that is true throughout the execution of the system that contains a collection of data. state - the stored data which a system accesses and alters. operation - an action that takes place in a system and reads or writes data to a state.
11
Programming Techniques Process of Writing a Formal Specification Process of writing a formal specification for some system function involves following: - Define a system state in terms of the objects manipulated by the function ( similar to variable declaration in a programming language ). - Using a simple mathematical function as an example, define the data invariant by writing data relations that will not change during the execution of the function. - Write the precondition and postcondition for the function using mathematical notation to show the system state before and after the execution of the function.
12
Programming Techniques State Many formal languages, such as OCL, use the notion of states as follows: a system can be in one of several states, each representing an externally observable mode of behavior. A different definition for the term state is used in the Z language. The Z language defines a state as the stored data which a system accesses and alters. Hence, Z suggests a much larger number of states, representing each possible configuration of the data.
13
Programming Techniques Data Invariant A data invariant is a condition that is true throughout the execution of the system that contains a collection of data
14
Programming Techniques Operation Operation - an action that takes place in a system and reads or writes data to a state Three types of conditions can be associated with operations: –invariants – defines what is guaranteed not to change. –precondition - defines the circumstances in which a particular operation is valid. –postcondition - defines what is guaranteed to be true upon completion of an operation. This is defined by its effect on the data.
15
Programming Techniques Specification Techniques Algebraic specification –The system is specified in terms of its operations and their relationships. Model-based specification –The system is specified in terms of a state model that is constructed using mathematical constructs such as sets and sequences. Operations are defined by modifications to the system’s state.
16
Programming Techniques Specification Techniques Algebraic specification can be cumbersome when the object operations are not independent of the object state. Model-based specification exposes the system state and defines the operations in terms of changes to that state. The Z notation is a mature technique for model- based specification. It combines formal and informal description and uses graphical highlighting when presenting specifications.
17
Programming Techniques Model-based Specification Formal specification of software by developing a mathematical model of the system Defines a model of a system using well- understood mathematical entities such as sets and functions. The state of the system is not hidden (unlike algebraic specification). State changes are straightforward to define. VDM and Z are the most widely used model-based specification languages.
18
Programming Techniques 2. Formal Specification Languages I A formal specification language is usually composed of three primary components: – a syntax that defines the specific notation with which the specification is represented – semantics to help define a "universe of objects" that will be used to describe the system – a set of relations that define the rules that indicate which objects properly satisfy the specification The syntactic domain of a formal specification language is often based on a syntax that is derived from standard set theory notation and predicate calculus. The semantic domain of a specification language indicates how the language represents system requirements.
19
Programming Techniques Formal specification languages II
20
Programming Techniques Object Constraint Language (OCL) A formal notation developed so that users of UML can add more precision to their specifications. All of the power of logic and discrete mathematics is available in the language. However the designers of OCL decided that only ASCII characters (rather than conventional mathematical notation) should be used in OCL statements.
21
Programming Techniques OCL Overview Like an object-oriented programming language, an OCL expression involves operators operating on objects. However, the result of a complete expression must always be a Boolean, i.e. true or false. The objects can be instances of the OCL Collection class, of which Set and Sequence are two subclasses. See Table 28.1 (Pressman) for summary of OCL notation
22
Programming Techniques 3. An Introduction to Z Z is a “notation” –not a “programming language” –not a “method” Z is a “formal notation” –based on discrete math and the predicate calculus Z is a “formal notation for requirements” –model “state” and “operations” of system
23
Programming Techniques Z as a Specification Language Based on typed set theory. Sets are discussed in detail in section 6. Z applies typed sets, relations, and functions within the context of first-order predicate logic to build schemas. Includes schemas, an effective low-level structuring facility. Schemas are specification building blocks. Graphical presentation of schemas make Z specifications easier to understand.
24
Programming Techniques What is Z System described through a set of "schemas”, which have - data invariant(s) - state(s) - operations – with precondition(s)/postcondition(s)
25
Programming Techniques Basic Components of Z Notation of discrete mathematics Structure of “paragraphs” called “schema” The “schema calculus” is used to combine smaller “schema” into larger, more complex “schema”
26
Programming Techniques The Z Schemas I Box-like structures that introduce variables and specify the relationships between these variables. Formal specification analogue of a programming language component. Describe the stored data used to define the state of a system and describes what data the operations alter to define a new state.
27
Programming Techniques Z Schemas II Introduce specification entities and defines invariant predicates over these entities. A schema includes: –A name identifying the schema. –A signature introducing entities and their types. –A predicate part defining invariants over these entities. Schemas can be included in other schemas and may act as type definitions. Names are local to schemas.
28
Programming Techniques Operation Specification Operations may be specified incrementally as separate schema then the schema combined to produce the complete specification. Define the “normal” operation as a schema. Define schemas for exceptional situations. Combine all schemas using the disjunction (or) operator.
29
Programming Techniques Z Schema Highlighting Within Z, a schema is a fragment of mathematical text in which some variables are declared and some additional predicates may be provided to restrict possible values of those variables. The general form for a schema is given below.
30
Programming Techniques Figure 1: A Z schema specifying a Container Container contents: capacity: Schema nameSchema signature (declarations) Schema predicate contents ø capacity
31
Programming Techniques Z Schema - Name The name of the schema (begins with a capital letter), SchemaName - Container, is embedded in the upper line of the open box. The name is used to denote the schema throughout the specification and cannot be used to denote any other element.
32
Programming Techniques Z Schema – Signature I One or more variables are declared in the declaration part. Each variable is declared to be of a particular type. A variable can be declared using any set expression. The variables declared in the declaration part are known as the components of the schema. The scope of variables declared in the declaration part is local to the schema, which means they are usable within the predicate part only. The declarations introduced in the declarative part of a schema constitute the signature for the schema. A signature is simply a collection of variables and their types.
33
Programming Techniques Z Schema – Signature II The schema signature declares the names and types of the entities introduced in the schema. In Figure 1 the signature introduces two state variables. These are contents and capacity which are modelled as natural numbers (indicated by N). A natural number is an integer that is greater than or equal to zero. These partially define a container which can hold a descrete quantity of something.
34
Programming Techniques Z Schema– Predicates I The predicate part is written using zero or more lines. On each line, a predicate appears. Predicates written on separate lines are assumed to be conjoined with each other as if there was a logical conjunction inserted between each of the lines. If a single predicate extends over several lines, then subsequent lines should be indented and these lines are NOT assumed to be conjoined. The predicate can involve variables other than those declared in the declaration part provided these variables have been declared and introduced in a way that is compatible with the scope rules.
35
Programming Techniques Z Schema– Predicates II It is possible to have a schema that does not restrict the values of the components, that is, a schema with a property equivalent to the predicate true. Such a schema might be written without a predicate part. However, a schema without a predicate part may nonetheless have a property that restricts the value of the components. This results from constraints introduced in the declaration part.
36
Programming Techniques Z Schema– Predicates III The schema predicate defines relationships between entities in the signature by stating a logical expression which must always be true (an invariant). In Figure 1, the predicate states the obvious fact that the contents of the container cannot exceed its capacity. This specification says nothing about the size of the container or what the container is intended to hold. The definition of contents and capacity as natural numbers states that the container must hold a discrete amount of contents. The specification in Figure 1 is a building block which can be used in further specifications.
37
Programming Techniques Figure 2: Indicator
38
Programming Techniques Example: Indicator The Indicator specified in Figure 2 introduces three entities namely light (modelled by the values off and on), reading and danger_level (modelled as natural numbers). Both light and reading would have some physical manifestation in the real system (a warning lamp and a dial, perhaps) which provides an operator with information about the system. The symbol Û in the predicate part can be read as ‘if and only if’. The predicate therefore specifies that the light should be on if and only if reading is less than or equal to danger_level. That is, a ‘low-contents’ warning is signalled. At his stage, danger_level is not defined.
39
Programming Techniques Example: Storage Tank Given the specification of an indicator and a container, they can be combined (Figure 3) to define a storage tank with some capacity and an indicator light. The combined specification includes all the state variable declarations and predicates of the included specifications. Thus, Storage_tank combines the signatures of Container and Indicator and their predicates. These are combined with any new signatures and predicates introduced in the specification. Predicates are implicitly anded when schemas are composed so must all hold for the schema invariant to be true.
40
Programming Techniques Figure 3: Storage Tank
41
Programming Techniques Storage Tank: Discussion I Storage_tank has three associated predicates which define constraints on the state variables introduced in the schemas Container and Indicator. In Z, writing predicates on separate lines means that they are separated by an implicit ‘and’. Thus the predicate can be read as “reading equals contents and capacity equals 5000 and danger_level equals 50”. Predicates may also be written on the same line separated by an ‘and’ symbol ( ).
42
Programming Techniques Storage Tank: Discussion II Including schemas in another schema as shown in Figure 3 is equivalent to merging these schemas (Figure 4). There is some redundancy here in that reading and contents represent the same thing; this results from the use of generalised schema building blocks. Z includes facilities for variable renaming which could remove this redundancy.
43
Programming Techniques Figure 4: Expanded specification of a storage tank
44
Programming Techniques Z Conventions I Z uses various conventions to identify particular types of schema and state variable used in operation specification: 1.If any variable name, N, is followed by ’ e.g. N’, this means that it represents the value of the state variable N after the operation. In Z terminology, N is decorated with a dash. 2. If a schema name is decorated with ’, this introduces the dashed values of all names defined in the specification together with the invariant applying to these values.
45
Programming Techniques Z Conventions II 3.If a variable name is decorated with !, this means that it is an output e.g. ‘message!’. 4.If a variable is decorated with ?, this means that it is an input e.g. ‘amount?’.
46
Programming Techniques Z Conventions III 5. If a schema name is prefixed with the Greek character Xi ( ), this means that dashed versions of the variables defined in the named schema are introduced. For all variable names introduced in the schema, the values of corresponding dashed names are the same. That is, the values of state variables are not changed by the operation. 6. If a schema name is prefixed with the Greek character Delta ( ), this implies that values of one or more state variables will be changed by the operation where that schema is introduced. For all variable names introduced in the named schema, corresponding dashed names are also introduced and may be referenced in operations.
47
Programming Techniques Figure 5: A partial specification of the fill operation
48
Programming Techniques Fill-OK Schema Discussion Figure 5 shows part of the specification of the fill operation which adds an amount to a container. The schema name is prefixed with Delta, indicating that the operation changes the state. The amount to be added to the container is an input. The predicate associated with the operation specifies that the state is changed by the operation if there is enough capacity in the container. The predicate for Fill-OK specifies that the contents after completion of the operation (referenced as contents’) is equal to the sum of the contents before the operation and the amount added to the container. This is only true if adding the specified amount does not exceed the capacity of the container. This is precluded because of the predicates defined in Container. If the addition of the specified amount would cause the container to overflow, the operation is undefined.
49
Programming Techniques Combining Schemas A convention in writing Z specifications of operations is that they are specified in parts. The first schema defines the ‘correct’ operation. Following schemas define what should happen in exceptional situations. These schemas are then combined using a disjunction (or) operator to specify the operation completely.
50
Programming Techniques Figure 6: Further specification of the fill operation
51
Programming Techniques OverFill Schema Discussion I Figure 6 is a specification of what should happen if adding the specified amount exceeds the capacity of the container. In this situation, nothing is added to the container and a warning message is output. Note the use of the Xi schema here indicating that the values of state variables are not changed. The predicate associated with OverFill is true when the capacity of the container is less than the current contents plus the amount to be added. Nothing is added to the container if there is not enough room to add all the specified amount. A message ‘Insufficient tank capacity - Fill cancelled’ is output.
52
Programming Techniques Figure 7: The complete specification of the fill operation
53
Programming Techniques Fill Operation To complete the specification of the fill operation, Fill-OK and OverFill must be combined using a disjunction (or) operator (Figure 7). The effect of this operator is to merge the signatures of Fill-OK and OverFill. These are identical in this case. The predicate parts are independent and are separated by an or operator ( ). Therefore either the predicate in Fill-OK or the predicate in Overfill must be true. When schemas are very short, as in Figure 7, they may be written as text without the normal graphical highlighting. The complete specification of the fill operation could have been written: Fill : Fill-OK Overfill
54
Programming Techniques Symbol Sheet State Variables change ORTrue if either a or b is true PPower Set{a,b} = {{},{a},{b}, {a,b} ANDTrue if both a and b are true Universal QuantifierFor all elements in a set Existential QuantifierThere exists at least one XiNo state change occurs for the named state variable Summation Implicationif a then b Equivalencea if and only if b element ofa is an element of b not an element ofa is not an element of b Union {a} {b} = {a,b} Intersection {a,b} {b,c} = {b} Null Set{} Equivalent Such That S:PXS is declared as a set of Xs See Table 28.2 (Pressman) for summary of Z notation
55
Programming Techniques Z Issues Z specifications can appear excessively long in relation to their implementation. Z needs software tools to keep track of the variables and schemas. A Z specification is not easily communicated to the user. Many software engineers do not have the mathematical training to write a Z specification. The precision Z gives a very high degree of confidence in the fedility of the implementation, that is, that the implementation behaves precisely as the specification.
56
Programming Techniques Z Issues Verification provides an alternative to testing. To verify an implementation is to demonstrate that it will perform as specified in all cases. This can be done using mathematical proof. Verification of large systems is not easy. The process of performing a proof is not something that can be completely automated. Although software tools can help, the task seems to be inherently creative in a way that cannot be captured within a systematic procedure.
57
Programming Techniques Z Example 1 1.(a) A container can hold a discrete quantity of something. The content of the container cannot exceed its capacity. Describe this situation using a Z schema. You should include any base types required. Solution 1.a):
58
Programming Techniques Z Example 1 1.b) How would you extend your schema to include the following: capacity equals 6000 Solution 1.b):
59
Programming Techniques Z Example 1 1.c) How would you extend your schema to include the following: An amount is to be added to the container. The container is filled successfully if adding the specified amount does not exceed the capacity of the container. Solution 1c):
60
Programming Techniques Example 2 You have been assigned to a team that is developing software for a fax modem. Your job is to develop the ‘phone book’ portion of the application. The phone book function enables up to MaxNames people to be stored along with associated company names, fax numbers and other related information. Using natural language, define: a) The data invariant b) The state c) The operations that are likely
61
Programming Techniques Example 2 Solution: 2.a) Data invariant: the phone book will contain no more than MaxNames names; there will be no duplicate names in the phone book. 2.b)The state is the data that the software access, therefore, in this case, the state is the phone book itself. Operations are similar to the operations defined for objects in that they are capable of changing the state. 2.c) Operations for this problem include: add, delete, edit, obtain.
62
Programming Techniques Representative Tools Z-EVES, developed by ORA Canada ( http://www.ora.on.ca/z-eves/distribution.html) http://www.ora.on.ca/z-eves/distribution.html
63
Programming Techniques 5. Mathematical Concepts To apply formal methods effectively, a software engineer must have a working knowledge of the mathematical notation associated with sets and sequences and the logical notation used in predicate calculus. Sets and constructive set specification Set operators Logic operators Sequences
64
Programming Techniques Sets A set is a collection of objects or elements and is used as a cornerstone of formal methods. Cardinality – the number of items in a set. The operator # returns a set’s cardinality.
65
Programming Techniques Sets and Constructive Specification There are two ways of defining a set: –Enumeration {C++, Pascal, Ada, COBOL, Java} – contains the names of five programming languages #{C++, Pascal, Ada, COBOL, Java} implies cardinality = 5 –Constructive set specification, where the general form of the members of a set is specified using a Boolean expression, is preferable to enumeration because it enables a succinct definition of large sets. {x, y : | x + y = 10 (x, y 2 )} -describes the set of pairs of natural numbers that have the form (x, y 2 ) and where the sum of x and y is 10. This is the set: {(1, 81), (2,64), (3, 49), …}
66
Programming Techniques Sets and Constructive Set Specification II The constructive set specification has three components: - signature – specifies the range of values that will be considered when forming the set; - predicate – (a Boolean expression) defines how the set is to be considered when forming the set; - term – gives the general form of the item of the set.
67
Programming Techniques Sets and Constructive Set Specification III Consider the example: {n: N | n<3 n} - signature: n : N - N stands for the natural numbers, therefore, natural numbers are to be considered; - predicate: n< 3 – indicates that only natural numbers less than 3 are to be included; - term: n – specifies that each element of the set will be of the form n. Therefore, this specification defines the set {0, 1, 2} When the form of the elements of a set is obvious, the term can be omitted. For example, the preceding set could be specified as: {n: N | n<3}
68
Programming Techniques Set Operators A specialized set of symbology is used to represent set and logic operations. –Examples - The operator is used to indicate membership of a set. For example, the expression x X Has the value true if x is a member of the set X and the value false otherwise. - The operators and take sets as their operands. The predicate A B has the value true if the members of the set A are contained in the set B and has the value false otherwise. –The union operator, , takes two sets and forms a set that contains all the elements in the set with duplicates eliminated. {File1, File2, Tax, Compiler} {NewTax, D2, D3, File2} is the set {File1, File2, Tax, Compiler, NewTax, D2, D3}
69
Programming Techniques Logic Operators Another important component of a formal method is logic: the algebra of true and false expressions. Examples: and V or ¬ not implies Universal quantification is a way of making a statement about the elements of a set that is true for every member of the set. Universal quantification uses the symbol, An example of its use is i, j : N i > j => i 2 > j 2 which states that for every pair of values in the set of natural numbers, if i is greater than j, then i 2 is greater than j 2.
70
Programming Techniques Sequences I A sequence is a mathematical structure that models the fact that its elements are ordered. A sequence is a set of pairs whose elements range from 1 to the highest number element. For example: {(1, Jones), (2, Wilson), (3, Shapiro), (4, Estavez)} is a sequence. Sequences are designated using angle brackets. For example, the preceding sequence would normally be written as Jones, Wilson, Shapiro, Estavez
71
Programming Techniques Sequences II Concatenation or catenation, ^, is a binary operator that forms a sequence constructed by adding its second operand to the end of its first operand. For example: 2, 3, 34, 1 ^ 12, 33, 34, 200 = 2, 3, 34, 1, 12, 33, 34, 200
72
Programming Techniques Sequences III Other operators that can be applied to sequences are head, tail, front, and last. - head: extracts the first element of a sequence; - tail: returns with the last n-1 elements in a sequence of length n; - last: extracts the final element in a sequence; - front: returns with the first n-1 elements in a sequence of length n. head = 2 tail = 3, 34, 1,99, 101 last = 101 front = 2, 3, 34, 1, 99
73
Programming Techniques 6. Sets Based on Chapter 2 of Formal Specification Using Z David Lightfoot
74
Programming Techniques Sets A set is a collection of elements or members. The Z notation uses typed set theory: All the possible values of a set are considered to have something in common, they are said to be the same type. For example: sets of persons, sets of numbers. We are not too interested in sets that can contain any sort of element. We will concentrate on typed set theory.
75
Programming Techniques Subsets Any set is considered to be a subset of its type. Example: even numbers are a subset of integers. A subset is any collection of values from a set.
76
Programming Techniques The Z built-in types The designated Integer symbol is: Z …,-3,-2,-1,0,1,2,3… The designated symbol for Natural numbers including zero is N 0,1,2,3… The designated symbol for Natural numbers excluding zero is N 1 1,2,3..
77
Programming Techniques Operations on Integers Z The following operators are defined for the type Integer (Z) and its subsets: +addition - subtraction * multiplication (integer) division modmodulus (remainder after division) E.g. 23 5 = 4 23 mod 5 = 3
78
Programming Techniques Relations on Integers The following relational operators are applicable to Integers:
79
Programming Techniques Basic Types Basic types are called given sets. The basic types of a specification are declared without concern for how the elements are represented. Example : [REGISTRATION] the set of all possible car registrations [PERSON] the set of all persons Basic types are written completely in capital letters. It is assumed that the elements are uniquely identifiable. Combined types: [REGISTRATION,PERSON]
80
Programming Techniques Free Types There is a need to invent names when creating a formal specification. This can be done with a free type. The rules for constructing such identifiers are similar to those of computer programming languages. Sometimes it is convenient to introduce a type by listing the identifiers of its elements.
81
Programming Techniques Free Types The general format of a free type is: freeType ::= element 1 | element 2 |...| element n Examples : RESPONSE ::= yes | no STATUS ::= inUse | free | onHold The symbol ::= means ‘is defined as’
82
Programming Techniques Declaring Variables Each variable name designating a value must be declared. That means it must be introduced and the type of value it refers must be stated. For example, to introduce a variable chauffeur to the basic type PERSON we write: chauffeur :PERSON chauffeur is one of the set of values of PERSON
83
Programming Techniques Example Set Let the set EU be the set of all countries in the European Union. It could have been declared as a basic type, a variable sized set [EU] the set of some of countries in the European Union. It could also be declared as a fixed size free type: EU ::= A | B | DK | F | SF | D | GB | GR | IRL | I | L | NL | P | E | S The variable homeland can refer to one element in the set EU homeland:EU
84
Programming Techniques Set values The value of a set can be written by listing its values within braces {}. For example : benelux={B,NL,L} Sets are not ordered. There are no duplicates, each element is unique.
85
Programming Techniques The Empty Set Singleton It is possible to have a set with no values, it is called the empty set and denoted as: 0 or { } A set that contains only one element is called a singleton set. For example: {IRL} Note the difference between the set {IRL} and element IRL: IRL does not have the same type as {IRL}
86
Programming Techniques Ranges of Integers A range of values is denoted as m…n, where m and n are integers, stands for the set of integers m to n inclusive. If m>n then m..n = 0 Examples: 3..5 = { 3, 4, 5} 2..2 = {2} 3..2 = 0
87
Programming Techniques Set Equivalence Two values of the same type can be tested to see if they are the same by using the equals sign, as in: x = y Two sets are equal if they contain exactly the same elements. For example the two sets below are equal: {B,NL,L} = {NL, B, L}
88
Programming Techniques Set Non-Equivalence Two values of the same type can be tested to see if they are not the same by using the not- equals sign. Two sets are not equal if they do not contain exactly the same elements {B,NL} {B,NL,L}
89
Programming Techniques Membership Operator The membership operator is written: e NL e {B, NL, L} - it is true; the Netherlands is a Benelux country General case below: X S.x.x [X] S: P X - S is declared as a set of Xs x:X x e S
90
Programming Techniques Non-membership Operator The non-membership operator is written: IRL {B, NL, L} it is true; Ireland is not a Benelux country General case: X S.x.x [X] S: P X - S is declared as a set of Xs x:X x S
91
Programming Techniques Size, Cardinality The number of values in a set is called its size, or cardinality, and is signified with the hash sign: #{B,NL,L} = 3 #{IRL} = 1 #IRL illegal, IRL is not a set #0 = 0
92
Programming Techniques Powersets I The powerset of a set is written PX It is the set of all subsets of X. S:PX - S is declared as a set of Xs For example the powerset of the Benelux countries is: P{B,NL,L} = { 0, {B},{NL},{L}, {B,NL},{B,L},{NL,L}, {B,NL,L}}
93
Programming Techniques Powersets II When a variable is to be declared to have a type that is a set of elements, the type is the powerset of the type of the elements: benelux: PEU This can be read as ‘the variable benelux is a subset of the set of countries EU’ or ‘the variable benelux is a set of EU countries’
94
Programming Techniques Powersets III The size of the powerset of a set is equal to two raised to the power of the size of the set. #(PS) = 2 #s #{B,NL,L} = 3 #(P{B,NL,L}) = 8
95
Programming Techniques Set Inclusion I The ‘is a subset of’ operator is: set1 z set2 The subset operator is true if the first set is included in the second set, that is every element of the first set must be in the second set.
96
Programming Techniques Set Inclusion II S X [X] S: P X T: P X T z S T The following statements are true: { B,NL} z {B,NL,L} 0 z {B,NL,L} {B,NL,L} z {B,NL,L} General case
97
Programming Techniques Set Inclusion III The empty set is a subset of every set, including itself. The empty set is not a member of every set. The empty set can only be a member of a set of sets. Elements of set EU that border the Pacific (none) 0 z S is true for all sets S 0 z 0 is true When checking for singleton inclusion: ({x} z S) (xeS)
98
Programming Techniques Union The union of two sets is the set containing all the elements that are in either the first set or the second set or both. S T X [X] S: P X T: P X T U S T U S = S U T S U 0 = S
99
Programming Techniques Intersection The intersection of two sets is the set containing all the elements that are in the first set and in the second set. S T X [X] S: P X T: P X T I S T I S = S I T S I 0 = 0
100
Programming Techniques Difference The difference of two sets is the set containing all the elements that are in the first set and are not in the second set. The shaded area is the difference of S and T. S X [X] S: P X T: P X S \ T S \ T = T \ S S \ 0 = S 0 \ S = 0 T
101
Programming Techniques Distributed Union The distributed union of a set of sets is the set containing just those elements that occur in at least one of the component sets. S X [X] S: P X R: P X T: P X { R,S,T} T R
102
Programming Techniques Distributed Intersection The distributed intersection of a set of sets is the set containing just those elements that occur in all of the component sets. S X [X] S: P X R: P X T: P X { R,S,T} T R
103
Programming Techniques Disjoint Sets Sets that are disjoint have no elements in common; their intersection is the empty set. For disjoint sets T and S the following expression is true: T I S = 0.
104
Programming Techniques More than 2 Disjoint Sets For more that two sets it becomes longer, since every pair must have an empty intersection. For example for sets A, B and C to be disjoint the following must be true: A I B = 0 and B I C = 0 and C I A = 0
105
Programming Techniques Disjoint Sets In Z, we often write: Example 1 disjoint Example 2 [PERSON] male, female: PERSON disjoint
106
Programming Techniques Partition A sequence of sets is said to partition another larger set if the sets are disjoint and their distributed union is the entire larger set if the sets are disjoint. For example: if disjoint and {A,B,C} = T then partition T E.g. partition PERSON
107
Programming Techniques Example Edward, Fleur, and Gareth have each been given an assignment consisting of 7 questions. Edward has attempted the questions numbered 1, 2, and 4; Fleur has attempted all but questions 5 and 6; Gareth has attempted only those questions with even numbers.
108
Programming Techniques Example Express these facts using Z typed set theory. Q1: Which questions have been attempted by these three students? Q2: Which questions were attempted by all three students?
109
Programming Techniques Example Base types [Student] the set of all students (not actually needed) [Questions] the set of all exam questions Variables edward, fleur gareth: Student edwardsQuestions : PQuestions fluersQuestions : PQuestions garethsQuestions: PQuestions
110
Programming Techniques Q1: Which questions have been attempted by these three students? edwardsQuestions ={ 1, 2, 4} fluersQuestions ={ 1, 2, 3, 4, 7} garethsQuestions ={ 2, 4, 6 } Answer: The specification of Query 1 is: {edwardsQuestions, fluersQuestions, garethsQuestions} The computed answer for Query 1 is: {1, 2, 3, 4, 6, 7}
111
Programming Techniques Q1 Which questions have been attempted by all three students? edwardsQuestions ={ 1, 2, 4} fluersQuestions ={ 1, 2, 3, 4, 7} garethsQuestions ={ 2, 4, 6 } Answer: The specification of Query 2 is: {edwardsQuestions, fluersQuestions, garethsQuestions} The computed answer for Query 2 is: { 2, 4, }
112
Programming Techniques Sets: Exercise 1 1. Certain people are registered as users of a computer system. At any given time, some of these users are logged in to the computer. Describe the situation using the concepts of Z.
113
Programming Techniques Exercise 1: Solution [PERSON] the set of all uniquely identifiable persons loggedIn, users: PPERSON loggedIn z users
114
Programming Techniques Exercise 2 2. Extend your description from Q1 as follows: There is a limit (unspecified) to the number of users logged in at any one time.
115
Programming Techniques Excersise 2: Solution limit: N #loggedIn limit
116
Programming Techniques Exercise 3 3. Extend your description from Q1 as follows: All users are either: staff users or customers.
117
Programming Techniques Exercise 3: Solution staff,customers: PPERSON staff customers = q staff customers = users or partition users
118
Programming Techniques Exercise 4 Q4. Express the following statements in Z notation: - All currently logged-in users are staff. - There are more customer users than staff users.
119
Programming Techniques Exercise 4: Solution loggedIn z staff #customers > #staff
120
Programming Techniques Exercise 5 Q5. In a modular university course some modules are acceptable and others are compulsory. Use the names acceptables and compulsories for the sets of modules. Each student studies modules from two fields. The acceptable from the first field are called firstAcc and secondAcc for the second. firstAcc z acceptables secondAcc z acceptables
121
Programming Techniques Exercise 5 (a) Write an expression to state that all compulsory modules are also acceptable. (b) Write an expression that states that there are three compulsory modules. (c) Write an expression to state that the acceptables for the first field are not the same as the acceptables for the second field. (d) Write an expression to state that some modules are acceptable for both the first field and the second field.
122
Programming Techniques Exercise 5(a) The base type is [MODULES] the set of all possible modules Variables are firstAcc, secondAcc, compulsories : PMODULES Write an expression to state that all compulsory modules are also acceptable. compulsories z acceptables
123
Programming Techniques Exercise 5(b) Write an expression that states that there are three compulsory modules #compulsories = 3
124
Programming Techniques Exercise 5(c) Write an expression to state that the acceptables for the first field are not the same as the acceptables for the second field firstAcc secondAcc
125
Programming Techniques Chapter 2 Exercise 5(d) Write an expression to state that some modules are acceptable for both the first field and the second field.
126
Programming Techniques Summary I Formal methods allow software engineers to create specifications using mathematical notation that is more complete, more consistent, and unambiguous. The mathematics used in formal software engineering methods relies heavily on set theory and logic. In many safety critical or mission critical systems, failures can have a high cost. Many safety critical systems can not be completely tested without endangering the lives of the people they are designed to protect. Use of formal methods reduces the number of specification errors dramatically, which means that the customer will encounter fewer errors when the product is deployed.
127
Programming Techniques Summary II Z specifications consist of a mathematical model of the system state and a definition of operation on that state. A Z specification is presented as a number of schemas where a schema introduces some typed names and defines predicates over these names. Schemas in Z may be distinguished from surrounding text by graphical highlighting. Schemas are building block which may be combined and used in other schemas. The effect of including a schema A in schema B is that schema B inherits the names and predicates of schema A. Operations may be specified in Z by their effect on the system state. It is normal to specify operations incrementally and then combine the specification fragments to produce the complete specification.
128
Programming Techniques 2005F Instructor John D Lin - johndlin@hotlinemail.com Lectures Tues & Thurs 10:00-11:30 RM. 100, Lower Block
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.