Debian Codegraph @

docs/source/Tutorials/TheBank2OO.rst

raw
1 .. Tutorials
2
3 .. .. image:: images/sm_SimPy_Logo.png
4 :align: left
5
6 ===============================================================================
7 The Bank Tutorial (OO API) Part 2: More examples of SimPy Simulation
8 ===============================================================================
9
10 :Authors: G A Vignaux, K G Muller
11 :Date: 2010 April
12 :SimPy release: |release|
13 :Python-Version: 2.6 and later
14
15 .. ---------------------------------------------------
16 .. TO DO
17 add example of using SimpyTrace
18 Reneging due to an event
19 Interrupts - YES
20 SimEvents?
21
22 .. ---------------------------------------------------
23
24
25
26 .. highlight:: python
27 :linenothreshold: 5
28
29
30 .. .. contents:: Table Of Contents
31 :depth: 2
32
33 ..
34 1 Introduction
35 2 Priority Customers
36 2.1 Priority Customers without preemption
37 2.2 Priority Customers with preemption
38 3 Balking and Reneging Customers
39 3.1 Balking Customers
40 3.2 Reneging (or abandoning) Customers
41 4 Processes
42 4.1 Interrupting a Process.
43 4.2 ``waituntil`` the Bank door opens
44 4.3 Wait for the doorman to give a signal: ``waitevent``
45 5 Monitors
46 5.1 Plotting a Histogram of Monitor results
47 5.2 Monitoring a Resource
48 5.3 Plotting from Resource Monitors
49 6 Acknowledgements
50 7 References
51
52
53
54 .. .. sectnum::
55 :depth: 2
56
57 .. raw:: latex
58
59 \newpage
60
61 OO API Bank Tutorial version
62 ----------------------------
63
64 This manual is a rework of the *Bank Tutorial Part 2*.
65 Its goal is to show how the simple tutorial models can
66 be written in the advanced OO API.
67
68 .. note:: To contrast the OO API with the procedural
69 SimPy API, the reader should read both "Bank Tutorial Part 2"
70 documents side by side.
71
72 Introduction
73 -------------------------------------
74
75 The first Bank tutorial, The Bank, developed and explained a
76 series of simulation models of a simple bank using SimPy_. In various
77 models, customers arrived randomly, queued up to be served at one or
78 several counters, modelled using the Resource class, and, in one case,
79 could choose the shortest among several queues. It demonstrated the
80 use of the Monitor class to record delays and showed how a ``model()``
81 mainline for the simulation was convenient to execute replications of
82 simulation runs.
83
84 In this extension to The Bank, I provide more examples of SimPy
85 facilities for which there was no room and for some that were
86 developed since it was written. These facilities are generally more
87 complicated than those introduced before. They include queueing with priority,
88 possibly with preemption, reneging, plotting, interrupting, waiting
89 until a condition occurs (``waituntil``) and waiting for events to
90 occur.
91
92 Starting with SimPy 2.0 an object-oriented programmer's interface was
93 added to the package and it is this version that is described here.
94 It is quite compatible with the procedural approach. The object-oriented
95 interface, however, can support the process of developing and extending a
96 simulation model better than the procedural approach.
97
98 .. _SimPy: http://simpy.sourceforge.net/
99
100 The programs are available without line numbers and ready to go, in
101 directory ``bankprograms``. Some have trace statements for
102 demonstration purposes, others produce graphical output to the
103 screen. Let me encourage you to run them and modify them for yourself.
104
105 SimPy itself can be obtained from: http://simpy.sourceforge.net/. It
106 is compatible with Python version 2.3 onwards. The examples in this
107 documentation run with SimPy version 1.5 and later.
108
109 This tutorial should be read with the SimPy Manual and CheatsheetOO at
110 your side for reference.
111
112
113 .. raw:: latex
114
115 \newpage
116
117 Priority Customers
118 -------------------
119
120 In many situations there is a system of priority service. Those
121 customers with high priority are served first, those with low priority
122 must wait. In some cases, preemptive priority will even allow a
123 high-priority customer to interrupt the service of one with a lower
124 priority.
125
126 SimPy implements priority requests with an extra numerical priority
127 argument in the ``yield request`` command, higher values meaning
128 higher priority. For this to operate, the requested Resource must have
129 been defined with ``qType=PriorityQ``. This require importing the ``PriorityQ``
130 class from ``SimPy.Simulation``.
131
132 Priority Customers without preemption
133 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
134
135 .. index:: priority
136
137 In the first example, we modify the program with random arrivals, one
138 counter, and a fixed service time (like ``bank07.py`` in The Bank
139 tutorial) to process a high priority customer. Warning: the ``seedVal``
140 value has been changed to ``98989`` to make the story more exciting.
141
142 The modifications are to the definition of the ``counter`` where we
143 change the ``qType`` and to the ``yield request`` command in the
144 ``visit`` PEM of the customer. We also need to provide each customer
145 with a priority. Since the default is ``priority=0`` this is easy for
146 most of them.
147
148 To observe the priority in action, while all other customers have the
149 default priority of 0, in lines 43 to 44 we create and
150 activate one special customer, ``Guido``, with priority 100 who
151 arrives at time ``23.0`` (line 44). This is to ensure that he arrives
152 after ``Customer03``.
153
154 The ``visit`` customer method has a new parameter, ``P=0`` (line
155 20) which allows us to set the customer priority.
156
157 In lines 39 to 40 the ``BankModel`` 's resource attribute ``k``
158 named ``Counter`` is defined with ``qType=PriorityQ`` so
159 that we can request it with priority (line 25) using the
160 statement ``yield request,self,self.sim.k,P``
161
162 In line 23 we print out the number of customers waiting when each
163 customer arrives.
164
165
166 .. literalinclude:: bankprograms_OO/bank20_OO.py
167
168 The resulting output is as follows. The number of customers in the
169 queue just as each arrives is displayed in the trace. That count does
170 not include any customer in service.
171
172 .. literalinclude:: bankprograms/bank20.out
173
174 .. index:: random arrival, bank20
175
176 Reading carefully one can see that when ``Guido`` arrives
177 ``Customer00`` has been served and left at ``12.000``), ``Customer01``
178 is in service and two (customers 02 and 03) are queueing. ``Guido``
179 has priority over those waiting and is served before them at
180 ``24.000``. When ``Guido`` leaves at ``36.000``, ``Customer02`` starts
181 service.
182
183
184 Priority Customers with preemption
185 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
186
187 .. index::
188 single: priority: preemption
189 single: bank23
190
191 Now we allow ``Guido`` to have preemptive priority. He will displace
192 any customer in service when he arrives. That customer will resume
193 when ``Guido`` finishes (unless higher priority customers
194 intervene). It requires only a change to one line of the program,
195 adding the argument, ``preemptable=True`` to the ``Resource``
196 statement in line 40.
197
198 .. literalinclude:: bankprograms_OO/bank23_OO.py
199
200
201 Though ``Guido`` arrives at the same time, ``23.000``, he no longer
202 has to wait and immediately goes into service, displacing the
203 incumbent, ``Customer01``. That customer had already completed
204 ``23.000-12.000 = 11.000`` minutes of his service. When ``Guido``
205 finishes at ``35.000``, ``Customer01`` resumes service and takes
206 ``36.000-35.000 = 1.000`` minutes to finish. His total service time
207 is the same as before (``12.000`` minutes).
208
209 .. literalinclude:: bankprograms/bank23.out
210
211
212
213 .. raw:: latex
214
215 \newpage
216
217 Balking and Reneging Customers
218 --------------------------------
219
220 .. index:: balking, reneging, abandoning (reneging)
221
222
223 Balking occurs when a customer refuses to join a queue if it is too
224 long. Reneging (or, better, abandonment) occurs if an impatient
225 customer gives up while still waiting and before being served.
226
227 Balking Customers
228 ~~~~~~~~~~~~~~~~~~~~~~
229
230 .. index::
231 single: balking
232 single: bank24
233
234 Another term for a system with balking customers is one where "blocked
235 customers" are "cleared", termed by engineers a BCC system. This is
236 very convenient analytically in queueing theory and formulae developed
237 using this assumption are used extensively for planning communication
238 systems. The easiest case is when no queueing is allowed.
239
240 As an example let us investigate a BCC system with a single server but
241 the waiting space is limited. We will estimate the rate of balking
242 when the maximum number in the queue is set to 1. On arrival into the
243 system the customer must first check to see if there is room. We will
244 need the number of customers in the system or waiting. We could keep a
245 count, incrementing when a customer joins the queue or, since we have
246 a Resource, use the length of the Resource's ``waitQ``. Choosing the
247 latter we test (on line 23). If there is not enough room, we
248 balk, incrementing a class variable ``Customer.numBalking`` at line
249 32 to get the total number balking during the run.
250
251
252 .. literalinclude:: bankprograms_OO/bank24_OO.py
253
254
255 The resulting output for a run of this program showing balking
256 occurring is given below:
257
258 .. literalinclude:: bankprograms/bank24.out
259
260
261 When ``Customer02`` arrives, numbers 00 is already in service and 01
262 is waiting. There is no room so 02 balks. By the vagaries of
263 exponential random numbers, 00 takes a very long time to serve (55.0607
264 minutes) so the first one to find room is number 07 at 73.0765.
265
266
267 Reneging (or abandoning) Customers
268 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
269
270 Often in practice an impatient customer will leave the queue before
271 being served. SimPy can model this *reneging* behaviour using a
272 *compound yield statement*. In such a statement there are two
273 yield clauses. An example is::
274
275 yield (request,self,counter),(hold,self,maxWaitTime)
276
277 The first tuple of this statement is the usual ``yield request``,
278 asking for a unit of ``counter`` Resource. The process will either get
279 the unit immediately or be queued by the Resource. The second tuple is
280 a reneging clause which has the same syntax as a ``yield hold``. The
281 requesting process will renege if the wait exceeds ``maxWaitTime``.
282
283 There is a complication, though. The requesting PEM must discover what
284 actually happened. Did the process get the resource or did it
285 renege? This involves a *mandatory* test of ``self.acquired(``\
286 *resource*\
287 ``)``. In our example, this test is in line 26.
288
289 .. literalinclude:: bankprograms_OO/bank21_OO.py
290
291
292
293 .. literalinclude:: bankprograms/bank21.out
294
295
296 ``Customer01`` arrives after 00 but has only 12 minutes
297 patience. After that time in the queue (at time 14.166) he abandons
298 the queue to leave 02 to take his place. 03 also abandons. 04 finds an
299 empty system and takes the server without having to wait.
300
301 .. ==================================================================
302
303 .. raw:: latex
304
305 \newpage
306
307 Processes
308 ---------------------
309
310 In some simulations it is valuable for one SimPy Process to interrupt
311 another. This can only be done when the *victim* is "active"; that is
312 when it has an event scheduled for it. It must be executing a ``yield
313 hold`` statement.
314
315 A process waiting for a resource (after a ``yield request``
316 statement) is passive and cannot be interrupted by another. Instead
317 the ``yield waituntil`` and ``yield waitevent`` facilities have been
318 introduced to allow processes to wait for conditions set by other
319 processes.
320
321 Interrupting a Process.
322 ~~~~~~~~~~~~~~~~~~~~~~~~~~
323
324 ``Klaus`` goes into the bank to talk to the manager. For clarity we
325 ignore the counters and other customers. During his conversation his
326 cellphone rings. When he finishes the call he continues the
327 conversation.
328
329 In this example, ``call`` is an object of the ``Call`` Process class
330 whose only purpose is to make the cellphone ring after a delay,
331 ``timeOfCall``, an argument to its ``ring`` PEM (line 26).
332
333 ``klaus``, a ``Customer``, is interrupted by the call (line 29).
334 He is in the middle of a ``yield hold`` (line 12). When he exits
335 from that command it is as if he went into a trance when talking to
336 the bank manager. He suddenly wakes up and must check (line 13)
337 to see whether has finished his conversation (if there was no call) or
338 has been interrupted.
339
340 If ``self.interrupted()`` is ``False`` he was not interrupted and
341 leaves the bank (line 21) normally. If it is ``True``, he was
342 interrupted by the call, remembers how much conversation he has left
343 (line 14), resets the interrupt (line 15) and then deals
344 with the call. When he finishes (line 19) he can resume the
345 conversation, with, now we assume, a thoroughly irritated bank manager
346 v(line 20).
347
348
349 .. literalinclude:: bankprograms_OO/bank22_OO.py
350
351
352 .. literalinclude:: bankprograms/bank22.out
353
354
355 As this has no random numbers the results are reasonably clear: the
356 interrupting call occurs at 9.0. It takes ``klaus`` 3 minutes to
357 listen to the message and he resumes the conversation with the bank
358 manager at 12.0. His total time of conversation is 9.0 + 11.0 = 20.0
359 minutes as it would have been if the interrupt had not occurred.
360
361
362 ``waituntil`` the Bank door opens
363 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
364
365 Customers arrive at random, some of them getting to the bank before
366 the door is opened by a doorman. They wait for the door to be opened
367 and then rush in and queue to be served. The door is modeled by an
368 attribute ``door`` of ``BankModel``.
369
370 This model uses the ``waituntil`` yield command. In the program listing
371 the door is initially closed (line 58) and a method to test if
372 it is open is defined at line 54.
373
374 The ``Doorman`` class is defined starting at line 7 and the single
375 ``doorman`` is created and activated at at lines 59 and 60. The
376 doorman waits for an average 10 minutes (line 11) and then
377 opens the door.
378
379 The ``Customer`` class is defined at 24 and a new customer prints out
380 ``Here I am`` on arrival. If the door is still closed, he adds ``but
381 the door is shut`` and settles down to wait (line 35), using the
382 ``yield waituntil`` command. When the door is opened by the doorman the
383 ``dooropen`` state is changed and the customer (and all others waiting
384 for the door) proceed. A customer arriving when the door is open will
385 not be delayed.
386
387
388 .. literalinclude:: bankprograms_OO/bank14_OO.py
389
390
391 An output run for this programs shows how the first three customers
392 have to wait until the door is opened.
393
394 .. literalinclude:: bankprograms/bank14.out
395
396
397 Wait for the doorman to give a signal: ``waitevent``
398 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
399
400 Customers arrive at random, some of them getting to the bank before
401 the door is open. This is controlled by an automatic machine called
402 the doorman which opens the door only at intervals of 30 minutes (it
403 is a very secure bank). The customers wait for the door to be opened
404 and all those waiting enter and proceed to the counter. The door is
405 closed behind them.
406
407 This model uses the ``yield waitevent`` command which requires a
408 ``SimEvent`` attribute for ``BankModel`` to be defined (line 56).
409 The ``Doorman`` class is defined
410 at line 7 and the ``doorman`` is created and activated at at labels
411 56 and 57. The doorman waits for a fixed time (label
412 12) and then tells the customers that the door is open. This is
413 achieved on line 13 by signalling the ``dooropen`` event.
414
415 The ``Customer`` class is defined at 24 and in its PEM, when a
416 customer arrives, he prints out ``Here I am``. If the door is still
417 closed, he adds `"but the door is shut`` and settles down to wait for
418 the door to be opened using the ``yield waitevent`` command (line
419 34). When the door is opened by the doorman (that is, he sends
420 the ``dooropen.signal()`` the customer and any others waiting may
421 proceed.
422
423
424 .. literalinclude:: bankprograms_OO/bank13_OO.py
425
426
427 An output run for this programs shows how the first three customers
428 have to wait until the door is opened.
429
430 .. literalinclude:: bankprograms/bank13.out
431
432
433 .. ==================================================================
434
435 .. raw:: latex
436
437 \newpage
438
439
440 Monitors
441 -------------
442
443 Monitors (and Tallys) are used to track and record values in a
444 simulation. They store a list of [time,value] pairs, one pair being
445 added whenever the ``observe`` method is called. A particularly
446 useful characteristic is that they continue to exist after the
447 simulation has been completed. Thus further analysis of the results
448 can be carried out.
449
450
451 Monitors have a set of simple statistical methods such as ``mean`` and
452 ``var`` to calculate the average and variance of the observed values
453 -- useful in estimating the mean delay, for example.
454
455 They also have the ``timeAverage`` method that calculates the
456 time-weighted average of the recorded values. It determines the total
457 area under the time~value graph and divides by the total time. This is
458 useful for estimating the average number of customers in the bank, for
459 example. There is an *important caveat* in using this method. To
460 estimate the correct time average you must certainly ``observe`` the
461 value (say the number of customers in the system) whenever it changes
462 (as well as at any other time you wish) but, and this is important,
463 observing the *new* value. The *old* value was recorded earlier. In
464 practice this means that if we wish to observe a changing value,
465 ``n``, using the Monitor, ``Mon``, we must keep to the the following
466 pattern::
467
468 n = n+1
469 Mon.observe(n,self.sim.now())
470
471 Thus you make the change (not only increases) and *then* observe the new
472 value. Of course the simulation time ``now()`` has not changed between
473 the two statements.
474
475
476
477 Plotting a Histogram of Monitor results
478 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
479
480 A Monitor can construct a histogram from its data using the
481 ``histogram`` method. In this model we monitor the time in the system
482 for the customers. This is calculated for each customer in line
483 29, using the arrival time saved in line 19. We create the
484 Monitor attribute of ``BankModel``, ``Mon``, at line 39 and the times
485 are ``observed`` at line 30.
486
487 The histogram is constructed from the Monitor, after the simulation
488 has finished, at line 58. The SimPy SimPlot package allows
489 simple plotting of results from simulations. Here we use the SimPlot
490 ``plotHistogram`` method. The plotting routines appear in lines
491 60-64. The ``plotHistogram`` call is in line 61.
492
493 .. literalinclude:: bankprograms_OO/bank17_OO.py
494
495
496
497
498 Monitoring a Resource
499 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
500
501 Now consider observing the number of customers waiting or executing in
502 a Resource. Because of the need to ``observe`` the value after the
503 change but at the same simulation instant, it is impossible to use the
504 length of the Resource's ``waitQ`` directly with a Monitor defined
505 outside the Resource. Instead Resources can be set up with built-in
506 Monitors.
507
508 Here is an example using a Monitored Resource. We intend to observe
509 the average number waiting and active in the ``counter``
510 resource. ``counter`` is defined at line 35 as a ``BankModel`` attribute
511 and we have set
512 ``monitored=True``. This establishes two Monitors: ``waitMon``, to
513 record changes in the numbers waiting and ``actMon`` to record changes
514 in the numbers active in the ``counter``. We need make no further
515 change to the operation of the program as monitoring is then
516 automatic. No ``observe`` calls are necessary.
517
518 After completion of the ``run`` method, we calculate the
519 ``timeAverage`` of both ``waitMon`` and ``actMon`` (lines 53-54).
520 These can then be printed at the end of the program (line 55).
521
522 .. literalinclude:: bankprograms_OO/bank15_OO.py
523
524
525
526
527 Plotting from Resource Monitors
528 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
529
530 Like all Monitors, ``waitMon`` and ``actMon`` in a monitored Resource
531 contain information that enables us to graph the output. Alternative
532 plotting packages can be used; here we use the simple ``SimPy.SimPlot``
533 package just to graph the number of customers waiting for the
534 counter. The program is a simple modification of the one that uses a
535 monitored Resource.
536
537 The SimPlot package is imported at line 3. No major changes are
538 made to the main part of the program except that I commented out the
539 print statements. The changes occur in the ``run`` method from lines
540 38 to 39. The simulation now generates and processes 20
541 customers (line 39). The Monitors of the ``counter`` Resource attribute
542 still exist when the simulation has terminated.
543
544 The additional plotting actions take place in lines 54 to
545 57. Line 55-56 construct a step plot and graphs the
546 number in the waiting queue as a function of time. ``waitMon`` is
547 primarily a list of *[time,value]* pairs which the ``plotStep`` method
548 of the SimPlot object, ``plt`` uses without change. On running the
549 program the graph is plotted; the user has to terminate the plotting
550 ``mainloop`` on the screen.
551
552
553 .. literalinclude:: bankprograms_OO/bank16_OO.py
554
555
556
557
558 .. Some of the following links need changing
559
560 .. _`SimPy`: http://simpy.sourceforge.net/
561 .. _Python: http://www.Python.org
562 .. _`Python web site`: http://www.Python.org
563
564
565
566 Acknowledgements
567 ------------------------------
568
569 I thank Klaus Muller, Bob Helmbold, Mukhlis Matti and the other
570 developers and users of SimPy for improving this document by sending
571 their comments. I would be grateful for any further corrections or
572 suggestions. Please send them to: *vignaux* at
573 *users.sourceforge.net*.
574
575
576 References
577 -------------------------------------
578
579 - Python website: http://www.Python.org
580
581 - SimPy homepage: http://simpy.sourceforge.net/
582
583 - The Bank:
584
585
586 ..
587 ------------------------------------------------------
588
589
590
591 ..
592 Local Variables:
593 mode: rst
594 indent-tabs-mode: nil
595 sentence-end-double-space: t
596 fill-column: 70
597 End:
598