Debian Codegraph @

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