22
ECE 449/549 Class Notes #3 DEVS Simulators and Executors / Methodology : How to model and simulate Sept. 2008

ECE 449/549 Class Notes #3 DEVS Simulators and Executors / Methodology : How to model and simulate Sept. 2008

Embed Size (px)

DESCRIPTION

We separated models and simulators – now we bring them together Simulator Single processor Distributed Simulator Real-Time Simulator C++ Non DEVS Java Other Representation DEVS Simulation Protocol The DEVS simulation protocol is the agreement between the DEVS modeler and the implemented simulator

Citation preview

Page 1: ECE 449/549 Class Notes #3 DEVS Simulators and Executors / Methodology : How to model and simulate Sept. 2008

ECE 449/549 Class Notes #3

DEVS Simulators and Executors/

Methodology : How to model and simulate

Sept. 2008

Page 2: ECE 449/549 Class Notes #3 DEVS Simulators and Executors / Methodology : How to model and simulate Sept. 2008

DEVS Simulators and Executors

• DEVS Simulation Protocol Classes • Atomic Model Simulator• Basic DEVS Simulation Protocol• Illustrating the DEVS Simulation Protocol within

DEVS itself • DEVS Simulation Protocol as Implemented in

DEVSJAVA• DEVS Simulation Protocol Specialized to Discrete

Time• Real Time Simulator/Executor

Page 3: ECE 449/549 Class Notes #3 DEVS Simulators and Executors / Methodology : How to model and simulate Sept. 2008

We separated models and simulators – now we bring them together

Simulator

Single processor

DistributedSimulator

Real-TimeSimulator

C++

NonDEVS

DEVS

Java

OtherRepresentation

DEVS SimulationProtocol

The DEVS simulation protocol is the agreement between the DEVS modeler and the implemented simulator

Page 4: ECE 449/549 Class Notes #3 DEVS Simulators and Executors / Methodology : How to model and simulate Sept. 2008

DEVS Simulation Protocol Classes

AtomicSimulator

coordinatorcoupledSimulator 1:n

coupledCoordinator 1:n

Stand alone atomic models are assigned to AtomicSimulators

Coupled models are assigned to coordinators

Atomic models as components within coupled models are assigned to coupledSimulators

Coupled models as components within coupled models are assigned to coupledCoordinators

Page 5: ECE 449/549 Class Notes #3 DEVS Simulators and Executors / Methodology : How to model and simulate Sept. 2008

Atomic Model Simulator• Every atomic model has a simulator assigned to it which keeps track of the time of the last event, tL and the time of the next event, tN.

• Initially, the state of the model is initialized as specified by the modeler to a desired initial state, sinit. The event times, tL and tN are set to 0 and ta(sinit), respectively.

• If there are no external events, the clock time, t is advanced to tN, the output is generated and the internal transition function of the model is executed. The simulator then updates the event times as shown, and processing continues to the next cycle.

• If an external event is injected to the model at some time, text (no earlier than the current clock and no later than tN), the clock is advanced to text.

•If text == tN the output is generated.•Then the input is processed by the confluent or external event transition function, depending on whether text coincides with tN or not.

tL =: t

tN =: t + ta(s)

When receive m

if m!= null and t < tN,

s := ext (s,t-tN,m)

if m!= null and t == tN,

s := con (s,t-tN,m)

if m= null and t == tN,

s =: int (s)

s =: s init

tL =: 0

tN =: ta(sinit)

mtimeline(abstract or logica)

inject at time t

tNtL

Legend:m = messages = statet = clock timetL = time of last eventtN = time of next event

If t == tN generate output (s)

Page 6: ECE 449/549 Class Notes #3 DEVS Simulators and Executors / Methodology : How to model and simulate Sept. 2008

coordinator

simulator

Component

tN

tN. tL

After each transition tN = t + ta(), tL = t

simulator

Component

tN

tN. tL

simulator

Component

tN

tN. tL

Coupled Model

1 nextTN

2. outTN

3 getOut

4 sendOut

5 applyDelt

Basic DEVS Simulation Protocol

Each simulator reacts to the incoming message as follows:

•If it is imminent and its input message is empty, then it invokes its model’s internal transition function•If it is imminent and its input message is not empty, it invokes its model’s confluence transition function•If is not imminent and its input message is not empty, it invokes its model’s external transition function•If is not imminent and its input message is empty then nothing happens.

Coupled Model Coordinator:

1. Coordinator sends nextTN to request tN from each of the simulators.

2. All the simulators reply with their tNs in the outTN message to the coordinator

3. Coordinator sends to each simulator a getOut message containing the global tN (the minimum of the tNs)

4. Each simulator checks if it is imminent (its tN = global tN) and if so, returns the output of its model in a message to the coordinator in a sendOut message.

5. Coordinator uses the coupling specification to distribute the outputs as accumulated messages back to the simulators in an applyDelt message to the simulators – for those simulators not receiving any input, the messages sent are empty.

For a coupled model with atomic model components, a coordinator is assigned to it and coupledSimulators are assigned to its components. In the basic DEVS Simulation Protocol, the coordinator is responsible for stepping simulators through the cycle of activities shown.

Page 7: ECE 449/549 Class Notes #3 DEVS Simulators and Executors / Methodology : How to model and simulate Sept. 2008

Illustrating The DEVS Simulation Protocol within DEVS itself

gpt

The DEVS Simulation Protocol can be illustrated within DEVSJAVA itself as follows:

The coupled model, simTrip, represents the simulation of coupled model gpt. We define simulator and sCoordinator subclasses of atomic.The components of simTrip are:3 instances of the simulator class, one each for g, p, and t 1 instance of the sCoordinator class.

Page 8: ECE 449/549 Class Notes #3 DEVS Simulators and Executors / Methodology : How to model and simulate Sept. 2008

coordinator

Atomic

ModelAtoimc3

coupledSimulator

simulators.tellAll("initialize“)

simulators.AskAll(“nextTN”)

simulators.tellAll

simulators.tellAll("sendMessages")

simulators.tellAll("DeltFunc“)

messagemessage

coupledSimulator coupledSimulator

Atomic

ModelAtomic

Model

simulators.tellAll("initialize“) --- at start of simulation

simulators.AskAll(“nextTN”)

simulators.tellAll (“computeInputOutput”)

simulators.tellAll("sendMessages")

simulators.tellAll("DeltFunc“) DEVS cycle

DEVS Simulation Protocol as Implemented in DEVSJAVA

coupling

The DEVS Simulation Protocol implemented in DEVSJAVA is basically the same as the one just discussed. However, instead of having simulators send their output messages to the coordinator, they exchange messages when told to do so by the coordinator. To be able to do so, they need the coupling that is relevant to their attached models – this is transmitted to them in a a step, called informCoupling, that is performed by the coordinator at start up.

For example, the simulator for generator, g in the coupled model gpt, knows that an output on port “out” should be paired with port “in” in a message to the simulator for processor p.

Page 9: ECE 449/549 Class Notes #3 DEVS Simulators and Executors / Methodology : How to model and simulate Sept. 2008

DTSSCoord

Atomic

ModelAtoimc3

DTSSSim

simulators.tellAll("initialize“)

simulators.tellAll("computeInputOutput“)

simulators.tellAll("sendMessages")

simulators.tellAll("DeltFunc“)

messagemessage

DTSSSim DTSSSim

Atomic

ModelAtomic

Model

simulators.tellAll("initialize“) --- at start of simulation

simulators.tellAll("computeInputOutput“)

simulators.tellAll("sendMessages")

simulators.tellAll("DeltFunc“)

DEVS Simulation Protocol Specialized to Discrete Time

coupling

For an isolated discrete time coupled model the DEVS simulation protocol can be simplified. Assuming the time advance of each atomic model is always the same, the global tN need not be computed. Further, all components are always imminent, leading to the cycle shown below.Note: This alternative only is more efficient that the standard DEVS protocol under the conditions of very high activity.

Page 10: ECE 449/549 Class Notes #3 DEVS Simulators and Executors / Methodology : How to model and simulate Sept. 2008

Real-Time Simulator/Executor

• When first entering the state, s, the simulator starts a thread to sleep for a time ta(s)

• If an external event is injected to the model at some time, text (no earlier than the current clock and no later than tN), the sleeping thread is interrupted and

•If text == tN the output is generated.•Then the input is processed by the confluent or external event transition function, depending on whether text coincides with tN or not.

tL =: t

tN =: t + ta(s)

When receive m

if m!= null and t < tN,

s := ext (s,t-tN,m)

if m!= null and t == tN,

s := con (s,t-tN,m)

if m= null and t == tN,

s =: int (s)

s =: s init

tL =: 0

tN =: ta(sinit)

mtimeline

inject at time t

tNtL

Legend:m = messages = statet = clock timetL = time of last eventtN = time of next event

If t == tN generate output (s)

sleep for ta(s)

Execution in real time of an atomic model is similar to its simulation in logical or abstract time. The difference is that rather than being controlled by an events list within the coordinator, each simulator governs itself according to the host processor system clock. Thus passage of time in the model is identical to that of a wall clock.

This difference is seen in the following alteration of the simulator:

real

Real time execution of DEVS models is facilitated by the separation of model from simulator which allows the simulator to be “changed out” by one that adheres to a real clock. The ease of migration from simulation to execution enables a designprocess called model-continuity discussed later.

Page 11: ECE 449/549 Class Notes #3 DEVS Simulators and Executors / Methodology : How to model and simulate Sept. 2008

M&S Methodology : how to model & simulate

• First think about your objectives- find a level of difficulty that seems achievable in the time available.

• Develop the experimental frames first to meet these objectives. Event Lists and Applications

• Develop your atomic models and coupled models and test them in hierarchical stage wise fashion in SimView.

• Start your exploratory phase -- get some preliminary results of execution within experimental frames. What is the “lay of the land”? Which factors appear to matter most?

• Start your production runs (for final results) by concentrating on the factors that seem to be important from your initial exploration.

• If you need better performance, remove all unessential code, including output and print statements. Switch execution from SimView to fast-as-can simulation as shown next.

• For greater performance migrate your model to parallel/distributed fast-as-can simulation (not currently available).

• If your objectives were to develop real-time execution models, migrate them to real-time execution (distributed, non-distributed) as shown next.

Page 12: ECE 449/549 Class Notes #3 DEVS Simulators and Executors / Methodology : How to model and simulate Sept. 2008

public class JobQueue extends ViewableAtomic{ The jobs that have arrived at this job-queue. protected Relation arrived = new Relation();

Those jobs that have become due. protected Bag due;

This component's record of what the current simulation time is. protected double clock;

The length of time after a job arrives until it is due. protected double jobDueDelay;

Entity wrapper for he minimum time of all the jobs that have arrived. protected doubleEnt minimumJobTime;

Determines the minimum time of all the jobs that have arrived.

protected void detmMinimumJobTime() { double min = INFINITY;

if there are any jobs that have arrived if (!arrived.isEmpty()) { for each job that has arrived Iterator i = arrived.iterator(); while (i.hasNext()) {

while (i.hasNext()) {

Pair pair = (Pair)i.next(); double time = ((doubleEnt)pair.getKey()).getv(); if (time < min) { min = time; } } }

minimumJobTime = new doubleEnt(min); }

JobQueue – an event list that illustrates DEVS closure under coupling

• DEVS closure under coupling – asserts that every coupled model is behaviorally equivalent to a basic DEVS

• This makes hierarchical construction possible

• Class JobQueue illustrates how coupled models can be expressed as atomic models (hence as basic DEVS)

• this constructive approach is to given an atomic model an event list with which it simulates the transitions of the coupled model it represents (it mimics the formal proof given within the DEVS formalism for closure under coupling)

• JobQueue delays incoming jobs by a fixed delay time

• it can easily be modified to allow arbitrary delay times including accepting the time advances of components of a coupled model as delays

CellGridPlot extends JobQueue where jobs become point plots and the delay is used to do a second plot to overwrite the first giving the dimming effect.

Page 13: ECE 449/549 Class Notes #3 DEVS Simulators and Executors / Methodology : How to model and simulate Sept. 2008

Makes this job-queue hold in phase "active" until the time of the next job of minimum timeAlso determines the new due jobs

protected void holdUntilNextJob() { detmMinimumJobTime(); if (!arrived.isEmpty()) { holdIn("active", minimumJobTime.getv() - clock); } else { passivate(); } detmDueJobs(); }

/////////////////////public void initialize() { passivate(); clock = 0; super.initialize(); arrived = new Relation(); due = new Bag(); minimumJobTime = new doubleEnt(INFINITY); }

/////////////////////public void deltint() { clock = clock + sigma;

deltintHook1(); //hook for use by CellGridPlot

removeAllMinimumJobs();

holdUntilNextJob(); } ///////////////////// protected void deltintHook1() {}

///////////////////// public message out() { message m = new message();

if (phaseIs("active")) { Iterator i = due.iterator(); while (i.hasNext()) { m.add(makeContent ("out", (entity)i.next()) }}

return m; }}

/////////////////////public void deltext(double e, message m) { clock = clock + e; Continue(e);

for (int i = 0; i < m.getLength(); i++) {

if (messageOnPort(m, "in", i)) { entity value = m.getValOnPort("in", i); arrived.put ( new doubleEnt(clock + jobDueDelay), value); } }

deltextHook1(message); //hook for use by CellGridPlot

holdUntilNextJob(); }

///////////////////// protected void deltextHook1(message message) {}

////////////////// public void deltcon(double e, message message) { // the order needed here is the reverse of the default deltcon order

deltext(e, message); deltint(); }

JobQueue – continued…

Creates a bag of jobs that are due consisting of those that have arrived mand have the minimum time.

protected void detmDueJobs() { for each arrived job due = new Bag(); Iterator i = arrived.iterator(); while (i.hasNext()) { // if the job is one of those that has the minimum time Pair pair = (Pair)i.next(); if (pair.getKey().equals(minimumJobTime)) { //add to this job to the bag of those that are due due.add(pair.getValue()); } } }

Removes all the jobs of the minimum time from the container of arrived jobs. protected void removeAllMinimumJobs() { for each arrived job Iterator i = arrived.iterator(); while (i.hasNext()) { // if the job is one of those that has the minimum time Pair pair = (Pair)i.next(); if (pair.getKey().equals(minimumJobTime)) { //remove the job from the arrived jobs container arrived.remove(pair.getKey(), pair.getValue());}}}

Page 14: ECE 449/549 Class Notes #3 DEVS Simulators and Executors / Methodology : How to model and simulate Sept. 2008

CellGridPlot

Plotting with CellGridPlot

• CellGridPlot is a subclass of ViewableAtomic that provides graph plotting.

• Each instance of CellGridPlot can draw on its own instance of class CellGridView. or can share instances of the latter.

• CellGridPlot is treated in the same way as other DEVS components This implies plotting occurs in step with the simulation and in real-time or distributed fashion as desired. Also plotters may be decoupled allowing faster production runs of core models.

• Different constructors and different input ports offer alternative drawing services and expect different kinds of entity values.

• CellGridPlot instances are hidden by default. To show an instance use its method setHidden(false).

• Since plotting occurs in real time dimming of past values isprovided. This allows either erasing (using white dimming) or tracking (using softer colors) past trajectory segments. The delay time specified in the constructor determines the size of the non-dimmed segment.

CellGridPlot sumP = new CellGridPlot("Sum Plot",1,200);sumP.setCellGridViewLocation(600,500);sumP.setSpaceSize(100,40);sumP.setCellSize(5);sumP.setTimeScale(50);

add(sumP);

addCoupling(sum,"out", sumP,"pulsePlot");

Example: BoxCar

• timePlot and pulsePlot input ports accept real valued entities (doubleEnt). • timePlot displays time trajectories•pulsePlot draws lines from the x axis to the plotted points

• delay time for dimming

• veritical scale of plot

time

Page 15: ECE 449/549 Class Notes #3 DEVS Simulators and Executors / Methodology : How to model and simulate Sept. 2008

Example: Harmonic Oscillator

CellGridPlot t = new CellGridPlot("XY PhasePlot",1, 3*initx,3*initx);t.setCellGridViewLocation(500,100);

add(t);addCoupling(x,"out",t,"drawI");addCoupling(y,"out",t,"drawJ");

Plotting with CellGridPlot…continued

• drawCellToScale input port expects DrawCellEntity as value and draws a point specified by both I and j as well as draw and dim colors.• drawI and drawJ input ports draw points with the I and j coordinates respectively given by the input using the last saved value of the other coordinate. This is needed since usually i and j don’t change simultaneously. The ports expect doubleEnt and drawing uses the user specified scale.• drawCell input port expects DrawCellEntity as value and does not draw to scale• draw2D input port expects DrawCellEntity as value and draws a color at i,j that is obtained from a table with input k• drawString input port expects a drawCellEntity and draws a string starting from the given point.(see CelGridPlot class for more detail)

specify X and Y scales

Example: oneDimCellSpace automates plots

public void addPlots ( double stateMax, int transitionMax, double timeMax){//all cells output ports are coupled to 3 common plots for state, transition and time }For example, the transition plot is:CellGridPlot transitionP = new CellGridPlot(" Transition Plot",1, "location",numCells, "transitions", transitionMax);//couple each cell to the plotteraddCoupling(cell, "outNum", transitionP, "drawCellToScale");

The output function of each oneDimCell is of the form:

public message out(){//…m.add(makeContent("outNum", new DrawCellEntity( drawPos, numTransitions,Color.black, Color.gray))); //…}

specify X and Y

labels and scales

each cell has its own drawPos

and numTransitions

draw color,dim color

Page 16: ECE 449/549 Class Notes #3 DEVS Simulators and Executors / Methodology : How to model and simulate Sept. 2008

Model Development using Model Continuity

Modeling

Implementation/Logical

Simulation

Checks Model Logical Behavior

Model Distribution/Distributed Simulation

Checks Model Logical Behavior

in DistributedEnvironmentDEVS

Formalism

Real-TimeDistributed Simulation/Execution

Checks Model Temporal Behavior

Page 17: ECE 449/549 Class Notes #3 DEVS Simulators and Executors / Methodology : How to model and simulate Sept. 2008

Even though ViewableAtomic and ViewableDigraph modelscan hold information intended for SimView, they need not be altered to run outside of SimView. For example, to run a ViewableDigraph model in a main routine define:

public static void main(String args[]){

ViewableDigraph d = new (Random,rule30CellSpace):

r = new coordinator (d);

r.initialize();

//to measure execution time if desired:initTime = System.currentTimeMillis();

r.simulate(100);termTime = System.currentTimeMillis();}

This can be executed in JBuilder of by changing directory to DevsJava/classes and entering on the command line –>java Random.rule30CellSpace

To understand how this is possible, consider that in atomicSimulator the Devs Simulator Cycle implementation includes “hooks” within its methods, e.g.,

public void computeInputOutput(double t){ if(equalTN(t)) { output = myModel.Out();} else{output = new message();} computeInputOutputHook1() ;}

These hooks are dummy methods within atomicSimulator, e.g.,

protected void computeInputOutputHook1() {}

In ViableAtomicSimulator the hooks are given definitions that allow the SimViewCoordinator to get the infromationit needs to display in SimView, .e.g.,

protected void computeInputOutputHook1(){ if (listener == null) return; ContentIteratorInterface iterator = output.mIterator(); while (iterator.hasNext()) { ContentInterface content = iterator.next(); listener.contentOutputted((content)content,\ viewableAtomic, content.getPort().getName()); } }

atomic

digraph

atomicSimulator

coupledSimulator

coordinator

ViewableAtomic

ViewableDigraph

ViewableAtomicSimulator

coupledRTSimulator

SimViewCoordinator

ViewableAtomic

ViewableDigraph

You can develop models and test them in SimView

Later, when ready for production runs, execute them without change in fast-as-can simulation

Using inheritance and polymorphism to allow easy switching from structure/behavior viewing to fast simulation

Page 18: ECE 449/549 Class Notes #3 DEVS Simulators and Executors / Methodology : How to model and simulate Sept. 2008

The modeler must define toString() for the simulator to use polymorphically. For example:

public String toString(){return doubleFormat.niceDouble( x ) + ","+doubleFormat.niceDouble(y);}

public String getName(){return toString();}

The modeler also needs to define toObject() and use this method in decoding the message.

public static vect2DEnt toObject(String nm){int commaIndex = nm.indexOf(",");String xs = nm.substring(0,commaIndex);String ys = nm.substring(commaIndex+1,nm.length());return new vect2DEnt(Double.parseDouble(xs),Double.parseDouble(ys));}

public static vect2DEnt toObject(entity ent){return toObject(ent.getName());}

public message out( ){ message m = new message(); m.add(makeContent("out", new vect2DEnt(x,y))); return m;}

public void deltext(double e ,message x){ for (int i=0; i< x.getLength();i++) if (messageOnPort(x,“in",i)) { entity en = x.getValOnPort(“in",i); position = vect2DEnt.toObject(en); }

Using toString() and toObject() to facilitate deploying models in distributed simulation

sender receiver

DEVS simulator uses toString() to encode the entity as a String which is sent across the wire

Page 19: ECE 449/549 Class Notes #3 DEVS Simulators and Executors / Methodology : How to model and simulate Sept. 2008

For the coupled model define a RTCoordinatorServer,e.g.,:

public class StartVehicleSpaceServer{ public static void main(String[] args) { try{ System.out.println("For use by clients, this host is " +InetAddress.getLocalHost().getHostAddress()); }catch(Exception c){} new RTCoordinatorServer(new vehicleSpace(), 10);}

You can now distribute these classes onto one or morecomputers and execute them from jBuilder or from thecommand line as illustrated before.

Later, when ready for production runs, execute them without change in distributed, real0time, decentralizedsimulation

Deploying a coupled model onto a distributed, decentralized, real-time simulation

For each component model define a RTCoordinatorClient, e.g.,:public class StartEvaderClient{

public static void main(String[] args) { new RTCoordinatorClient( new vehicle("evader",new vect2DEnt(40,40)), "192.168.1.101", //RTCoordinatorServer’s address //or if on same machine as the server //you can use "localhost",

Constants.serverPortNumber); }}

This will give you the address needed by clients

You can develop models and test them in SimView

StartVehicleSpaceServer

StartEvaderClient

StartPursuerClient

intranet or internet

You can also distribute hierarchically using RTCoordinatorServerAndClient

Page 20: ECE 449/549 Class Notes #3 DEVS Simulators and Executors / Methodology : How to model and simulate Sept. 2008

Verification &Validation

Page 21: ECE 449/549 Class Notes #3 DEVS Simulators and Executors / Methodology : How to model and simulate Sept. 2008

Hierarchy of System Specifications and Morphisms

Network of systems Network of systems‘

Multi-component system Multi-component system‘

Structured system Structured system‘

I/O system I/O system‘

I/O function I/O function‘

I/O relation I/O relation‘

I/O frame I/O frame‘

Systemspecificationlevels

Morphisms at each level

behaviortostructure

structuretobehavior

V&V loop

experimental testing at low

levels

simulation model

construction at high levels

Page 22: ECE 449/549 Class Notes #3 DEVS Simulators and Executors / Methodology : How to model and simulate Sept. 2008

M&S Framework

Network

Simulation

Modeling

Search

Decision

Collaboration

DEVSMiddleware

Model

Real World Simulator

modelingrelation

simulationrelation

Experimental Frame

Objectives represented by

Layered architecture

Entities formalized as systems; relations as system morphisms