SimPy Manual — SimPy 2.3b1 documentation.pdf

download SimPy Manual — SimPy 2.3b1 documentation.pdf

of 54

Transcript of SimPy Manual — SimPy 2.3b1 documentation.pdf

  • 8/14/2019 SimPy Manual SimPy 2.3b1 documentation.pdf

    1/54

    mPy Manual SimPy 2.3b1 documentation

    ///C|/Users/Manolo/Downloads/ADO/SimPy Manual SimPy 2.3b1 documentation.htm[10/03/2013 01:01:30 p.m.]

    SimPy Manual Au thors:

    Tony Vignaux < [email protected] >Klaus Muller < [email protected] >Bob Helmbold

    SimPy release:

    2.3b1

    SimPy Web-site:http://simpy.sourceforge.net/

    Python-Version:2.6 and later

    Date: April 29, 2012

    Contents

    SimPy ManualIntroductionSimulation with SimPyProcessesResourcesLevelsStoresRandom Number GenerationRecording Simulation ResultsOther Links

    Acknowledgments AppendicesGlossary

    This document describes SimPy version 2.3b1. Changes from the previous versionare listed in Appendix A0 .

    Note: This document does not describe the object oriented (OO) API which hasbeen added to SimPy with version 2.0. SimPy 2.0 is fully backward compatible withprevious versions. The procedural API and the OO API co-exist happily in SimPy2.x.

    [1]The variable ver si on , imported from Si mPy. Si mul ati on , contains the revisionnumber and date of the current version.

    Introduction

    Navigation

    index

    next |

    previous |

    SimPy 2.3b1 documentation

    Manuals

    http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#id15http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#simpy-manualmailto:Vignaux%40users.sourceforge.netmailto:Muller%40users.sourceforge.nethttp://simpy.sourceforge.net/http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#simpy-manualhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#introductionhttp://c%7C/Users/Manolo/Downloads/ADO/SimPy%20Manual%20%E2%80%94%20SimPy%202.3b1%20documentation_files/SimPy%20Manual%20%E2%80%94%20SimPy%202.3b1%20documentation.htmhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#processeshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#resourceshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#levelshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#storeshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#random-number-generationhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#recording-simulation-resultshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#other-linkshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#acknowledgmentshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#appendiceshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#glossaryhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#a0-changes-from-the-previous-version-of-simpyhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#id2http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#id16http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#introductionhttp://simpy.sourceforge.net/SimPy_Manual/genindex.htmlhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/SimPyOO_API.htmlhttp://simpy.sourceforge.net/SimPy_Manual/Manuals.htmlhttp://simpy.sourceforge.net/SimPy_Manual/index.htmlhttp://simpy.sourceforge.net/SimPy_Manual/Manuals.htmlhttp://simpy.sourceforge.net/SimPy_Manual/Manuals.htmlhttp://simpy.sourceforge.net/SimPy_Manual/index.htmlhttp://simpy.sourceforge.net/SimPy_Manual/Manuals.htmlhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/SimPyOO_API.htmlhttp://simpy.sourceforge.net/SimPy_Manual/genindex.htmlhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#introductionhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#id16http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#id2http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#a0-changes-from-the-previous-version-of-simpyhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#glossaryhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#appendiceshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#acknowledgmentshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#other-linkshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#recording-simulation-resultshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#random-number-generationhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#storeshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#levelshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#resourceshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#processeshttp://c%7C/Users/Manolo/Downloads/ADO/SimPy%20Manual%20%E2%80%94%20SimPy%202.3b1%20documentation_files/SimPy%20Manual%20%E2%80%94%20SimPy%202.3b1%20documentation.htmhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#introductionhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#simpy-manualhttp://simpy.sourceforge.net/mailto:Muller%40users.sourceforge.netmailto:Muller%40users.sourceforge.netmailto:Muller%40users.sourceforge.netmailto:Muller%40users.sourceforge.netmailto:Muller%40users.sourceforge.netmailto:Muller%40users.sourceforge.netmailto:Muller%40users.sourceforge.netmailto:Vignaux%40users.sourceforge.netmailto:Vignaux%40users.sourceforge.netmailto:Vignaux%40users.sourceforge.netmailto:Vignaux%40users.sourceforge.netmailto:Vignaux%40users.sourceforge.netmailto:Vignaux%40users.sourceforge.netmailto:Vignaux%40users.sourceforge.nethttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#simpy-manualhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#id15
  • 8/14/2019 SimPy Manual SimPy 2.3b1 documentation.pdf

    2/54

  • 8/14/2019 SimPy Manual SimPy 2.3b1 documentation.pdf

    3/54

    mPy Manual SimPy 2.3b1 documentation

    ///C|/Users/Manolo/Downloads/ADO/SimPy Manual SimPy 2.3b1 documentation.htm[10/03/2013 01:01:30 p.m.]

    averages and variances, time-weighted averages, or histograms. They can begathered on the queues associated with Resources, Levels and Stores. For example we may collect data on the average number of cars waiting at a gasstation and the distribution of their waiting times. Tallys update the current statisticsas the simulation progresses, but cannot preserve complete time-series records.Monitors can preserve complete time-series records that may later be used for more advanced post-simulation analyses.

    Before attempting to use SimPy, you should be able to write Python code. Inparticular, you should be able to define and use classes and their objects. Python isfree and usable on most platforms. We do not expound it here. You can find outmore about it and download it from the Python web-site ( http://www.Python.org ).SimPy requires Python 2.3 or later.

    [Return to Top ]

    Simulation with SimPy

    To use the SimPy simulation system you must import its Si mul ati on module (or oneof the alternatives ):

    f r omSi mPy. Si mul ati on i mport *

    All discrete-event simulation programs automatically maintain the current simulationtime in a software clock. This cannot be changed by the user directly. In SimPy thecurrent clock value is returned by the now( ) function.

    At the start of the simulation the software clock is set to 0.0. While the simulationprogram runs, simulation time steps forward from one event to the next. An eventoccurs whenever the state of the simulated system changes. For example, an eventmight be the arrival or departure of a car from the gas station.

    The following statement initializes global simulation variables and sets the softwareclock to zero. It must appear in the script before any SimPy process objects areactivated.

    i ni t i al i ze( )

    This is followed by SimPy statements creating and activating process objects. Activation of process objects adds events to the simulation schedule. Execution of the simulation itself starts with the following statement:

    si mul at e( unt i l = endtime )

    The simulation starts, and SimPy seeks and executes the first scheduled event.Having executed that event, the simulation seeks and executes the next event, andso on.

    Typically a simulation is terminated when endtime is reached but it can be stoppedat any time by the command:

    st opSi mul ati on( )

    now( ) will then equal the time when this was called. The simulation will also stop if there are no more events to execute (so now( ) equals the time the last scheduledevent occurred)

    After the simulation has stopped, further statements can be executed. now( ) willretain the time of stopping and data held in Monitors will be available for display or further analysis.

    The following fragment shows only the main block in a simulation program.

    http://www.python.org/http://www.python.org/http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#contentshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#contentshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#id17http://c%7C/Users/Manolo/Downloads/ADO/SimPy%20Manual%20%E2%80%94%20SimPy%202.3b1%20documentation_files/SimPy%20Manual%20%E2%80%94%20SimPy%202.3b1%20documentation.htmhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#alternative-simpy-simulation-librarieshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#alternative-simpy-simulation-librarieshttp://c%7C/Users/Manolo/Downloads/ADO/SimPy%20Manual%20%E2%80%94%20SimPy%202.3b1%20documentation_files/SimPy%20Manual%20%E2%80%94%20SimPy%202.3b1%20documentation.htmhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#id17http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#contentshttp://www.python.org/http://www.python.org/
  • 8/14/2019 SimPy Manual SimPy 2.3b1 documentation.pdf

    4/54

  • 8/14/2019 SimPy Manual SimPy 2.3b1 documentation.pdf

    5/54

  • 8/14/2019 SimPy Manual SimPy 2.3b1 documentation.pdf

    6/54

  • 8/14/2019 SimPy Manual SimPy 2.3b1 documentation.pdf

    7/54

    mPy Manual SimPy 2.3b1 documentation

    ///C|/Users/Manolo/Downloads/ADO/SimPy Manual SimPy 2.3b1 documentation.htm[10/03/2013 01:01:30 p.m.]

    1112131415161718192021

    2223

    def go ( sel f ) : print ( ' %s %s %s ' % ( now( ) , s el f . i , ' St a r t i ng' ) ) yield hol d, sel f , 100. 0 print ( ' %s %s %s ' % ( now( ) , s el f . i , ' Arr i ved' ) )

    i ni t i al i ze( )p1 = Message( 1 , 203 ) # new messageacti vat e(p1, p1 . go( ) ) # activate itp2 = Message( 2 , 33 )acti vat e(p2, p2 . go( ) , at =6. 0 )si mul at e(unt i l =200 ) print ( ' Cur r ent t i me i s %s ' % now( ) ) # will print 106.0

    Running this program gives the following output:

    0 1 St ar t i ng6. 0 2 St ar t i ng100. 0 1 Ar r i ved106. 0 2 Ar r i vedCur r ent t i me i s 106. 0

    Elapsing time in a Process

    A PEM uses the yi el d hol d command to temporarily delay a process objectsoperations.

    yield hold

    yi el d hol d, s el f , t

    Causes the process object to delay t time units [2]. After the delay, itcontinues with the next statement in its PEM. During the hol d theobjects operations are suspended.

    [3]unless it is further delayed by being interrupted .

    This is used to model any elapsed time an entity might be involved in. For example while it is passively being provided with service.

    Example 2: In this example the Process Execution Method, buy , has anextra argument, budget :

    1 2 3 4 5 6 7 8 9101112131415

    from SimPy.Simulation import Process , ac t i vat e, hol d,i ni t i al i ze, s i mul at e

    class Customer ( Pr ocess) : def buy ( sel f , budget =0) : print ( ' Her e I am at t he shops %s ' % sel f . name) t = 5. 0 for i in r ange ( 4) : yield hol d, sel f , t # executed 4 times at intervals of t time units print ( ' I j ust bought somet hi ng %s ' % sel f . name) budget - = 10. 00 print ( ' Al l I have l ef t i s %s I am goi ng home %s ' %( budget , s el f . name) )

    http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#elapsing-time-in-a-processhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#pemhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#yield-holdhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#id3http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#id6http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#asynchronous-interruptionshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#asynchronous-interruptionshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#id6http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#id3http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#yield-holdhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#pemhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#elapsing-time-in-a-process
  • 8/14/2019 SimPy Manual SimPy 2.3b1 documentation.pdf

    8/54

    mPy Manual SimPy 2.3b1 documentation

    ///C|/Users/Manolo/Downloads/ADO/SimPy Manual SimPy 2.3b1 documentation.htm[10/03/2013 01:01:30 p.m.]

    161718192021222324

    i ni t i al i ze( )

    # create a customer named "Evelyn",C = Cust omer ( name =' Evel yn' )

    # and activate her with a budget of 100act i vat e( C, C . buy( budget =100 ) , at =10. 0 )

    si mul at e(unt i l =100. 0 )

    Starting and stopping SimPy Process Objects

    A process object is passive when first created, i.e., it has no scheduled events. Itmust be activated to start its Process Execution Method. To activate an instance of a Process class you can use either the act i vat e function or the s ta r t method of theProcess. (see the Glossary for an explanation of the modified Backus-Naur Form(BNF) notation used).

    activate

    acti vat e( p, p.pemname([args]) [ , {at=now( ) | del ay=0}] [ , pr i or=Fal se])

    activates process object p , provides its Process Execution Methodp.pemname( ) with arguments args and possibly assigns values to the other optional parameters. The default is to activate at the current time ( at =now( ) )with no delay ( del ay=0. 0 ) and pr i or set to Fal se . You may assign other valuesto at , del ay , and pr i or .

    Example: to activate a process object, cust with name cust 001 at time 10.0

    using a PEM called l i f et i me :

    act i vat e( cus t , cus t . l i f et i me( name =' cust 001' ) , at =10. 0 )

    However, del ay overrides at , in the sense that when a del ay= period clause isincluded, then activation occurs at now( ) or now( ) + period (whichever islarger), irrespective of what value of t is assigned in the at = t clause. This istrue even when the value of period in the delay clause is zero, or evennegative. So it is better and clearer to choose one (or neither) of at = t anddel ay= period , but not both.

    If you set pr i or=True , then process object p will be activated before any othersthat happen to be scheduled for activation at the same time. So, if severalprocess objects are scheduled for activation at the same time and all havepr i or=True , then the last one scheduled will actually be the first to beactivated, the next-to-last of those scheduled, the second to be activated, andso forth.

    Retroactive activations that attempt to activate a process object before thecurrent simulation time terminate the simulation with an error report.

    start

    An alternative to act i vat e( ) function is the s ta r t method. There are a number of ways of using it:

    http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#starting-and-stopping-simpy-process-objectshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#glossaryhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#activatehttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#starthttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#starthttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#activatehttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#glossaryhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#starting-and-stopping-simpy-process-objects
  • 8/14/2019 SimPy Manual SimPy 2.3b1 documentation.pdf

    9/54

  • 8/14/2019 SimPy Manual SimPy 2.3b1 documentation.pdf

    10/54

    mPy Manual SimPy 2.3b1 documentation

    ///C|/Users/Manolo/Downloads/ADO/SimPy Manual SimPy 2.3b1 documentation.htm[10/03/2013 01:01:30 p.m.]

    cancel

    sel f . cancel ( p )

    deletes all scheduled future events for process object p . A process cannotcancel itself. If that is required, use yi el d passi vat e, sel f instead. Only activeprocess objects can be canceled.

    A process object is terminated after all statements in its process execution methodhave been completed. If the object is still referenced by a variable, it becomes just adata container. This can be useful for extracting information. Otherwise, it isautomatically destroyed.

    Even activated process objects will not start operating until thesi mul at e( unt i l = endtime ) statement is executed. This starts the simulation goingand it will continue until time endtime (unless it runs out of events to execute or thecommand st opSi mul ati on( ) is executed).

    Example 3 This simulates a firework with a time fuse. We have put in a few extra

    yi el d hol d commands for added suspense.

    1 2 3 4 5 6 7 8 91011121314151617181920

    from SimPy.Simulation import Pr oces s, act i vat e , i ni t i al i z e, hol d,now, si mul at e

    class Firework ( Pr ocess) :

    def execut e ( sel f ) : print ( ' %s f i r ework l aunched' % now( ) ) yield hol d, sel f , 10. 0 # wait 10.0 time units for i in r ange ( 10 ) : yield hol d, sel f , 1. 0

    print ( ' %s t i ck' % now( ) ) yield hol d, sel f , 10. 0 # wait another 10.0 time units print ( ' %s Boom! ! ' % now( ) )

    i ni t i al i ze( )f = Fi r ewor k() # create a Firework object, and # activate it (with some default parameters)act i vat e ( f , f . execut e() , at =0. 0 )si mul at e(unt i l =100 )

    Here is the output. No formatting was attempted so it looks a bit ragged:

    0 f i r ework l aunched11. 0 t i ck12. 0 t i ck13. 0 t i ck14. 0 t i ck15. 0 t i ck16. 0 t i ck17. 0 t i ck18. 0 t i ck19. 0 t i ck20. 0 t i ck30. 0 Boom! !

    A source fragment

    One useful program pattern is the source . This is a process object with a ProcessExecution Method (PEM) that sequentially generates and activates other process

    http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#cancelhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#a-source-fragmenthttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#a-source-fragmenthttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#cancel
  • 8/14/2019 SimPy Manual SimPy 2.3b1 documentation.pdf

    11/54

    mPy Manual SimPy 2.3b1 documentation

    ///C|/Users/Manolo/Downloads/ADO/SimPy Manual SimPy 2.3b1 documentation.htm[10/03/2013 01:01:30 p.m.]

    objects it is a source of other process objects. Random arrivals can be modelledusing random intervals between activations.

    Example 4: A source . Here a source creates and activates a series of customerswho arrive at regular intervals of 10.0 units of time. This continues until thesimulation time exceeds the specified f i ni shTi me of 33.0. (Of course, to modelcustomers with random inter-arrival times the yi el d hol d statement would use arandom variate, such as expovari ate( ) , instead of the constant 10.0 inter-arrivaltime used here.) The following example assumes that the Cust omer class haspreviously been defined with a PEM called r un that does not require any arguments:

    cl ass Sour ce( Process) :

    def execut e( sel f , f i ni sh) : whi l e now( ) < f i ni sh: c = Cust omer ( ) # cr eat e a new cust omer obj ect , and # act i vat e i t ( usi ng def aul t par amet er s) ac t i vat e (c , c . run( ) ) pr i nt ( ' %s %s) % ( now( ) , ' cust omer ' ) yi el d hol d, s el f , 10. 0

    i ni t i al i ze( )g = Sour ce( ) # cr eat e t he Sour ce obj ect , g, # and acti vat e i tact i vat e( g, g. execut e( f i ni sh=33. 0) , at=0. 0)si mul ate( unt i l =100)

    Asynchronous interruptions

    An active process object can be interrupted by another but cannot interrupt itself.

    interrupt

    sel f . i nte r rupt ( vi c t i m)

    The interrupter process object uses its i nt err upt method to interrupt the victimprocess object. The interrupt is just a signal . After this statement, theinterrupter process object continues its PEM.

    For the interrupt to have an immediate effect, the victim process object mustbe active that is it must have an event scheduled for it (that is, it isexecuting a yi el d hol d ). If the victim is not active (that is, it is either passive

    or terminated ) the interrupt has no effect. For example, process objectsqueuing for resource facilities cannot be interrupted because they are passiveduring their queuing phase.

    If interrupted, the victim returns from its yi el d hol d statement prematurely. It mustthen check to see if it has been interrupted by calling:

    interrupted

    sel f . i nte r rupted( )

    which returns Tr ue if it has been interrupted. The victim can then either continue in the current activity or switch to an alternative, making sure it tidiesup the current state, such as releasing any resources it owns.

    http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#asynchronous-interruptionshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#interrupthttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#interruptedhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#interruptedhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#interrupthttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#asynchronous-interruptions
  • 8/14/2019 SimPy Manual SimPy 2.3b1 documentation.pdf

    12/54

    mPy Manual SimPy 2.3b1 documentation

    ///C|/Users/Manolo/Downloads/ADO/SimPy Manual SimPy 2.3b1 documentation.htm[10/03/2013 01:01:30 p.m.]

    interruptCause

    sel f . i nt er rupt Cause

    when the victim has been interrupted, sel f . i nt err upt Cause is a reference to theinterrupter object.

    interruptLeft sel f . i nte r ruptLef t

    gives the time remaining in the interrupted yi el d hol d . The interruption isreset (that is, turned off) at the victims next call to a yi el d hol d .

    ..index:: interruptReset

    interruptReset

    sel f . i nte r ruptReset ( )

    will reset the interruption.

    It may be helpful to think of an interruption signal as instructing the victim todetermine whether it should interrupt itself. If the victim determines that it shouldinterrupt itself, it then becomes responsible for making any necessary readjustments

    not only to itself but also to any other simulation components that are affected.(The victim must take responsibility for these adjustments, because it is the onlysimulation component that knows such details as whether or not it is interruptingitself, when, and why.)

    Example 5 . A simulation with interrupts. A bus is subject to breakdowns that aremodelled as interrupts caused by a Breakdown process. Notice that the yi el dhol d, s el f , t r i pl ef t statement may be interrupted, so if the sel f . i nte r rupt ed( ) testreturns Tr ue a reaction to it is required. Here, in addition to delaying the bus for repairs, the reaction includes scheduling the next breakdown. In this example theBus Process class does not require an __ i ni t __( ) method:

    1 2 3 4 5 6 7 8 91011121314151617181920

    from SimPy.Simulation import ( P r oces s , a ct i vat e , hol d, i ni t i al i z e,now,

    r eacti vat e, si mul at e)

    class Bus ( Pr ocess) :

    def operat e ( sel f , r epai rdura t i on, t r i pl engt h) : # PEM t r i pl ef t = t r i pl engt h # time needed tofinish trip while t r i pl ef t > 0 : yield hol d, sel f , t r i pl ef t # try to finish thetrip if s el f . i nt e r rupted( ) : # if another breakdownoccurs print ( ' %s at %s ' % ( sel f . i nt er r upt Cause . name, now( ) ) ) t r i pl ef t = sel f . i nt er r upt Lef t # time to finish the

    trip s el f . i nt er r upt Reset ( ) # end interrupt state reac t i vat e(br , del ay =r epai r dur at i on) # restartbreakdown br yield hol d, sel f , repai rdura t i on # delay forrepairs print ( ' Bus r epai r ed at %s ' % now( ) )

    http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#interruptcausehttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#interruptlefthttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#interruptresethttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#interruptresethttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#interruptlefthttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#interruptcause
  • 8/14/2019 SimPy Manual SimPy 2.3b1 documentation.pdf

    13/54

    mPy Manual SimPy 2.3b1 documentation

    ///C|/Users/Manolo/Downloads/ADO/SimPy Manual SimPy 2.3b1 documentation.htm[10/03/2013 01:01:30 p.m.]

    21222324252627282930313233343536373839404142

    else : break # no more breakdowns, bus finished trip print ( ' Bus has arr i ved at %s ' % now( ) )

    class Breakdown ( Pr ocess) : def __i ni t __ ( sel f , myBus) : Pr ocess . __i ni t __ ( sel f , name =' Br eakdown ' + myBus . name) sel f . bus = myBus

    def br eakBus ( sel f , i nt er val ) : # process execution method

    while Tr ue : yield hol d, sel f , i nt er val # breakdown interarrivals if s el f . bus . t er mi nat ed( ) : break s el f . i nt er r upt ( sel f . bus) # breakdown to myBus

    i ni t i al i ze( )b = Bus( ' Bus' ) # create a bus objectact i vat e( b, b . oper at e(r epai r dur ati on =20 , t r i pl engt h =1000 ) )br = Br eakdown( b) # create breakdown br to bus bact i vat e( br , br . breakBus( 300 ) )si mul at e(unt i l =4000 ) print ( ' Si mPy: No mor e event s at t i me %s ' % now( ) )

    The output from this example:

    Br eakdown Bus at 300Bus r epai r ed at 320Br eakdown Bus at 620Bus r epai r ed at 640Br eakdown Bus at 940Bus r epai r ed at 960Bus has ar r i ved at 1060Si mPy: No mor e event s at t i me 1260

    The bus finishes at 1060 but the simulation finished at 1260. Why? The br eakdown sPEM consists of a loop, one breakdown following another at 300 intervals. The lastbreakdown finishes at 960 and then a breakdown event is scheduled for 1260. Butthe bus finished at 1060 and is not affected by the breakdown. These details caneasily be checked by importing from Si mPy. Si mul ati onTrace and re-running theprogram.

    Where interrupts can occur, the victim of interrupts must test for interruptoccurrence after every appropriate yi el d hol d and react appropriately to it. A victimholding a resource facility when it gets interrupted continues to hold it.

    Advanced synchronization/scheduling capabilities

    The preceding scheduling constructs all depend on specified time values. That is,they delay processes for a specific time, or use given time parameters whenreactivating them. For a wide range of applications this is all that is needed.

    However, some applications either require or can profit from an ability to activateprocesses that must wait for other processes to complete. For example, models of real-time systems or operating systems often use this kind of approach. EventSignalling is particularly helpful in such situations. Furthermore, some applicationsneed to activate processes when certain conditions occur, even though when (or if)

    they will occur may be unknown. SimPy has a general wait until to support cleanimplementation of this approach.

    This section describes how SimPy provides event Signalling and wait untilcapabilities.

    http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#advanced-synchronization-scheduling-capabilitieshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#eventhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#wait-untilhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#eventhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#wait-untilhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#wait-untilhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#eventhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#wait-untilhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#eventhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#advanced-synchronization-scheduling-capabilities
  • 8/14/2019 SimPy Manual SimPy 2.3b1 documentation.pdf

    14/54

    mPy Manual SimPy 2.3b1 documentation

    ///C|/Users/Manolo/Downloads/ADO/SimPy Manual SimPy 2.3b1 documentation.htm[10/03/2013 01:01:30 p.m.]

    Creating and Signalling SimEvents

    As mentioned in the Introduction, for ease of expression when no confusion canarise we often refer to both process objects and their classes as processes, andmention their object or class status only for added clarity or emphasis. Analogously,we will refer to objects of SimPys Si mEvent class as SimEvents [3] (or, if noconfusion can arise, simply as events). However, we sometimes mention their

    object or class character for clarity or emphasis.

    [4] The name SimEvent was chosen because event is already used in Pythonsstandard library. See Python Library Reference section 7.5 threading Higher-level threading interface , specifically subsection 7.5.5.

    SimEvent objects must be created before they can be fired by a si gnal . You createthe SimEvent object, sE , from SimPys Si mEvent class by a statement like thefollowing:

    sE = Si mEvent ( name=' I j ust had a gr eat new i dea! ' )

    A SimEventsname

    attribute defaults toa_Si mEvent

    unless you provide your own, asshown here. Its occur r ed attribute, sE. occur r ed , is a Boolean that defaults to Fal se . Itindicates whether the event sE has occurred.

    You program a SimEvent to occur or fire by signalling it like this:

    sE. si gnal ( )

    This signal is received by all processes that are either waiting or queueing for this event to occur. What happens when they receive this signal is explained in thenext section. The is optional it defaults to None . It can be of any Python type. Any process can retrieve it from the events si gnal param attribute,for example by:

    message = sE. si gnal param

    Waiting or Queueing for SimEvents

    You can program a process either to wait or to queue for the occurrence of SimEvents. The difference is that all processes waiting for some event arereactivated as soon as it occurs. For example, all firemen go into action when thealarm sounds. In contrast, only the first process in the queue for some event isreactivated when it occurs. That is, the queue is FIFO [5]. An example might beroyal succession when the present ruler dies: The king is dead. Long live the(new) king! (And all others in the line of succession move up one step.)

    [5](1, 2 , 3) First-in-First-Out or FCFS, First-Come-First-Served

    You program a process to wai t for SimEvents by including in its PEM:

    yield waitevent

    yi el d wai t event , sel f ,

    where can be either:

    one SimEvent object, e.g. myEvent , or a tuple of SimEvent objects, e.g. ( myEvent , myOt herEvent , Ti meOut ) , or

    http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#creating-and-signalling-simeventshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#id5http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#waiting-or-queueing-for-simeventshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#fifohttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#fifohttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#id8http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#id9http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#id10http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#yield-waiteventhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#yield-waiteventhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#id10http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#id9http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#id8http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#fifohttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#waiting-or-queueing-for-simeventshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#id5http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#creating-and-signalling-simevents
  • 8/14/2019 SimPy Manual SimPy 2.3b1 documentation.pdf

    15/54

    mPy Manual SimPy 2.3b1 documentation

    ///C|/Users/Manolo/Downloads/ADO/SimPy Manual SimPy 2.3b1 documentation.htm[10/03/2013 01:01:30 p.m.]

    a list of SimEvent objects, e.g. [ myEvent , myOt herEvent , Ti meOut ]

    If none of the events in the have occurred, the process ispassivated and joined to the list of processes waiting for some event in to occur (or to recur).

    On the other hand, when any of the events in the occur, then allof the processes waiting for those particular events are reactivated at thecurrent time. Then the occur r ed flag of those particular events is reset toFal se . Resetting their occur r ed flag prevents the waiting processes from beingconstantly reactivated. (For instance, we do not want firemen to keepresponding to any such false alarms.) For example, suppose the lists events a, b and c in that order. If events a and c occur, then all of the processes waiting for event a are reactivated. So are all processes waitingfor event c but not a . Then the occur r ed flags of events a and c are toggled toFal se . No direct changes are made to event b or to any processes waiting for it to occur.

    You program a process to queue for events by including in its PEM:

    yield queueevent

    yi el d queueevent , sel f ,

    where the is as described above.

    If none of the events in the has occurred, the process ispassivated and appended to the FIFO queue of processes queuing for someevent in to occur (or recur).

    But when any of the events in occur, the process at the head of the queue is taken off the queue and reactivated at the current time. Thenthe occur r ed flag of those events that occurred is reset to Fal se as in thewaiting case.

    Finding Which Processes Are Waiting/Queueing for an Event, and WhichEvents Fired

    SimPy automatically keeps current lists of what processes are waiting or queueing for SimEvents. They are kept in the wai t s and queues attributes of theSimEvent object and can be read by commands like the following:

    ThePr ocessesWai t i ngFor_myEvent = myEvent . wai t s ThePr ocess esQueuedFor_myEvent = myEvent . queues

    However, you should not attempt to change these attributes yourself.

    Whenever myEvent occurs, i.e., whenever a myEvent . s i gnal ( . . . ) statement isexecuted, SimPy does the following:

    If there are any processes waiting or queued for that event, it reactivates themas described in the preceding section.

    If there are no processes waiting or queued (i.e., myEvent . wai t s andmyEvent . queues are both empty), it toggles myEvent . occur r ed to Tr ue .

    SimPy also automatically keeps track of which events were fired when a processobject was reactivated. For example, you can get a list of the events that were fired

    http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#yield-queueeventhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#finding-which-processes-are-waiting-queueing-for-an-event-and-which-events-firedhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#finding-which-processes-are-waiting-queueing-for-an-event-and-which-events-firedhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#yield-queueevent
  • 8/14/2019 SimPy Manual SimPy 2.3b1 documentation.pdf

    16/54

    mPy Manual SimPy 2.3b1 documentation

    ///C|/Users/Manolo/Downloads/ADO/SimPy Manual SimPy 2.3b1 documentation.htm[10/03/2013 01:01:30 p.m.]

    when the object Godzi l l a was reactivated with a statement like this:

    Godzi l l aRevi vedBy = Godzi l l a . event sFi r ed

    Example 6 . This complete SimPy script illustrates these constructs. (It alsoillustrates that a Process class may have more than one PEM. Here theWai t _Or _Queue class has two PEMs wai t up and queueup .):

    1 2 3 4 5 6 7 8 910111213

    141516171819202122232425262728

    293031323334353637383940414243444546474849505152535455565758596061626364

    from SimPy.Simulation import *

    class Wait_Or_Queue ( Pr ocess) : def wai t up ( sel f , myEvent ) : # PEM illustrating "waitevent" # wait for "myEvent" to occur yield wai t event , s el f , myEvent print ' At %s , some Si mEvent ( s) occur r ed t hat \ act i vat ed obj ect %s . ' %( now( ) , s el f . name) print ' The act i vat i ng event ( s) wer e %s ' \ %( [ x . name for x in s el f . event sFi r ed] )

    def queueup ( sel f , myEvent ) : # PEM illustrating "queueevent" # queue up for "myEvent" to occur

    yield queueevent , s el f , myEvent print ' At %s , some Si mEvent( s) occur r ed t hat \ act i vat ed obj ect %s . ' %( now( ) , s el f . name) print ' The act i vat i ng event ( s) wer e %s ' \ %( [ x . name for x in s el f . event sFi r ed] )

    class Signaller ( Pr ocess) : # here we just schedule some events to fire def sendSi gnal s ( sel f ) : yield hol d, sel f , 2 event 1 . s i gnal ( ) # fire "event1" at time 2 yield hol d, sel f , 8 event 2 . s i gnal ( ) # fire "event2" at time 10 yield hol d, sel f , 5 event 1 . s i gnal ( ) # fire all four events at time 15

    event 2 . s i gnal ( ) event 3 . s i gnal ( ) event 4 . s i gnal ( ) yield hol d, sel f , 5 event 4 . s i gnal ( ) # event4 recurs at time 20

    i ni t i al i ze( )

    # Now create each SimEvent and give it a nameevent 1 = Si mEvent ( ' Event - 1' )event 2 = Si mEvent ( ' Event - 2' )event 3 = Si mEvent ( ' Event - 3' )event 4 = Si mEvent ( ' Event - 4' )Event _ l i s t = [ event 3, event 4] # define an event list

    s = Si gnal l er ( )# Activate Signaller "s" *after* events created ac t i vat e ( s , s . sendSi gnal s( ) )

    w0 = Wai t _Or _Queue( ' W- 0' )# create object named "W-0", and set it to# "waitup" for SimEvent "event1" to occur acti vat e ( w0, w0 . wai t up( event 1) )w1 = Wai t _Or _Queue( ' W- 1' )acti vat e ( w1, w1 . wai t up( event 2))w2 = Wai t _Or _Queue( ' W- 2' )acti vat e( w2, w2 . wai t up( Event _l i s t ) )q1 = Wai t _Or _Queue( ' Q- 1' )# create object named "Q-1", and put it to be first# in the queue for Event_list to occur

    acti vat e(q1, q1 . queueup( Event _l i st ) )q2 = Wai t _Or _Queue( ' Q- 2' )# create object named "Q-2", and append it to# the queue for Event_list to occur acti vat e(q2, q2 . queueup( Event _l i st ) )

  • 8/14/2019 SimPy Manual SimPy 2.3b1 documentation.pdf

    17/54

    mPy Manual SimPy 2.3b1 documentation

    ///C|/Users/Manolo/Downloads/ADO/SimPy Manual SimPy 2.3b1 documentation.htm[10/03/2013 01:01:30 p.m.]

    65 s i mul at e( unt i l =50 )

    This program outputs:

    At 2, some Si mEvent( s) occur r ed t hat act i vat ed obj ect W- 0. The act i vat i ng event ( s) wer e [ ' Event - 1' ]At 10, some Si mEvent( s) occur r ed t hat act i vat ed obj ect W- 1. The act i vat i ng event ( s) wer e [ ' Event - 2' ]At 15, some Si mEvent( s) occur r ed t hat act i vat ed obj ect W- 2.

    The act i vat i ng event ( s) wer e [ ' Event - 3' ]At 15, some Si mEvent ( s) occur r ed t hat act i vat ed obj ect Q- 1. The acti vat i ng event ( s) wer e [ ' Event - 3' , ' Event - 4' ]At 20, some Si mEvent ( s) occur r ed t hat act i vat ed obj ect Q- 2. The act i vat i ng event ( s) wer e [ ' Event - 4' ]

    Each output line, The act i vat i ng event ( s) wer e . . . , lists the contents of the namedobjects event sFi r ed attribute. One of those events caused the object to reactivateat the indicated time. Note that at time 15 objects W- 0 and W- 1 were not affected bythe recurrence of event 1 and event 2 because they already were active. Also at time15, even though objects W- 2 , Q- 1 and Q- 2 were all waiting for event 3 , only W- 2 andQ- 1 were reactivated. Process object Q- 2 was not reactivated at that time because it

    was not first in the queue. Finally, Q- 2 was reactivated at time 20, when event 4 firedagain.

    waituntil synchronization waiting for any condition

    SimPy provides the wai t unt i l feature that makes a processs progress depend onthe state of the simulation. This is useful if, for example, you need to reactivate aprocess when (if ever) the simulation enters the state goodWeat her OR( nr Cust omer s>50 AND pr i ce

  • 8/14/2019 SimPy Manual SimPy 2.3b1 documentation.pdf

    18/54

    mPy Manual SimPy 2.3b1 documentation

    ///C|/Users/Manolo/Downloads/ADO/SimPy Manual SimPy 2.3b1 documentation.htm[10/03/2013 01:01:30 p.m.]

    1 2 3 4 5 6 7 8 910

    111213141516171819202122232425

    262728293031323334353637383940

    414243444546474849505152

    from SimPy.Simulation import *import random

    class Player ( Pr ocess) :

    def __i ni t __ ( sel f , l i ves =1, name =' I maTarget ' ) : Pr ocess . __i ni t __ ( sel f , name) s el f . l i ves =l i ves # provide Player objects with a "damage" property s el f . damage =0

    def l i f e ( sel f ) : s el f . message =' Dr at ! Some %s survi ved Feder at i on at t ack!' %( t ar get . name)

    def ki l l ed ( ) : # function testing for "damage > 5" return s el f . damage >5

    while Tr ue : yield wai tunt i l , s el f , ki l l ed sel f . l i ves - =1; sel f . damage =0 if s el f . l i ves == 0 : s el f . message = ' %s wi ped out by Federat i on at \ t i me %s ! ' %( t ar get . name, now( ) ) st opSi mul at i on()

    class Federation ( Pr ocess) :

    def f i ght ( sel f ) : # simulate Federation operations print ' Thr ee %s att empt i ng t o escape! ' %( t ar get . name) while Tr ue : if r andom . r andi nt ( 0 , 10 )

  • 8/14/2019 SimPy Manual SimPy 2.3b1 documentation.pdf

    19/54

    mPy Manual SimPy 2.3b1 documentation

    ///C|/Users/Manolo/Downloads/ADO/SimPy Manual SimPy 2.3b1 documentation.htm[10/03/2013 01:01:30 p.m.]

    Ha! Romul ans hi t ! Damage = 3Ha! Romul ans hi t ! Damage = 4Ha! Romul ans hi t ! Damage = 5 No mor e Romul ans l ef t !Romul ans wi ped out by Feder at i on at t i me 73!

    The wai t unt i l construct is so general that in principle it could replace all the other synchronization approaches (but at a run time cost).

    [Return to Top ]

    Resources

    The three resource facilities provided by SimPy are Resources , Levels and Stores .Each models a congestion point where process objects may have to queue up toobtain resources. This section describes the Resource type of resource facility.

    An example of queueing for a Resource might be a manufacturing plant in which a Task (modelled as a process object ) needs work done by a Machi ne (modelled as a

    Resource object). If all of the Machi nes are currently being used, the Task must waituntil one becomes free. A SimPy Resource can have a number of identical uni t s ,such as a number of identical machi ne units. A process obtains a unit of theResource by r equest i ng it and, when it is finished, rel easi ng it. A Resourcemaintains a list of process objects that have requested but not yet received one of the Resources units (called the wai t Q ), and another list of processes that arecurrently using a unit (the acti veQ ). SimPy creates and updates these queues itself

    the user can access them, but should not change them.

    Defining a Resource object

    A Resource object, r , is established by the following statement:

    r = Resour ce( capaci t y =1 , name =' a_resour ce' , uni t Name =' uni t s ' , qType =FI FO, preemptabl e =Fal se , moni t or ed =Fal se , moni t or Type =Moni t or )

    where

    capaci t y is a positive real or integer value that specifies the totalnumber of identical units in Resource object r .

    name is a descriptive name for this Resource object (e.g.,' gasSt at i on' ).uni t Name is a descriptive name for a unit of the resource (e.g.,' pump' ).qType is either FI FO [5] or Pr i or i t y Q . It specifies the queuediscipline of the resources wai t Q ; typically, this is FI FO and that isthe default value. If Pr i or i t y Q is specified, then higher-priorityrequests waiting for a unit of Resource r are inserted into the wai t Qahead of lower priority requests. See Priority requests for aResource unit for details.preempt abl e is a Boolean ( Fal se or Tr ue ); typically, this is Fal se andthat is the default value. If it is Tr ue , then a process requesting aunit of this resource may preempt a lower-priority process in theacti veQ , i.e., one that is already using a unit of the resource. SeePreemptive requests for a Resource unit for details.

    http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#contentshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#contentshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#id19http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#resourceshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#resourceshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#levelshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#storeshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#defining-a-resource-objecthttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#fifohttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#priority-requests-for-a-resource-unithttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#priority-requests-for-a-resource-unithttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#priority-requests-for-a-resource-unithttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#preemptive-requests-for-a-resource-unithttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#preemptive-requests-for-a-resource-unithttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#preemptive-requests-for-a-resource-unithttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#priority-requests-for-a-resource-unithttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#priority-requests-for-a-resource-unithttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#fifohttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#defining-a-resource-objecthttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#storeshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#levelshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#resourceshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#resourceshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#id19http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#contents
  • 8/14/2019 SimPy Manual SimPy 2.3b1 documentation.pdf

    20/54

    mPy Manual SimPy 2.3b1 documentation

    ///C|/Users/Manolo/Downloads/ADO/SimPy Manual SimPy 2.3b1 documentation.htm[10/03/2013 01:01:30 p.m.]

    moni t or ed is a boolean ( Fal se or Tr ue ). If set to Tr ue , theninformation is gathered on the sizes of r s wai t Q and acti veQ ,otherwise not.moni t or Type is either Moni t or or Tal l y and indicates the type of Recorder to be used (see Recording Resource queue lengths for an example and additional discussion).

    Each Resource object, r , has the following additional attributes:

    r . n , the number of units that are currently free.r. wai t Q , a queue (list) of processes that have requested but not yetreceived a unit of r , so l en( r . wai t Q) is the number of processobjects currently waiting.r. ac t i veQ , a queue (list) of process objects currently using one of the Resources units, so l en( r. act i veQ) is the number of units thatare currently in use.r . wai t Mon , the record (made by a Moni t or or a Tal l y whenever moni t or ed==Tr ue ) of the activity in r. wai t Q . So, for example,r . wai t Mon. t i meaver age() is the average number of processes in

    r. wai t Q . See Recording Resource queue lengths for an example.r . actMon , the record (made by a Moni t or or a Tal l y whenever moni t or ed==Tr ue ) of the activity in r. act i veQ .

    Requesting and releasing a unit of a Resource

    A process can request and later release a unit of the Resource object, r , by usingthe following yield commands in a Process Execution Method:

    yield request

    yi el d r eques t , sel f , r [,P=0]

    requests a unit of Resource r with (optional) real or integer priority value P . If no priority is specified, it defaults to 0. Larger values of P represent higher priorities. See the following sections on Queue Order for more information onhow priority values are used. Although this form of request can be used for either FI FO or Pr i or i t y Q priority types, these values are ignored whenqType==FI FO .

    yield release

    yi el d r el eas e, s el f , r

    releases the unit of r .

    Queue Order

    If a requesting process must wait it is placed into the resources wai t Q in an order determined by settings of the resources qType and preempt abl e attributes and of thepriority value it uses in the r equest call.

    Non-priority queueing

    http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#recording-simulation-resultshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#recording-resource-queue-lengthshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#recording-resource-queue-lengthshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#recording-resource-queue-lengthshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#requesting-and-releasing-a-unit-of-a-resourcehttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#yield-requesthttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#queue-orderhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#yield-releasehttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#queue-orderhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#non-priority-queueinghttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#non-priority-queueinghttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#queue-orderhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#yield-releasehttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#queue-orderhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#yield-requesthttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#requesting-and-releasing-a-unit-of-a-resourcehttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#recording-resource-queue-lengthshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#recording-resource-queue-lengthshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#recording-simulation-results
  • 8/14/2019 SimPy Manual SimPy 2.3b1 documentation.pdf

    21/54

    mPy Manual SimPy 2.3b1 documentation

    ///C|/Users/Manolo/Downloads/ADO/SimPy Manual SimPy 2.3b1 documentation.htm[10/03/2013 01:01:30 p.m.]

    If the qType is not specified it takes the presumed value of FI FO [5]. In that caseprocesses wait in the usual first-come-first-served order.

    If a Resource unit is free when the request is made, the requesting process takes itand moves on to the next statement in its PEM. If no Resource unit is availablewhen the request is made, then the requesting process is appended to theResources wai t Q and suspended. The next time a unit becomes available the firstprocess in the r. wai t Q takes it and continues its execution. All priority assignmentsare ignored. Moreover, in the FIFO case no preemption is possible, for preemptionrequires that priority assignments be recognized. (However, see the Note onpreemptive requests with waitQ in FIFO order for one way of simulating suchsituations.)

    Example In this complete script, the ser ver Resource object is given two resourceunits ( capaci t y=2 ). By not specifying its Qt ype it takes the default value, FI FO. Heresix clients arrive in the order specified by the program. They all request a resourceunit from the ser ver Resource object at the same time. Even though they all specifya priority value in their requests, it is ignored and they get their Resource units inthe same order as their requests:

    1 2 3 4 5 6 7 8 91011

    121314151617181920212223242526

    2728293031323334353637383940414243444546

    from SimPy.Simulation import ( Pr ocess, Resour ce, acti vat e,i ni t i al i ze, hol d, now, r el ease, r equest , si mul at e)

    class Client ( Pr ocess) : i nCl i ent s = [ ] # list the clients in order by their requests out Cl i ent s = [ ] # list the clients in order by completion ofservice

    def __i ni t __ ( sel f , name) : Pr ocess . __i ni t __ ( sel f , name)

    def gets erved ( sel f , ser vt i me, pr i or i t y, mySer ver ) : Cl i ent . i nCl i ent s . append( sel f . name) print ( ' %s r equest s 1 uni t at t = %s ' % ( sel f . name, now( ) ) ) # request use of a resource unit yield request , s el f , myServer , pr i or i t y yield hol d, sel f , ser vt i me # release the resource yield r el ease, s el f , myServer print ( ' %s done at t = %s ' % ( sel f . name, now( ) ) ) Cl i ent . out Cl i ent s . append( sel f . name)

    i ni t i al i ze( )

    # the next line creates the ``server ` Resource objectser ver = Resour ce( capaci t y =2) # server defaults to qType==FIFO

    # the next lines create some Client process objectsc1, c2 = Cl i ent ( name =' c1' ) , Cl i ent ( name =' c2' )c3, c4 = Cl i ent ( name =' c3' ) , Cl i ent ( name =' c4' )c5, c6 = Cl i ent ( name =' c5' ) , Cl i ent ( name =' c6' )

    # in the next lines each client requests# one of the ``server``'s Resource unitsact i vat e( c1, c1 . get served( servt i me =100 , pr i or i t y =1, myServer =server))ac t i vat e( c2, c2 . get served( servt i me =100 , pr i or i t y =2, myServer =server))ac t i vat e( c3, c3 . getser ved( servt i me =100 , pr i or i t y =3, myServer =ser ver ) )ac t i vat e( c4, c4 . get served( servt i me =100 , pr i or i t y =4 , myServer =ser ver ) )ac t i vat e( c5, c5 . get served( servt i me =100 , pr i or i t y =5, myServer =server))ac t i vat e( c6, c6 . get served( servt i me =100 , pr i or i t y =6, myServer =server))

    si mul at e(unt i l =500 )

    print ( ' Request or der : %s ' % Cl i ent . i nCl i ent s ) print ( ' Ser vi ce order : %s ' % Cl i ent . out Cl i ent s)

    http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#fifohttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#note-on-preemptive-requests-with-waitq-in-fifo-orderhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#note-on-preemptive-requests-with-waitq-in-fifo-orderhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#note-on-preemptive-requests-with-waitq-in-fifo-orderhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#note-on-preemptive-requests-with-waitq-in-fifo-orderhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#fifo
  • 8/14/2019 SimPy Manual SimPy 2.3b1 documentation.pdf

    22/54

    mPy Manual SimPy 2.3b1 documentation

    ///C|/Users/Manolo/Downloads/ADO/SimPy Manual SimPy 2.3b1 documentation.htm[10/03/2013 01:01:30 p.m.]

    This program results in the following output:

    c1 r equest s 1 uni t at t = 0c2 r equest s 1 uni t at t = 0c3 r equest s 1 uni t at t = 0c4 r equest s 1 uni t at t = 0c5 r equest s 1 uni t at t = 0c6 r equest s 1 uni t at t = 0c1 done at t i me = 100

    c2 done at t i me = 100c3 done at t i me = 200c4 done at t i me = 200c5 done at t i me = 300c6 done at t i me = 300

    Reques t or der : [ ' c1' , ' c2' , ' c3' , ' c4' , ' c5' , ' c6' ]Ser vi ce or der : [ ' c1' , ' c2' , ' c3' , ' c4' , ' c5' , ' c6' ]

    As illustrated, the clients are served in FIFO order. Clients c1 and c2 each take oneResource unit right away, but the others must wait. When c1 and c2 finish with their resources, clients c3 and c4 can each take a unit, and so forth.

    Priority requests for a Resource unit

    If the Resource r is defined with qType==Pr i or i t yQ , priority values in requests arerecognized. If a Resource unit is available when the request is made, the requestingprocess takes it. If no Resource unit is available when the request is made, therequesting process is inserted into the Resources wai t Q in order of priority (fromhigh to low) and suspended. For an example where priorities are used, we simplychange the preceding examples specification of the ser ver Resource object to:

    ser ver =Resour ce( capaci t y =2, qType =Pr i or i t yQ)

    where, by not specifying it, we allow preempt abl e to take its default value, Fal se .

    Example After this change the programs output becomes:

    c1 r equest s 1 uni t at t = 0c2 r equest s 1 uni t at t = 0c3 r equest s 1 uni t at t = 0c4 r equest s 1 uni t at t = 0c5 r equest s 1 uni t at t = 0c6 r equest s 1 uni t at t = 0c1 done at t i me = 100c2 done at t i me = 100c6 done at t i me = 200c5 done at t i me = 200c4 done at t i me = 300c3 done at t i me = 300

    Reques t or der : [ ' c1' , ' c2' , ' c3' , ' c4' , ' c5' , ' c6' ]Ser vi ce or der : [ ' c1' , ' c2' , ' c6' , ' c5' , ' c4' , ' c3' ]

    Although c1 and c2 have the lowest priority values, each requested and got aser ver unit immediately. That was because at the time they made those requests aser ver unit was available and the ser ver . wai t Q was empty it did not start to fill untilc3 made its request and found all of the ser ver units busy. When c1 and c2completed service, c6 and c5 (with the highest priority values of all processes in thewai t Q ) each got a Resource unit, etc.

    When some processes in the wai t Q have the same priority level as a process

    http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#priority-requests-for-a-resource-unithttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#priority-requests-for-a-resource-unit
  • 8/14/2019 SimPy Manual SimPy 2.3b1 documentation.pdf

    23/54

    mPy Manual SimPy 2.3b1 documentation

    ///C|/Users/Manolo/Downloads/ADO/SimPy Manual SimPy 2.3b1 documentation.htm[10/03/2013 01:01:30 p.m.]

    making a priority request, SimPy inserts the requesting process immediately behindthem. Thus for a given priority value, processes are placed in FIFO order. For example, suppose that when a priority 3 process makes its priority request thecurrent wai t Q consists of processes with priorities [ 5, 4, 3a, 3b, 3c, 2a, 2b, 1] , where theletters indicate the order in which the equal-priority processes were placed in thequeue. Then SimPy inserts this requesting process into the current wai t Qimmediately behind its last priority 3 process. Thus, the new wai t Q will be[ 5, 4, 3a, 3b, 3c, 3d, 2a, 2b, 1] , where the inserted process is 3d .

    One consequence of this is that, if all priority requests are assigned the samepriority value, then the wai t Q will in fact be maintained in FI FO order. In that case,using a FI FO instead of a Pr i or i t y Q discipline provides some saving in executiontime which may be important in simulations where the wai t Q may be long.

    Preemptive requests for a Resource unit

    In some models, higher priority processes can actually preempt lower priorityprocesses, i.e., they can take over and use a Resource unit currently being used by

    a lower priority process whenever no free Resource units are available. A Resourceobject that allows its units to be preempted is created by setting its properties toqType==Pr i or i t yQ and pr eempt abl e==Tr ue .

    Whenever a pr eempt abl e Resource unit is free when a request is made, then therequesting process takes it and continues its execution. On the other hand, when ahigher priority request finds all the units in a pr eempt abl e Resource in use, thenSimPy adopts the following procedure regarding the Resources act i veQ and wai t Q :

    The process with the lowest priority is removed from the acti veQ , suspended,and put at the front of the wai t Q so (barring additional preemptions) it will be

    the next one to get a resource unit.The preempting process gets the vacated resource unit and is inserted intothe act i veQ in order of its priority value.The time for which the preempted process had the resource unit is taken intoaccount when the process gets into the acti veQ again. Thus, its total hold timeis always the same, regardless of how many times it has been preempted.

    Warning: SimPy only supports preemption of processes which are implemented inthe following pattern:

    yi el d r equest ( one or more r equest st at ement s)yi el d hol d ( one or mor e hol d st at ement s)yi el d r el ease (one or more r el ease st atement s)

    Modelling the preemption of a process in any other pattern may lead to errors or exceptions.

    We emphasize that a process making a pr eempt i ve request to a fully-occupiedResource gets a resource unit if but only if some process in the current acti veQhas a lower priority. Otherwise, it will be inserted into the wai t Q at a locationdetermined by its priority value and the current contents of the wai t Q , using a

    procedure analogous to that described for priority requests near the end of thepreceding section on Priority requests for a Resource unit . This may have the effectof advancing the preempting process ahead of any lower-priority processes thathad earlier been preempted and put at the head of the wai t Q . In fact, if severalpreemptions occur before a unit of resource is freed up, then the head of the wai t Q

    http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#preemptive-requests-for-a-resource-unithttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#priority-requests-for-a-resource-unithttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#priority-requests-for-a-resource-unithttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#preemptive-requests-for-a-resource-unit
  • 8/14/2019 SimPy Manual SimPy 2.3b1 documentation.pdf

    24/54

    mPy Manual SimPy 2.3b1 documentation

    ///C|/Users/Manolo/Downloads/ADO/SimPy Manual SimPy 2.3b1 documentation.htm[10/03/2013 01:01:30 p.m.]

    will consist of the processes that have been preempted in order from the lastprocess preempted to the first of them.

    Example In this example two clients of different priority compete for the sameresource unit:

    1 2 3 4 5 6 7 8 910111213141516171819202122

    from SimPy.Simulation import *

    class Client ( Pr ocess) : def __i ni t __ ( sel f , name) : Pr ocess . __i ni t __ ( sel f , name)

    def get ser ved ( sel f , ser vt i me, pr i or i t y, mySer ver ) : print s el f . name, ' r equest s 1 uni t at t =' , now( ) yield request , s el f , myServer , pr i or i t y yield hol d, sel f , ser vti me yield r el ease, s el f , myServer print s el f . name, ' done at t = ' , now( )

    i ni t i al i ze( )# create the *server* Resource objectser ver =Resour ce( capaci t y =1 , qType =Pr i or i t yQ, pr eempt abl e =1)# create some Client process objectsc1 =Cl i ent ( name =' c1' )c2 =Cl i ent ( name =' c2' )ac t i vat e( c1, c1 . get served( servt i me =100 , pr i or i t y =1, myServer =server ) , at =0)act i vat e( c2, c2 . get served( servt i me =100 , pr i or i t y =9, myServer =server ) , at =50 )si mul at e(unt i l =500 )

    The output from this program is:

    c1 r equest s 1 uni t at t = 0c2 request s 1 uni t at t = 50c2 done at t = 150c1 done at t = 200

    Here, c1 is preempted by c2 at t =50 . At that time, c1 had held the resource for 50 of its total of 100 time units. When c2 finished and released the resource unit at 150,c1 got the resource back and finished the last 50 time units of its service at t =200 .

    If preemption occurs when the last few processes in the current acti veQ have thesame priority value, then the last process in the current acti veQ is the one that willbe preempted and inserted into the wai t Q ahead of all others. To describe this, it willbe convenient to indicate by an added letter the order in which equal-priorityprocesses have been inserted into a queue. Now, suppose that a priority 4process makes a preemptive request when the current acti veQ priorities are[ 5, 3a, 3b] and the current wai t Q priorities are [ 2, 1, 0a, 0b] . Then process 3b will bepreempted. After the preemption the acti veQ will be [ 5, 4, 3a] and the wai t Q will be[ 3b, 2, 1, 0a, 0b] .

    Note on preemptive requests with waitQ in FIFO order

    You may consider doing the following to model a system whose queue of itemswaiting for a resource is to be maintained in FIFO order, but in which preemption isto be possible. It uses SimPys preempt abl e Resource objects, and uses priorities in

    a way that allows for preempts while maintaining a FIFO wai t Q order.Set qType=Pri ori t yQ and pr eempt abl e=Tr ue (so that SimPy will processpreemptive requests correctly).Model system requests that are to be considered as non-preemptive in

    http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#note-on-preemptive-requests-with-waitq-in-fifo-orderhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#note-on-preemptive-requests-with-waitq-in-fifo-order
  • 8/14/2019 SimPy Manual SimPy 2.3b1 documentation.pdf

    25/54

    mPy Manual SimPy 2.3b1 documentation

    ///C|/Users/Manolo/Downloads/ADO/SimPy Manual SimPy 2.3b1 documentation.htm[10/03/2013 01:01:30 p.m.]

    SimPy as process objects each of which has exactly the same (low) priorityvalue for example, either assign all of them a priority value of 0 (zero) or letit default to that value. (This has the effect of maintaining all of these processobjects in the wai t Q in FIFO order, as explained at the end of the section onPriority requests for a Resource unit , above.)Model system requests that are to be considered as preemptive in SimPy asprocess objects each of which is assigned a uniform priority value, but givethem a higher value than the one used to model the non-preemptive systemrequests for example, assign all of them a priority value of 1 (one). Thenthey will have a higher priority value than any of the non-preemptive requests.

    Example Here is an example of how this works for a Resource with two Resourceunits we give the act i veQ before the wai t Q throughout this example:

    1. Suppose that the current acti veQ and wai t Q are [ 0a, 0b] and [0c] ,respectively.

    2. A priority 1 process makes a preemptive request. Then the queues become:[ 1a, 0a] and`` [0b,0c]``.

    3. Another priority 1 process makes a preemptive request. Then the queues

    become: [ 1a, 1b] and [ 0a, 0b, 0c] .4. A third priority 1 process makes a preemptive request. Then the queues

    become: [ 1a, 1b] and [ 1c, 0a, 0b, 0c] .5. Process 1a finishes using its resource unit. Then the queues become: [ 1b, 1c]

    and [ 0a, 0b, 0c] .

    Reneging leaving a queue before acquiring a resource

    In most real world situations, people and other items do not wait forever for a

    requested resource facility to become available. Instead, they leave its queue whentheir patience is exhausted or when some other condition occurs. This behaviour iscalled reneging , and the reneging person or thing is said to renege .

    SimPy provides an extended (i.e., compound) yi el d request statement to handlereneging.

    Reneging yield request

    There are two types of reneging clause, one for reneging after a certain time and

    one for reneging when an event has happened. Their general form isyi el d ( r eques t , sel f , r [,P] ) , ( )

    to request a unit of Resource r (with optional priority P , assuming the Resource hasbeen defined as a pr i or i t y Q ) but with reneging.

    A SimPy program that models Resource requests with reneging must use thefollowing pattern of statements:

    yi el d ( r equest , sel f , r ) , ( )i f sel f . acqui r ed( r esour ce) : ## process got r esource and so di d NOT r enege . . . . yi el d r el ease, sel f , r esour ceel se: ## process r eneged bef or e acqui r i ng r esour ce . . . . .

    http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#priority-requests-for-a-resource-unithttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#reneging-leaving-a-queue-before-acquiring-a-resourcehttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#reneging-yield-requesthttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#reneging-yield-requesthttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#reneging-leaving-a-queue-before-acquiring-a-resourcehttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#priority-requests-for-a-resource-unit
  • 8/14/2019 SimPy Manual SimPy 2.3b1 documentation.pdf

    26/54

    mPy Manual SimPy 2.3b1 documentation

    ///C|/Users/Manolo/Downloads/ADO/SimPy Manual SimPy 2.3b1 documentation.htm[10/03/2013 01:01:30 p.m.]

    A call to the sel f . acqui r ed( r esour ce) method is mandatory after a compound yi el dr equest statement. It not only indicates whether or not the process has acquired theresource, it also removes the reneging process from the resources wai t Q .

    Reneging after a time limit

    To make a process give up (renege) after a certain time, use a reneging clause of

    the following form:yi el d ( r eques t , sel f , r [,P] ) , ( hol d, s el f , waittime )

    Here the process requests one unit of the resource r with optional priority P . If aresource unit is available it takes it and continues its PEM. Otherwise, as usual, it ispassivated and inserted into r s wai t Q .

    The process takes a unit if it becomes available before waittime expires andcontinues executing its PEM. If, however, the process has not acquired a unitbefore the waittime has expired it abandons the request (reneges) and leaves thewai t Q .

    Example : part of a parking lot simulation:

    . . . .parki ng_l ot =Resour ce(capaci t y=10)pat i ence=5 # wai t no l onger t han " pat i ence" ti me uni t s # f or a par ki ng spacepark_t i me=60 # park f or "par k_t i me" t i me uni t s i f get a parki ng space. . . .yi el d ( r eques t , s el f , park i ng_ l ot ) , (hol d, sel f , pat i ence)i f s el f . acqui r ed(park i ng_ l ot ) : # par k t he car yi el d hol d, sel f , park_t i me

    yi el d r el ease, sel f , parki ng_l otel se: # pat i ence exhaust ed, so gi ve up pr i nt ' I ' m not wai t i ng any l onger . I am goi ng home now. '

    Reneging when an event has happened

    To make a process renege at the occurrence of an event, use a reneging clausehaving a pattern like the one used for a yi el d wai t event statement, namelywai t event , sel f , events (see yield waitevent ). For example:

    yi el d ( r eques t , sel f , r [,P] ) , ( wai t event , s el f , events )

    Here the process requests one unit of the resource r with optional priority P . If aresource unit is available it takes it and continues its PEM. Otherwise, as usual, it ispassivated and inserted into r s wai t Q .

    The process takes a unit if it becomes available before any of the events occur, andcontinues executing its PEM. If, however, any of the SimEvents in events occur first, it abandons the request (reneges) and leaves the wai t Q . (Recall that eventscan be either one event, a list, or a tuple of several SimEvents.)

    Example Queuing for movie tickets (part):

    . . . .seat s=Resource( capaci t y=100)sol d_out =Si mEvent ( ) # si gnal s " out of seat s"

    http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#reneging-after-a-time-limithttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#reneging-when-an-event-has-happenedhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#yield-waiteventhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#yield-waiteventhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#reneging-when-an-event-has-happenedhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#reneging-after-a-time-limit
  • 8/14/2019 SimPy Manual SimPy 2.3b1 documentation.pdf

    27/54

    mPy Manual SimPy 2.3b1 documentation

    ///C|/Users/Manolo/Downloads/ADO/SimPy Manual SimPy 2.3b1 documentation.htm[10/03/2013 01:01:30 p.m.]

    t oo_l at e=Si mEvent ( ) # si gnal s " t oo l ate f or t hi s show". . . .# Leave t he t i cket count er queue when movi e sol d out# or i t i s t oo l at e for t he showyi el d ( reques t , sel f , seat s ) , ( wai t event , sel f , [ sol d_out , t oo_l at e] )i f s el f . acqui r ed( seat s ) : # wat ch t he movi e yi el d hol d, sel f , 120 yi el d r e l ease, s el f , s eat sel se: # di d not get a seat pr i nt ' Who needs t o see t hi s si l l y movi e anyhow?'

    Exiting conventions and preemptive queues

    Many discrete event simulations (including SimPy) adopt the normal exitingconvention, according to which processes that have once started using a Resourceunit stay in some Resource queue until their hol d time has completed. This is of course automatically the case for FIFO and non-preemptable Pr i or i t y Q disciplines.The point is that the exiting convention is also applied in the preempt abl e queuediscipline case. Thus, processes remain in some Resource queue until their hol d

    time has completed, even if they are preempted by higher priority processes.Some real-world situations conform to this convention and some do not. Anexample of one that does conform can be described as follows. Suppose that atwork you are assigned tasks of varying levels of priority. You are to set aside lower priority tasks in order to work on higher priority ones. But you are eventually tocomplete all of your assigned tasks. So you are operating like a SimPy resourcethat obeys a pr eempt abl e queue discipline and has one resource unit. With thisconvention, half-finished low-priority tasks may be postponed indefinitely if they arecontinually preempted by higher-priority tasks.

    An example that does not conform to the exiting convention can be described asfollows. Suppose again that you are assigned tasks of varying levels of priority andare to set aside lower priority tasks to work on higher priority ones. But you areinstructed that any tasks not completed within 24 hours after being assigned are tobe sent to another department for completion. Now, suppose that you are assignedTask-A that has a priority level of 3 and will take 10 hours to complete. After working on Task-A for an hour, you are assigned Task-B, which has a priority levelof 5 and will take 20 hours to complete. Then, at 11 hours, after working on Task-Bfor 10 hours, you are assigned Task-C, which has a priority level of 1 and will take 4hours to complete. (At this point Task-B needs 10 hours to complete, Task-A needs9 hours to complete, and Task-C needs 4 hours to complete.) At 21 hours youcomplete Task-B and resume working on Task-A, which at that point needs 9 hoursto complete. At 24 hours Task-A still needs another 6 hours to complete, but it hasreached the 24-hour deadline and so is sent to another department for completion.

    At the same time, Task-C has been in the waitQ for 13 hours, so you take it up andcomplete it at hour 28. This queue discipline does not conform to the exitingconvention, for under that convention at 24 hours you would continue work on Task-

    A, complete it at hour 30, and then start on Task-C.

    Recording Resource queue lengths

    Many discrete event models are used mainly to explore the statistical properties of

    the wai t Q and acti veQ associated with some or all of their simulated resources.SimPys support for this includes the Monitor and the Tally. For more information onthese and other recording methods, see the section on Recording SimulationResults .

    http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#exiting-conventions-and-preemptive-queueshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#recording-resource-queue-lengthshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#defining-tallys-and-monitorshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#defining-tallys-and-monitorshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#defining-tallys-and-monitorshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#recording-simulation-resultshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#recording-simulation-resultshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#recording-simulation-resultshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#recording-simulation-resultshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#recording-simulation-resultshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#defining-tallys-and-monitorshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#defining-tallys-and-monitorshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#recording-resource-queue-lengthshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#exiting-conventions-and-preemptive-queues
  • 8/14/2019 SimPy Manual SimPy 2.3b1 documentation.pdf

    28/54

    mPy Manual SimPy 2.3b1 documentation

    ///C|/Users/Manolo/Downloads/ADO/SimPy Manual SimPy 2.3b1 documentation.htm[10/03/2013 01:01:30 p.m.]

    If a Resource, r , is defined with moni t or ed=Tr ue SimPy automatically records thelength of its associated wai t Q and acti veQ . These records are kept in the recorder objects called r . wai t Mon and r . actMon , respectively. This solves a problem,particularly for the wai t Q which cannot easily be recorded externally to the resource.

    The property moni t or Type indicates which variety of recorder is to be used, either Monitor or Tally. The default is Moni t or . If this is chosen, complete time series for both queue lengths are maintained and can be used for advanced post-simulation

    statistical analyses as well as for displaying summary statistics (such as averages,standard deviations, and histograms). If Tal l y is chosen summary statistics can bedisplayed, but complete time series cannot. For more information on these andSimPys other recording methods, see the section on Recording Simulation Results .

    Example The following program uses a Moni t or to record the ser ver resourcesqueues. After the simulation ends, it displays some summary statistics for eachqueue, and then their complete time series:

    1 2 3 4 5 6 7 8 910111213141516171819202122232425262728293031323334353637383940414243

    44454647484950

    from math import sqrt

    from SimPy.Simulation import ( Moni t or , Pr ocess, Resour ce, acti vat e,i ni t i al i ze, hol d, now, r el ease, r equest , si mul ate)

    class Client ( Pr ocess) : i nCl i ent s = [ ] out Cl i ent s = [ ]

    def __i ni t __ ( sel f , name) : Pr ocess . __i ni t __ ( sel f , name)

    def get ser ved ( sel f , servt i me, mySer ver ) : print ( ' %s r equests 1 uni t at t = %s ' % ( sel f . name,now( ) ) )

    yield request , s el f , myServer yield hol d, sel f , ser vt i me yield r el ease, s el f , myServer print ( ' %s done at t = %s ' % ( sel f . name, now( ) ) )

    i ni t i al i ze( )

    ser ver = Resour ce( capaci t y =1, moni t ored = Tr ue , moni t or Type =Moni t or)

    c1, c2 = Cl i ent ( name =' c1' ) , Cl i ent ( name =' c2' )c3, c4 = Cl i ent ( name =' c3' ) , Cl i ent ( name =' c4' )

    ac t i vat e( c1, c1 . get served( servt i me =100 , myServer =server))ac t i vat e( c2, c2 . get served( servt i me =100 , myServer =ser ver ) )ac t i vat e(c3, c3 . get served( servt i me =100 , myServer =server))ac t i vat e( c4, c4 . getser ved( servt i me =100 , myServer =server))

    si mul at e(unt i l =500 )

    print ( ' ' ) print ( ' ( Ti meAver age no. wai t i ng: %s ' % ser ver . wai t Mon . t i meAver age( ) ) print ( ' ( Number ) Aver age no. wai t i ng: %.4f ' % ser ver . wai t Mon . mean( ) ) print ( ' ( Number ) Var of no. wai t i ng: %.4f ' % ser ver . wai t Mon . va r ( ) ) print ( ' ( Number) SD of no. wai t i ng: %.4f ' %sqr t ( ser ver . wai t Mon . v a r ( ) ) ) print ( ' ( Ti meAver age no. i n ser vi ce: %s ' %ser ver . act Mon . t i meAver age( ) ) print ( ' ( Number ) Aver age no. i n servi ce: %.4f ' % ser ver . act Mon . mean( ) ) print ( ' ( Number ) Var of no. i n ser vi ce: %.4f ' % ser ver . act Mon . va r ( ) ) print ( ' ( Number ) SD of no. i n ser vi ce: %.4f ' %sqr t ( ser ver . act Mon . v a r ( ) ) ) print ( ' =' * 40 ) print ( ' Ti me hi st or y f or t he "ser ver " wai t Q: ' ) print ( ' [ t i me, wai t Q] ' )for i t em in ser ver . wai t Mon:

    http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#defining-tallys-and-monitorshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#defining-tallys-and-monitorshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#defining-tallys-and-monitorshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#recording-simulation-resultshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#recording-simulation-resultshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#defining-tallys-and-monitorshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#defining-tallys-and-monitors
  • 8/14/2019 SimPy Manual SimPy 2.3b1 documentation.pdf

    29/54

    mPy Manual SimPy 2.3b1 documentation

    ///C|/Users/Manolo/Downloads/ADO/SimPy Manual SimPy 2.3b1 documentation.htm[10/03/2013 01:01:30 p.m.]

    515253

    print ( i t em) print ( ' =' * 40 ) print ( ' Ti me hi st or y f or t he "ser ver " acti veQ: ' ) print ( ' [ t i me, acti veQ] ' )for i t em in ser ver . act Mon: print ( i t em)

    The output from this program is:

    c1 r equest s 1 uni t at t = 0c2 r equest s 1 uni t at t = 0c3 r equest s 1 uni t at t = 0c4 r equest s 1 uni t at t = 0c1 done at t = 100c2 done at t = 200c3 done at t = 300c4 done at t = 400

    ( Ti me) Aver age no. wai t i ng: 1. 5( Number ) Aver age no. wai t i ng: 1. 5( Number ) Var of no. wai t i ng: 0. 916666666667( Number ) SD of no. wai t i ng: 0. 957427107756( Ti me) Aver age no. i n ser vi ce: 1. 0( Number ) Aver age no. i n ser vi ce: 0. 5

    ( Number ) Var of no. i n ser vi ce: 0. 25( Number ) SD of no. i n servi ce: 0. 5========================================

    Ti me hi st or y f or t he ' ser ver ' wai t Q:[ t i me, wai t Q][ 0, 1][ 0, 2][ 0, 3][ 100, 2][ 200, 1][ 300, 0]========================================

    Ti me hi st or y f or t he ' ser ver ' act i veQ:[ t i me, act i veQ][ 0, 1]

    [ 100, 0][ 100, 1][ 200, 0][ 200, 1][ 300, 0][ 300, 1][ 400, 0]

    This output illustrates the difference between the (Time) Average and the number statistics . Here process c1 was in the wai t Q for zero time units, process c2 for 100time units, and so forth. The total wait time accumulated by all four processesduring the entire simulation run, which ended at time 400, amounts to 0 + 100 + 200+ 300 = 600 time units. Dividing the 600 accumulated time units by the simulationrun time of 400 gives 1.5 for the (Time) Average number of processes in the wai t Q .It is the time-weighted average length of the wai t Q , but is almost always calledsimply the average length of the wai t Q or the average number of items waiting for aresource.

    It is also the expected number of processes you would find in the wai t Q if you took asnapshot of it at a random time during the simulation. The acti veQ s time averagecomputation is similar, although in this example the resource is held by someprocess throughout the simulation. Even though the number in the acti veQmomentarily drops to zero as one process releases the resource and immediatelyrises to one as the next process acquires it, that occurs instantaneously and socontributes nothing to the (Time) Average computation.

    Number statistics such as the Average, Variance, and Standard Deviation arecomputed differently. At time zero the number of processes in the wai t Q starts at 1,

  • 8/14/2019 SimPy Manual SimPy 2.3b1 documentation.pdf

    30/54

    mPy Manual SimPy 2.3b1 documentation

    ///C|/Users/Manolo/Downloads/ADO/SimPy Manual SimPy 2.3b1 documentation.htm[10/03/2013 01:01:30 p.m.]

    then rises to 2, and then to 3. At time 100 it drops back to two processes, and soforth. The average and standard deviation of the six values [1, 2, 3, 2, 1, 0] is 1.5and 0.9574..., respectively. Number statistics for the act i veQ are computed usingthe eight values [1, 0, 1, 0, 1, 0, 1, 0] and are as shown in the output.

    When the moni t or Type is changed to Tal l y , all the output up to and including thelines:

    Ti me hi st or y f or t he ' ser ver ' wai t Q:

    [ t i me, wai t Q]

    is displayed. Then the output concludes with an error message indicating a problemwith the reference to server. wai t Mon . Of course, this is because Tal l y does notgenerate complete time series.

    [Return to Top ]

    Levels

    The three resource facilities provided by the SimPy system are Resources , Levelsand Stores . Each models a congestion point where process objects may have toqueue up to obtain resources. This section describes the Level type of resourcefacility.

    Levels model the production and consumption of a homogeneous undifferentiatedmaterial. Thus, the currently-available amount of material in a Level resourcefacility can be fully described by a scalar (real or integer). Process objects mayincrease or decrease the currently-available amount of material in a Level facility.

    For example, a gasoline station stores gas (petrol) in large tanks. Tankers increase,and refuelled cars decrease, the amount of gas in the stations storage tanks. Bothgetting amounts and putting amounts may be subjected to reneging like requestingamounts from a Resource.

    Defining a Level

    You define the Level resource facility lev by a statement like this:

    l ev = Level ( name =' a_ l evel ' , uni t Name =' uni t s ' , capaci t y =' unbounded' , i ni t i al Buf f er ed =0, put QType =FI FO, get QType =FI FO, moni t or ed =Fal se , moni t orType =Moni t or )

    where

    name (string type) is a descriptive name for the Level object lev isknown (e.g., ' i nvent or y' ).uni t Name (string type) is a descriptive name for the units in whichthe amount of material in lev is measured (e.g., ' ki l ogr ams' ).capaci t y (positive real or integer) is the capacity of the Level objectlev . The default value is set to ' unbounded' which is interpreted assys. maxi nt .

    i ni t i al Buf f er ed (positive real or integer) is the initial amount of material in the Level object lev .put QType (FI FO or Pr i or i t y Q ) is the (producer) queue discipline.get QType (FI FO or Pr i or i t y Q ) is the (consumer) queue discipline.moni t or ed (boolean) specifies whether the queues and the amount

    http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#contentshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#contentshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#id20http://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#levelshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#resourceshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#levelshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#storeshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#reneging-leaving-a-queue-before-acquiring-a-resourcehttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#defining-a-levelhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#defining-a-levelhttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#reneging-leaving-a-queue-before-acquiring-a-resourcehttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#storeshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#levelshttp://simpy.sourceforge.net/SimPy_Manual/Manuals/Manual.html#resourceshttp://simpy.sourceforge.net/Si