Debian Codegraph @

docs/source/Manuals/SimPyOO_API.rst

raw
1 =============================================================
2 SimPy's Object Oriented API
3 =============================================================
4
5 :Authors: - Klaus Muller <[email protected]>
6 :SimPy release: |release|
7 :Python version: 2.6 and later
8 :Date: |today|
9
10 .. contents:: Contents
11 :depth: 2
12
13 .. highlight:: python
14 :linenothreshold: 12
15
16 Introduction
17 =============
18
19 This document describes the object oriented (OO) programming
20 interface introduced with SimPy 2.0. This
21 is an add-on to the existing API, an alternative API. There is full backward compatibility:
22
23 Motivation
24 -------------
25
26 Many simulation languages support a procedural modelling style. Using them,
27 problems are decomposed into procedures (functions, subroutines) and either
28 represented by general components, such as queues, or represented in code
29 with data structures.
30
31 There are fundamental problems with using the procedural style of
32 modelling and simulation. Procedures do not correspond to real world
33 components. Instead, they correspond to methods and algorithms.
34 Mapping from the real (problem) world to the model and back is difficult
35 and not obvious, particularly for users expert in the problem domain, but
36 not in computer science. Perhaps the greatest limitation of the procedural
37 style is the lack of model extensibility. The only way in this style
38 to change simulation models is through functional extension. One can
39 add structural functionality but not alter any of its basic processes.
40
41 Right from its beginning, SimPy, on the other hand, has supported an
42 **object oriented approach** to simulation modelling.
43 In SimPy, models can be implemented as collections of autonomous,
44 cooperating objects.
45 These objects are self-sufficient and independent. The actions on these
46 objects are tied to the objects and their attributes. The object-oriented
47 capabilities of Python strongly support this encapsulation.
48
49 Why does this matter for simulation models? It helps with the mapping from
50 real-world objects and their activities to modelled objects and activities,
51 and back. This not only reduces the complexity of the models, it also
52 makes for easier validation of models and interpretation of simulation
53 results in real world terms.
54
55 The new API allows different, often more concise, cleaner program patterns.
56 It strongly supports the development of libraries
57 of model components for specific real world domains. It also supports
58 the re-use and extension of models when model specifications change.
59 In particular larger SimPy programs written with the advanced OO API should be
60 easier to maintain and extend. Users are advised to familiarize themselves
61 with this programming paradigm by reading the models in the
62 `SimPyModels` folder. Most of them are provided in two implementations, i.e. in the
63 existing and in the OO API. Similarly, the programs in the Bank tutorials
64 are provided with both APIs.
65
66 The advanced OO API has been developed very elegantly by Stefan Scherfke and
67 Ontje L |uumlaut| nsdorf, starting from SimPy 1.9. Thanks, guys, for this great job!
68
69 .. |uumlaut| unicode:: U+00FC
70 :trim:
71
72 Readers of this document should be familiar with the basics of SimPy and
73 have read at least "Basic SimPy - Manual For First Time Users". They should
74 also know how subclassing is done in Python.
75
76 Basic SimPy OO API Design
77 ==========================
78
79 A class ``Simulation`` has been added to module ``SimPy.Simulation``.
80 ``SimulationTrace``, ``SimulationStep`` and ``SimulationRT`` are subclasses of
81 ``Simulation``. Multiple instances of these classes can co-exist in a SimPy program.
82
83 Backward compatibility
84 -----------------------------
85
86 Since SimPy 2.0, the package offers both the existing procedural API and an
87 object-oriented API
88 where simulation capabilities are provided by instantiating ``Simulation``.
89 ``SimulationTrace``, ``SimulationStep`` or ``SimulationRT`` are subclasses of
90 ``Simulation``.
91
92 Each ``SimulationXX`` instance has its own event list and therefore its own simulation time.
93 A ``SimulationXX`` instance can effectively be considered as a simulated, isolated parallel
94 world. Any *Process*, *Resource*, *Store*, *Level*, *Monitor*, *Tally* or *SimEvent*
95 instance belongs to one and only one world (i.e., ``Simulationxx`` instance).
96
97 The following program shows what this means for API and program structure::
98
99 from SimPy.Simulation import *
100 """Object Oriented SimPy API"""
101
102 ## Model components -------------------------------
103
104 class Car(Process):
105 def run(self,res):
106 yield request,self,res
107 yield hold,self,10
108 yield release,self,res
109 print "Time: %s"%self.sim.now()
110
111 ## Model and Experiment ---------------------------
112
113 s=Simulation()
114 s.initialize()
115 r = Resource(capacity=5,sim=s)
116 auto = Car(sim=s)
117 s.activate(auto,auto.run(res=r))
118 s.simulate(until=100)
119
120 Using the existing API, the following program is semantically the same and also works
121 under the OO version::
122
123 from SimPy.Simulation import *
124 """Traditional SimPy API"""
125
126 ## Model components -------------------------------
127
128 class Car(Process):
129 def run(self,res):
130 yield request,self,res
131 yield hold,self,10
132 yield release,self,res
133 print "Time: %s"%now()
134
135 ## Model and Experiment ---------------------------
136
137 initialize()
138 r = Resource(capacity=5)
139 auto = Car()
140 activate(auto,auto.run(res=r))
141 simulate(until=100)
142
143 This full (backwards) compatibility is achieved by the automatic generation
144 of a *SimulationXX* instance "behind the scenes".
145
146 Models as SimulationXX subclasses
147 -----------------------------------
148
149 The advanced OO API can be used to generate model classes which are SimulationXX subclasses.
150 This ties a model and a SimulationXX instance together beautifully. See the following
151 example::
152
153 ## CarModel.py
154 from SimPy.Simulation import *
155 """Advanced Object Oriented SimPy API"""
156
157 ## Model components -------------------------------
158
159 class Car(Process):
160 def park(self):
161 yield request,self,sim.self.parking
162 yield hold,self,10
163 yield release,self,sim.self.parking
164 print "%s done at %s"%(self.name, self.sim.now())
165
166 ## Model ------------------------------------------
167
168 class Model(Simulation):
169 def __init__(self,name,nrCars,spaces):
170 Simulation.__init__(self)
171 self.name = name
172 self.nrCars = nrCars
173 self.spaces = spaces
174 def runModel(self):
175 ## Initialize Simulation instance
176 self.initialize()
177 self.parking = Resource(name="Parking lot",unitName="spaces",
178 capacity=self.spaces,sim=self)
179 for i in range(self.nrCars):
180 auto = Car(name="Car%s"%i, sim=self)
181 self.activate(auto, auto.park())
182 self.simulate(until=100)
183
184 if __name__=="__main__":
185
186 ## Experiment ----------------------------------
187
188 myModel = Model(name="Experiment 1", nrCars=10, spaces=5)
189 myModel.runModel()
190 print myModel.now()
191
192 class ``Model`` here is a subclass of ``Simulation``. Every model execution, i.e. call to
193 ``runModel``, reinitializes the simulation (creates an empty event list and sets
194 the time to 0) (see line 24). ``runModel`` can thus be called repeatedly for multiple runs of
195 the same experiment setup::
196
197 if __name__=="__main__":
198
199 ## Experiments ---------------------------------
200
201 myModel = Model(name="Experiment 1",nrCars=10,spaces=5)
202 for repetition in range(100):
203
204 ## One Experiment -------------------------------
205
206 myModel.runModel()
207 print myModel.now()
208
209 Model extension by subclassing
210 ---------------------------------
211
212 With the advanced OO API, it is now very easy and clean to extend a model by subclassing. This
213 effectively allows the creation of model libraries.
214
215 For example, the model in the previous example can be extended to one in which also vans
216 compete for parking spaces. This is done by importing the ``CarModel`` module
217 and subclassing ``Model`` as follows::
218
219 ## CarModelExtension.py
220
221 ## Model components -------------------------------
222
223 from CarModel import *
224
225 class Van(Process):
226 def park(self):
227 yield request,self,sim.self.parking
228 yield hold,self,5
229 yield release,self,sim.self.parking
230 print "%s done at %s"%(self.name,self.sim.now())
231
232 ## Model ------------------------------------------
233
234 class ModelExtension(Model):
235 def __init__(self,name,nrCars,capacity,spaces,nrTrucks):
236 Model.__init__(self,name=name,nrCars=nrCars,spaces=spaces)
237 self.nrTrucks = nrTrucks
238
239 def runModel(self):
240 self.initialize()
241 r = Resource(capacity=self.resCapacity,sim=self)
242 for i in range(self.nrCars):
243 auto = Car(name="Car%s"%i,sim=self)
244 self.activate(auto,auto.park())
245 for i in range(self.nrTrucks):
246 truck = Van(name="Van%s"%i,sim=self)
247 self.activate(truck,truck.park())
248 self.simulate(until=100)
249
250 ## Experiment ----------------------------------
251
252 myModel1 = ModelExtension(name="Experiment 2",nrCars=10,spaces=5,nrTrucks=3)
253 myModel1.runModel()
254
255 Let's walk through this:
256
257 *Line 5*:
258 This import makes available all the objects of SimPy.Simulation and the ones defined by
259 the ``CarModel`` module (class ``Car`` and class ``Model``).
260
261 *Lines 7-12*:
262 Addition of a ``Van`` class with a ``park`` PEM.
263
264 *Line 16*:
265 Definition of a subclass ``ModelExtension`` which extends class ``Model``.
266
267 *Lines 17-18*:
268 Initialization of the model class (``Model``) from which ``ModelExtension``
269 is derived. When subclassing a class in Python, this is always necessary:
270 Python does **not** automatically initialize the super-class.
271
272 *Lines 21-30*:
273 Defines a ``runModel`` method for ``ModelExtension`` which also generates
274 and activates ``Van`` objects.
275
276 API changes
277 ============
278
279 Module ``SimPy.Simulation``
280 -----------------------------------
281
282 The only change to the API of module ``SimPy.Simulation``
283 is the addition of class ``Simulation``::
284
285 Module SimPy.Simulation:
286 ################ Unchanged ################
287 ## yield-verb constants --------------------
288 get
289 hold
290 passivate
291 put
292 queueevent
293 release
294 request
295 waitevent
296 waituntil
297 ## version constant ------------------------
298 version
299 ## classes ---------------------------------
300 FatalSimerror
301 Simerror
302 ################ Added ################
303 Simulation
304
305 Thus, after the import::
306
307 from SimPy.Simulation import *
308
309 class ``Simulation`` is available to a program.
310
311 Actually,::
312
313 from SimPy.Simulation import Simulation
314
315 is sufficient and even clearer.
316
317 class ``Simulation``
318 ~~~~~~~~~~~~~~~~~~~~~
319
320 The simulation capabilities of a model are provided by instantiating class
321 ``Simulation`` like this::
322
323 from SimPy.Simulation import *
324
325 aSimulation = Simulation()
326 ## model code follows
327
328 Better OO programming style is actually to define a model class which inherits
329 from ``Simulation``::
330
331 from SimPy.Simulation import *
332
333 class MyModel(Simulation):
334 def run(self):
335 self.initialize()
336 ## model code follows
337
338 myMo = MyModel()
339 myMo.run()
340
341 The ``self.initialize()`` is not really necessary, as the ``Simulation`` instance is
342 initialized at generation time. If method ``run`` for a model (here ``myMo`` ) is
343 executed more than once, e.g. for running a simulation repeatedly, ``self.initialize()``
344 resets the model to an empty event list and simulation time 0.
345
346 Methods of class Simulation
347 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
348
349 class ``Simulation`` has these methods::
350
351 class Simulation:
352 ## Methods ----------------------------------
353 __init__(self)
354 initialize(self)
355 now(self)
356 stopSimulation(self)
357 allEventNotices(self)
358 allEventTimes(self)
359 activate(self, obj, process, at='undefined', delay='undefined', prior=False)
360 reactivate(self, obj, at='undefined', delay='undefined', prior=False)
361 startCollection(self, when=0.0, monitors=None, tallies=None)
362 simulate(self, until=0)
363
364 The semantics and parameters (except for ``self``) of the methods are identical to those of the non-OO
365 ``SimPy.Simulation`` functions of the same name. For example, to get the current
366 simulation time of a Simulation object ``so``, the call is::
367
368 tcurrent = so.now()
369
370 ..
371 New classes
372 ------------
373
374 class ``Simulation``
375 ~~~~~~~~~~~~~~~~~~~~~
376
377 The simulation capabilities are provided by instantiating class ``Simulation``. The three
378 other SimPy run modes (``SimulationTrace``, ``SimulationRT`` and ``SimulationStep``) are
379 subclasses of ``Simulation``.
380
381 Methods of class ``Simulation``
382 ++++++++++++++++++++++++++++++++
383
384 The semantics and parameters of the methods are identical to those of the non-OO
385 ``SimPy.Simulation`` functions of the same name.
386
387 - *initialize*
388
389 - *activate*
390
391 - *reactivate*
392
393 - *simulate*
394
395 - *now*
396
397 - *stopSimulation*
398
399 - *startCollection*
400
401 - *allEventNotices*
402
403 - *allEventTimes*
404
405 Example calls (snippet)::
406
407 from SimPy.Simulation import *
408 s = Simulation()
409 s.initialize()
410 s.simulate(until=100)
411
412 Module ``SimPy.SimulationTrace``
413 ----------------------------------------------
414
415 The only change to the API of module ``SimPy.SimulationTrace``
416 is the addition of class ``SimulationTrace``::
417
418 Module SimPy.SimulationTrace:
419 ################ Unchanged ################
420 ## yield-verb constants --------------------
421 get
422 hold
423 passivate
424 put
425 queueevent
426 release
427 request
428 waitevent
429 waituntil
430 ## version constant ------------------------
431 version
432 ## classes ---------------------------------
433 FatalSimerror
434 Simerror
435 Trace
436 ################ Added ################
437 SimulationTrace
438
439
440 class ``SimulationTrace``
441 ~~~~~~~~~~~~~~~~~~~~~~~~~
442
443 The simulation capabilities of a model with tracing are provided by instantiating class
444 ``SimulationTrace`` like this::
445
446 from SimPy.SimulationTrace import *
447
448 aSimulation = SimulationTrace()
449 ## model code follows
450
451 Again, better OO programming style is actually to define a model class which inherits
452 from Simulation::
453
454 from SimPy.SimulationTrace import *
455
456 class MyModel(SimulationTrace):
457 def run(self):
458 self.initialize()
459 # model code follows
460
461 myMo = MyModel()
462 myMo.run()
463
464 class ``SimulationTrace`` is a subclass of ``Simulation`` and thus
465 provides the same methods, albeit with tracing added.
466
467 The semantics and parameters of the methods are identical to those of the non-OO
468 ``SimPy.SimulationTrace`` functions of the same name.
469
470 Methods and attributes of class SimulationTrace
471 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
472
473 ::
474
475 class SimulationTrace:
476 ## Methods ----------------------------------
477 __init__(self)
478 initialize(self)
479 now(self)
480 stopSimulation(self)
481 allEventNotices(self)
482 allEventTimes(self)
483 activate(self, obj, process, at='undefined', delay='undefined', prior=False)
484 reactivate(self, obj, at='undefined', delay='undefined', prior=False)
485 startCollection(self, when=0.0, monitors=None, tallies=None)
486 simulate(self, until=0)
487 ## trace attribute ---------------------------
488 trace
489
490 Attribute ``trace``
491 ++++++++++++++++++++
492
493 An initialization of class ``SimulationTrace`` generates an instance of
494 class ``Trace``. This becomes an attribute ``trace`` of the ``SimulationTrace``
495 instance.
496
497 ``Trace`` methods
498 +++++++++++++++++++++
499
500 The semantics and parameters of the ``Trace`` methods are identical to those of
501 the non-OO ``SimPy.SimulationTrace`` ``trace`` instance of the same name.
502
503 - trace.start(self)
504
505 Example::
506
507 s.trace.start()
508
509 - trace.stop(self)
510
511 - trace.treset(self)
512
513 - trace.tchange(self, \*\*kmvar)
514
515 - trace.ttext(self,par)
516
517 Example calls (snippet)::
518
519 from SimPy.SimulationTrace import *
520 s = SimulationTrace()
521 s.initialize()
522 s.trace.ttext("Here we go")
523
524 Again, note that you have to qualify the ``trace`` instance (see e.g. the last line
525 of the snippet) with the ``SimulationTrace`` instance, here ``s``.
526
527 Module ``SimPy.SimulationRT``
528 ----------------------------------------------
529
530 class ``SimulationRT``
531 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
532
533 The simulation capabilities plus real time synchronization are provided by instantiating
534 class ``SimulationRT``.
535
536 Methods of class ``SimulationRT``
537 +++++++++++++++++++++++++++++++++++++++
538
539 The ``SimulationRT`` subclass adds two methods to those inherited
540 from ``Simulation``.
541
542 The semantics and parameters of the methods are identical to those of the non-OO
543 ``SimPy.SimulationRT`` functions of the same name.
544
545 - rtnow
546
547 - rtset
548
549 Example calls (snippet)::
550
551 from SimPy.SimulationRT import *
552 class Car(Process):
553 def __init__(self):
554 Process.__init__(self, sim=self.sim)
555 def run(self):
556 print self.sim.rtnow()
557 yield hold,self,10
558
559
560 class ``SimulationStep``
561 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
562
563 The simulation capabilities plus event stepping are provided by instantiating
564 class ``SimulationStep``.
565
566 Methods of class ``SimulationStep``
567 +++++++++++++++++++++++++++++++++++++++
568
569 The ``SimulationStep`` subclass adds three methods to those inherited
570 from ``Simulation``.
571
572 The semantics and parameters of the methods are identical to those of the non-OO
573 ``SimPy.SimulationStep`` functions of the same name.
574
575 - startStepping
576
577 - stopStepping
578
579 - simulateStep
580
581 Example call (snippet)::
582
583 from SimPy.SimulationStep import *
584 s = SimulationStep()
585 s.initialize()
586 s.simulateStep(until=100, callback=myCallBack)
587
588
589 Classes with a ``SimulationXX`` attribute
590 ------------------------------------------
591
592 All SimPy entity (*Process*, *Resource*, *Store*, *Level*, *SimEvent*)
593 and monitoring (*Monitor*, *Tally*) classes have time-related functions.
594 In the OO-API of SimPy, they therefore have a ``.sim`` attribute which is a
595 reference to the *SimulationXX* instance to which they belong. This association
596 is made by providing that reference as a parameter to the constructor of the class.
597
598 .. Important::
599 **All class instances instances must refer to the same SimulationXX instance,
600 i.e., their .sim attributes must have the same value. That value must be the
601 reference to the SimulationXX instance.** Any deviation from this will
602 lead to strange mis-functioning of a SimPy script.
603
604 The constructor calls (signatures) for the classes in question thus change as follows:
605
606 class ``Process``
607 ~~~~~~~~~~~~~~~~~~
608
609 ::
610
611 Process.__init__(self, name = 'a_process', sim = None)
612
613 Example 1 (snippet)::
614
615 class Car(Process):
616 def drive(self):
617 yield hold,self,10
618 print "Arrived at", self.sim.now()
619
620 aSim = Simulation()
621 aSim.initialize()
622 c=Car(name="Mine", sim=aSim)
623
624 Example 2, with an ``__init__`` method (snippet):
625
626 class Car(Process):
627 def __init__(self,name):
628 Process.__init__(self,name=name, sim=self.sim)
629
630 aSim = Simulation()
631 aSim.initialize()
632 c=Car(name="Mine", whichSim=aSim)
633
634 class ``Resource``
635 ~~~~~~~~~~~~~~~~~~~~~
636
637 ::
638
639 Resource.__init__(self, capacity = 1, name = 'a_resource', unitName = 'units',
640 qType = FIFO, preemptable = 0, monitored = False,
641 monitorType = Monitor,sim=None)
642
643 Example (snippet)::
644
645 aSim = Simulation()
646 aSim.initialize()
647 res=Resource(name="Server",sim=aSim)
648
649 classes ``Store`` and ``Level``
650 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
651
652 ::
653
654 Store.__init__(self, name = None, capacity = 'unbounded', unitName = 'units',
655 putQType = FIFO, getQType = FIFO,
656 monitored = False, monitorType = Monitor, initialBuffered = None,
657 sim = None)
658
659 ::
660 Level.__init__(self, name = None, capacity = 'unbounded', unitName = 'units',
661 putQType = FIFO, getQType = FIFO,
662 monitored = False, monitorType = Monitor, initialBuffered = None,
663 sim = None)
664
665 Example (snippet)::
666
667 aSim = Simulation()
668 aSim.initialize()
669 buffer = Store(name="Parts",sim=aSim)
670
671 class ``SimEvent``
672 ~~~~~~~~~~~~~~~~~~~~~~
673
674 ::
675
676 SimEvent.__init__(self, name = 'a_SimEvent', sim = None)
677
678 Example (snippet)::
679
680 aSim = Simulation()
681 aSim.initialize()
682 evt = SimEvent("Boing!", sim=aSim)
683
684 classes ``Monitor`` and ``Tally``
685 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
686
687 ::
688
689 Monitor.__init__(self, name = 'a_Monitor', ylab = 'y', tlab = 't', sim = None)
690
691 ::
692 Tally.__init__(self, name = 'a_Tally', ylab = 'y', tlab = 't', sim = None)
693
694 Example (snippet)::
695
696 aSim = Simulation()
697 aSim.initialize()
698 myMoni = Monitor(name="Counting cars", sim=aSim)
699
700