design of discrete event simulators cop 4331 and eel4884 oo processes for sw development © dr....
TRANSCRIPT
Design of Discrete Event Simulators
COP 4331 and EEL4884OO Processes for SW Development
© Dr. David A. WorkmanSchool of EE and Computer Science
October 13, 2004Revised: March 23, 2010
March 23, 2010 2
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 23, 2010 3
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; especially when a training scenario might end with catastrophic results to life and/or equipment.
• Simulators can help system and software engineers evaluate alternative designs before having to commit to implementing one of those alternatives.
March 23, 2010 4
Introduction
Simulator
Simulation User
Virtual WorldBeing Simulated
Controlsthe Simulator
Views theVirtual World
March 23, 2010 5
Discrete Event Simulator: Use Case Diagram
Discrete Event Simulator
ConstructWorld
Instance
SpecifyInput
SimulateWorld
OutputWorld
Objects
ReportPost
SimulationResults
InitializeSimulation
Simulation Analyst
SpecifyOutput
File System(Input File)
File System(Output File)Output
Events
March 23, 2010 6
Discrete Event Simulator: Activity Diagram
Start
Stop
?[More events]
AcquireInputFile
CreateSimulation
Log FIle
ConstructVirtualWorld
OutputVirtualWorld
InitializeVirtualWorld
GeneratePost Simulation
Report
OutputEvent
DispatchEvent
OutputVirtualWorld
Simulate Virtual World
Virtual World Model:Grocery Checkout System
Virtual World Model:Grocery Checkout System
COP 4331
© Dr. David A. Workman
School of EE and CS
University of Central Florida
November 21, 2005
March 23, 2010 8
Super Food Market
Entry
Exit
Ais
le 1
Ais
le 2
Cart Pool Conveyor
0
1
2
9
Aisle Delta
Checkout Queue
clerk
Ais
le n
Aisle Width
StartingPoint
SalesRegister
BaggingBin
bagg
er
ShopperEnters
Bagger ReturnsCart
Bagger& Shopper
Exit
CheckoutSubsyste
m
Shopper & Cart
March 23, 2010 9
Checkout Station Model
ConveyorScales
&Scanner
Clerk
BaggingBin
SalesTerminal
Bagger
Shopper Cart Cart
1: Shopper unloads groceryitems, if there is room on conveyor.
2: Shopper places plasticdivider on conveyor afterlast grocery item.
3: Conveyor has a fixedcapacity in numbers of items and transports themat a constant rate to theclerk’s station.
4:Clerk removes grocery itemsfrom conveyor and enterstheir identity and price intothe sales system. Some itemsare identified and priced bybar codes. Other items mustby manually identified and weighed.
5: When all items have been processed by the clerk, the shopperis presented with the total amountof the purchase.
6: The shopper pays for the groceriesand is given a sales receipt.
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 grocerybags with items that havebeen priced by the clerk.Bags are held in the bin until the cart becomes available from the shopper.
9:When the payment transaction has been completed and all bagshave been loaded in thecart, the shopper leavesthe store with the baggedgroceries.
March 23, 2010 10
Activity Diagram for Use Case Flow
Start
BaggerLoads Cart
WithBags
ShopperPays ForGroceries
Stop
ShopperUnloads
Cart
ClerkRings Up
Items
BaggerBags
Groceries
March 23, 2010 11
Conveyor Model
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.
slot Nslot 1
• • • •
Shopper Clerk
N = Conveyor capacity in Slots.
March 23, 2010 12
Communication Diagram: Unload Cart
Shopper
Cart1: remove item
2: request slot for item3: deliver empty slot
4: deposit item
Bagging BinConveyor Clerk
Bagger
Bag
5: request item
6: deliver item
8: deposit item
9: remove item
10: add item
ANALYSIS MODEL(DESIGN MODEL)
USE CASEUSE CASE MODEL
USE CASE
Sales Terminal
7: add item price
March 23, 2010 13
Discrete Event Simulator: Architecture Diagram
March 23, 2010 14
Simulator Design: Class DiagramSee Notes
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.
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 sub-classes. Instances of the root class Message carry no data and denotesignals that require some action on the part of the receiver Agent.
World
Message
Players
Agent
Event
2
Passive Class Layer
Message Layer
Agent Layer(Active Objects)
Interface and Control Layer
EventMgr *
1Other
Subclasses
All ActiveObjects
* *
All PassiveClasses/Objects
* *
*
This layer consists of all active object classes. Active objects must beinstances of some subclass of abstract class Agent. The simulation progresses as a result of Events created andserviced by Agents. An Event has four components: a Sender agent, a Recvr agent, an instance of some Messagesubclass, and an event time. When one Agent wishes to interact with another, it must do so by creating an Eventthat defines a “future” time at which the interaction will occur. The message component defines an action to theRecevr agent and possibly data necessary to complete the action.
SimModels Classes SimMgmt Classes
March 23, 2010 15
Discrete Event Simulator : SimMgmt
Event
Event( Time, Sendr Recvr, Msg )GetSndr(): Agent *GetRecvr(): Agent *GetTime(): intGetMsg(): Message *Operator <<
simtime: intsendr: Agent *recvr: Agent *msg: Message *
The object by whichactive objects interact.
EventMgr
EventMgr()PostEvent( Event )NextEvent(): EventMoreEvents(): BooleanClock() : SimtimeGetSendr(): Agent *GetRecvr(): Agent *
eventQ: List<Event>
The encapsulatedevent queue. Thequeue orders postedevents by their Time.The Clock() alwaysreturns the currentsimulation time.
Agent
Agent()Initialize( Message * )Dispatch( Message * )Operator<< ( ofstream&, &Agent )Operator>> ( ifstream&, &Agent)+Extract( ifstream& )+Insert( ofstream& )#Get( ifstream& )#Put( ofstream& )NameOf(): String
Name: string
An abstract class.All active agents ofthe simulated world must be derived subclasses of this class.The Dispatch() methodinterprets the Messageof the receiver agent.
Message
handler: intdescr: string
Message( int, string )GetId(): intOperator <<
An concrete class.All Messages denotean interaction eventthat must be servicedby the recipient agent.The agent dispatchmethod uses the Id todetermine the methodof the agent that shouldbe called to service theevent. This class is extended bythe agent to define thedata needed by theMethod called to servicethe event.
March 23, 2010 16
Discrete Event Simulator: Virtual World Interface
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.
World
World()Initialize()Simulate()Insert()WrapUp()
The object that representsthe simulated world. Itis the only interface withthe application main()
March 23, 2010 17
Agent Subclass Interface Structure
Subclass
Subclass data members
+Constructor()+Initialize( Message* players)+Dispatch( Message* msg)+Extract() //default program input stream+Insert() //default program output stream#Get()#Put()
+AcceptMsg1(…) //handler id = 1 +AcceptMsg2(…) //handler id = 2…+AcceptMsgk(…) //handler id = k
-doAcceptMsg1(…) //handler id = 1-doAcceptMsg2(…) //handler id = 2…-doAcceptMsgk(…) //handler id = k
Redefined inherited and virtual methodsdefined in Agent
Public methods corresponding to messagesthis Agent subclass can receive. Eachconstructs an appropriate Message instanceencoding the handler id and message data.
Private message handlers corresponding to messages this Agent subclass can receive.
Called by other Agent subclasses
Called by Dispatch()
Called by Worldobject
March 23, 2010 18
Example: Agent Design
A
C
B
Agent
AtoB(delta)
AtoC
BtoB
BtoC
BtoA(beta)
CtoA(alpha)
Passive Data ClassesAlphaBetaDelta
Message
AlphaMsg DeltaMsgBetaMsg
March 23, 2010 19
Sending Messages via Events1. Agent A is in control (executing one of its handlers in response to a message it
was sent.) A wants to send a message to B asking B to do something (service1) using data Delta (instance of a passive class). This message will take t clock ticks from now to arrive at B.
2. Agent A directly calls a public method, B::AcceptService1(Delta), to construct the message (Msg) A wants to send to B; this call is necessary to give B and opportunity to encode in the message the identity of the private handler B will use to perform Service1.
3. Agent A then constructs: Event e( theEventMgr.clock() +t ,A, B, Msg).
4. Agent A posts e to theEventMgr: theEventMgr.postEvent(e);
5. Agent A completes its behavior and returns.
6. Some time later (after t clock ticks), Msg is Dispatched to B.
7. B executes the handler encoded in Msg: doAcceptService1(Delta).
March 23, 2010 20
Example: Agent Design
A
Subclass data members
+Constructor()+Initialize( Message* players)+Dispatch( Message*)+Extract() //default program input stream+Insert() //default program output stream#Get()#Put()
+AcceptBtoA(beta): BetaMsg* //handler id = 1 +AcceptCtoA(alpha): AlphaMsg* //handler id = 2
-doBtoA(beta) //handler id = 1-doCtoA(alpha) //handler id = 2
Called by other Agent subclasses
Called by Dispatch()
Called by Worldobject
March 23, 2010 21
Example: Agent Design
C
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
B
Subclass data members
+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
March 23, 2010 22
Case Study: Conversation Simulation
S1
S5S4
S3
S2
Ques(1-3)
Ans(3-1)
Que
s(3-
4)
Ans(4-3
)
Que
s(2-
5)A
ns(5
-2)
Conversation Simulation
Virtual World ScenarioA group of N students are in a classroomand behave by getting acquainted with eachother. The dialog between students consistsof each student asking another student (atrandom), "What is your name?". The studentto which the question is asked responds withthe answer, "My name is ___________.". When each student has answered all the questionsdirected at them, they leave the room (terminate).
To complicate the dynamics of this conversation,each student may vary in the number of clock ticsit takes them to formulate a question, and in thenumber of clock tics it takes them to respond withan answer. We therefore define two simulationinput parameters: QuestionDelay and AnswerDelay to define these time lapses for each student independently.
Furthermore, the number, N, of students enteringinto the Conversation can be greater than or equalto 1. (If N = 1, the student carries on the dialogwith him or her self.)
March 23, 2010 23
Case Study: Conversation SimulationDesign 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.
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 Simulationwould use approach 2(a).
March 23, 2010 24
Case Study: Conversation Simulation
Agent Message
Student
Conversation
ScanComplete (1)Question (2)Answer (2)
TerminatePlayers QuesMsg AnsMsg
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.
See ImplementationProvided
Combine to form one class: SpeakMsg
March 23, 2010 25
Conversation Sim Architecture
SimMgmt
SimModels
StudentConversation
Agent
1..*
IOMgmt
InMgrOutMgr
TokenError IOError
AppError
StringTokenizerTokenizer
Message Event
EventMgrtheEventMgr: EventMgr
Players
simInMgr: InMgr
simOutMgr: OutMgr
SpeakMsg
Conversation::Conversation()
March 23, 2010 26
Conversation::Conversation(){ ifstream& fin = simInMgr.getStream(); string token;// Parse opening token fin >> token; if ( token != "Conversation{" ) // throw TokenError exception// parse data member # of students fin >> token; if ( token != "#students:" ) // throw TokenError exception fin >> token; numStudents = atoi(token.c_str()); if( numStudents <= 0 ) // throw TokenError exception students = new AGENTPTR[numStudents];// Construct Student instances for(int i = 0; i < numStudents; i++) { students[i] = new Student(); students[i]->Extract(); }//for// Parse closing token fin >> token; if ( token != "}Conversation" ) // throw TokenError exception numEvents = 0; //Event counter for terminating simulation loopputHeader(); //Write simulation header and team information}
Conversation::Initialize()
March 23, 2010 27
void Conversation::Initialize(){ ostream& simlog = simOutMgr.getStream(); // Construct new Players object Players *players = new Players(numStudents); int i;
// Set students for( i=0; i < numStudents; i++ ) players->setAgent( students[i]->NameOf() , students[i] );
// Initialize students for( i=0; i < numStudents; i++ )students[i]->Initialize( players );
simOutMgr.newLine(); simlog << *players; simOutMgr.newLine();
// Memory management delete players;}//Initialize()
Conversation::Simulate()
March 23, 2010 28
void Conversation::Simulate(){ Event e; Message *msg; string token; ostream& simlog = simOutMgr.getStream();
while( theEventMgr.moreEvents() ) { //retrive next event and message e = theEventMgr.getNextEvent(); msg = e.getMsg(); // Output to simlog simOutMgr.newLine(); simlog << e; simOutMgr.newLine(); // Dispatch e.getRecvr()->Dispatch( msg ); // destruct message delete msg; // Update statistical data lastEvent = e.getTime(); numEvents++; }//while //code to terminate all Students for( int i = 0; i < numStudents; i++) { students[i]->Dispatch(((Student *)students[i])->AcceptTerminate()); }//for}//Simulate
Student.h
March 23, 2010 29
class Student : public Agent { // Inherits from Agent public: Student(); ~Student(); void Initialize (MSGPTR players); void Dispatch (MSGPTR msg); virtual void Extract() throw(TokenError); virtual void Insert(); SpeakMsg *AcceptQuestion(string aquestion); SpeakMsg *AcceptAnswer (string response); Message *AcceptTerminate(); Message *AcceptScanComplete(); protected: virtual void Get() throw(TokenError); virtual void Put(); private: void doQuestions(string question); void doAnswers (string answer); void doTerminate(); void doScanComplete(); Student *me; AGENTPTR *you; int lastyou; int ansrDelay; int questDelay; int scanDelay; int interest; }; //Student
Required by Agent
Incoming Message Types forrequested services.
Required by Agent
Handlers for requested services.
Student data members
Student data members definingsimulation parameters.
1-1 Correspondence
Student::Initialize(Players* players)
March 23, 2010 30
void Student::Initialize(MSGPTR players){ // Obtaining player's handle me = (Student *)((Players *)players)->getAgent(NameOf()); //getAgent() returns AGNTPTR // Pick and Agent at random to send a question to. you = ((Players *)players)->getOthers(interest); //getOther() returns AGNTPTR // Construct new message Message *scanMsg = ((Student *)me) -> AcceptScanComplete(); // Construct new Event Event e( scanDelay , me , me, scanMsg ); //Now = 0 // Post Event theEventMgr.postEvent(e);}
Student::AcceptQuestion()Student::AcceptTerminate()
March 23, 2010 31
SpeakMsg *Student::AcceptQuestion (string aquestion){ return new SpeakMsg ( 1, "question", aquestion);}
Message *Student::AcceptTerminate(){ return new Message( 4, "Terminate: " + NameOf());}
Student::doQuestions()
March 23, 2010 32
void Student::doQuestions(string question){ int time = theEventMgr.clock() + ansrDelay ; SpeakMsg *strMsg = AcceptAnswer("My name is:" + NameOf() + "!" ); Event e( time , me , theEventMgr.getSendr() , strMsg ); theEventMgr.postEvent(e);}//doQuestions
Student::doAnswers()
March 23, 2010 33
void Student::doAnswers(string response){ ostream& simlog = simOutMgr.getStream(); //Output the time, the identity of the sender, and the answer received. simOutMgr.newLine(); simOutMgr.pushMargin(); simlog << "At time: " << theEventMgr.clock(); simlog << ", Student: " + NameOf() + " received the following response from: " + theEventMgr.getSendr()->NameOf(); simOutMgr.advToMargin(); simlog << response; simOutMgr.popMargin(); simOutMgr.advToMargin(); //Check to see if all questions have been asked for the students of interest if( lastyou < interest-1 ) { int time = theEventMgr.clock() + questDelay; SpeakMsg *strMsg = ((Student *)you[++lastyou])->AcceptQuestion("What is your name?");
// Construct new Event Event e( time , me , you[lastyou] , strMsg );
// Post Event theEventMgr.postEvent(e); }//if
}//doAnswers
March 23, 2010 34
Case Study: Grocery Checkout
Agents:ShopperClerkBaggerConveyor
See Notes!
Passive:CartGroceryPlasticBarMoneyReceipt
Shopper
Clerk
Conveyor
Bagger
1: Unload Grocery from Cart2a: Deposit Grocery on Conveyor2b: Conveyor receives GroceryRepeat (1 – 2b) Until Cart empty3a: Deposit plastic bar on Conveyor3b: Conveyor receives plastic bar4a: Hand empty Cart to Bagger4b: Bagger receives Cart5: Clerk says pay Money6: Give payment to Clerk7: Clerk returns change8a: Clerk returns receipt8b: Clerk tells Bagger to release loaded Cart9: Bagger returns loaded Cart
Shopper Behavior Scenario
2a,3a
2b,3b
4a4b,9
5,7,8a
6
8b
March 23, 2010 35
Case Study: Grocery CheckoutShopper
+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*
-doItemACK()-doBarACK()-doCartACK()-doPayAmt( Money )-doReturnChange(Money)-doReturnReceipt( Receipt)-doReturnCart( Cart* )
Message
MoneyMsg CartMsgReceiptMsg
Agent
Shopper ClerkConveyorBagger
ReceiptMoney
Grocery
BarCoded Produce
Cart*
1 1
1
Bar
Item
0..Nslots
March 23, 2010 36
Simulator Design: Grocery Checkout SystemSee Notes
World
Message
Players
Agent
Event
2
Passive Class Layer
Message Class Layer
Agent Layer(Active Objects)
Interface and Control Layer
EventMgr *
1
CartMsg
Conveyor
Cart
SimModels Classes
SimMgmt Classes
ItemMsgReceiptMsg MoneyMsg
Bagger Clerk Shopper
Post Events to
MoneyReceipt Bar Grocery
WeighedBarcoded
March 23, 2010 37
State Transition Models
ActivityStart [C] Event/Action [C] Event/Action
• [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.
StopStop
March 23, 2010 38
Shopper Model
Unloading
[1] ItemACK/Remove Item/DepositItem
Start DividerSent
[~1] ItemACK/DepositItem
[1] /Remove Item/DepositItem
WaitACK
ItemACK/TakeCart
Transition Conditions:[1] More items in Cart[2] Cash >= Sales Total
CartACK
PayACK
CartACKPayAmt
/Save Amount
WaitReceipt
WaitChange
[2] PayAmt/TakeCash
[2]CartACK/TakeCash
[~2]CartACK/TakeCredit
ReturnCard/Save Card
ReturnChange/Save Change
WaitCart
Done
ReturnReceipt/Save Receipt
ReturnCart/Save Cart
Messages SentDepositItem => ConveyorTakeCart => BaggerTakeCash => ClerkTakeCredit => Clerk
Messages ReceivedItemACK <= ConveyorCartACK <= BaggerPayAmt <= ClerkReturnChange <= ClerkReturnCard <= ClerkReturnReceipt <= ClerkReturnCart <= Bagger
WaitCredit
[~2] PayAmt/TakeCredit
March 23, 2010 39
Case Study: Grocery CheckoutShopper
+Shopper()+Initialize( Message* )+Dispatch( Message* )+Extract()+Insert()#Get()#Put()
-Wallet: Money-Change: Money-CartHandle: Cart*-Conveyor, Bagger, Clerk: Agent*-SalesRecord: Receipt*-State: string ( initially = "start")
+ItemACK() Message* //Change name (see Note)+CartACK() Message* //Not needed (see Notes)+PayAmt( Money )MoneyMsg*+ReturnChange(Money) MoneyMsg*+ReturnReceipt( Receipt*) ReceiptMsg*+ReturnCart( Cart* ) CartMsg*
-doItemACK() // Change name(see Notes)-doCartACK() //Not needed (see Notes)-doPayAmt( Money )-doReturnChange(Money)-doReturnReceipt( Receipt)-doReturnCart( Cart* )
Message* Shopper::Acknowledged() { return new Message( 1, "Object Received.") }// "1" is the handler id for: doAcknowledge().
void Shopper::Dispatch( Message* msg) throw(AppError) { int handler = msg->getId(); switch( handler ) { case 1: doAcknowledge(); break; … default: throw AppError(" Unrecognizable Handler Id!"); }}
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
-barDelay: int //Simulation input-groceryDelay: int //Simulation input
add
March 23, 2010 40
Conveyor Model
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.
slot Nslot 1
• • • •
Shopper Clerk
N = Conveyor capacity in Slots.
March 23, 2010 43
Clerk Model
Ring-upItems
[1] ReturnItem/RequestItem
Start DividerReceived
[~1] ReceiveItem/PayAmount
/LastItemInBin
[1] /RequestItem
[2]TakeCash/(update receipt)/ReturnChange
Transition Conditions:[1] Grocery item received[2] Cash Received > Sales Total
MakeChange
ProduceReceipt
TakeCredit/(update receipt)
Done
Messages Sent:RequestItem => ConveyorLastItemInBin => BaggerReleaseCart => BaggerPayAmt => ShopperReturnChange => ShopperReturnReceipt => Shopper
Messages Received:ReturnItem <= ConveyorTakeCash <= ShopperTakeCredit <= Shopper
/ReleaseCart/ReturnReceipt
March 23, 2010 44
Bagger Model
BaggingItems
Sans CartStart
BaggingItems
With Cart
TakeCart
Last Itemwith Cart
Sans Release
CheckBin/CheckBin/[1]fill bag
Transition Conditions:[1] More items in Bin[2] No Items, but More Bags[3] No Items, No Bags
BaggingItems with
Release
Fill CartSans Release
Waitfor
Release
Load Cartwith
Release
Done
Messages Sent:CheckBin => BaggerReturnCart => Shopper
Messages Received:CheckBin <= BaggerLastItemInBin <= ClerkReleaseCart <= Clerk
/CheckBin/(open bag)
CheckBin/CheckBin/[1]fill bag
LastItemInBin/CheckBin
CheckBin [1] /CheckBin/[1]fill bag
ReleaseCart [1]/CheckBin
CheckBin [~1]/CheckBin CheckBin [ 2 ]
/CheckBin/load bag in cart
CheckBin [2]/CheckBin
/load bag in cart
[2] ReleaseCart/CheckBin
CheckBin [~1]
CheckBin [1] /CheckBin/[1]fill bag
CheckBin [3]
CheckBin [3] / ReturnCart
ReleaseCart/ReturnCart
Simulation Protocoland
Execution Flow
COP 4331: OO Processes for Software Development
© Dr. David A. Workman
School of Electrical Engineering and Computer Science
March 23, 2010 46
Simulation Dynamics
simInMgr:InMgr::IOMgmt USERC++
RuntimeConstruct()
fin-name
[1][1] “Enter simulation input file name: “
fin.Open(fin-name)
fin:ifstream
simOutMgr:OutMgr::IOMgmt USER
Construct()
fout-name
[2][2] “Enter simulation log file name: “
fout.Open(fout-name)
fout:ostream
March 23, 2010 47
Simulation Dynamics
theEventMgr:EventMgr::SimMgmtC++
RuntimeConstruct()
main()
crazyCheckout:GCKS::SimModels
Construct()
Insert()
Initialize()
Simulate()
Insert()
WrapUp()
fin:ifstream
fout:ostream
Virtual World Instance
The messages tofout are conceptual - they abstract a chainof messages thatresult in output
March 23, 2010 48
Simulation Dynamics
World fin:ifstreamWorld() :Agent
Construct( )
anAgent
Repeat untilthe Agent
specificationhas been read.
Construct in a similar way all other objects of the Virtual World that must be specified in the input file
See Notes
:Passive
Extract( )
Get( )
>> token
>> token*
>> token
This completes the use casefor constructing an instanceof the virtual world.
closing token
Member label
opening token
Extract( )* >> token
March 23, 2010 49
Simulation Dynamics
WorldInitialize() *A :Agent
Construct( )
*P :Players
*addAgent( anAgent )
*addPassiv( anObjct )
A->Initialize( P )
E: Event theEventMgr
Construct( time, sendr, recvr, Msg )
E
postEvent (E )Repeat for each Agent,A.
Note that a (Msg) object is passed to the Event constructor. Msg must be an instance of class Message or one of its subclasses. Theprocess for constructing message instances will be explained later.
This completes the use casefor initializing the simulation.
March 23, 2010 50
Simulation DynamicsWorld fout: ofstreamPassive
World.Insert()
Agent
* fout << datamember
fout << anAgent
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.
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.
fout << aPassiveObj
fout << datamember
Repeat untilAgent
Image has beenwritten to
SimLog
Repeat untilPassive obj imagehave been output.
Output allother objects ofthe VirtualWorld.
March 23, 2010 51
Simulation Dynamics
WorldWorld.Simulate() theEventMgr
Recvr
[MoreEvents()]NextEvent()
GetRecvr()
(E:Event) E: Event
Repeat until thereare no more Eventsto dispatch. This ends the simulation.
Recvr->Dispatch( E.GetMsg() )
Recvr: AgentM: Message
GetHandler()
Hid
Method[Hid](M)*PostEvent( newE )
The Recevr agentcomputes Messagesto other agents forfuture interactionEvents – these areposted to theEventMgr
See Notes
M = E.GetMsg()
fout: ofstream
fout << E
March 23, 2010 52
Simulation Dynamics
WorldWorld.Simulate() theEventMgr
Recvr
[MoreEvents()]NextEvent()
GetRecvr()
(E:Event) E: Event
Recvr->Dispatch( E.GetMsg() )
Recvr: AgentM: Message
GetHandler()
Hid
Method[Hid](M)*PostEvent( newE )
M = E.GetMsg()
Simlog: OutputFile
Simlog << EThe details of event handling areshown on the next slide for the Grocery Checkout System. Specifically, we show part of the behavior of Shopper and the Conveyor NEXT SLIDE
March 23, 2010 53
Example: Message Passing
Conveyor: AgentShopper: Agent
Simulated World (Time)
T0 T0 + = T1
Accept Item (aGrocery)
= time required to remove a grocery item from the cart (a simulation input parameter for Shopper)
Shopper: Agent
T1 +
Item Accepted
= 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)
T1
Conveyor: Agent
Simulated World (Time)
March 23, 2010 54
Example: Message Passing (continued)
Shopper
:Event theEventMgr
Conveyor
doItemAccepted()
Cart
removeItem()
Construct( handler /* 1 */, “Request to Place Item on Conveyor”, aGrocery )
aGrocery
Return to Simulate()
GroceryMsg
false
Empty()?
AcceptItem(aGrocery)
->aGroceryMsg->aGroceryMsg
Construct( t1, *Self, *Conveyor, ->aGroceryMsg)
e
postEvent (e1 )
March 23, 2010 55
Example: Message Passing (continued)
Conveyor
Dispatch(->aGroceryMsg)getHandler()
aGroceryMsg
1
getGrocery()
aGrocery
doAcceptGrocery( aGrocery )
Return to Simulate()
1
Saves aGrocery for processing onthe next SlotAdvance event.
March 23, 2010 56
Example: Message Passing (continued)
Conveyor
Dispatch(->aMessage)getHandler()
aMessage
2
doSlotAdvance()
Return to Simulate()
2
Belt
Slot[1] empty?yes
Slot[1] <= aGrocery
Shopper
Construct( handler /* 1 */, “Item Accepted”)
Message
->aMessage
ItemAccepted()
->aMessage
:Event theEventMgr
Construct( t1, Self, Shopper, ->aMessage)
e
postEvent (e1 )
NOTE: Not shown is logic of doSlotAdvance() that checks to see if the Belt isin a state of motion, and ifso, creates and posts anotherSlotAdvance event to itself.
March 23, 2010 57
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 Dynamics1. For each Agent: model the interactions it initiates with other Agents (messages it sends)
2. For each Agent: model the behavior in response to messages sent.
3. Iterate 1 & 2 until all interactions have been defined
4. Define Message subclasses required
5. Construct Agent Interaction Table
6. Construct Agent State Model
• Define Passive Classes & Behaviors
March 23, 2010 58
Agent Interaction Table
Sender Receiver Action or Purpose(identify any data needed)
Message Class Time delay spec.
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 23, 2010 59
Modeling Principles1. 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.
ActivePassiveMsg
Active
Message
March 23, 2010 60
Modeling Principles2. 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 Passive Active
March 23, 2010 61
Modeling Principles3. 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.
ActiveActive
(Shared)Active