ECE 575 - Arizona Center of Integrative Modeling and

Download Report

Transcript ECE 575 - Arizona Center of Integrative Modeling and

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
We separated models and simulators – now
we bring them together
Single
processor
Distributed
Simulator
Real-Time
Simulator
DEVS
Simulation
Protocol
Simulator
Non
DEVS
C++
Java
DEVS
Other
Representation
The DEVS simulation
protocol is the agreement
between the DEVS
modeler and the
implemented simulator
DEVS Simulation
Protocol Classes
Atomic models as
components within
coupled models are
assigned to
coupledSimulators
coupledSimulator
coupledCoordinator
Atomic
Simulator
Stand alone
atomic models are
assigned to
AtomicSimulators
coordinator
1:n
1:n
Coupled models as
components within
coupled models are
assigned to
coupledCoordinators
Coupled
models are
assigned to
coordinators
Atomic Model Simulator
m
timeline
(abstract or logica)
tN
tL
inject at time t
s =: s init
If t == tN
tL =: 0
generate output  (s)
tN =: ta(sinit)
When receive m
if m!= null and t < tN,
s := ext (s,t-tN,m)
Legend:
if m!= null and t == tN,
m = message
s = state
t = clock time
tL = time of last event
tN = time of next event
s := con (s,t-tN,m)
if m= null and t == tN,
s =: int (s)
tL =: t
tN =: t + ta(s)
• 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.
Basic DEVS Simulation Protocol
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.
1 nextTN
3 getOut
coordinator
Coupled
Model
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.
5 applyDelt
4 sendOut
simulator
tN
2. outTN
simulator
tN
simulator
tN
After each transition
tN = t + ta(), tL = t
Component
tN. tL
Component
tN. tL
Component
tN. tL
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.
Illustrating The DEVS Simulation Protocol within DEVS itself
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.
gpt
DEVS Simulation Protocol as Implemented in DEVSJAVA
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.
simulators.tellAll("initialize“) --- at start of simulation
coordinator
simulators.AskAll(“nextTN”)
simulators.tellAll (“computeInputOutput”)
simulators.tellAll("sendMessages")
simulators.tellAll("DeltFunc“)
DEVS cycle
message
message
coupledSimulator
coupledSimulator
Atomic
Atomic
Model
Model
coupledSimulator
Atomic
Atoimc3
Model
coupling
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.
DEVS Simulation Protocol Specialized to Discrete Time
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.
simulators.tellAll("initialize“) --- at start of simulation
DTSSCoord
simulators.tellAll("computeInputOutput
“)
simulators.tellAll("sendMessages")
simulators.tellAll("DeltFunc“)
message
message
DTSSSim
DTSSSim
Atomic
Atomic
Model
Model
coupling
DTSSSim
Atomic
Atoimc3
Model
Real-Time Simulator/Executor
m
real timeline
tN
tL
inject at time t
s =: s init
If t == tN
tL =: 0
tN =: ta(sinit)
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.
generate output  (s)
sleep
for ta(s)
When receive m
if m!= null and t < tN,
s := ext (s,t-tN,m)
Legend:
This difference is seen in the following
alteration of the simulator:
• When first entering the state, s, the
simulator starts a thread to sleep for a
time ta(s)
if m!= null and t == tN,
m = message
s = state
t = clock time
tL = time of last event
tN = time of next event
s := con (s,t-tN,m)
if m= null and t == tN,
s =: int (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
tL =: t
tN =: t + ta(s)
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 modelcontinuity discussed later.
•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.
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.
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
public class JobQueue extends ViewableAtomic
{
The jobs that have arrived at this job-queue.
• Class JobQueue illustrates how coupled models can be expressed as
atomic models (hence as basic DEVS)
protected Relation arrived = new Relation();
Those jobs that have become due.
• 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
protected Bag due;
This component's record of what the current simulation
time is.
protected double clock;
• 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.
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.
while (i.hasNext()) {
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()) {
Pair pair = (Pair)i.next();
double time = ((doubleEnt)pair.getKey()).getv();
if (time < min) {
min = time; } } }
minimumJobTime = new doubleEnt(min);
}
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());}}}
/////////////////////
public void initialize()
{
passivate();
clock = 0;
super.initialize();
arrived = new Relation();
due = new Bag();
minimumJobTime = new doubleEnt(INFINITY);
}
/////////////////////
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)) {
/////////////////////
public void deltint()
{
entity value = m.getValOnPort("in", i);
arrived.put (
new doubleEnt(clock + jobDueDelay),
value);
clock = clock + sigma;
deltintHook1();
//hook for use by CellGridPlot
}
}
removeAllMinimumJobs();
deltextHook1(message);
//hook for use by CellGridPlot
holdUntilNextJob();
}
holdUntilNextJob();
/////////////////////
protected void deltintHook1() {}
Makes this job-queue hold in phase "active"
until the time of the next job of minimum time
Also determines the new due jobs
protected void holdUntilNextJob()
{
detmMinimumJobTime();
if (!arrived.isEmpty()) {
holdIn("active",
minimumJobTime.getv() - clock);
}
else { passivate(); }
detmDueJobs();
}
/////////////////////
public message out()
{
message m = new message();
if (phaseIs("active")) {
Iterator i = due.iterator();
while (i.hasNext()) {
m.add(makeContent
("out", (entity)i.next()) }}
}
/////////////////////
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();
}
return m;
}}
Plotting with CellGridPlot
CellGridPlot
• 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
Example: BoxCar
time
• 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 is
provided. 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);
• delay time
for dimming
add(sumP);
• veritical
scale of plot
addCoupling(sum,"out", sumP,"pulsePlot");
Plotting with CellGridPlot…continued
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 plotter
addCoupling(cell, "outNum", transitionP,
"drawCellToScale");
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");
specify X
and Y
scales
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)));
//…}
draw color,
dim color
specify X
and Y
labels and
scales
each cell has its
own drawPos
and
numTransitions
• 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)
Model Development using Model Continuity
Implementation/
Logical
Simulation
Model
Distribution/
Distributed
Simulation
Real-Time
Distributed
Simulation/
Execution
Checks Model
Logical Behavior
Checks Model
Logical Behavior
in Distributed
Environment
Checks Model
Temporal
Behavior
Modeling
DEVS
Formalism
Using inheritance and polymorphism to allow easy switching from
structure/behavior viewing to fast simulation
Even though ViewableAtomic and ViewableDigraph models
can 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:
SimView
Coordinator
Viewable
Digraph
coupledRTSimulator
public static void main(String args[]){
ViewableAtomic
Simulator
ViewableDigraph d = new (Random,rule30CellSpace):
Viewable
Atomic
r = new coordinator (d);
Later, when
ready for
production
runs,
execute
them without
change in
fast-as-can
simulation
r.initialize();
//to measure execution time if desired:
initTime = System.currentTimeMillis();
r.simulate(100);
termTime = System.currentTimeMillis();}
You can develop
models and test
them in SimView
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() {}
coordinator
Viewable
Digraph
digraph
coupledSimulator
atomicSimulator
Viewable
Atomic
In ViableAtomicSimulator the hooks are given definitions
that allow the SimViewCoordinator to get the infromation
it 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
Using toString() and toObject() to facilitate deploying models in
distributed simulation
receiver
sender
DEVS simulator uses
toString() to encode
the entity as a String
which is sent across
the wire
public message out( ){
message m = new message();
m.add(makeContent("out",
new vect2DEnt(x,y)));
return m;
}
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();
}
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);
}
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());
}
Deploying a coupled model onto a distributed, decentralized, real-time simulation
For the coupled model define a RTCoordinatorServer,e.g.,:
public class StartVehicleSpaceServer{
You can develop
public static void main(String[] args)
models and test
{
them in SimView
try{
System.out.println("For use by clients, this host is "
+InetAddress.getLocalHost().getHostAddress());
This will give you
}catch(Exception c){}
new RTCoordinatorServer(new vehicleSpace(), 10);}the address
needed by clients
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",
StartVehicleSpace
Server
StartPursuer
Client
StartEvader
Client
intranet or internet
Constants.serverPortNumber); }}
You can now distribute these classes onto one or more
computers and execute them from jBuilder or from the
command line as illustrated before.
Later, when ready for
production runs, execute them
without change in distributed,
real0time, decentralized
simulation
You can also distribute hierarchically using RTCoordinatorServerAndClient
Verification &Validation
simulation model
construction
at high levels
Hierarchy of System Specifications
and Morphisms
Multi-component system
Multi-component system‘
structure
to
behavior
Structured system‘
Structured system
System
specific
ation
levels
V&V loop
Network of systems‘
Network of systems
I/O system
I/O system‘
I/O function
I/O function‘
I/O relation
I/O relation‘
I/O frame‘
I/O frame
behavior
to
structure
Morphisms
at each level
experimental
testing at low
levels
M&S Framework
Objectives represented by
Experimental Frame
Collaboration
Decision
Real World
Simulator
Search
modeling
relation
simulation
relation
Model
DEVS
Middleware
Modeling
Simulation
Network
Layered architecture
Entities formalized as systems; relations as system morphisms