Debian Codegraph @

docs/SManual/SManual.rst

raw
1 .. meta::
2 :description: Basic Manual SimPy Python Simulation Language
3 :keywords: simulation python stochastic
4
5 .. highlight:: python
6 :linenothreshold: 5
7
8 ======================================================
9 Introduction to SimPy
10 ======================================================
11
12 :Authors: G A Vignaux and Klaus Muller
13 :Date: |today|
14 :SimPy release: |release|
15 :Python-Version: 2.6 and later
16
17 .. THIS WAS PUT UNDER SUBVERSION 2008/08/07
18
19 .. REPLACEMENTS ===================================================
20 .. |yrequest| replace:: ``yield request,self,``
21 .. |rrequest| replace:: ``yield (request,self,``\ *r [,P]*\ ``),``
22 .. |init| replace:: ``__init__``
23 .. ================================================================
24
25
26 .. contents:: Contents
27 :depth: 2
28
29
30
31 ..
32 1 Introduction
33 2 Simulation with SimPy
34 3 Processes
35 3.1 Defining a process
36 3.2 Creating a process object
37 3.3 Starting SimPy Process Objects
38 3.3.1 activate
39 3.3.2 start
40 3.3.3 The standard PEM name, ACTIONS
41 3.4 Elapsing time in a Process
42 3.4.1 yield hold
43 3.5 More about Processes
44 3.6 A SimPy Program
45 4 Resources
46 4.1 Defining a Resource object
47 4.2 Requesting and releasing a unit of a Resource
48 4.2.1 yield request
49 4.2.2 yield release
50 4.3 Resource Example
51 5 Levels
52 5.1 Defining a Level
53 5.2 Putting amounts into a Level
54 5.3 Getting amounts from a Level
55 6 Random Number Generation
56 7 Monitors and Recording Simulation Results
57 7.1 Defining Monitors
58 7.2 Observing data
59 7.3 Data summaries
60 7.4 Monitoring Resource Queues
61 7.5 More on Monitors
62 8 Appendices
63 8.1 SimPy Contacts
64 8.2 The Resource Example with Tracing
65
66
67
68 Introduction
69 -------------------
70
71 SimPy is a free, open-source discrete-event simulation system written
72 in Python. It provides a number of tools for programmers writing
73 simulation programs. This document is a description of basic
74 techniques of SimPy. It describes a subset of SimPy's capabilities -
75 sufficient, we think, to develop standard simulations. You may also
76 find `The Bank`_ tutorial included in SimPy's distribution helpful in
77 the early stages. The full SimPy Manual, included in the distribution, is
78 more detailed.
79
80 The active elements (or *entities*) of a SimPy model are objects of a
81 class defined by the programmer (see Processes_, section 3). Each
82 entity has a standard method, a Process Execution Method (referred to
83 by SimPy programmers as a PEM) which specifies its actions in detail.
84 Each PEM runs in parallel with (and may interact with) the PEMs of
85 other entities.
86
87 The activity of an entity may be delayed for fixed or random times,
88 queued at resource facilities, and may be interrupted by or interact
89 in different ways with other entities and components. For example in a
90 gas station model, automobile entities (objects of an Automobile
91 Class) may have to wait at the gas station for a pump to become
92 available. On obtaining a pump it takes time to fill the tank. The
93 pump is then released for the next automobile in the queue if there is
94 one.
95
96 .. A SimPy program contains the declaration of one or more Process
97 classes and the creation and activating of objects from them.
98
99
100 SimPy has three kinds of resource facilities (Resources, Levels, and
101 Stores). Each type models a congestion point where entities queue
102 while waiting to acquire or, in some cases, to deposit a
103 resource.SimPy automatically handles the queueing.
104
105 .. index:: resources
106
107
108 - Resources_ have one or more identical resource units, each of which
109 can be held by entities. Extending the example above, the gas
110 station might be modelled as a Resource with its pumps as resource
111 units. When a car requests a pump the gas station resource
112 automatically queues it until a pump becomes available (perhaps
113 immediately). The car holds the pump until it finishes refuelling
114 and then releases it for use by the next car.
115
116 .. index:: levels; definition
117
118 - ``Levels`` (not treated here) model the supply and consumption of a
119 homogeneous undifferentiated "material". The Level holds an amount
120 that is fully described by a non-negative number which can be
121 increased or decreased by entities. For example, a gas station
122 stores gas in large storage tanks. The tanks can be filled by
123 tankers and emptied by cars refuelling. In contrast to the operation
124 of a Resource, a car need not return the gas to the gas station.
125
126 .. index:: stores; definition
127
128 - ``Stores`` (not treated here) model the production and consumption of
129 distinguishable items. A Store holds a list of items. Entities can
130 insert or remove items from the list and these can be of any
131 type. They can even be SimPy process objects. For example, the gas
132 station holds spares of different types. A car might request a set
133 of spares from the Store. The store is replenished by deliveries
134 from a warehouse.
135
136 SimPy also supplies Monitors and Tallys to record simulation
137 events. Monitors_ are used to compile summary statistics such as
138 waiting times and queue lengths. These statistics includes simple
139 averages and variances, time-weighted averages, or histograms. In
140 particular, data can be gathered on the queues associated with
141 Resources, Levels and Stores. For example we may collect data on the
142 average number of cars waiting at the gas station and the distribution
143 of their waiting times. Monitors preserve complete time-series records
144 that may later be used for more advanced post-simulation analyses. A
145 simpler version of a Monitor is a Tally which provides most of the
146 statistical facilities but does not retain a complete time-series
147 record. See the SimPy Manual for details on the Tally.
148
149 You need to write Python code to develop a SimPy model. In
150 particular, you will have to define and use classes and their
151 objects. Python is free and open-source and is available on most
152 platforms. You can find out more about it and download it from the
153 `Python web-site`_ where there is full documentation and
154 tutorials. SimPy requires Python version 2.3 or later.
155
156
157 Simulation with SimPy
158 -------------------------
159
160 To use the SimPy simulation system in your Python program you must import its
161 ``Simulation`` module using:
162
163 ``from SimPy.Simulation import *``
164
165 We recommend that new users instead import ``SimPy.SimulationTrace``,
166 which works the same but also automatically produces a timed listing of
167 events as the model executes. (An example of such a trace is shown in
168 `The Resource Example with Tracing`_):
169
170 ``from SimPy.SimulationTrace import *``
171
172
173 Discrete-event simulation programs automatically maintain the current
174 simulation time in a software clock. This cannot be directly changed
175 by the user. In SimPy the current clock value is returned by the
176 ``now()`` function and you can access this or print it out. At the
177 start of the simulation it is set to 0.0. While the simulation
178 program runs, simulation time steps forward from one *event* to the
179 next. An event occurs whenever the state of the simulated system
180 changes such as when a car arrives or departs from the gas station.
181
182 The ``initialize`` statement initialises global simulation variables and
183 sets the software clock to 0.0. It must appear in your program before
184 any SimPy process objects are activated.
185
186 ``initialize()``
187
188 This is followed by SimPy statements creating and activating entities
189 (that is, SimPy process objects). Activation of entities adds events
190 to the simulation event schedule. Execution of the simulation itself
191 starts with the following statement:
192
193 ``simulate(until=``\ *endtime*\ ``)``
194
195 The simulation then starts, and SimPy seeks and executes the first event in
196 the schedule. Having executed that event, the simulation seeks and
197 executes the next event, and so on.
198
199 Typically a simulation terminates when there are no more events to
200 execute or when the *endtime* is reached but it can be stopped at any
201 time by the command:
202
203 ``stopSimulation( )``
204
205 After the simulation stops, further statements can be executed.
206 ``now()`` will retain the time of stopping and data held in Monitors
207 will be available for display or further analysis.
208
209 The following fragment shows only the *main* block in a simulation
210 program to illustrate the general structure. A complete `Example
211 Program`_ is shown later. Here ``Car`` is a Process class with a
212 ``go`` as its PEM (described later) and ``c`` is made an entity of
213 that class, that is, a particular car. Activating ``c`` has the effect
214 of scheduling at least one event by starting ``c``\ 's PEM. The
215 ``simulate(until=1000.0)`` statement starts the simulation
216 itself. This immediately jumps to the first scheduled event. It will
217 continue executing events until it runs out of events to execute or
218 the simulation time reaches ``1000.0``. When the simulation stops the
219 ``Report`` function is called to display the results::
220
221 class Car(Process):
222 def go(self):
223 # PEM for a Car
224 ...
225
226 def Report():
227 # print results when finished
228 ...
229
230 initialize()
231 c = Car(name="Car23")
232 activate(c, c.go(), at=0.0)
233 simulate(until=1000.0)
234
235 Report()
236
237
238 In addition to *SimPy.Simulation* there are three alternative
239 simulation libraries with the same simulation capabilities but with
240 special facilities. Beside ``SimPy.SimulationTrace``, already
241 mentioned, there are ``SimPy.SimulationRT`` for real time
242 synchronisation and ``SimPy.SimulationStep`` for event-stepping through
243 a simulation. See the SimPy Manual for more information.
244
245
246 .. ==================================================================
247
248 .. index:: processes
249
250
251 Processes
252 -------------------
253
254 SimPy's active objects (entities) are process objects -- instances of
255 a class written by the user that inherits from SimPy's Process class.
256
257 For example, if we are simulating a gas station we might model each
258 car as an object of the class ``Car``. A car arrives at the gas
259 station (modelled as a Resource with ``pump``\s). It requests a pump
260 and may need to wait for it. Then it fills its tank and when it has
261 finished it releases the pump. It might also buy an item from the
262 station store. The ``Car`` class specifies the logic of these actions
263 in its Process Execution Method (PEM). The simulation creates a number
264 of cars as it runs and their evolutions are directed by their ``Car``
265 class's PEM.
266
267 .. index:: process; defining
268
269
270 Defining a process
271 ~~~~~~~~~~~~~~~~~~~~~~~~~
272
273 Each Process class inherits from SimPy's ``Process`` class. For example
274 the header of the definition of a ``Car`` Process class would
275 be:
276
277 ``class Car(Process):``
278
279
280 At least one Process Execution Method (PEM) must be defined in each
281 Process class (though an entity can have only one PEM active). A PEM
282 may have arguments in addition to the required ``self`` argument
283 needed by all Python class methods. Naturally, other methods and, in
284 particular, an ``__init__``, may be defined.
285
286
287 .. _PEM:
288
289 * ``A Process Execution Method (PEM)`` defines the actions that are
290 performed by its process objects. *Each PEM must contain at least
291 one of the special ``yield`` statements, described later*. This
292 makes the PEM a Python generator function so that it has resumable
293 execution -- it can be restarted again after the yield statement
294 without losing its current state. A PEM may have any name of your
295 choice. For example it may be called ``execute( )`` or ``run(
296 )``. However, if a PEM is called ``ACTIONS``, SimPy recognises this
297 as a PEM. This can simplify the ``start`` method as explained below.
298
299
300
301 The ``yield`` statements are simulation commands which affect an
302 ongoing life cycle of Process objects. These statements control the
303 execution and synchronisation of multiple processes. They can delay
304 a process, put it to sleep, request a shared resource or provide a
305 resource. They can add new events to the simulation event schedule,
306 cancel existing ones, or cause processes to wait for a change in the
307 simulated system's state.
308
309
310 For example, here is a Process Execution Method, ``go(self)``,
311 for the simple ``Car`` class that does no more than delay for a
312 time. As soon as it is activated it prints out the current time,
313 the car object's name and the word ``Starting``. After a
314 simulated delay of 100.0 time units (in the ``yield hold, ...``
315 statement) it announces that this car has "Arrived"::
316
317 def go(self):
318 print now(), self.name, 'Starting'
319 yield hold,self,100.0
320 print now(), self.name, 'Arrived'
321
322 A process object's PEM starts execution when the object is
323 activated, provided the ``simulate(until=``\ *endtime*\ ``)``
324 statement has been executed.
325
326
327 * **__init__(self, ...)**, where *...* indicates other arguments. This
328 method is optional but is useful to initialise the process object,
329 setting values for its attributes. As for any sub-class in Python,
330 the first line of this method must call the ``Process`` class's
331 ``__init__( )`` method in the form:
332
333 ``Process.__init__(self)``
334
335 You can then use additional commands to initialise attributes of the
336 Process class's objects. You can also override the standard ``name``
337 attribute of the object.
338
339 If present, the ``__init__( )`` method is always called whenever
340 you create a new process object. If you do not wish to provide for
341 any attributes other than a ``name``, the ``__init__`` method may be
342 dispensed with. An example of an ``__init__( )`` method is shown in
343 the `Example Program`_.
344
345 .. index:: process; creation
346
347
348 Creating a process object
349 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
350
351 An entity (process object) is created in the usual Python manner by
352 calling the Class. Process classes have a single attribute, ``name``
353 which can be specified even if no |init| method is defined. ``name``
354 defaults to ``'a_process'`` unless the user specified a different one.
355
356 For example to create a new ``Car`` object with a name ``Car23``:
357
358 ``c = Car(name="Car23")``
359
360
361
362
363
364 .. index:: process; starting
365
366 .. =================================================================
367
368 Starting SimPy Process Objects
369 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
370
371 An entity (process object) is "passive" when first created, i.e., it
372 has no events scheduled for it. It must be *activated* to start its
373 Process Execution Method. To do this you can use either the
374 ``activate`` function or the ``start`` method of the Process.
375
376 .. index::
377 single: process object; activation
378
379
380 activate
381 +++++++++
382
383 .. |arguments| replace:: \ ``[,{at=now()|delay=0}][,prior=False])``
384 .. |arguments2| replace:: \ ``[,{at=now()|delay=0}])``
385 .. |arguments3| replace:: \ ``[,{at=``\ *t*\ ``|delay=``\ *period*\ ``}])``
386
387 Activating an entity by using the SimPy ``activate`` function:
388
389 - ``activate(``\ *p, p.pemname([args])*\ |arguments3|
390
391 activates process object *p*, provides its Process Execution
392 Method *p.pemname( )* with the arguments *args* and possibly assigns
393 values to the other optional parameters. You must choose one (or
394 neither) of ``at=``\ *t* and ``delay=``\ *period*. The default is
395 to activate at the current time (``at=now( )``) and with no delay
396 (``delay=0``).
397
398 For example: to activate an entity, ``cust`` at time 10.0
399 using its PEM called ``lifetime``::
400
401 cust = Customer()
402 activate(cust, cust.lifetime(), at=10.0)
403
404 .. index::
405 pair: process; start
406
407 start
408 +++++++++
409
410 An alternative to the ``activate()`` function is the ``start`` method
411 of Process objects:
412
413 - *p.*\ ``start(``\ *p.pemname([args])*\ |arguments3|
414
415 Here *p* is a Process object. Its PEM, *pemname*, can have any
416 identifier (such as ``run``, ``lifecycle``, etc) and any
417 arguments *args*.
418
419 For example, to activate the process object ``cust`` using the PEM
420 with identifier ``lifetime`` at time 10.0 we would use::
421
422 cust.start(cust.lifetime(),at=10.0)
423
424 The standard PEM name, ACTIONS
425 +++++++++++++++++++++++++++++++++
426
427 The identifier ``ACTIONS`` is recognised by SimPy as a PEM name and
428 can be used (or implied) in the ``start`` method.
429
430 - *p.*\ ``start([``\ *p.*\ ``ACTIONS()]`` |arguments3|
431
432 ``ACTIONS`` *cannot* have parameters. The call *p.*\ ``ACTIONS()``
433 is optional but may make your code clearer.
434
435 For example, to activate the Process object ``cust`` with a PEM
436 called ``ACTIONS`` at time 10.0, the following are equivalent
437 (and the second version more convenient)::
438
439 cust.start(cust.ACTIONS(), at=10.0)
440 cust.start(at=10.0)
441
442 *A reminder*: Even activated process objects will not actually start
443 operating until the ``simulate()`` statement is executed.
444
445
446
447 Elapsing time in a Process
448 ~~~~~~~~~~~~~~~~~~~~~~~~~~
449
450 A PEM_ uses the ``yield hold`` command to temporarily delay a process
451 object's operations. This might represent a service time for the
452 entity. (Waiting is handled automatically by the resource facilities
453 and is not modelled by ``yield hold``)
454
455 .. index::
456 pair: yield; hold
457
458 yield hold
459 ++++++++++++
460
461 ``yield hold,self,``\ *t*
462
463 Causes the entity to delay *t* time units. After the delay, it
464 continues with the next statement in its PEM. During the ``hold`` the
465 entity's operations are suspended.
466
467 Paradoxically, in the model world, the entity is considered to be
468 *busy* during this simulated time. For example, it might be involved
469 in filling up with gas or driving. In this state it can be
470 interrupted by other entities.
471
472
473 More about Processes
474 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
475
476 .. index::
477 pair: yield; passivate
478 single: sleep a process
479 single: process; sleep
480
481
482 An entity (Process object) can be "put to sleep" or passivated using
483
484 ``yield passivate,self``
485
486 (and it can be reactivated by another entity
487 using ``reactivate``), or permanently removed from the future event
488 queue by the command ``self.cancel()``. Active entities can be
489 ``interrupt``\ed by other entities. Examine the full SimPy Manual for
490 details.
491
492 ------
493
494 A SimPy Program
495 ~~~~~~~~~~~~~~~~
496
497 .. index:: example;car
498
499 .. _`Example Program`:
500
501
502 This is a complete SimPy script. We define a ``Car`` class with a PEM
503 called ``go( )``. We also (for interest) define an ``__init__( )``
504 method to provide individual cars with an identification name and
505 engine size, ``cc``. The ``cc`` attribute is not used in this very
506 simple example.
507
508 Two cars, ``p1`` and ``p2`` are created. ``p1`` and ``p2`` are
509 activated to start at simulation times 0.6 and 0.0, respectively. Note
510 that these will *not* start in the order they appear in the program
511 listing. ``p2`` actually starts first in the simulation. Nothing
512 happens until the ``simulate(until=200)`` statement at which point the
513 event scheduler starts operating by finding the first event to
514 execute. When both cars have finished (at time ``6.0+100.0=106.0``)
515 there will be no more events so the simulation will stop::
516
517 .. .. literalinclude:: source/programs/car.py
518
519 Running this program gives the following output::
520
521 .. .. literalinclude:: source/programs/car.out
522
523 If, instead one chose to import ``SimPy.SimulateTrace`` at the start
524 of the program one would obtain the following output. (The meaning of
525 the phrase ``prior : False`` in the first two lines is described in
526 the full SimPy Manual. ``prior`` is an advanced technique for fine control
527 of PEM priorities but seldom affects simulated operations and so
528 normally can be ignored/)
529
530 .. include:: source/programs/carT.out
531 :literal:
532
533
534 -------
535
536
537
538 .. ==================================================================
539
540 .. index:: !resources
541
542
543 Resources
544 -------------------
545
546 The three resource facilities provided by SimPy are Resources_,
547 ``Levels`` and ``Stores``. Each models a congestion point where process
548 objects may have to queue up to access resources. This section
549 describes the Resource type of resource facility. ``Levels`` and
550 ``Stores`` are not treated in this introduction.
551
552 An example of queueing for a Resource might be a manufacturing plant
553 in which a ``Task`` (modelled as an entity or *Process object*) needs
554 work done by a ``Machine`` (modelled as a *Resource object*). If all
555 of the ``Machines`` are currently being used, the ``Task`` must wait
556 until one becomes free. A SimPy Resource can have a number of
557 identical ``units``, such as a number of identical ``machine``
558 units. An entity obtains a unit of the Resource by ``requesting`` it
559 and, when it is finished, ``releasing`` it. A Resource maintains a
560 list (the ``waitQ``) of entities that have requested but not yet
561 received one of the Resource's units, and another list (the
562 ``activeQ``) of entities that are currently using a unit. SimPy
563 creates and updates these queues itself -- the user can read their
564 values, but should not change them.
565
566 .. index:: resource; define
567
568
569 Defining a Resource object
570 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
571
572 A Resource object, ``r``, is established by the following statement::
573
574 r = Resource(capacity=1,
575 name='a_resource', unitName='units',
576 monitored=False)
577
578 where
579
580 ..index:: resource; capacity
581
582 - ``capacity`` (positive integer) specifies the total
583 number of identical units in Resource object ``r``.
584
585 ..index:: resource; name
586
587 - ``name`` (string) the name for this Resource object (e.g.,
588 ``'gasStation'``).
589
590 ..index:: resource; unitName
591
592 - ``unitName`` (string) the name for a unit of the resource (e.g.,
593 ``'pump'``).
594
595 ..index:: resource; monitored
596
597 - ``monitored`` (``False`` or ``True``) If set to ``True``, then
598 information is gathered on the sizes of ``r``'s ``waitQ`` and
599 ``activeQ``, otherwise not.
600
601
602 For example, in the model of a 2-pump gas-station we might define::
603
604 gasstation = Resource(capacity=2,name='gasStation',unitName='pump')
605
606 ..index:: resource; attributes
607
608 Each Resource object, ``r``, has the following additional attributes:
609
610 ..index:: resource; n
611
612 - ``r.n``, the number of units that are currently free.
613
614 ..index:: resource; waitQ
615
616 - ``r.waitQ``, a queue (list) of processes that have requested but
617 not yet received a unit of ``r``, so ``len(r.waitQ)`` is the
618 number of process objects currently waiting.
619
620 ..index:: resource; activeQ
621
622 - ``r.activeQ``, a queue (list) of process objects currently using
623 one of the Resource's units, so ``len(r.activeQ)`` is the number of
624 units that are currently in use.
625
626 ..index:: resource; waitMon
627
628 - ``r.waitMon``, the record (made by a ``Monitor`` whenever
629 ``monitored==True``) of the activity in ``r.waitQ``. So, for
630 example, ``r.waitMon.timeaverage()`` is the average number of
631 processes in ``r.waitQ``. See `Data Summaries`_
632 for an example.
633
634 ..index:: resource; actMon
635
636 - ``r.actMon``, the record (made by a ``Monitor`` whenever
637 ``monitored==True``) of the activity in ``r.activeQ``.
638
639
640
641 Requesting and releasing a unit of a Resource
642 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
643
644 A process can request and later release a unit of the Resource object,
645 ``r``, by using the following yield commands in a Process Execution
646 Method:
647
648 .. index::
649 single: yield; request a resource
650 pair: yield; request
651
652 yield request
653 +++++++++++++++
654
655
656 - |yrequest|\ *r*
657
658 Requests a unit of Resource *r*
659
660 If a Resource unit is free when the request is made, the requesting
661 entity takes it and moves on to the next statement in its PEM. It is
662 added to the Resource's ``activeQ``.
663
664 If no Resource unit is available when the request is made, the
665 requesting entity is appended to the Resource's ``waitQ`` and
666 suspended. The next time a unit becomes available the first entity in
667 the ``r.waitQ`` takes it and continues its execution.
668
669 For example, a ``Car`` might request a ``pump``::
670
671 yield request,self,gasstation
672
673 (It is actually requesting a *unit* of the ``gasstation``, i.e. a
674 ``pump``.) An entity holds a resource unit until it releases it.
675
676 Entities can use a priority system for queueing. They can also preempt
677 (that is, interrupt) others already in the system. They can also
678 *renege* from the ``waitQ`` (that is, abandon the queue if it takes
679 too long). This is achieved by an extension to the ``yield request``
680 command. See the main SimPy Manual.
681
682
683 .. index:: yield; release a resource
684 pair: yield; release
685
686 yield release
687 +++++++++++++++
688
689 ``yield release,self,r``
690
691 Releases the unit of ``r``.
692
693
694 The entity is removed from ``r.activeQ`` and continues with its next
695 statement. If, when the unit of ``r`` is released, another entity is
696 waiting (in ``waitQ``) it will take the unit, leave the ``waitQ`` and
697 move into the ``activeQ`` and go one with its PEM.
698
699 For example the ``Car`` might release the ``pump`` unit of the
700 gasstation::
701
702 yield release,self,gasstation
703
704
705
706 ------------
707
708 .. index:: resource; example
709 .. index:: example;resource
710 .. index:: example;cars
711
712 Resource Example
713 ~~~~~~~~~~~~~~~~~
714
715 In this complete script, the ``gasstation`` Resource object is given
716 two resource units (``capacity=2``). Four cars arrive at the times
717 specified in the program (not in the order they are listed). They all
718 request a ``pump`` and use it for 100 time units:
719
720 .. literalinclude:: source/programs/cars.py
721 :language: python
722 :linenos:
723
724
725 This program results in the following output:
726
727 .. literalinclude:: source/programs/cars.out
728
729
730 And, if we use ``SimPy.SimulationTrace`` to get an automatic trace we
731 get the result shown in Appendix `The Resource Example with Tracing`_.
732 (It is rather long to be inserted here).
733
734 -------
735
736
737 .. ==========================================================================
738
739 .. index:: !random number generation
740
741 Random Number Generation
742 -------------------------
743
744 Simulations usually need random numbers. By design, SimPy does not
745 provide its own random number generators, so users need to import them
746 from some other source. Perhaps the most convenient is the standard
747 `Python random module`_. It can generate random variates from the
748 following continuous distributions: uniform, beta, exponential, gamma,
749 normal, log-normal, Weibull, and vonMises. It can also generate
750 random variates from some discrete distributions. Consult the module's
751 documentation for details. Excellent brief descriptions of these
752 distributions, and many others, can be found in the `Wikipedia
753 <http://www.wikipedia.com/>`_.
754
755 Python's ``random`` module can be used in two ways: you can import the
756 methods directly or you can import the ``Random`` class and make your
757 own random objects. In the second method, each object gives a
758 different random number sequence, thus providing multiple random
759 streams as in some other simulation languages such as Simscript and
760 ModSim.
761
762 Here the first method is illustrated. A single pseudo-random sequence
763 is used for all calls. You ``import`` the methods you need from the
764 ``random`` module. For example::
765
766 from random import seed, random, expovariate, normalvariate
767
768 In simulation it is good practice to set the initial ``seed`` for the
769 pseudo-random sequence at the start of each run. You then have good
770 control over the random numbers used. Replications and comparisons are
771 easier and, together with variance reduction techniques, can provide
772 more accurate estimates. In the following code snippet we set the
773 initial seed to ``333555``. ``X`` and ``Y`` are pseudo-random
774 variates from the two distributions. Both distributions have the same
775 mean::
776
777 from random import seed, expovariate, normalvariate
778
779 seed(333555)
780 X = expovariate(0.1)
781 Y = normalvariate(10.0, 1.0)
782
783
784 .. ============================================================================
785
786 .. index:: Monitors
787 .. index:: Recording Simulation Results
788
789
790 Monitors and Recording Simulation Results
791 ---------------------------------------------
792
793
794
795 A Monitor enables us to observe a particular variable of interest and
796 to hold a time series of its values. It can return a simple data
797 summary either during or at the completion of a simulation run.
798
799 For example we might use one Monitor to record the waiting time for
800 each of a series of customers and another to record the total number
801 of customers in the shop. In a discrete-event system the number of
802 customers changes only at arrival or departure events and it is at
803 those events that the number in the shop must be observed. A Monitor
804 provides simple statistics useful either alone or as the start of a
805 more sophisticated statistical analysis.
806
807 When Resources are defined, a Monitor can be set up to automatically
808 observe the lengths of each of their queues.
809
810 The simpler version, the Tally, is not covered in this document. See
811 the SimPy Manual for more details.
812
813 .. index:: monitors; defining
814
815 Defining Monitors
816 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
817
818
819 The ``Monitor`` class preserves a complete time-series of the observed
820 data values, ``y``, and their associated times, ``t``. The data are held
821 in a list of two-item sub-lists, ``[t,y]``. Monitors calculate data
822 summaries using this time-series when your program requests them. In
823 long simulations their memory demands may be a disadvantage
824
825 To define a new Monitor object:
826
827 * ``m = Monitor(name='a_Monitor')``
828
829 where ``name`` is a descriptive name for the Monitor object. The
830 descriptive name is used when the data is graphed or tabulated.
831
832 For example, to record the waiting times of cars in the gas station we
833 might use a Monitor::
834
835 waittimes = Monitor(name='Waiting times')
836
837
838 .. index:: monitors; observe
839 .. index:: observing data
840
841
842 Observing data
843 ~~~~~~~~~~~~~~~~~
844
845 Monitors use their ``observe`` method to record data. Here and in the
846 next section, ``m`` is a Monitor object:
847
848 * ``m.observe(y [,``\ *t*\ ``])``
849
850 records the current value of the variable, ``y`` and time *t* (or
851 the current time, ``now()``, if *t* is missing). A Monitor retains
852 the two values as a sub-list ``[t,y]``.
853
854 For example, using the Monitor in the previous example, we might
855 record the waiting times of the cars as shown in the following
856 fragment of the PEM of a ``Car``::
857
858 startwaiting = now() # start wait
859 yield request, self, gasstation
860 waitingtime = now() - startwaiting # time spent waiting
861
862 waittimes.observe(waitingtime)
863
864 The first three lines measure the waiting time (from the time of the
865 request to the time the ``pump`` is obtained). The last records the
866 waiting time in the ``waittimes`` Monitor.
867
868 .. index::
869 pair: monitors; reset
870
871 The data recording can be ``reset`` to start at any time in the
872 simulation:
873
874 * ``m.reset([``\ *t*\ ``])``
875
876 resets the observations. The recorded data is re-initialised, and
877 the observation starting time is set to *t*, or to the current
878 simulation time, ``now( )``, if *t* is missing.
879
880
881
882 .. index:: monitors; data summaries
883
884
885 Data summaries
886 ~~~~~~~~~~~~~~~~~
887
888 The following simple data summaries are available from Monitors at
889 any time during or after the simulation run:
890
891
892 * ``m[i]`` holds the ``i``\-th observation as a two-item list, *[ti,
893 yi]*
894
895 .. index::
896 pair: monitors; yseries
897
898 * ``m.yseries( )`` is a list of the recorded data values, *yi*
899
900 .. index::
901 pair: monitors; tseries
902
903 * ``m.tseries( )`` is a list of the recorded times, *ti*
904
905
906 .. index::
907 pair: monitors; count
908
909 * ``m.count( )``, the current number of observations. (This is the
910 same as ``len(r)``).
911
912 .. index::
913 pair: monitors; total
914
915 * ``m.total( )``, the sum of the ``y`` values
916
917 .. index::
918 pair: monitors; mean
919
920 * ``m.mean( )``, the simple numerical average of the observed *y*
921 values, *ignoring the times at which they were made*. This is
922 ``m.total( )/m.count( )``.
923
924 .. figure:: /_static/images/Mon004.*
925 :alt: Standard mean value
926 :figwidth: 400
927 :align: center
928
929 ``m.mean`` is the simple average of the *y* values observed.
930
931 .. index::
932 pair: monitors; var
933
934 * ``m.var( )`` the *sample* variance of the observations, ignoring the
935 times at which they were made. If an unbiased estimate of the
936 *population* variance is desired, the sample variance should be
937 multiplied by *n/(n-1)*, where *n = m.count( )*. In either case the
938 standard deviation is, of course, the square-root of the variance
939
940
941 .. index::
942 pair monitors; timeAverage
943
944 * ``m.timeAverage(``\ *[t]*\ ``)`` the time-weighted average of ``y``,
945 calculated from time 0 (or the last time ``m.reset(``\ *[t]*\ ``)``
946 was called) to time *t* (or to the current simulation time,
947 ``now()``, if *t* is missing).
948
949 This is intended to measure the average of a quantity that always
950 exists, such as the length of a queue or the amount in a Level [#]_.
951 In discrete-event simulation such quantity changes are always
952 instantaneous jumps occurring at events. The recorded times and new
953 levels are sufficient information to calculate the average over
954 time. The graph shown in the figure below illustrates the calculation. The
955 total area under the line is calculated and divided by the total
956 time of observation. For accurate time-average results *y* must be
957 piecewise constant like this and observed *just after* each change
958 in its value. That is, the *y* value observed must be the *new*
959 value after the state change.
960
961
962 .. figure:: /_static/images/Mon005.*
963 :alt: Time Average
964 :figwidth: 400
965 :align: center
966
967 ``m.timeAverage([t])`` is the time-weighted average of the observed
968 ``y`` values. Each ``y`` value is weighted by the time for which
969 it exists. The average is the area under the above curve divided
970 by the total time, *t*.
971
972
973 .. [#] ``timeAverage`` is not intended to measure instantaneous
974 values such as a service time or a waiting time. ``m.mean()``
975 is used for that.
976
977 .. index::
978 pair: monitors; timeVarience
979
980 * ``m.timeVariance([t])`` the time-weighted variance of the ``y``
981 values calculated from time 0 (or the last time ``m.reset([t])`` was
982 called) to time *t* (or to the current simulation time, ``now()``,
983 if *t* is missing).
984
985
986 .. index::
987 pair: monitors; current state
988
989 * ``m.__str__( )`` is a string that briefly describes the current state
990 of the monitor. This can be used in a print statement.
991
992 .. index:: resource queue; monitoring
993 .. index:: monitoring; resource queues
994
995 Monitoring Resource Queues
996 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
997
998 If a Resource, ``m``, (and similarly for a Level or a Store) is
999 defined with ``monitored=True``, SimPy automatically records the
1000 lengths of its associated queues (i.e. ``waitQ`` and ``activeQ`` for
1001 Resources, and the analogous queues for Levels and Stores). These
1002 records are kept in Monitors ``m.waitMon`` for the ``waitQ`` and
1003 ``m.actMon`` for the ``activeQ`` (and analogously for the other
1004 resource types). This solves a problem, particularly for the ``waitQ``
1005 which cannot easily be recorded externally to the resource.
1006
1007 Complete time series for queue lengths are maintained and can be used
1008 for advanced post-simulation statistical analyses and to display
1009 summary statistics.
1010
1011
1012 ..index::
1013 pair: monitors; histogram
1014 pair: monitor; allMonitors
1015 pair: monitor; startCollection
1016
1017 More on Monitors
1018 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1019
1020
1021 When a Monitor is defined it is automatically entered into a global
1022 list ``allMonitors``. Each Monitor also has a descriptive label for
1023 its variable values, ``y``, and their corresponding times, ``t``, that can
1024 be used when the data are plotted. The function ``startCollection()``
1025 can be called to initialise all the Monitors in ``allMonitors`` at a
1026 certain simulation time. This is helpful when a simulation needs a
1027 'warmup' period to achieve steady state before measurements are
1028 started. A Monitor can also generate a ``Histogram`` of the data
1029 (The SimPy ``Tally`` is an alternative to ``Monitor`` that does essentially
1030 the same job but uses less storage space at some cost of speed and
1031 flexibility. See the SimPy Manual for more information on these options.)
1032
1033
1034
1035
1036 Appendices
1037 ---------------
1038
1039 SimPy Information
1040 ~~~~~~~~~~~~~~~~~
1041
1042 :SimPy Web-site: http://simpy.sourceforge.net/
1043 :Python-Version: 2.6 and later
1044 :SimPy version: |release|
1045 :Date: |today|
1046
1047 ..index:: example; resource with tracing
1048 ..index:: SimulationTrace
1049
1050 The Resource Example with Tracing
1051 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1052
1053 This is the trace produced in the Resource example when
1054 ``SimPy.SimulationTrace`` is imported at the head of the program. The
1055 relevance of the phrases ```prior: False``` and ```priority:
1056 default``` refer to advanced but seldom-needed methods for
1057 fine-grained control of event timing, as explained in the SimPy Manual. The
1058 trace contains the results of all the ``print`` output specifically
1059 called for by the user's program (for example, line 5) but adds a line
1060 for every event executed. (The ``request`` at time ``3.0``, for
1061 example, lists the contents of the ``waitQ`` and the ``activeQ`` for
1062 the ``gasstation``.)
1063
1064 .. literalinclude:: source/programs/carsT.out
1065 :linenos:
1066
1067 ..
1068 .. image:: http://sourceforge.net/sflogo.php?group_id=62366&type=4
1069 :width: 125
1070 :alt: SourceForge Logo
1071 :height: 37
1072
1073 .. ------------------------------------------------------------------------
1074 .. some useful stuff used above
1075
1076
1077 .. _`simpydownload`: http://sourceforge.net/projects/simpy/
1078 .. _`Python web-site` : http://www.Python.org
1079
1080
1081
1082 .. _`SimPy.SimulationRT`: http://simpy.sourceforge.net/SimPyDocs/SimRTManual.html
1083 .. _`SimPy.SimulationStep`: http://simpy.sourceforge.net/SimPyDocs/SimStepManual/SimStepManual.html
1084 .. _`The Bank`: http://simpy.sourceforge.net/SimPyDocs/TheBank.html
1085
1086
1087 .. .. _Top: Contents_
1088
1089 .. _monitors: `Monitors and Recording Simulation Results`_
1090
1091
1092 .. _`Python random module`: http://www.python.org/doc/current/lib/module-random.html
1093 .. _Python: http://www.Python.org
1094
1095
1096
1097
1098 ..
1099 Local Variables:
1100 mode: rst
1101 indent-tabs-mode: nil
1102 sentence-end-double-space: t
1103 fill-column: 70
1104 End: