Debian Codegraph @

docs/source/Tutorials/TheBankOO.rst

raw
1 ============================================================================
2 The Bank (Object Oriented version)
3 ============================================================================
4
5 .. Tutorials/TheBankOO
6
7 .. highlight:: python
8 :linenothreshold: 5
9
10 .. index::
11 Simulation,Monitors, Tallys, Processes,Resources, Levels, Stores
12
13 .. :Authors: G A Vignaux, K G Muller
14 :Date: 2010 April
15
16 Introduction
17 -------------------------------------
18
19 `SimPy`_ is used to develop a simple simulation of a bank with a
20 number of tellers. This Python package provides *Processes* to model
21 active components such as messages, customers, trucks, and planes. It
22 has three classes to model facilities where congestion might occur:
23 *Resources* for ordinary queues, *Levels* for the supply of quantities
24 of material, and *Stores* for collections of individual items. Only
25 examples of *Resources* are described here. It also provides
26 *Monitors* and *Tallys* to record data like queue lengths and delay
27 times and to calculate simple averages. It uses the standard Python
28 random package to generate random numbers.
29
30 Starting with SimPy 2.0 an object-oriented programmer's interface was
31 added to the package and it is this version that is described here.
32 It is quite compatible with the procedural approach. The object-oriented
33 interface, however, can support the process of developing and extending a
34 simulation model better than the procedural approach.
35
36
37 .. _`SimPy`: http://simpy.sourceforge.net/
38
39
40 SimPy can be obtained from: http://sourceforge.net/projects/simpy.
41 This tutorial is best read with the SimPy Manual and CheatsheetOO at
42 your side for reference.
43
44 Before attempting to use SimPy you should be familiar with the Python_
45 language. In particular you should be able to use *classes*. Python is
46 free and available for most machine types. You can find out more about
47 it at the `Python web site`_. SimPy is compatible with Python version
48 2.3 and later.
49
50 .. _Python: http://www.Python.org
51 .. _`Python web site`: http://www.Python.org
52
53
54
55 A single Customer
56 -------------------
57
58 In this tutorial we model a simple bank with customers arriving at
59 random. We develop the model step-by-step, starting out simply, and
60 producing a running program at each stage. The programs we develop are
61 available without line numbers and ready to go, in the
62 ``bankprograms_OO`` directory. Please copy them, run them and improve
63 them - and in the tradition of open-source software suggest your
64 modifications to the SimPy users list. Object-orented versions of all
65 the models are included in the same directory.
66
67 A simulation should always be developed to answer a specific question;
68 in these models we investigate how changing the number of bank servers
69 or tellers might affect the waiting time for customers.
70
71 .. index:: bank01
72
73
74 A Customer arriving at a fixed time
75 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
76
77
78 We first model a single customer who arrives at the bank for a visit,
79 looks around at the decor for a time and then leaves. There is no
80 queueing. First we will assume his arrival time and the time he spends
81 in the bank are fixed.
82
83
84
85
86 Examine the following listing which is a complete runnable Python
87 script, except for the line numbers. We use comments to divide the
88 script up into sections. This makes for clarity later when the
89 programs get more complicated. Line 1 is a normal Python
90 documentation string; line 2 makes available the SimPy constructs
91 needed for this model: the ``Simulation`` class, the ``Process`` class,
92 and the ``hold`` verb.
93
94 We define a ``Customer`` class derived from the SimPy ``Process``
95 class. We create a ``Customer`` object, ``c`` who arrives at the bank
96 at simulation time ``5.0`` and leaves after a fixed time of ``10.0``
97 minutes. The ``Customer`` class definition, lines 5-12, defines our
98 customer class and has the required generator method (called
99 ``visit``) (line 9) having a ``yield`` statement (line
100 11)). Such a method is called a Process Execution Method (PEM) in
101 SimPy.
102
103 The customer's ``visit`` PEM, lines 9-12, models his
104 activities. When he arrives (it will turn out to be a 'he' in this
105 model), he will print out the simulation time, ``self.sim.now()``,
106 and his name (line 10). ``self.sim`` is a reference to the ``BankModel``
107 simulation object where this customer exists. Every ``Process`` instance
108 is linked to the simulation in which it is created by assigning to
109 its ``sim`` parameter when it is created (see line 19).
110 The method ``now()`` can be used at any
111 time in the simulation to find the current simulation time though it cannot be
112 changed by the programmer. The customer's name will be set when the
113 customer is created later in the script (line 19).
114
115 He then stays in the bank for a fixed simulation time ``timeInBank``
116 (line 11). This is achieved by the ``yield hold,self,timeInBank`` statement.
117 This is the first of the special simulation commands that ``SimPy`` offers.
118
119 After a simulation time of ``timeInBank``, the program's execution
120 returns to the line after the ``yield`` statement, line 12. The
121 customer then prints out the current simulation time and his
122 name. This completes the declaration of the ``Customer`` class.
123
124 Though we do not do it here, it is also possible to define an
125 ``__init__()`` method for a ``Process`` if you need to give the
126 customer any attributes. Bear in mind that such an ``__init__``
127 method must first call ``Process.__init__(self)`` and can then
128 initialize any instance variables needed.
129
130 Lines 6 to 21 define a class ``BankModel``, composing a model of a bank from
131 the ``Simulation`` class, a ``Customer`` class and the global experiment data.
132 The definition ``class BankModel(Simulation)`` gives an instance of a
133 ``BankModel`` all the attributes of class ``Simulation``. (In OO terms,
134 ``BankModel`` *inherits* from ``Simulation``.) Any instance of ``BankModel``
135 *is* a ``Simulation`` instance. This gives a ``BankModel`` its own event list
136 and thus its own time axis. Also, it allows a ``BankModel`` instance to
137 activate processes and to start the execution of a simulation on its time axis.
138
139 Lines 17 to 21 define a ``run`` method; when called, it results in
140 the execution of a ``BankModel`` instance, i.e. the performance of
141 a simulation experiment. Line 18 initializes this
142 simulation, i.e. it creates a new event list. L.19 creates a ``Customer``
143 object. The parameter assignment ``sim = self`` ties the customer
144 instance to this and only this simulation. The customer does not exist
145 outside this simulation. L.20 activates the customer's ``visit`` process (PEM).
146 Finally the call of ``simulate(until=maxTime)`` in line 24
147 starts the simulation. It will run until the simulation time is
148 ``maxTime`` unless stopped beforehand either by the
149 ``stopSimulation()`` command or by running out of events to execute
150 (as will happen here). ``maxTime`` was set to ``100.0`` in line
151 25.
152
153 .. note::
154
155 If model classes like the``BankModel`` are to be given any other attributes, they
156 must have an ``__init__`` method in which these attributes are assigned
157 with the syntax ``self.attrib1 = . . .``. Such an ``__init__``
158 method must first call ``Simulation.__init__(self)`` to also initialize the
159 ``Simulation`` class from which the model inherits.
160
161 The simulation model is executed by line 32. ``BankModel()`` constructs the
162 model, and ``.run()`` executes it. This is just a short form of::
163
164 bM = BankModel()
165 bM.run()
166
167 ..
168 We define a ``Customer`` class derived from the SimPy ``Process``
169 class. We create a ``Customer`` object, ``c`` who arrives at the bank
170 at simulation time ``5.0`` and leaves after a fixed time of ``10.0``
171 minutes.
172
173 Examine the following listing which is a complete runnable Python
174 script, except for the line numbers. We use comments to divide the
175 script up into sections. This makes for clarity later when the
176 programs get more complicated. Line 1 is a normal Python
177 documentation string; line 2 imports the SimPy simulation code.
178
179 .. index::
180 pair: PEM; Process Execution Method
181
182 ..
183 The ``Customer`` class definition, lines 6-12, defines our
184 customer class and has the required generator method (called
185 ``visit``) (line 9) having a ``yield`` statement (line
186 11)). Such a method is called a Process Execution Method (PEM) in
187 SimPy.
188
189 The customer's ``visit`` PEM, lines 9-12, models his
190 activities. When he arrives (it will turn out to be a 'he' in this
191 model), he will print out the simulation time, ``now()``, and his name
192 (line 10). The function ``now()`` can be used at any time in the
193 simulation to find the current simulation time though it cannot be
194 changed by the programmer. The customer's name will be set when the
195 customer is created later in the script (line 22).
196
197 He then stays in the bank for a fixed simulation time ``timeInBank``
198 (line 11). This is achieved by the ``yield
199 hold,self,timeInBank`` statement. This is the first of the special
200 simulation commands that ``SimPy`` offers.
201
202 After a simulation time of ``timeInBank``, the program's execution
203 returns to the line after the ``yield`` statement, line 12. The
204 customer then prints out the current simulation time and his
205 name. This completes the declaration of the ``Customer`` class.
206
207 Line 21 calls ``initialize()`` which sets up the simulation
208 system ready to receive ``activate`` calls. In line 22, we create
209 a customer, ``c``, with name ``Klaus``. All SimPy Processes have a
210 ``name`` attribute. We ``activate`` ``Klaus`` in line 23
211 specifying the object (``c``) to be activated, the call of the action
212 routine (``c.visit(timeInBank = 10.0)``) and that it is to be activated
213 at time 5 (``at = 5.0``). This will activate
214 ``Klaus`` exactly ``5`` minutes after the current time, in this case
215 after the start of the simulation at ``0.0``. The call of an action
216 routine such as ``c.visit`` can specify the values of arguments, here
217 the ``timeInBank``.
218
219 Finally the call of ``simulate(until=maxTime)`` in line 24 will
220 start the simulation. This will run until the simulation time is
221 ``maxTime`` unless stopped beforehand either by the
222 ``stopSimulation()`` command or by running out of events to execute
223 (as will happen here). ``maxTime`` was set to ``100.0`` in line
224 16.
225
226
227 ..
228 Though we do not do it here, it is also possible to define an
229 ``__init__()`` method for a ``Process`` if you need to give the
230 customer any attributes. Bear in mind that such an ``__init__``
231 method must first call ``Process.__init__(self)`` and can then
232 initialize any instance variables needed.
233
234
235 .. literalinclude:: bankprograms_OO/bank01_OO.py
236
237
238 The short trace printed out by the ``print`` statements shows the
239 result. The program finishes at simulation time ``15.0`` because there are
240 no further events to be executed. At the end of the ``visit`` routine,
241 the customer has no more actions and no other objects or customers are
242 active.
243
244 .. literalinclude:: bankprograms/bank01.out
245
246
247 .. index:: random arrival, bank05
248
249 A Customer arriving at random
250 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
251
252 Now we extend the model to allow our customer to arrive at a random
253 simulated time though we will keep the time in the bank at 10.0, as
254 before.
255
256
257 The change occurs in line 3 of the program and in lines 19, 21,
258 23, 31 and 35. In line 3 we import from the standard
259 Python ``random`` module to give us ``expovariate`` to generate the
260 random time of arrival. We also import the ``seed`` function to
261 initialize the random number stream to allow control of the random
262 numbers. The ``run`` method is given a parameter ``aseed`` for the
263 initial seed (line 19) .In line 31 we provide an initial seed of
264 ``99999``. An exponential random variate, ``t``, is generated in line 23. Note
265 that the Python Random module's ``expovariate`` function uses the rate
266 (here, ``1.0/tMeanArrival``) as the argument. The generated random variate,
267 ``t``, is used in line 24 as the ``at`` argument to the
268 ``activate`` call. ``tMeanArrival`` is assigned a value of ``5.0`` minutes
269 at line 31.
270
271 In line 35, the ``BankModel`` entity is generated and its ``run`` function
272 called with parameter assignment ``aseed=seedVal``.
273
274 ..
275 The change occurs in line 3 of the program and in lines 22,
276 25, and 26. In line 3 we import from the standard
277 Python ``random`` module to give us ``expovariate`` to generate the
278 random time of arrival. We also import the ``seed`` function to
279 initialize the random number stream to allow control of the random
280 numbers. In line 22 we provide an initial seed of ``99999``. An
281 exponential random variate, ``t``, is generated in line 25. Note
282 that the Python Random module's ``expovariate`` function uses the rate
283 (that is, ``1.0/mean``) as the argument. The generated random variate,
284 ``t``, is used in Line 26 as the ``at`` argument to the
285 ``activate`` call.
286
287
288 .. literalinclude:: bankprograms_OO/bank05_OO.py
289
290
291 The result is shown below. The customer now arrives at time
292 10.5809. Changing the seed value would change that time.
293
294 .. literalinclude:: bankprograms/bank05.out
295
296
297 The display looks pretty untidy. In the next example I will try and
298 make it tidier.
299
300
301 .. index:: bank02
302
303 More Customers
304 -------------------------------------
305
306 Our simulation does little so far. To consider a simulation with
307 several customers we return to the simple deterministic model and add
308 more ``Customers``.
309
310 The program is almost as easy as the first example (`A Customer
311 arriving at a fixed time`_). The main change is in lines
312 19-24 where we create, name, and activate three
313 customers. We also increase the maximum simulation time to ``400``
314 (line 29 and referred to in line 25). Observe that we need
315 only one definition of the ``Customer`` class and create several
316 objects of that class. These will act quite independently in this
317 model.
318
319 Each customer stays for a different ``timeInBank`` so, instead of
320 setting a common value for this we set it for each customer. The
321 customers are started at different times (using ``at=``). ``Tony's``
322 activation time occurs before ``Klaus's``, so ``Tony`` will arrive
323 first even though his activation statement appears later in the
324 script.
325
326 As promised, the print statements have been changed to use Python
327 string formatting (lines 10 and 12). The statements look
328 complicated but the output is much nicer.
329
330
331 ..
332 The program is almost as easy as the first example (`A Customer
333 arriving at a fixed time`_). The main change is in lines
334 22-27 where we create, name, and activate three
335 customers. We also increase the maximum simulation time to ``400``
336 (line 16 and referred to in line 29). Observe that we need
337 only one definition of the ``Customer`` class and create several
338 objects of that class. These will act quite independently in this
339 model.
340
341 Each customer stays for a different ``timeInBank`` so, instead of
342 setting a common value for this we set it for each customer. The
343 customers are started at different times (using ``at=``). ``Tony's``
344 activation time occurs before ``Klaus's``, so ``Tony`` will arrive
345 first even though his activation statement appears later in the
346 script.
347
348 As promised, the print statements have been changed to use Python
349 string formatting (lines 10 and 12). The statements look
350 complicated but the output is much nicer.
351
352
353 .. literalinclude:: bankprograms_OO/bank02_OO.py
354
355
356 The trace produced by the program is shown below. Again the
357 simulation finishes before the ``400.0`` specified in the ``simulate``
358 call.
359
360 .. literalinclude:: bankprograms/bank02.out
361
362
363 .. -------------------------------------------------------------
364
365 .. index:: bank03
366
367 Many Customers
368 ~~~~~~~~~~~~~~~~~~~
369
370
371 Another change will allow us to have more customers. As it is
372 tedious to give a specially chosen name to each one, we will
373 call them ``Customer00, Customer01,...`` and use a separate
374 ``Source`` class to create and activate them. To make things clearer
375 we do not use the random numbers in this model.
376
377 .. index:: Source of entities
378
379 The following listing shows the new program. Lines 6-13
380 define a ``Source`` class. Its PEM, here called ``generate``, is
381 defined in lines 9-13. This PEM has a couple of arguments:
382 the ``number`` of customers to be generated and the Time Between
383 Arrivals, ``TBA``. It consists of a loop that creates a stream
384 of numbered ``Customers`` from ``0`` to ``(number-1)``, inclusive. We
385 create a customer and give it a name in line 11. The parameter
386 assignment ``sim = self.sim`` ties the customers to the ``BankModel``
387 to which the ``Source`` belongs. The customer is
388 then activated at the current simulation time (the final argument of
389 the ``activate`` statement is missing so that the default value of
390 ``self.sim.now()``, the current simulation time for the instance of
391 ``BankModel``, is used as the time; here, it is ``0.0``). We also specify
392 how long the customer
393 is to stay in the bank. To keep it simple, all customers stay
394 exactly ``12`` minutes. After each new customer is activated, the
395 ``Source`` holds for a fixed time (``yield hold,self,TBA``)
396 before creating the next one (line 13).
397
398 ``class BankModel(Simulation)`` (line 24) provides a ``run`` method
399 which executes this model consisting of a customer source and the global data.
400 As ``BankModel`` inherits from ``Simulation``, it has its own event list which gets
401 initialized as empty in line 26.
402
403 A ``Source``, ``s``, is created in line 27 and activated at line
404 28 where the number of customers to be generated is set to
405 ``maxNumber = 5`` and the interval between customers to ``ARRint = 10.0``.
406 The parameter assignment ``sim = self`` links the ``Source`` process
407 to this ``BankModel`` instance. Once started at time ``0.0``, ``s`` creates
408 customers at intervals and each customer then operates independently of the others.
409
410 In line 40, a ``BankModel`` object is created and its ``run`` method executed:
411
412 ..
413 The following listing shows the new program. Lines 6-13
414 define a ``Source`` class. Its PEM, here called ``generate``, is
415 defined in lines 9-13. This PEM has a couple of arguments:
416 the ``number`` of customers to be generated and the Time Between
417 Arrivals, ``TBA``. It consists of a loop that creates a sequence
418 of numbered ``Customers`` from ``0`` to ``(number-1)``, inclusive. We
419 create a customer and give it a name in line 11. It is
420 then activated at the current simulation time (the final argument of
421 the ``activate`` statement is missing so that the default value of
422 ``now()`` is used as the time). We also specify how long the customer
423 is to stay in the bank. To keep it simple, all customers stay
424 exactly ``12`` minutes. After each new customer is activated, the
425 ``Source`` holds for a fixed time (``yield hold,self,TBA``)
426 before creating the next one (line 13).
427
428 A ``Source``, ``s``, is created in line 32 and activated at line
429 33 where the number of customers to be generated is set to
430 ``maxNumber = 5`` and the interval between customers to ``ARRint =
431 10.0``. Once started at time ``0.0`` it creates customers at intervals
432 and each customer then operates independently of the others:
433
434
435 .. literalinclude:: bankprograms_OO/bank03_OO.py
436
437
438 The output is:
439
440 .. literalinclude:: bankprograms/bank03.out
441
442
443 .. -------------------------------------------------------------
444
445 Many Random Customers
446 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
447
448 .. index:: bank06
449
450
451 We now extend this model to allow arrivals at random. In simulation this
452 is usually interpreted as meaning that the times between customer
453 arrivals are distributed as exponential random variates. There is
454 little change in our program, we use a ``Source`` object, as before.
455
456 The exponential random variate is generated in line 14 with
457 ``meanTBA`` as the mean Time Between Arrivals and used in line
458 15. Note that this parameter is not exactly intuitive. As already
459 mentioned, the Python ``expovariate`` method uses the *rate* of
460 arrivals as the parameter not the average interval between them. The
461 exponential delay between two arrivals gives pseudo-random
462 arrivals. In this model the first customer arrives at time ``0.0``.
463
464 The ``seed`` method is called to initialize the random number stream
465 in the ``run`` routine of ``BankModel`` (line 30). It uses the value
466 provided by parameter ``aseed``. It is possible to leave this
467 call out but if we wish to do serious comparisons of systems, we must
468 have control over the random variates and therefore control over the
469 seeds. Then we can run identical models with different seeds or
470 different models with identical seeds. We provide the seeds as
471 control parameters of the run. Here a seed is assigned in line 41
472 but it is clear it could have been read in or manually entered on an
473 input form.
474
475 The ``BankModel`` is generated in line 45 and its ``run`` method called with
476 the seed value as parameter.
477
478 ..
479 We now extend this model to allow arrivals at random. In simulation this
480 is usually interpreted as meaning that the times between customer
481 arrivals are distributed as exponential random variates. There is
482 little change in our program, we use a ``Source`` object, as before.
483
484 The exponential random variate is generated in line 14 with
485 ``meanTBA`` as the mean Time Between Arrivals and used in line
486 15. Note that this parameter is not exactly intuitive. As already
487 mentioned, the Python ``expovariate`` method uses the *rate* of
488 arrivals as the parameter not the average interval between them. The
489 exponential delay between two arrivals gives pseudo-random
490 arrivals. In this model the first customer arrives at time ``0.0``.
491
492 The ``seed`` method is called to initialize the random number stream
493 in the ``model`` routine (line 33). It is possible to leave this
494 call out but if we wish to do serious comparisons of systems, we must
495 have control over the random variates and therefore control over the
496 seeds. Then we can run identical models with different seeds or
497 different models with identical seeds. We provide the seeds as
498 control parameters of the run. Here a seed is assigned in line 33
499 but it is clear it could have been read in or manually entered on an
500 input form.
501
502
503 .. literalinclude:: bankprograms_OO/bank06_OO.py
504
505
506
507 This generates the following output:
508
509 .. literalinclude:: bankprograms/bank06.out
510
511
512 .. ---------------------------------------------------------------
513
514 .. index::
515 pair: Resource; queue
516
517
518 A Service counter
519 ------------------
520
521
522 So far, the model bank has been more like an art gallery, the customers
523 entering, looking around, and leaving. Now they are going to require
524 service from the bank clerk. We extend the model to include a service
525 counter which will be modelled as an object of SimPy's ``Resource``
526 class with a single resource unit. The actions of a ``Resource`` are
527 simple: a customer ``requests`` a unit of the resource (a clerk). If
528 one is free he gets service (and removes the unit, i.e., makes it busy).
529 If there is no
530 free clerk the customer joins the queue (managed by the resource
531 object) until it is his turn to be served. As each customer
532 completes service and ``releases`` the unit, the clerk automatically
533 starts serving the next in line. This is done by reactivating that customer's
534 process where it had been blocked.
535
536
537 .. ---------------------------------------------------------------
538
539 .. index:: bank07, Service counter
540
541 One Service counter
542 ~~~~~~~~~~~~~~~~~~~~~~~~~~
543
544 As this model is built with the ``Resource`` class from ``SimPy.Simulation``,
545 it and the related ``request`` and ``release`` verbs are mported, in addition
546 to the imports made in the previous programs
547 (line 2).
548
549 The service counter is created as a ``Resource`` attribute ``self.k``
550 of the ``BankModel`` (line 39). The resource exists in the ``BankModel``,
551 and this is indicated by the parameter assignment ``sim = self``.
552 The ``Source`` PEM ``generate`` can access this attribute by
553 ``self.sim.k``, its ``BankModel``'s resource attribute (line 14).
554
555 The actions involving the ``Counter`` referred to by the parameter
556 ``res`` in the customer's PEM are:
557
558 - the ``yield request`` statement in line 25. If the server is
559 free then the customer can start service immediately and the code
560 moves on to line 26. If the server is busy, the customer is
561 automatically queued by the Resource. When it eventually comes
562 available the PEM moves on to line 26.
563
564 - the ``yield hold`` statement in line 28 where the operation of
565 the service counter is modelled. Here the service time is a fixed
566 ``timeInBank``. During this period the customer is being served
567 and the resource (the counter) is busy.
568
569 - the ``yield release`` statement in line 29. The current
570 customer completes service and the service counter becomes available
571 for any remaining customers in the queue.
572
573 Observe that the service counter is used with the pattern (``yield
574 request..``; ``yield hold..``; ``yield release..``).
575
576 To show the effect of the service counter on the activities of the
577 customers, I have added line 22 to record when the customer
578 arrived and line 26 to record the time between arrival in the
579 bank and starting service. Line 26 is *after* the ``yield
580 request`` command and will be reached only when the request is
581 satisfied. It is *before* the ``yield hold`` that corresponds to the
582 start of service. The variable ``wait`` will record how long the
583 customer waited and will be 0 if he received service at once. This
584 technique of saving the arrival time in a variable is common. So the
585 ``print`` statement also prints out how long the customer waited in
586 the bank before starting service.
587
588 ..
589 The service counter is created as a ``Resource`` (``k``) in line
590 38. This is provided as an argument to the ``Source`` (line
591 45) which, in turn, provides it to each customer it creates and
592 activates (line 14).
593
594 The actions involving the ``counter`` in the customer's PEM are:
595
596 - the ``yield request`` statement in line 25. If the server is
597 free then the customer can start service immediately and the code
598 moves on to line 26. If the server is busy, the customer is
599 automatically queued by the Resource. When it eventually comes
600 available the PEM moves on to line 26.
601
602 - the ``yield hold`` statement in line 28 where the operation of
603 the service counter is modelled. Here the service time is a fixed
604 ``timeInBank``. During this period the customer is being served.
605
606 - the ``yield release`` statement in line 29. The current
607 customer completes service and the service counter becomes available
608 for any remaining customers in the queue.
609
610 Observe that the service counter is used with the pattern (``yield
611 request..``; ``yield hold..``; ``yield release..``).
612
613 To show the effect of the service counter on the activities of the
614 customers, I have added line 22 to record when the customer
615 arrived and line 26 to record the time between arrival in the
616 bank and starting service. Line 26 is *after* the ``yield
617 request`` command and will be reached only when the request is
618 satisfied. It is *before* the ``yield hold`` that corresponds to the
619 start of service. The variable ``wait`` will record how long the
620 customer waited and will be 0 if he received service at once. This
621 technique of saving the arrival time in a variable is common. So the
622 ``print`` statement also prints out how long the customer waited in
623 the bank before starting service.
624
625
626 .. literalinclude:: bankprograms_OO/bank07_OO.py
627
628
629
630 Examining the trace we see that the first two customers get instant service but the others
631 have to wait. We still only have five customers (line 44) so we
632 cannot draw general conclusions.
633
634 .. literalinclude:: bankprograms/bank07.out
635
636
637
638 .. index::
639 Resource, Random service time, bank08
640 pair: M/M/1; queue
641
642 .. ---------------------------------------------------------------
643
644 A server with a random service time
645 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
646
647 This is a simple change to the model in that we retain the single
648 service counter but make the customer service time a random variable. As
649 is traditional in the study of simple queues we first assume an exponential service
650 time and set the mean to ``timeInBank``.
651
652 The service time random variable, ``tib``, is generated in line
653 26 and used in line 27. The argument to be used in the call
654 of ``expovariate`` is not the mean of the distribution,
655 ``timeInBank``, but is the rate ``1.0/timeInBank``.
656
657 We have put together the exeriment data by defining a
658 number of appropriate variables and giving them values. These are in
659 lines 44 to 48.
660
661 ..
662 This is a simple change to the model in that we retain the single
663 service counter but make the customer service time a random variable. As
664 is traditional in the study of simple queues we first assume an exponential service
665 time and set the mean to ``timeInBank``.
666
667 The service time random variable, ``tib``, is generated in line
668 26 and used in line 27. The argument to be used in the call
669 of ``expovariate`` is not the mean of the distribution,
670 ``timeInBank``, but is the rate ``1/timeInBank``.
671
672 We have also collected together a number of constants by defining a
673 number of appropriate variables and giving them values. These are in
674 lines 31 to 42.
675
676
677 .. literalinclude:: bankprograms_OO/bank08_OO.py
678
679
680 And the output:
681
682 .. literalinclude:: bankprograms/bank08.out
683
684
685 This model with random arrivals and exponential service times is an
686 example of an M/M/1 queue and could rather easily be solved
687 analytically to calculate the steady-state mean waiting time and other
688 operating characteristics. (But not so easily solved for its transient
689 behavior.)
690
691 .. ---------------------------------------------------------------
692
693 Several Service Counters
694 -------------------------------------
695
696
697 When we introduce several counters we must decide on a queue
698 discipline. Are customers going to make one queue or are they going to
699 form separate queues in front of each counter? Then there are
700 complications - will they be allowed to switch lines (jockey)? We
701 first consider a single queue with several counters and later consider
702 separate isolated queues. We will not look at jockeying.
703
704
705
706 .. ---------------------------------------------------------------
707
708 .. index:: Resource, several counters, bank09
709
710 Several Counters but a Single Queue
711 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
712
713
714 Here we model a bank whose customers arrive randomly and are to be
715 served at a group of counters, taking a random time for service, where
716 we assume that waiting customers form a single first-in first-out
717 queue.
718
719 The *only* difference between this model and the single-server model
720 is in line 37. We have provided two counters by increasing the
721 capacity of the ``counter`` resource to 2. This value is set in line 50
722 (``Nc = 2``). These *units* of the
723 resource correspond to the two counters. Because both clerks cannot be
724 called ``Karen``, we have used a general name of ``Clerk`` as resource
725 unit.
726
727 ..
728 The *only* difference between this model and the single-server model
729 is in line 42. We have provided two counters by increasing the
730 capacity of the ``counter`` resource to 2. These *units* of the
731 resource correspond to the two counters. Because both clerks cannot be
732 called ``Karen``, we have used a general name of ``Clerk``.
733
734
735 .. literalinclude:: bankprograms_OO/bank09_OO.py
736
737
738 The waiting times in this model are much shorter than those for the
739 single service counter. For example, the waiting time for
740 ``Customer02`` has been reduced from ``51.213`` to ``12.581``
741 minutes. Again we have too few customers processed to draw general
742 conclusions.
743
744 .. literalinclude:: bankprograms/bank09.out
745
746
747
748 .. ---------------------------------------------------------------
749 .. index::
750 pair: Several queues; Resource
751 single: bank10
752
753 Several Counters with individual queues
754 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
755
756 Each counter is now assumed to have its own queue. The programming is
757 more complicated because the customer has to decide which queue to
758 join. The obvious technique is to make each counter a separate
759 resource and it is useful to make a list of resource objects (line
760 56).
761
762 In practice, a customer will join the shortest queue. So we define
763 the Python function, ``NoInSystem(R)`` (lines 17-19) which
764 returns the sum of the number waiting and the number being served for
765 a particular counter, ``R``. This function is used in line 28 to
766 list the numbers at each counter. It is then easy to find which
767 counter the arriving customer should join. We have also modified the
768 trace printout, line 29 to display the state of the system when
769 the customer arrives. We choose the shortest queue in lines
770 30-33 (the variable ``choice``).
771
772 The rest of the program is the same as before.
773
774 ..
775 Each counter is now assumed to have its own queue. The programming is
776 more complicated because the customer has to decide which queue to
777 join. The obvious technique is to make each counter a separate
778 resource and it is useful to make a list of resource objects (line
779 56).
780
781 In practice, a customer will join the shortest queue. So we define
782 the Python function, ``NoInSystem(R)`` (lines 17-19) which
783 returns the sum of the number waiting and the number being served for
784 a particular counter, ``R``. This function is used in line 28 to
785 list the numbers at each counter. It is then easy to find which
786 counter the arriving customer should join. We have also modified the
787 trace printout, line 29 to display the state of the system when
788 the customer arrives. We choose the shortest queue in lines
789 30-32 (the variable ``choice``).
790
791 The rest of the program is the same as before.
792
793
794
795 .. literalinclude:: bankprograms_OO/bank10_OO.py
796
797
798 The results show how the customers choose the counter with the
799 smallest number. Unlucky ``Customer02`` who joins the wrong queue has
800 to wait until ``Customer00`` finishes at time ``55.067``. There are,
801 however, too few arrivals in these runs, limited as they are to five
802 customers, to draw any general conclusions about the relative
803 efficiencies of the two systems.
804
805 .. literalinclude:: bankprograms/bank10.out
806
807
808 .. ---------------------------------------------------------------
809
810 .. index:: Monitors, Gathering statistics, statistics
811
812
813 Monitors and Gathering Statistics
814 -------------------------------------
815
816
817 The traces of output that have been displayed so far are valuable for
818 checking that the simulation is operating correctly but would become
819 too much if we simulate a whole day. We do need to get results from
820 our simulation to answer the original questions. What, then, is the
821 best way to summarize the results?
822
823 One way is to analyze the traces elsewhere, piping the trace output,
824 or a modified version of it, into a *real* statistical program such as
825 *R* for statistical analysis, or into a file for later examination by
826 a spreadsheet. We do not have space to examine this thoroughly here.
827 Another way of presenting the results is to provide graphical
828 output.
829
830 SimPy offers an easy way to gather a few simple statistics such as
831 averages: the ``Monitor`` and ``Tally`` classes. The ``Monitor``
832 records the values of chosen variables as time series.
833 (but see the comments in `Final Remarks`_).
834
835
836
837 .. -------------------------------------------------------------
838
839 .. index::
840 pair: Monitored; queue
841 single: bank11
842
843 The Bank with a Monitor
844 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
845
846 We now demonstrate a ``Monitor`` that records the average waiting
847 times for our customers. We return to the system with random arrivals,
848 random service times and a single queue and remove the old trace
849 statements. In practice, we would make the printouts controlled by a
850 variable, say, ``TRACE`` which is set in the experimental data (or
851 read in as a program option - but that is a different story). This
852 would aid in debugging and would not complicate the data analysis. We
853 will run the simulations for many more arrivals.
854
855 In addition to the imports in the programs shown before, we now have
856 to import the ``Monitor`` class (line 2).
857
858 A Monitor, ``wM``, is created in line 37. We make the monitor an
859 attribute of the ``BankModel`` by the assignment to ``self.wM``.
860 The monitor ``observes`` the
861 waiting time mentioned in line 25. As the monitor is an attribute
862 of the ``BankModel`` to which the customer belongs,
863 ``self.sim.wM`` can refere to it. We run
864 ``maxNumber = 50`` customers (in the call of ``generate`` in line
865 39) and have increased ``maxTime`` to ``1000.0`` minutes.
866
867 ..
868 A Monitor, ``wM``, is created in line 42. It ``observes`` the
869 waiting time mentioned in line 24. We run
870 ``maxNumber=50`` customers (in the call of ``generate`` in line
871 45) and have increased ``maxTime`` to ``1000`` minutes.
872
873
874 .. literalinclude:: bankprograms_OO/bank11_OO.py
875
876 In previous programs, we have generated the ``BankModel``
877 anonymously. Here, we do it differently: we assign the ``BankModel``
878 object to the variable ``experi`` (line 53). This way,
879 we can reference its monitor attribute by ``experi.wM`` (line 58).
880 The average waiting time for 50 customers in this 2-counter system is
881 more reliable (i.e., less subject to random simulation effects) than
882 the times we measured before but it is still not sufficiently reliable for
883 real-world decisions. We should also replicate the runs using different
884 random number seeds. The result of this run is:
885
886 .. literalinclude:: bankprograms/bank11.out
887
888
889
890 .. -------------------------------------------------------------
891
892 .. index::
893 single: Multiple runs, replications, bank12
894 single: Random Number Seed
895 pair: model; function
896
897 Multiple runs
898 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
899
900 To get a number of independent measurements we must replicate the runs
901 using different random number seeds. Each replication must be
902 independent of previous ones so the Monitor and Resources must be
903 nely generated for each run.
904
905 ``model()`` is run for several different random-number seeds to get a set
906 of replications (lines 55-58). The seeds are stored in a list ``seedVals``
907 (line 50). The ``for`` loop walks through this list and runs the model's ``run`` method
908 for each entry.
909
910 Note that the ``bankModel`` is only generated once (line 54). This
911 is sufficient, as the ``run`` method freshly generates an empty event list,
912 a new counter resource, a new monitor, and a new source. This way, all
913 iterations are independent of each other.
914
915 ..
916 To get a number of independent measurements we must replicate the runs
917 using different random number seeds. Each replication must be
918 independent of previous ones so the Monitor and Resources must be
919 redefined for each run. We can no longer allow them to be global
920 objects as we have before.
921
922
923 We will define a function, ``model`` with a parameter ``runSeed`` so
924 that the random number seed can be different for different runs (lines
925 40-50). The contents of the function are the same as the
926 ``Model/Experiment`` section in the previous program except for one
927 vital change.
928
929 This is required since the Monitor, ``wM``, is defined inside the
930 ``model`` function (line 43). A customer can no longer refer to
931 it. In the spirit of quality computer programming we will pass ``wM``
932 as a function argument. Unfortunately we have to do this in two steps,
933 first to the ``Source`` (line 48) and then from the ``Source`` to
934 the ``Customer`` (line 13).
935
936 ``model()`` is run for four different random-number seeds to get a set
937 of replications (lines 54-57).
938
939
940 .. literalinclude:: bankprograms_OO/bank12_OO.py
941
942
943
944 The results show some variation. Remember, though, that the system is still
945 only operating for 50 customers so the system may not be in
946 steady-state.
947
948 .. literalinclude:: bankprograms/bank12.out
949
950
951 .. index::
952 GUI input, Graphical Output,Statistical Output
953 Priorities and Reneging,Other forms of Resource Facilities
954 Advanced synchronization/scheduling commands
955
956
957 Final Remarks
958 -------------------------------------
959
960 This introduction is too long and the examples are getting
961 longer. There is much more to say about simulation with *SimPy* but no
962 space. I finish with a list of topics for further study:
963
964 * **GUI input**. Graphical input of simulation parameters could be an
965 advantage in some cases. *SimPy* allows this and programs using
966 these facilities have been developed (see, for example, program
967 ``MM1.py`` in the examples in the *SimPy* distribution)
968
969 * **Graphical Output**. Similarly, graphical output of results can
970 also be of value, not least in debugging simulation programs and
971 checking for steady-state conditions. SimPlot is useful here.
972
973 * **Statistical Output**. The ``Monitor`` class is useful in
974 presenting results but more powerful methods of analysis are often
975 needed. One solution is to output a trace and read that into a
976 large-scale statistical system such as *R*.
977
978 * **Priorities and Reneging in queues**. *SimPy* allows processes to
979 request units of resources under a priority queue discipline
980 (preemptive or not). It also allows processes to renege from a queue.
981
982 * **Other forms of Resource Facilities**. *SimPy* has two other
983 resource structures: ``Levels`` to hold bulk commodities, and
984 ``Stores`` to contain an inventory of different object types.
985
986 * **Advanced synchronization/scheduling commands**. *SimPy* allows
987 process synchronization by events and signals.
988
989
990
991 Acknowledgements
992 -------------------------------------
993
994 I thank Klaus Muller, Bob Helmbold, Mukhlis Matti and other developers
995 and users of SimPy for improving this document by sending their
996 comments. I would be grateful for further suggestions or
997 corrections. Please send them to: *vignaux* at
998 *users.sourceforge.net*.
999
1000 References
1001 -------------------------------------
1002
1003 - Python website: http://www.Python.org
1004
1005 - SimPy website: http://sourceforge.net/projects/simpy
1006
1007
1008 ..
1009 ------------------------------------------------------
1010
1011
1012 ..
1013 Local Variables:
1014 mode: rst
1015 indent-tabs-mode: nil
1016 sentence-end-double-space: t
1017 fill-column: 70
1018 End: