Grocery Store Simulation

Download Report

Transcript Grocery Store Simulation

Design of Discrete Event Simulators
COP 4331 and EEL4884
OO Processes for SW Development
© Dr. David A. Workman
School of EE and Computer Science
October 13, 2004
Revised: March 19, 2009
Introduction
•
•
•
Computer Simulation is one of the most fundamental and one of the most
widely used tools for studying the behavior of complex systems.
Some Applications: Space travel, weather forecasting, war games, training
people to use complex tools and how to behave in life threatening
situations, entertainment, medicine, biology, chemistry, cosmology.
Computer Simulation can be classified according to several criteria
including:
– Stochastic or deterministic (and as a special case of deterministic, chaotic)
Stochastic simulations use random number generators to model chance or to
generate random events; they are also called Monte Carlo simulations.
Deterministic simulations use models of reality where the behavior of the
simulated system is governed by well-defined rules – given the same inputs, the
system will respond the same or exhibit the same behavior
– Continuous or discrete (and as an important special case of discrete, discrete
event or DE models)
Continuous simulations exploit mathematical models to predict the behavior of
physical systems (have to solve systems of linear and non-linear equations based
on continuous mathematics)(use numerical integration)
Discrete-event simulations model the flow of events and the interaction of objects
over time. Models are driven (enacted) by their response to discrete events in
time.
March 19, 2009
(c) Dr. David Workman
2
Benefits of Simulation
•
Building a simulator of a complex real world system is almost always
more cost and time effective than building the system being simulated.
•
A simulator of a real world system enables the user to slow down or speed
up the dynamics of the virtual world so that they can be more easily
observed and studied. Example, a simulator for subatomic interactions
based on quantum theory enables a physicist to observe in slow motion
the interactions that might take only pico-seconds in the real world.
Example. A simulator for the dynamics of galaxy collisions enables a
cosmologist to speed up the collision process to a few minutes or hours,
when in reality the process might take a billion years.
•
A simulator of a complex system (e.g. an aircraft) can be used to create a
training environment that is greatly more cost and time effective than
conducting training exercises on the real system in the real world.
•
Simulators can help system and software engineers evaluate alternative
designs before having to commit to implementing one of those
alternatives.
March 19, 2009
(c) Dr. David Workman
3
Introduction
Virtual World
Being Simulated
Simulator
Controls
the Simulator
Views the
Virtual World
Simulation
User
March 19, 2009
(c) Dr. David Workman
4
Discrete Event Simulator: Use Case Diagram
Discrete Event Simulator
Specify
Input
Construct
World
Instance
Simulation
Analyst
Specify
Output
Initialize
Simulation
Output
World
Objects
Output
Events
Simulate
World
March 19, 2009
File System
(Input File)
File System
(Output File)
Report
Post
Simulation
Results
(c) Dr. David Workman
5
Discrete Event Simulator: Activity Diagram
Acquire
Input
File
Simulate Virtual World
Construct
Virtual
World
Initialize
Virtual
World
Dispatch
Event
Start
Output
Event
Output
Virtual
World
Create
Simulation
Log FIle
[More events]
Stop
March 19, 2009
(c) Dr. David Workman
Generate
Post Simulation
Report
?
Output
Virtual
World
6
Virtual World Model:
Grocery Checkout System
COP 4331
© Dr. David A. Workman
School of EE and CS
University of Central Florida
November 21, 2005
Super Food Market
Aisle Width
Aisle n
Aisle 2
Aisle 1
9
2
1
0
Starting
Point
Aisle Delta
Exit
Cart Pool
Checkout
Queue
Conveyor
clerk
Entry
Shopper
Enters
March 19, 2009
Sales
Register
Bagger Returns
Cart
Bagging
Bin
bagger
Shopper & Cart
Bagger
& Shopper
Exit
Checkout
Subsyste
m
(c) Dr. David Workman
8
Checkout Station Model
6: The shopper pays for the groceries
and is given a sales receipt.
2: Shopper places plastic
divider on conveyor after
last grocery item.
5: When all items have been
processed by the clerk, the shopper
is presented with the total amount
of the purchase.
1: Shopper unloads grocery
items, if there is room on conveyor.
Shopper
Cart
Cart
Scales
&
Scanner
Conveyor
3: Conveyor has a fixed
capacity in numbers of
items and transports them
at a constant rate to the
clerk’s station.
Clerk
Bagging
Bin
Sales
Terminal
4:Clerk removes grocery items
from conveyor and enters
their identity and price into
the sales system. Some items
are identified and priced by
bar codes. Other items must
by manually identified and
weighed.
March 19, 2009
9:When the payment
transaction has been
completed and all bags
have been loaded in the
cart, the shopper leaves
the store with the bagged
groceries.
(c) Dr. David Workman
Bagger
7: When the cart has been
unloaded, the shopper gives
the cart to the bagger to be
filled with bags of groceries.
8:The bagger loads grocery
bags with items that have
been priced by the clerk.
Bags are held in the bin
until the cart becomes
available from the shopper.
9
Activity Diagram for Use Case Flow
Bagger
Bag
Groceries
Bagger
Load Cart
With
Bags
Stop
Start
Shopper
Unloads
Cart
Shopper
Pay For
Groceries
Clerk
Price
Checks
Items
March 19, 2009
(c) Dr. David Workman
10
Conveyor Model
• •
• •
slot 1
slot N
Shopper
Clerk
N = Conveyor capacity in Slots.
RULES:
(1) A slot is the space that can be occupied by a single item.
(2) The shopper always deposits the next item at slot 1, when it is empty.
(3) The clerk always removes an item from slot N, when it is full.
(4) If slot N is empty and at least one other slot is filled, the conveyor
rotates one slot to the right. The amount of time necessary for the
conveyor to rotate one slot position is a model parameter and is
specified as a multiple of the simulation time granule.
March 19, 2009
(c) Dr. David Workman
11
Communication Diagram: Unload Cart
ANALYSIS MODEL
(DESIGN MODEL)
USE CASE
USE CASE MODEL
USE CASE
10: add item
Bag
Bagger
Cart
Sales Terminal
9: remove item
7: add item price
Shopper
5: request item
8: deposit item
Clerk
Conveyor
Bagging Bin
6: deliver item
March 19, 2009
(c) Dr. David Workman
12
Discrete Event Simulator: Architecture Diagram
March 19, 2009
(c) Dr. David Workman
14
Simulator Design: Class Diagram
See Notes
Interface and Control Layer
World
*
EventMgr
*
All Active
Objects
2
*
This layer consists of all active object classes. Active objects must be
instances of some subclass of abstract class Agent. The simulation progresses as a result of Events created and
serviced by Agents. An Event has four components: a Sender agent, a Recvr agent, an instance of some Message
subclass, and an event time. When one Agent wishes to interact with another, it must do so by creating an Event
that defines a “future” time at which the interaction will occur. The message component defines an action to the
Recevr agent and possibly data necessary to complete the action.
This layer contains all the derived subclasses of Message.
These classes are used to pass data for servicing interaction events
between Agents. Only recipient Agent classes know the content and use
of instances of these classes. Methods of Agents receiving messages
optionally take parameters which are instances of one (or more) of the
Passive classes and return an instance of class Message or one of its subclasses. Instances of the root class Message carry no data and denote
signals that require some action on the part of the receiver Agent.
*
All Passive
Classes/Objects
Event
Agent
Agent Layer
(Active Objects)
Message
*
Other
Subclasses
1
Players
Message Layer
*
Passive Class Layer
The Passive layer contains all classes that model problem data and inanimate objects of the simulated world. Agents make direct
calls on passive objects, but must account for the simulation time consumed when doing so. Passive objects make direct calls to
each other, if necessary. Passive objects may be passed from one Agent to another as part of a instance of some Message subclass.
SimModels Classes
March 19, 2009
(c) Dr. David Workman
SimMgmt Classes
15
Discrete Event Simulator : SimMgmt
Event
simtime: int
sendr: Agent *
recvr: Agent *
msg: Message *
Event( Time,
Sendr
Recvr,
Msg )
GetSndr(): Agent *
GetRecvr(): Agent *
GetTime(): int
GetMsg(): Message *
Operator <<
The object by which
active objects interact.
March 19, 2009
EventMgr
Agent
eventQ: List<Event>
Name: string
EventMgr()
PostEvent( Event )
NextEvent(): Event
MoreEvents(): Boolean
Clock() : Simtime
GetSendr(): Agent *
GetRecvr(): Agent *
Agent()
Initialize( Message * )
Dispatch( Message * )
Operator<< ( ofstream&,
&Agent )
Operator>> ( ifstream&,
&Agent)
+Extract( ifstream& )
+Insert( ofstream& )
#Get( ifstream& )
#Put( ofstream& )
NameOf(): String
The encapsulated
event queue. The
queue orders posted
events by their Time.
The Clock() always
returns the current
simulation time.
An abstract class.
All active agents of
the simulated world
must be derived
subclasses of this
class.
The Dispatch() method
interprets the Message
of the receiver agent.
(c) Dr. David Workman
Message
handler: int
descr: string
Message( int, string )
GetId(): int
Operator <<
An concrete class.
All Messages denote
an interaction event
that must be serviced
by the recipient agent.
The agent dispatch
method uses the Id to
determine the method
of the agent that should
be called to service the
event.
This class is extended by
the agent to define the
data needed by the
Method called to service
the event.
16
Discrete Event Simulator: Virtual World Interface
World
World()
Initialize()
Simulate()
Insert()
WrapUp()
The object that represents
the simulated world. It
is the only interface with
the application main()
March 19, 2009
World(): The Constructor – it invokes the
constructors of all “parts” of the simulated
world that must exist when simulation
starts. Each constructor parses its image
from an input file.
Initialize(): This method “connects” the active
agents that may need to interact during
simulation. Each Agent is given an
opportunity to “prime” the EventMgr to
start the simulation.
Simulate(): This manages the simulation loop
and outputs events to the simulation log. It
may also serve to update the simulation
display.
Insert(): This method outputs to the simulation
log the instantaneous state of the simulated
world object – it calls Put for each “part”,
etc.
WrapUp(): This is the postmortem analysis
method. It controls any clean up and
display of simulation results.
(c) Dr. David Workman
17
Agent Subclass Interface Structure
Subclass
Subclass data members
Called by World
object
Called by other
Agent subclasses
Called by Dispatch()
March 19, 2009
+Constructor()
+Initialize( Message* players)
+Dispatch( Message* msg)
+Extract() //default program input stream
+Insert() //default program output stream
#Get()
#Put()
Redefined inherited and virtual methods
defined in Agent
+AcceptMsg1(…)
+AcceptMsg2(…)
…
+AcceptMsgk(…)
Public methods corresponding to messages
this Agent subclass can receive. Each
constructs an appropriate Message instance
encoding the handler id and message data.
//handler id = 1
//handler id = 2
//handler id = k
-doAcceptMsg1(…) //handler id = 1
-doAcceptMsg2(…) //handler id = 2
…
-doAcceptMsgk(…) //handler id = k
(c) Dr. David Workman
Private message handlers corresponding to
messages this Agent subclass can receive.
18
Example: Agent Design
Message
Agent
AlphaMsg
A
BetaMsg
DeltaMsg
BtoA(beta)
BtoB
AtoB(delta)
BtoC
B
AtoC
CtoA(alpha)
C
Passive Data Classes
Alpha
Beta
Delta
March 19, 2009
(c) Dr. David Workman
19
Sending Messages via Events
1. Agent A is in control (executing one of its handlers in response to a message it
2.
3.
4.
5.
6.
7.
was sent.) A wants to send a message to B telling B to do alpha using data D
(instance of a passive class). This message will take t clock ticks to arrive at B.
Agent A directly calls a public method, B::AcceptAlpha( D), to construct the
message (Msg) A wants to send to B.
Agent A then constructs: Event e( theEventMgr.clock() +t ,A, B, Msg).
Agent A posts e to theEventMgr: theEventMgr.postEvent(e);
Agent A completes its behavior and returns.
Some time later (after t clock ticks), Msg is Dispatched to B.
B executes the handler assigned to Msg: doAcceptAlpha(D).
March 19, 2009
(c) Dr. David Workman
20
Example: Agent Design
A
Subclass data members
Called by World
object
+Constructor()
+Initialize( Message* players)
+Dispatch( Message*)
+Extract() //default program input stream
+Insert() //default program output stream
#Get()
#Put()
Called by other
Agent subclasses
+AcceptBtoA(alpha): AlphaMsg*
+AcceptCtoA(beta):BetaMsg*
Called by Dispatch()
-doBtoA(alpha) //handler id = 1
-doCtoA(beta) //handler id = 2
March 19, 2009
//handler id = 1
//handler id = 2
(c) Dr. David Workman
21
Example: Agent Design
C
B
Subclass data members
Subclass data members
+Constructor()
+Initialize( Message* players)
+Dispatch( Message*)
+Extract() //default program input stream
+Insert() //default program output stream
#Get()
#Put()
+AcceptAtoC(): Message* //handler id = 1
+AcceptBtoC(): Message* //handler id = 2
-doAtoC() //handler id = 1
-doBtoC() //handler id = 2
March 19, 2009
+Constructor()
+Initialize( Message* players)
+Dispatch( Message*)
+Extract() //default program input stream
+Insert() //default program output stream
#Get()
#Put()
+AcceptAtoB(delta): DeltaMsg* //handler id = 1
- AcceptBtoB(): Message*
//handler id = 2
-doAtoB(delta) //handler id = 1
-doBtoB()
//handler id = 2
(c) Dr. David Workman
22
Case Study: Conversation Simulation
Virtual World Scenario
A group of N students are in a classroom
and behave by getting acquainted with each
other. The dialog between students consists
of each student asking another student (at
random), "What is your name?". The student
to which the question is asked responds with
the answer, "My name is ___________.".
When each student has answered all the questions
directed at them, they leave the room (terminate).
Conversation Simulation
S2
S1
S3
S5
S4
To complicate the dynamics of this conversation,
each student may vary in the number of clock tics
it takes them to formulate a question, and in the
number of clock tics it takes them to respond with
an answer. We therefore define two simulation
input parameters: QuestionDelay and
AnswerDelay to define these time lapses for each
student independently.
Furthermore, the number, N, of students entering
into the Conversation can be greater than or equal
to 1. (If N = 1, the student carries on the dialog
with him or her self.)
March 19, 2009
(c) Dr. David Workman
23
Case Study: Conversation Simulation
Design Problems:
(1) Where should we place the decision as to which
student a given student will ask the question?
(2) How will a student know how long to stay in the
room? That is, each student must wait around
long enough to answer all the questions s/he is
asked before they can terminate. What is the
best way to implement this?
Design Solution:
(1) Where should we place the decision as to which
student a given student will ask the question?
Clearly, in the real world, each student would
initially scan the other students to decide who
they want to get acquainted with before they
ask their questions. Having decided who
they want to converse with, they would sequentially
ask the question and wait for the answer. So to
implement this behavior, we define a scanDelay
simulation parameter that defines an initial
period of time at the beginning of each student's
behavior where they decide who they will interact
with.
March 19, 2009
Design Solution:
(2) How will a student know how long to stay in the
room? There are two ways to implement this.
(a) Add a new Agent to the simulation (other than
the students) – in the simulation world, this is
called the "Ground Truth" object that is all
knowing (a kind of God agent). At the end of
the scan phase, each student informs GT who
they intend to ask questions of. GT responds
with a message that tells the student how many
questions they can expect to wait for.
(b) All students wait for a special message to terminate.
This signal would be sent by the Virtual World
object to each of the students when the VW
discovers there are no more events to be
dispatched.
For simplicity, we will chose approach 2(b).
Simulations like the Alien War Game Simulation
would use approach 2(a).
(c) Dr. David Workman
24
Case Study: Conversation Simulation
Agent
Conversation
Student
Terminate
ScanComplete (1)
Question (2)
Answer (2)
Message
Players
AnsMsg
Combine to form one class: SpeakMsg
Notes:
(1) ScanComplete is always sent by a Student to itself.
(2) Question and Answer messages are usually sent to
a different Student, but when N=1, they will be
directed to self.
March 19, 2009
QuesMsg
(c) Dr. David Workman
See Implementation
Provided
25
Conversation Sim Architecture
AppError
SimMgmt
IOMgmt
simInMgr: InMgr
TokenError
IOError
simOutMgr: OutMgr
Tokenizer
StringTokenizer
theEventMgr: EventMgr
OutMgr
EventMgr
InMgr
Agent
Message
Event
SimModels
Conversation
1..*
Student
SpeakMsg
March 19, 2009
(c) Dr. David Workman
Players
26
Case Study: Grocery Checkout
Bagger
Agents:
Shopper
Clerk
Bagger
Conveyor
4b,9
Shopper Behavior Scenario
1: Unload Grocery from Cart
2a: Deposit Grocery on Conveyor
2b: Conveyor receives Grocery
Repeat (1 – 2b) Until Cart empty
3a: Deposit plastic bar on Conveyor
3b: Conveyor receives plastic bar
4a: Hand empty Cart to Bagger
4b: Bagger receives Cart
5: Clerk says pay Money
6: Give payment to Clerk
7: Clerk returns change
8a: Clerk returns receipt
8b: Clerk tells Bagger to release
loaded Cart
9: Bagger returns loaded Cart
4a
2a,3a
See Notes!
Shopper
Conveyor
2b,3b
Passive:
Cart
Grocery
PlasticBar
Money
Receipt
March 19, 2009
5,7,8a
6
8b
Clerk
(c) Dr. David Workman
27
Case Study: Grocery Checkout
Shopper
Agent
+Shopper()
+Initialize( Message* )
+Dispatch( Message* )
+Extract()
+Insert()
#Get()
#Put()
+ItemACK() Message*
+BarACK() Message*
+CartACK() Message*
+PayAmt( Money )MoneyMsg*
+ReturnChange(Money) MoneyMsg*
+ReturnReceipt( Receipt) ReceiptMsg*
+ReturnCart( Cart* ) CartMsg*
Shopper
Bagger
Conveyor
Message
MoneyMsg
ReceiptMsg
CartMsg
0..Nslots
1
Money
1
Item
Receipt
-doItemACK()
-doBarACK()
-doCartACK()
-doPayAmt( Money )
-doReturnChange(Money)
-doReturnReceipt( Receipt)
-doReturnCart( Cart* )
1
Cart
*
BarCoded
March 19, 2009
Clerk
(c) Dr. David Workman
Grocery
Bar
Produce
28
See Notes
Simulator Design: Grocery Checkout System
Interface and Control Layer
World
*
EventMgr
Event
Post Events to
2
Agent
Bagger
Conveyor
Clerk
Agent Layer
(Active Objects)
Shopper
Message Class Layer
Message
1
Players
ReceiptMsg
MoneyMsg
CartMsg
ItemMsg
Passive Class Layer
Receipt
Money
Cart
SimModels Classes
Bar
Grocery
Barcoded
Weighed
SimMgmt Classes
March 19, 2009
(c) Dr. David Workman
29
State Transition Models
Start
[C] Event/Action
Activity
[C] Event/Action
Stop
• [C]
an [optional] boolean precondition that must be true before the Event
can trigger a transition; no precondition implies the transition will occur
unconditionally whenever the Event occurs in the system.
• Event: a signal or message received that triggers a change in state.
• Action: computation performed and/or message(s) sent in response to an event.
• Activity: a state of processing that will continue until the next event; an activity
could be a state of idleness.
March 19, 2009
(c) Dr. David Workman
30
Shopper Model
Start
[1]
/Remove Item
/DepositItem
[~1] ItemACK
/DepositItem
Unloading
Messages Sent
DepositItem => Conveyor
TakeCart => Bagger
TakeCash => Clerk
TakeCredit => Clerk
Divider
Sent
ItemACK
/TakeCart
[1] ItemACK
/Remove Item
/DepositItem
Wait
ACK
PayAmt
/Save Amount
CartACK
Transition Conditions:
[1] More items in Cart
[2] Cash >= Sales Total
Cart
ACK
[~2] PayAmt
/TakeCredit
[2]CartACK
/TakeCash
[2] PayAmt
/TakeCash
Messages Received
ItemACK <= Conveyor
CartACK <= Bagger
PayAmt <= Clerk
ReturnChange <= Clerk
ReturnCard <= Clerk
ReturnReceipt <= Clerk
ReturnCart <= Bagger
Pay
ACK
[~2]CartACK
/TakeCredit
Done
ReturnCart
/Save Cart
Wait
Change
Wait
Credit
ReturnCard
/Save Card
ReturnChange
/Save Change
Wait
Cart
March 19, 2009
ReturnReceipt
/Save Receipt
Wait
Receipt
(c) Dr. David Workman
31
Case Study: Grocery Checkout
Shopper
void Shopper::Dispatch( Message* msg) throw(AppError)
{ int handler = msg->getId();
switch( handler )
{ case 1: doAcknowledge(); break;
…
default: throw AppError(" Unrecognizable Handler Id!");
}
}
-Wallet: Money
-Change: Money
-CartHandle: Cart*
-Conveyor, Bagger, Clerk: Agent*
-SalesRecord: Receipt*
-State: string ( initially = "start")
+Shopper()
+Initialize( Message* )
+Dispatch( Message* )
+Extract()
+Insert()
#Get()
#Put()
Message* Shopper::Acknowledged()
{ return new Message( 1, "Object Received.") }
// "1" is the handler id for: doAcknowledge().
+ItemACK() Message* //Change name (see Note)
+CartACK() Message* //Not needed (see Notes)
+PayAmt( Money )MoneyMsg*
+ReturnChange(Money) MoneyMsg*
+ReturnReceipt( Receipt*) ReceiptMsg*
+ReturnCart( Cart* ) CartMsg*
add
-doItemACK() // Change name(see Notes)
-doCartACK() //Not needed (see Notes)
-doPayAmt( Money )
-doReturnChange(Money)
-doReturnReceipt( Receipt)
-doReturnCart( Cart* )
-barDelay: int //Simulation input
-groceryDelay: int //Simulation input
March 19, 2009
void Shopper::doAcknowledged()
{ int simtime;
if( State =="Unloading" )
{ if( CartHandle->IsEmpty() )
{ simtime = theEventMgr.Clock()+barDelay;
theEventMgr.PostEvent( Event( simtime, self, Conveyor,
Conveyor->TakeItem( new Bar() ));
State = "DividerSent"; return;
}else{
Grocery* groceryitem = CartHandle->getItem();
simtime = theEventMgr.Clock()+groceryDelay;
theEventMgr.PostEvent( Event( simtime, self, Conveyor,
Conveyor->TakeItem( groceryitem ));
return;
}
}//unloading
}//end
(c) Dr. David Workman
32
Conveyor Model
• •
• •
slot 1
slot N
Shopper
Clerk
N = Conveyor capacity in Slots.
RULES:
(1) A slot is the space that can be occupied by a single item.
(2) The shopper always deposits the next item at slot 1, when it is empty.
(3) The clerk always removes an item from slot N, when it is full.
(4) If slot N is empty and at least one other slot is filled, the conveyor
rotates one slot to the right. The amount of time necessary for the
conveyor to rotate one slot position is a model parameter and is
specified as a multiple of the simulation time granule.
March 19, 2009
(c) Dr. David Workman
33
Clerk Model
Start
Ring-up
Items
[1] /RequestItem
[1] ReturnItem
/RequestItem
March 19, 2009
Divider
Received
[2]TakeCash
/(update receipt)
/ReturnChange
Transition Conditions:
[1] Grocery item received
[2] Cash Received > Sales Total
Messages Sent:
RequestItem => Conveyor
LastItemInBin => Bagger
ReleaseCart
=> Bagger
PayAmt
=> Shopper
ReturnChange => Shopper
ReturnReceipt => Shopper
[~1] ReceiveItem
/PayAmount
/LastItemInBin
Make
Change
TakeCredit
/(update receipt)
Produce
Receipt
/ReleaseCart
/ReturnReceipt
Messages Received:
ReturnItem <= Conveyor
TakeCash <= Shopper
TakeCredit <= Shopper
(c) Dr. David Workman
Done
36
Bagger Model
Start
CheckBin
/CheckBin
/[1]fill bag
/CheckBin
/(open bag)
Bagging
Items
Sans Cart
TakeCart
CheckBin
/CheckBin
/[1]fill bag
Bagging
Items
With Cart
LastItemInBin
/CheckBin
Last Item
with Cart
Sans Release
Messages Sent:
CheckBin => Bagger
ReturnCart => Shopper
ReleaseCart [1]
/CheckBin
Messages Received:
CheckBin
<= Bagger
LastItemInBin <= Clerk
ReleaseCart
<= Clerk
CheckBin [~1]
/CheckBin
Fill Cart
Sans Release
[2] ReleaseCart
/CheckBin
CheckBin [ 2 ]
/CheckBin
/load bag in cart
CheckBin [3]
CheckBin [~1]
Load Cart
with
Release
CheckBin [2]
/CheckBin
/load bag in cart
March 19, 2009
CheckBin [1]
/CheckBin
/[1]fill bag
Bagging
Items with
Release
CheckBin [1]
/CheckBin
/[1]fill bag
Transition Conditions:
[1] More items in Bin
[2] No Items, but More Bags
[3] No Items, No Bags
(c) Dr. David Workman
Wait
for
Release
CheckBin [3]
/ ReturnCart
ReleaseCart
/ReturnCart
Done
37
Simulation Protocol
and
Execution Flow
COP 4331: OO Processes for Software Development
© Dr. David A. Workman
School of Electrical Engineering and Computer Science
Simulation Dynamics
C++
Runtime
simInMgr:InMgr::IOMgmt
USER
Construct()
[1] “Enter simulation
input file name: “
[1]
fin-name
fin:ifstream
fin.Open(fin-name)
simOutMgr:OutMgr::IOMgmt
USER
Construct()
[2]
[2] “Enter simulation
log file name: “
fout-name
fout:ostream
fout.Open(fout-name)
March 19, 2009
(c) Dr. David Workman
39
Simulation Dynamics
C++
Runtime
theEventMgr:EventMgr::SimMgmt
Virtual World Instance
Construct()
crazyCheckout:GCKS::SimModels
main()
fin:ifstream
Construct()
fout:ostream
Insert()
Initialize()
Simulate()
The messages to
fout are conceptual they abstract a chain
of messages that
result in output
Insert()
WrapUp()
March 19, 2009
(c) Dr. David Workman
40
Simulation Dynamics
World()
World
:Agent
fin:ifstream
:Passive
Construct( )
Extract( )
>> token
opening token
Get( )
* >> token
See Notes
Member label
Repeat until
the Agent
specification
has been read.
Extract( )
* >> token
>> token
closing token
anAgent
Construct in a similar way all other
objects of the Virtual World that
must be specified in the input file
March 19, 2009
(c) Dr. David Workman
This completes the use case
for constructing an instance
of the virtual world.
41
Simulation Dynamics
Initialize()
World
*P :Players
*A :Agent
E: Event
theEventMgr
Construct( )
Note that a (Msg) object is passed to the Event
constructor. Msg must be an instance of class
Message or one of its subclasses. The
process for constructing message instances
will be explained later.
*addAgent( anAgent )
*addPassiv( anObjct )
A->Initialize( P )
Construct( time, sendr, recvr, Msg )
Repeat for each Agent,
A.
E
postEvent (E )
This completes the use case
for initializing the simulation.
March 19, 2009
(c) Dr. David Workman
42
Simulation Dynamics
World
Agent
Passive
fout: ofstream
World.Insert()
fout << anAgent
Repeat until
Agent
Image has been
written to
SimLog
* fout << datamember
fout << aPassiveObj
Repeat until
Passive obj image
have been output.
Output all
other objects of
the Virtual
World.
fout << datamember
World.Insert():
This method is used to output the initial and final state of the Virtual
World.
NOTE: fout is an ofstream encapsulated by the default program output
manager, foutMgr, defined in the SimMgmt namespace and is therefore
visible to each Agent and any Passive objects that need it.
NOTE: Every class/object in SimModels must provide an output (friend
<<) operator for writing its image on an ASCII output stream. For
classes Agent and Message, this operator calls the Insert() and Put()
methods of the appropriate subclass using the mechanism of
polymorphism and runtime binding.
March 19, 2009
(c) Dr. David Workman
43
Simulation Dynamics
World.Simulate()
World
theEventMgr
[MoreEvents()]NextEvent()
E: Event
(E:Event)
GetRecvr()
Recvr
Recvr: Agent
M: Message
Recvr->Dispatch( E.GetMsg() )
GetHandler()
Repeat until there
are no more Events
to dispatch.
This ends the
simulation.
M = E.GetMsg()
Hid
The Recevr agent
computes Messages
to other agents for
future interaction
Events – these are
posted to theEventMgr
*PostEvent( newE )
Method[Hid](M)
fout: ofstream
See Notes
March 19, 2009
fout << E
(c) Dr. David Workman
44
Simulation Dynamics
World.Simulate()
World
theEventMgr
[MoreEvents()]NextEvent()
E: Event
(E:Event)
GetRecvr()
Recvr
Recvr: Agent
M: Message
Recvr->Dispatch( E.GetMsg() )
M = E.GetMsg()
GetHandler()
Hid
*PostEvent( newE )
Method[Hid](M)
Simlog: OutputFile
Simlog << E
March 19, 2009
The details of event handling are
shown on the next slide for the
Grocery Checkout System.
Specifically, we show part of the
behavior of Shopper and the Conveyor
(c) Dr. David Workman
NEXT SLIDE
45
Example: Message Passing
Simulated World (Time)
T0 +  = T1
T0
Accept Item (aGrocery)
Shopper: Agent
Conveyor: Agent
 = time required to remove a grocery item from the cart
(a simulation input parameter for Shopper)
Simulated World (Time)
T1 + 
T1
Conveyor: Agent
Item Accepted
Shopper: Agent
 = time required for next vacant conveyor slot to rotate into
position at the Shopper’s unload point
(this must be computed by Conveyor – it depends on the
rate speed of the belt and the processing rate of the Clerk)
March 19, 2009
(c) Dr. David Workman
46
Example: Message Passing (continued)
Cart
Shopper
doItemAccepted()
Conveyor
GroceryMsg
Empty()?
false
removeItem()
aGrocery
Construct( handler /* 1 */,
“Request to Place Item on Conveyor”
, aGrocery )
AcceptItem(aGrocery)
->aGroceryMsg
->aGroceryMsg
:Event
theEventMgr
Construct( t1, *Self, *Conveyor,
->aGroceryMsg)
e
postEvent (e1 )
Return to
Simulate()
March 19, 2009
(c) Dr. David Workman
47
Example: Message Passing (continued)
Conveyor
Dispatch(->aGroceryMsg)
aGroceryMsg
getHandler()
1
getGrocery()
aGrocery
1
doAcceptGrocery( aGrocery )
Return to
Simulate()
March 19, 2009
Saves aGrocery for processing on
the next SlotAdvance event.
(c) Dr. David Workman
48
Example: Message Passing (continued)
Conveyor
Dispatch(->aMessage)
aMessage
getHandler()
2
Belt
2
Shopper
Message
doSlotAdvance()
Slot[1] empty?
yes
Slot[1] <= aGrocery
Construct( handler /* 1 */,
“Item Accepted”)
ItemAccepted()
->aMessage
->aMessage
:Event
theEventMgr
Construct( t1, Self, Shopper,
->aMessage)
NOTE: Not shown is logic
of doSlotAdvance() that
checks to see if the Belt is
in a state of motion, and if
so, creates and posts another
SlotAdvance event to itself.
e
postEvent (e1 )
Return to
Simulate()
March 19, 2009
(c) Dr. David Workman
49
Discrete Event Simulation: Design Process
•
Identify Virtual Objects
1. Objects and/or their data members appear as nouns and/or noun phrases in virtual world
description.
2. Actions or interactions among objects appear as verb phrases and/or adverbial clauses in the
virtual world scenario.
•
Determine Static Object Relationships in the Virtual World (e.g composition,
aggregation, subtypes (specialization), association
1. Identify or Define a World object whose constituents are all other interacting objects.
2. Identify Active objects (these become Agent subclasses)
3. Identify Passive objects (concurrent access to Passive objects force them to be modeled as
Agent subclasses)
4. Construct a Class Diagram documenting the above.
•
Model the Virtual World Dynamics
1.
2.
3.
4.
5.
6.
•
For each Agent: model the interactions it initiates with other Agents (messages it sends)
For each Agent: model the behavior in response to messages sent.
Iterate 1 & 2 until all interactions have been defined
Define Message subclasses required
Construct Agent Interaction Table
Construct Agent State Model
Define Passive Classes & Behaviors
March 19, 2009
(c) Dr. David Workman
50
Agent Interaction Table
Sender
Receiver
Shopper
Conveyor
Request deposit of a(Grocery) item.
GroceryMsg
Shopper.delayUnload
Conveyor
Conveyor
Advance belt one slot.(signal)
Message
Conveyor.beltSpeed
Conveyor
Shopper
Accepted item for deposit.(signal)
Message
0(instantaneous)
March 19, 2009
Action or Purpose
(identify any data needed)
Message Class
(c) Dr. David Workman
Time delay spec.
51
Modeling Principles
1. Scenario: Two or more Active objects communicate indirectly through a Passive
object, where information flow is one-way.
Active
Passive
Active
Design Principle: Model the relationship as a direct interaction between the Active objects, where
a derived Message subclass is introduced to carry an instance of the Passive class,
or the equivalent information.
Active
Active
PassiveMsg
Message
March 19, 2009
(c) Dr. David Workman
52
Modeling Principles
2. Scenario: Two or more Active objects communicate indirectly through a Passive
object, where information flow is two-way, but access by Active objects is mutually
exclusive in time.
Active
Passive
Active
Design Principle: Model the new relationship so that all interaction with the Passive object is
initiated by the Active objects, regardless of the direction of information flow in the original
relationship. The designer is burdened with proving or guaranteeing that no two Active
objects sharing the Passive object will attempt access at the same time.
Active
March 19, 2009
Passive
(c) Dr. David Workman
Active
53
Modeling Principles
3. Scenario: Two or more Active objects communicate indirectly through a Passive
object, where information flow is two-way, but access by the Active objects may not be
mutually exclusive in time.
Active
Passive
Active
Design Principle: For this scenario, the Passive object must be modeled and implemented as an Active
object to guarantee that its state will not be corrupted by concurrent access by two or more
Active objects that attempt to change its state.
Active
March 19, 2009
Active
(Shared)
(c) Dr. David Workman
Active
54