Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 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 23, 2010

2 March 23, 20102 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.

3 March 23, 20103 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.

4 March 23, 20104 Introduction Simulator Simulation User Virtual World Being Simulated Controls the Simulator Views the Virtual World

5 March 23, 20105 Discrete Event Simulator: Use Case Diagram Discrete Event Simulator Construct World Instance Specify Input Simulate World Output World Objects Report Post Simulation Results Initialize Simulation Analyst Specify Output File System (Input File) File System (Output File) Output Events

6 March 23, 20106 Discrete Event Simulator: Activity Diagram Start Stop ? [More events] Acquire Input File Create Simulation Log FIle Construct Virtual World Output Virtual World Initialize Virtual World Generate Post Simulation Report Output Event Dispatch Event Output Virtual World Simulate Virtual World

7 Virtual World Model: Grocery Checkout System COP 4331 © Dr. David A. Workman School of EE and CS University of Central Florida November 21, 2005

8 March 23, 20108 Super Food Market Entry Exit Aisle 1 Aisle 2 Cart Pool Conveyor 0 1 2 9 Aisle Delta Checkout Queue clerk Aisle n Aisle Width Starting Point Sales Register Bagging Bin bagger Shopper Enters Bagger Returns Cart Bagger & Shopper Exit Checkout Subsyste m Shopper & Cart

9 March 23, 20109 Checkout Station Model Conveyor Scales & Scanner Clerk Bagging Bin Sales Terminal Bagger Shopper Cart 1: Shopper unloads grocery items, if there is room on conveyor. 2: Shopper places plastic divider on conveyor after last grocery item. 3: Conveyor has a fixed capacity in numbers of items and transports them at a constant rate to the clerk’s station. 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. 5: When all items have been processed by the clerk, the shopper is presented with the total amount of the purchase. 6: The shopper pays for the groceries and 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 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: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.

10 March 23, 201010 Activity Diagram for Use Case Flow Start Bagger Loads Cart With Bags Shopper Pays For Groceries Stop Shopper Unloads Cart Clerk Rings Up Items Bagger Bags Groceries

11 March 23, 201011 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 N slot 1 ShopperClerk N = Conveyor capacity in Slots.

12 March 23, 201012 Communication Diagram: Unload Cart Shopper Cart 1: remove item 2: request slot for item 3: deliver empty slot 4: deposit item Bagging Bin Conveyor Clerk Bagger Bag 5: request item 6: deliver item 8: deposit item 9: remove item 10: add item ANALYSIS MODEL (DESIGN MODEL) USE CASE USE CASE MODEL USE CASE Sales Terminal 7: add item price

13 March 23, 201013 Discrete Event Simulator: Architecture Diagram

14 March 23, 201014 Simulator Design: Class Diagram See 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 denote signals 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 * 1 Other Subclasses All Active Objects * * All Passive Classes/Objects * * * 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. SimModels ClassesSimMgmt Classes

15 March 23, 201015 Discrete Event Simulator : SimMgmt Event Event( Time, Sendr Recvr, Msg ) GetSndr(): Agent * GetRecvr(): Agent * GetTime(): int GetMsg(): Message * Operator << simtime: int sendr: Agent * recvr: Agent * msg: Message * The object by which active objects interact. EventMgr EventMgr() PostEvent( Event ) NextEvent(): Event MoreEvents(): Boolean Clock() : Simtime GetSendr(): Agent * GetRecvr(): Agent * eventQ: List The encapsulated event queue. The queue orders posted events by their Time. The Clock() always returns the current simulation 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 of the simulated world must be derived subclasses of this class. The Dispatch() method interprets the Message of the receiver agent. 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 March 23, 201016 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 represents the simulated world. It is the only interface with the application main()

17 March 23, 201017 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 methods defined in Agent Public methods corresponding to messages this Agent subclass can receive. Each constructs an appropriate Message instance encoding 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 World object

18 March 23, 201018 Example: Agent Design A C B Agent AtoB(delta) AtoC BtoB BtoC BtoA(beta) CtoA(alpha) Passive Data Classes Alpha Beta Delta Message AlphaMsgDeltaMsg BetaMsg

19 March 23, 201019 Sending Messages via Events 1.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).

20 March 23, 201020 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 World object

21 March 23, 201021 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

22 March 23, 201022 Case Study: Conversation Simulation S1 S5 S4 S3 S2 Ques(1-3) Ans(3-1) Ques(3-4) Ans(4-3) Ques(2-5) Ans(5-2) 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). 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.)

23 March 23, 201023 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. 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).

24 March 23, 201024 Case Study: Conversation Simulation Agent Message Student Conversation ScanComplete (1) Question (2) Answer (2) Terminate Players QuesMsgAnsMsg 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 Implementation Provided Combine to form one class: SpeakMsg

25 March 23, 201025 Conversation Sim Architecture SimMgmt SimModels StudentConversation Agent 1..* IOMgmt InMgrOutMgr TokenErrorIOError AppError StringTokenizerTokenizer MessageEvent EventMgrtheEventMgr: EventMgr Players simInMgr: InMgr simOutMgr: OutMgr SpeakMsg

26 Conversation::Conversation() March 23, 201026 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 loop putHeader(); //Write simulation header and team information }

27 Conversation::Initialize() March 23, 201027 void Conversation::Initialize() { ostream& simlog = simOutMgr.getStream(); // Construct new Players object Players *players = new Players(numStudents); int i; // Set students for( i=0; i setAgent( students[i]->NameOf(), students[i] ); // Initialize students for( i=0; i Initialize( players ); simOutMgr.newLine(); simlog << *players; simOutMgr.newLine(); // Memory management delete players; }//Initialize()

28 Conversation::Simulate() March 23, 201028 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

29 Student.h March 23, 201029 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 for requested services. Required by Agent Handlers for requested services. Student data members Student data members defining simulation parameters. 1-1 Correspondence

30 Student::Initialize(Players* players) March 23, 201030 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); }

31 Student::AcceptQuestion() Student::AcceptTerminate() March 23, 201031 SpeakMsg *Student::AcceptQuestion (string aquestion) { return new SpeakMsg ( 1, "question", aquestion); } Message *Student::AcceptTerminate() { return new Message( 4, "Terminate: " + NameOf()); }

32 Student::doQuestions() March 23, 201032 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

33 Student::doAnswers() March 23, 201033 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 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

34 March 23, 201034 Case Study: Grocery Checkout Agents: Shopper Clerk Bagger Conveyor See Notes! Passive: Cart Grocery PlasticBar Money Receipt Shopper Clerk Conveyor Bagger 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 Shopper Behavior Scenario 2a,3a 2b,3b 4a 4b,9 5,7,8a 6 8b

35 March 23, 201035 Case Study: Grocery Checkout Shopper +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 MoneyMsgCartMsgReceiptMsg Agent ShopperClerkConveyorBagger Receipt Money Grocery BarCodedProduce Cart * 1 1 1 Bar Item 0..Nslots

36 March 23, 201036 Simulator Design: Grocery Checkout System See 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 ItemMsgReceiptMsgMoneyMsg BaggerClerkShopper Post Events to MoneyReceiptBarGrocery WeighedBarcoded

37 March 23, 201037 State Transition Models Activity Start [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. Stop

38 March 23, 201038 Shopper Model Unloading [1] ItemACK /Remove Item /DepositItem Start Divider Sent [~1] ItemACK /DepositItem [1] /Remove Item /DepositItem Wait ACK ItemACK /TakeCart Transition Conditions: [1] More items in Cart [2] Cash >= Sales Total Cart ACK Pay ACK CartACK PayAmt /Save Amount Wait Receipt Wait Change [2] PayAmt /TakeCash [2]CartACK /TakeCash [~2]CartACK /TakeCredit ReturnCard /Save Card ReturnChange /Save Change Wait Cart Done ReturnReceipt /Save Receipt ReturnCart /Save Cart Messages Sent DepositItem => Conveyor TakeCart => Bagger TakeCash => Clerk TakeCredit => Clerk Messages Received ItemACK <= Conveyor CartACK <= Bagger PayAmt <= Clerk ReturnChange <= Clerk ReturnCard <= Clerk ReturnReceipt <= Clerk ReturnCart <= Bagger Wait Credit [~2] PayAmt /TakeCredit

39 March 23, 201039 Case Study: Grocery Checkout Shopper +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

40 March 23, 201040 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 N slot 1 ShopperClerk N = Conveyor capacity in Slots.

41 March 23, 201041 Exercise: Conveyor Conveyor N: int //Belt capacity (simulation parm>0 Belt: *Item[N] //Belt storage WaitingItem: Item* WaitingReq: boolean Motion: boolean SlotDelay: int //simulation parm. +Constructor() +Initialize( Message* players) +Dispatch( Message*) +Extract() //default program input stream +Insert() //default program output stream #Get() #Put() +RequestItem(): Message* //handler id = 1 +DepositItem(Item *): ItemMsg* //handler id = 2 -AdvanceBelt(): Message * //handler id = 3 -doRequestItem() //handler id = 1 -doDepositItem(Item *) //handler id = 2 -doAdvanceBelt() //handler id = 3

42 March 23, 201042 State Transition Models Conveyor State Model No Item Waiting Item Waiting Item Request Advance [C 1 ]: Deposit Request [~C 1 ]: Deposit Request Advance | Item Request No Request Pending Request Pending [C 5 ]Item Request Deposit Request | Advance [~C 7 ]: Advance [C 7 ]: Advance [~C 6 ]: Deposit Request [~C 5 ] Item Request [C 6 ]: Deposit Request Not Moving Item | Deposit Request [C 4 ]: Advance [~C 4 ]: Advance [~C 2 ]: Item Request [C 3 ]: Deposit Request [C 2 ]: Item Request [~C 3 ]: Deposit Request See Notes For Methods

43 March 23, 201043 Clerk Model Ring-up Items [1] ReturnItem /RequestItem Start Divider Received [~1] ReceiveItem /PayAmount /LastItemInBin [1] /RequestItem [2]TakeCash /(update receipt) /ReturnChange Transition Conditions: [1] Grocery item received [2] Cash Received > Sales Total Make Change Produce Receipt TakeCredit /(update receipt) Done Messages Sent: RequestItem => Conveyor LastItemInBin => Bagger ReleaseCart => Bagger PayAmt => Shopper ReturnChange => Shopper ReturnReceipt => Shopper Messages Received: ReturnItem <= Conveyor TakeCash <= Shopper TakeCredit <= Shopper /ReleaseCart /ReturnReceipt

44 March 23, 201044 Bagger Model Bagging Items Sans Cart Start Bagging Items With Cart TakeCart Last Item with 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 Bagging Items with Release Fill Cart Sans Release Wait for Release Load Cart with Release Done Messages Sent: CheckBin => Bagger ReturnCart => Shopper Messages Received: CheckBin <= Bagger LastItemInBin <= Clerk ReleaseCart <= 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] / ReturnCart ReleaseCart /ReturnCart

45 Simulation Protocol and Execution Flow COP 4331: OO Processes for Software Development © Dr. David A. Workman School of Electrical Engineering and Computer Science

46 March 23, 201046 Simulation Dynamics simInMgr:InMgr::IOMgmt USER C++ Runtime Construct() 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

47 March 23, 201047 Simulation Dynamics theEventMgr:EventMgr::SimMgmt C++ Runtime Construct() main() crazyCheckout:GCKS::SimModels Construct() Insert() Initialize() Simulate() Insert() WrapUp() fin:ifstream fout:ostream Virtual World Instance The messages to fout are conceptual - they abstract a chain of messages that result in output

48 March 23, 201048 Simulation Dynamics World fin:ifstream World() :Agent Construct( ) anAgent Repeat until the Agent specification has 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 * This completes the use case for constructing an instance of the virtual world. closing token Member label opening token Extract( ) * >> token

49 March 23, 201049 Simulation Dynamics World Initialize() *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. The process for constructing message instances will be explained later. This completes the use case for initializing the simulation.

50 March 23, 201050 Simulation Dynamics World 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 until Agent Image has been written to SimLog Repeat until Passive obj image have been output. Output all other objects of the Virtual World.

51 March 23, 201051 Simulation Dynamics World World.Simulate() theEventMgr Recvr [MoreEvents()]NextEvent() GetRecvr() (E:Event) E: Event Repeat until there are no more Events to dispatch. This ends the simulation. Recvr->Dispatch( E.GetMsg() ) Recvr: AgentM: Message GetHandler() Hid Method [Hid] (M) *PostEvent( newE ) The Recevr agent computes Messages to other agents for future interaction Events – these are posted to theEventMgr See Notes M = E.GetMsg() fout: ofstream fout << E

52 March 23, 201052 Simulation Dynamics World World.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 << E 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 NEXT SLIDE

53 March 23, 201053 Example: Message Passing Conveyor: AgentShopper: Agent Simulated World (Time) T0T0 T 0 +  = T 1 Accept Item (aGrocery)  = time required to remove a grocery item from the cart (a simulation input parameter for Shopper) Shopper: Agent T 1 +  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) T1T1 Conveyor: Agent Simulated World (Time)

54 March 23, 201054 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 Construct( t1, *Self, *Conveyor, ->aGroceryMsg) e postEvent (e1 )

55 March 23, 201055 Example: Message Passing (continued) Conveyor Dispatch(->aGroceryMsg) getHandler() aGroceryMsg 1 getGrocery() aGrocery doAcceptGrocery( aGrocery ) Return to Simulate() 1 Saves aGrocery for processing on the next SlotAdvance event.

56 March 23, 201056 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 is in a state of motion, and if so, creates and posts another SlotAdvance event to itself.

57 March 23, 201057 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.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

58 March 23, 201058 Agent Interaction Table SenderReceiverAction or Purpose (identify any data needed) Message ClassTime delay spec. ShopperConveyorRequest deposit of a(Grocery) item.GroceryMsgShopper.delayUnload Conveyor Advance belt one slot.(signal)MessageConveyor.beltSpeed ConveyorShopperAccepted item for deposit.(signal)Message0(instantaneous)

59 March 23, 201059 Modeling Principles 1.Scenario: Two or more Active objects communicate indirectly through a Passive object, where information flow is one-way. ActivePassiveActive 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 PassiveMsg Active Message

60 March 23, 201060 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. ActivePassiveActive 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. ActivePassiveActive

61 March 23, 201061 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. ActivePassiveActive 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 (Shared) Active


Download ppt "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."

Similar presentations


Ads by Google