53
TIVDM1 Modelling ordered collections 1 Modelling ordered collections Peter Gorm Larsen

Modelling ordered collections

  • Upload
    yanni

  • View
    31

  • Download
    1

Embed Size (px)

DESCRIPTION

Modelling ordered collections. Peter Gorm Larsen. Agenda. Sequence Characteristics and Primitives Revisiting the Minimum Safety Altitude Warning System The Congestion Warning System. Sequence Characteristics. Sequences are ordered collections of elements - PowerPoint PPT Presentation

Citation preview

Page 1: Modelling ordered collections

TIVDM1 Modelling ordered collections 1

Modelling ordered collections

Peter Gorm Larsen

Page 2: Modelling ordered collections

TIVDM1 Modelling ordered collections 2

Agenda

Sequence Characteristics and Primitives• Revisiting the Minimum Safety Altitude Warning System• The Congestion Warning System

Page 3: Modelling ordered collections

TIVDM1 Modelling ordered collections 3

Sequence Characteristics

• Sequences are ordered collections of elements• There can be many copies of each element• The elements themselves can be arbitrary

complex, e.g. they can be sequences as well• Sequences in VDM++ are finite• Sequence types in VDM++ are written as:

• seq of Type• seq1 of Type (for non-empty sequences)

Page 4: Modelling ordered collections

TIVDM1 Modelling ordered collections 4

Sequence Enumeration

• A sequence enumeration consists of a comma-separated list enclosed between square brackets, ”[…]”

• For example• [1,5,8,1,3]• [true, false]• [{}, {4,3},{2,4}]• [‘g’,’o’,’d’]• [3.567, 0.33455,7,7,7,7]

Are all sequences• The empty sequence can be written as “[ ]”

Page 5: Modelling ordered collections

TIVDM1 Modelling ordered collections 5

Sequence Length

• The length of a sequence is the number of elements in the sequence i.e. its size

• Multiple occurrences of the same value counts• The length of a sequence L is written as “ len L”• Quick examples:

• len [1,2,3] • len [ ]

• len [3,2,3,2]

Page 6: Modelling ordered collections

TIVDM1 Modelling ordered collections 6

Sequence Equality

• Two sequences are equal if both have the same length and for all indices in the sequences the respective index values are equal

• Quick examples:• [2,4,1,2] = [4,1,2]• [true, true, false] = [false, true]• [1,1,1,1,1,1,1,1,1,1,1,1] = [1]• [{3,4,5},{4}] = [{3,5,4},{4,4,4}]

Page 7: Modelling ordered collections

TIVDM1 Modelling ordered collections 7

Sequence Head and Tail

• A non-empty sequence can be divided into its head (hd) and its tail (tl).

• The head of a sequence is the first element• The tail of a sequence is the rest of the

sequence• Quick examples:

• hd [1,2,3,4,5]• tl [1,2,3,4,5]• hd [[5],[6,1],[4,4,4]]• tl [[5],[6,1],[4,4,4]]

Page 8: Modelling ordered collections

TIVDM1 Modelling ordered collections 8

Sequence Elements

• It is possible to extract the elements of a sequence using an elems operator

• elems takes a sequence an yield a set of its elements (i.e. destroying the ordering information)

• Quick examples:• elems [1,2,2]• elems [ ]• elems [[3],[2,3],[1]]

Page 9: Modelling ordered collections

TIVDM1 Modelling ordered collections 9

Sequence Indices

• It is possible to get hold of the indices for a sequence using the inds operator

• In VDM++ indexing starts with 1• Quick examples:

• inds [1,2,21,6,5]• inds [{ }, {true}] • inds [ ]• inds [[3,2],[3],[1]]

Page 10: Modelling ordered collections

TIVDM1 Modelling ordered collections 10

Sequence Application

• Given a non-empty sequence it is possible to hold of its contents at the ith index

• Sequence application is written as function application, i.e. sequence(index expression)

• Quick examples:• [1,2,21,6,5](3)• [{ },{false}](2)

• [[3,2],[3,1],[4]](1)

Page 11: Modelling ordered collections

TIVDM1 Modelling ordered collections 11

Sequence Modification

• Given a non-empty sequence it is possible to obtain a new sequence where the contents of certain indices are changed

• A sequence modification expression looks as: sequence ++ modified mapping

• The modified mapping goes from index to new value at that index

• Quick examples• [{2,4},{3,1,2},{2,3,4,3}] ++ {1 |-> {}}• [[2,4],[3,1,1],[ ]] ++ {2 |-> [7,5],1 |-> [8]}• [{true},{false},{}] ++ {3 |-> {true,false}}

Page 12: Modelling ordered collections

TIVDM1 Modelling ordered collections 12

Sequence Concatenation

• Two sequences A and B can be concatenated together to form a new sequence where A’s elements are followed by B’s elements

• Sequence concatenation is written as ”A ^ B”• Quick examples:

• [1,2,2] ^ [1,6,5] • [ ] ^ [true] • [{3,2},{3},{1}] ^ [{4}]

Page 13: Modelling ordered collections

TIVDM1 Modelling ordered collections 13

Distributed Sequence Concatenation

• If we have a sequence of sequences then the elements can be concatenated together in a distributed fashion

• Distributed sequence concatenation is written as ”conc SS” where SS is a sequence of sequences

• Quick examples:• conc [[1,2,2], [1,6,5], [ ], [8,3]] • conc [[ ],[true],[false]] • conc [[{3,2},{3},{1}],[ ],[{9,5}],[{4}]]

Page 14: Modelling ordered collections

TIVDM1 Modelling ordered collections 14

Sequence Operators

hd l Head seq1 of A -> A

tl l Tail seq1 of A -> seq of A

len l Length seq of A -> nat

elems l Elements seq of A -> set of A

inds l Indexes seq of A -> set of nat1

l1 ^ l2 Concatenation seq of A * seq of A -> seq of A

conc ll Distr. conc. seq of seq of A -> seq of A

l(i) Seq. application seq1 of A * nat1 -> A

l ++ m Seq. modification seq1 of A * map nat1 to A -> seq1 of A

l1 = l2 Equality seq of A * seq of A -> bool

l1 <> l2 Inequality seq of A * seq of A -> bool

Page 15: Modelling ordered collections

TIVDM1 Modelling ordered collections 15

Sequence Comprehensions

• Using predicates to define sequences implicitly• In VDM++ formulated like:

• [element | numeric set binding & predicate]

• The predicate part is optional• The numeric order of the binding is used to

determine the order in the sequence• The smallest number is taken to be the first

index• Quick examples

• [3 * x | x in set {0,…,2}] • [x | x in set {0,…,4} & x > 2]

Page 16: Modelling ordered collections

TIVDM1 Modelling ordered collections 16

Questions

• What are the sequence enumerations for:• [x|x in set {8,…,1} & x < 3]• [x|x in set {1,…,10} & x > 3 and x < 6]• [{y}| y in set {3,1,7,3}]• [x+6| x in set {1,2}]• [mk_(x,8)| x in set {1,2,7} & x > 4]• [y|y in set {0,1,2} & exists x in set {0,…,3} & x = 2 * y]• [x = 7| x in set {1,…,10} & x < 6]

Page 17: Modelling ordered collections

TIVDM1 Modelling ordered collections 17

Sub-sequence Expressions

• A subsequence of a sequence L is a sequence formed from consecutive elements of L; from index n1 up to and including index n2. It has the form:• L(n1, ..., n2)

• where n1 and n2 are integer expressions. • Quick Examples

• [5,4,3,7,8,2](2,…,4)• [5,4,3,7,8,2](-6,…,4)• [5,4,3,7,8,2](2,…,8)• [5,4,3,7,8,2](6,…,4)

Page 18: Modelling ordered collections

TIVDM1 Modelling ordered collections 18

Agenda

Sequence Characteristics and Primitives Revisiting the Minimum Safety Altitude Warning System• The Congestion Warning System

Page 19: Modelling ordered collections

TIVDM1 Modelling ordered collections 19

Adding Predictions and Priorities

• In order to warn flying objects before they crash into an obstacle we need to be able to predict flight path

• To deal with saturated radars we could introduce priorities

• The flying objects that arrive in the airspace after the capacity is exceeded with be warned

Page 20: Modelling ordered collections

TIVDM1 Modelling ordered collections 20

An Updated Class Diagram

Page 21: Modelling ordered collections

TIVDM1 Modelling ordered collections 21

Adding a History Type

• How can we define a history type?

Class GLOBAL

public History = seq of Position

end GLOBAL

Page 22: Modelling ordered collections

TIVDM1 Modelling ordered collections 22

Flying Objects Needs a History

class FO is subclass of GLOBAL

instance variables id : Id; coord : Coordinates; alt : Altitude; hist : History := []; inv len hist <= 3;

operationspublic registerPosition : () ==> ()registerPosition() == if len hist < 3 then hist := hist ^ [mk_Position(coord,alt)] else hist := tl hist ^ [mk_Position(coord,alt)];

Page 23: Modelling ordered collections

TIVDM1 Modelling ordered collections 23

Introducing Vectors

class GLOBAL

types

public Vector ::

X : real

Y : real;

operations

protected vectorSum : Vector * Vector -> Vector

vectorSum(v1,v2) ==

mk_Vector(v1.X + v2.X, v1.Y + v2.Y);

end GLOBAL

Page 24: Modelling ordered collections

TIVDM1 Modelling ordered collections 24

Using Vectors

class FO…operations

public getDirectionHistory : () ==> seq of VectorgetDirectionHistory() == let p1 = hist(1), p2 = hist(2), p3 = hist(3) in return [mk_Vector(p1.coord.X - p2.coord.X, p1.coord.Y - p2.coord.Y),

mk_Vector(p2.coord.X - p3.coord.X, p2.coord.Y - p3.coord.Y)]pre len hist = 3;

end FO

Page 25: Modelling ordered collections

TIVDM1 Modelling ordered collections 25

Updating ATC Threads

public findThreats : () ==> ()findThreats() == let allFOs = dunion { r.getDetected() | r in set radars } in (for all fo in set allFOs do for all ob in set obstacles do if not isFOSafe(ob,fo.getPosition()) then writeObjectWarning(ob,fo) else if len fo.getHistory() = 3 then willFObeSafe(ob,fo); for all r in set radars do if r.saturatedRadar() then writeRadarWarning(r) );

Page 26: Modelling ordered collections

TIVDM1 Modelling ordered collections 26

Will a Flying Object be Safe?

willFObeSafe : Obstacle * FO ==> ()willFObeSafe(obs,fo) == let pred = isPredictPossible(fo) in for all p in set pred do if not isFOSafe(obs,p) then let id = fo.getId(), cs = fo.getCoordinates(), alt = fo.getAltitude(), type = <EstimationWarning>, msa = obs.getMSA(), t = World`timerRef.GetTime() in World`env.handleFOWarningEvent(id, cs, alt, type, msa, t)pre len fo.getHistory() = 3;

Page 27: Modelling ordered collections

TIVDM1 Modelling ordered collections 27

Adding priorities to Radarclass Radar is subclass of GLOBAL

instance variables … priority : seq of FO := [];

operationsprivate addNewlyDetected : set of FO ==> ()addNewlyDetected(newlyDetect) == priority := priority ^ set2seqFO(newlyDetect);

functionsset2seqFO : set of FO -> seq of FOset2seqFO(fos) == if fos = {} then [] else let fo in set fos in [fo] ^ set2seqFO(fos\{fo})

Page 28: Modelling ordered collections

TIVDM1 Modelling ordered collections 28

Updating priorities in Radarclass Radar is subclass of GLOBAL

instance variables … priority : seq of FO := [];

operationsprivate removeNotDetected : set of FO ==> ()removeNotDetected(fos) == priority := [priority(i) | i in set inds priority & priority(i) not in set fos];

private UpdatePriorityList : () ==> ()UpdatePriorityList() == let notDetect = elems priority \ detected, newlyDet = detected \ elems priority in ( removeNotDetected(notDetect); addNewlyDetected(newlyDet) );

Page 29: Modelling ordered collections

TIVDM1 Modelling ordered collections 29

Using Sequences in Environmentclass Environment is subclass of GLOBAL

types

inline = Id * int * int * Altitude * Time; outline = FOOut | RadarOut;

FOOut = Id * Coordinates * Altitude * FOWarning * MinimumSafetyAltitude * Time;RadarOut = Coordinates * nat1 * RadarWarning * nat * Time; instance variables

inlines : seq of inline := []; outlines : seq of outline := [];operations public Environment : String ==> EnvironmentEnvironment(fname) == def mk_(-,input) = io.freadval[seq of inline](fname) in inlines := input;

Page 30: Modelling ordered collections

TIVDM1 Modelling ordered collections 30

Updating Flying Objectsclass Environment…operationsprivate updateFOs : () ==> ()updateFOs() == (if len inlines > 0 then (dcl curtime : Time := World`timerRef.GetTime(), done : bool := false; while not done do def mk_(id,x,y,altitude,pt) = hd inlines in if pt <= curtime then let p = mk_Coordinates(x,y) in (airspace.updateFO(id,p,altitude); inlines := tl inlines; done := len inlines = 0 ) else done := true ) else busy := false );

Page 31: Modelling ordered collections

TIVDM1 Modelling ordered collections 31

Agenda

Sequence Characteristics and Primitives Revisiting the Minimum Safety Altitude Warning System The Congestion Warning System

Page 32: Modelling ordered collections

TIVDM1 Modelling ordered collections 32

History for Altitude

class FO

public getAltitudeHistory : () ==> seq of nat

getAltitudeHistory() ==

let lastHist = hist(2,...,3)

in

return [lastHist(i).altitude

| i in set inds lastHist]

end FO

Page 33: Modelling ordered collections

TIVDM1 Modelling ordered collections 33

The Congestion Warning System

• A system for warning drivers of upcoming congestion on highways with lower speed limits to reduce the likelihood of collisions.

Page 34: Modelling ordered collections

TIVDM1 Modelling ordered collections 34

The Main CWS Components

• Sensors: These are used to derive status information about the traffic. Sensors include video cameras, radar and human observers.

• Traffic Controls: This interpret the data coming from sensors and take appropriate action.

• Actuators: These are used to signal to the drivers about potential congestions. Here traffic signs will be used but different technologies could be envisaged as well.

Page 35: Modelling ordered collections

TIVDM1 Modelling ordered collections 35

Overview of the CWS System

Page 36: Modelling ordered collections

TIVDM1 Modelling ordered collections 36

UML Class Diagram for CWS

Page 37: Modelling ordered collections

TIVDM1 Modelling ordered collections 37

Example Journey Plan

class CWS…instance variablesroadNetwork: seq of CongestionMonitor := [];sensors : seq of PassageSensor := [];inv len roadNetwork = len sensors;

am: ActuatorManager := new ActuatorManager();op: OperatorControl := new OperatorControl();

types

Location = nat1end CWS

Page 38: Modelling ordered collections

TIVDM1 Modelling ordered collections 38

Multiple Assignment Statements

• We somehow need to update the roadNetwork and the sensors instance variables synchronously to ensure the invariant

• VDM++ Construct: atomic (assignment statement 1; assignment statement 2; ... assignment statement n )

Page 39: Modelling ordered collections

TIVDM1 Modelling ordered collections 39

The AddCongestionMonitor Operation

public AddCongestionMonitor: Location ==> ()

AddCongestionMonitor(loc) ==

(def sensor = new PassageSensor(loc);

cm = new CongestionMonitor(loc, sensor, am, op)

in

let numberOfWarners = len roadNetwork

in

atomic(roadNetwork := roadNetwork(1,...,loc) ^

[cm] ^

roadNetwork(loc+1,...,

numberOfWarners);

sensors := sensors(1,...,loc) ^ [sensor] ^

sensors(loc+1,...,numberOfWarners)

);

am.AddActuator(loc)

)

Page 40: Modelling ordered collections

TIVDM1 Modelling ordered collections 40

Different kinds of Sensors

Page 41: Modelling ordered collections

TIVDM1 Modelling ordered collections 41

Sensors and PassageSensors

class Sensor

instance variables

protected location: CWS`Location

end Sensor

class PassageSensor is subclass of Sensor

instance variables

passages: seq of CWS`Speed := []

operations

public PassageSensor: CWS`Location ==> PassageSensor

PassageSensor(loc) ==

location := loc;

end PassageSensor

Page 42: Modelling ordered collections

TIVDM1 Modelling ordered collections 42

Finding the Average Speed

class PassageSensor is subclass of Sensor…public AverageSpeed: nat1 ==> CWS`SpeedAverageSpeed(numberOfPassages) ==( dcl accSpeed: CWS`Speed := 0; let passInAccount = passages(1,...,numberOfPassages) in ( for speed in passInAccount do accSpeed := accSpeed + speed; return (accSpeed/numberOfPassages) ))pre len passages >= numberOfPassages

end PassageSensor

Page 43: Modelling ordered collections

TIVDM1 Modelling ordered collections 43

The Congestion Sensor

class CongestionSensor is subclass of Sensortypespublic CongestionStatus = <Congestion>|<NoCongestion>| <Doubt>operationspublic CongestionSensor: PassageSensor ==> CongestionSensorCongestionSensor(sensor) == passageSensor := sensor;

public IssueCongestionStatus: () ==> CongestionStatus IssueCongestionStatus() == def averageSpeed = passageSensor.AverageSpeed(noPassages) in if averageSpeed < congestionThreshold then return <Congestion> elseif averageSpeed > noCongestionThreshold then return <NoCongestion> else return <Doubt>end CongestionSensor

Page 44: Modelling ordered collections

TIVDM1 Modelling ordered collections 44

Actuator Structure

as: seq of Actuator

public Signal = <NoWarning>| <PreAnnouncement>|

<CongestionWarning>;

Page 45: Modelling ordered collections

TIVDM1 Modelling ordered collections 45

Show Signal in Actuation Managerclass ActuationManager…public ShowSignal: CWS`Location * CongestionMonitor`Signal ==> ()ShowSignal(location, signal) ==(let downstream = as(location + 1), actuator = as(location), upstream = as(location - 1) in -- Set the right signal at the location itself (ShowSignalAtLoc(signal,downstream,actuator); -- Set the right signal upstream ShowSignalUpstream(signal,upstream) )) pre location in set {2,..., len as -1} and (signal = <NoWarning> or signal = <CongestionWarning>);end ActuationManager

Page 46: Modelling ordered collections

TIVDM1 Modelling ordered collections 46

Show Signal at a given Locationclass ActuationManager… ShowSignalAtLoc: CongestionMonitor`Signal * Actuator * Actuator ==> ()ShowSignalAtLoc(signal,downstream,actuator) == if signal = <NoWarning> then def downstreamsignal = downstream.GetSignal() in if downstreamsignal = <CongestionWarning> then actuator.SetSignal(<PreAnnouncement>) else actuator.SetSignal(<NoWarning>) else def currentsignal = actuator.GetSignal() in let safest = MostRestrictive(currentsignal, signal) in actuator.SetSignal(safest);end ActuationManager

Page 47: Modelling ordered collections

TIVDM1 Modelling ordered collections 47

Most Restrictive Signalclass ActuationManager…functions

MostRestrictive: CongestionMonitor`Signal * CongestionMonitor`Signal -> CongestionMonitor`SignalMostRestrictive(s1, s2) == if s1 = <CongestionWarning> or s2 = <CongestionWarning> then <CongestionWarning> elseif s1 = <PreAnnouncement> or s2 = <PreAnnouncement> then <PreAnnouncement> else <NoWarning>end ActuationManager

Page 48: Modelling ordered collections

TIVDM1 Modelling ordered collections 48

Adding and Replacing Actuatorsclass ActuationManager…public AddActuator: CWS`Location ==> ()AddActuator(loc) == def act = new Actuator() in as := as(1,...,loc) ^ [act] ^ as(loc+1,..., len as)pre loc in set inds as;

public ReplaceActuator: CWS`Location ==> ()ReplaceActuator(loc) == def act = new Actuator() in as := as ++ {loc |-> act}pre loc in set inds as;end ActuationManager

Page 49: Modelling ordered collections

TIVDM1 Modelling ordered collections 49

Operator Control

class OperatorControl

instance variables

messageLog: seq of seq1 of char := [];

locations : seq of CWS`Location := [];

inv len messageLog = len locations

end OperatorControl

Page 50: Modelling ordered collections

TIVDM1 Modelling ordered collections 50

Manipulating Log Messagesclass OperatorControl…operations

public ResetLog: () ==> ()ResetLog() ==atomic (messageLog := []; locations :=[] );

public WriteLog: seq1 of char * CWS`Location ==> ()WriteLog(message, location) ==atomic(messageLog := messageLog ^ [message ^ ConvertNum2String(location)]; locations := locations ^ [location]);end OperatorControl

Notice that WriteLog has an error in the book. This is

the right version.

Page 51: Modelling ordered collections

TIVDM1 Modelling ordered collections 51

Operator Utilities

class OperatorControl…operations

public CongestionSpots: () ==> set of CWS`LocationCongestionSpots() == return elems locations;

ConvertLog2File: () ==> seq of charConvertLog2File() == return conc messageLogend OperatorControl

Page 52: Modelling ordered collections

TIVDM1 Modelling ordered collections 52

Summary

• What have I presented today? • The notion of sequences as ordered collections

• The basic operations in VDM++ for manipulating sequences

• The congestion warning system example

• What do you need to do now?• Continue with your project

• Present your status to all of us

• Read chapter 8 before next lecture

Page 53: Modelling ordered collections

TIVDM1 Modelling ordered collections 53

Quote of the day

By Sir Francis Darwin(1848 - 1925)

In science the credit goes to the man who convinces the world, not the man to whom the idea first occurs.