| 1 |
.. meta:: |
| 2 |
:description: SimPy Python Simulation Language |
| 3 |
:keywords: simulation python stochastic |
| 4 |
|
| 5 |
.. highlight:: python |
| 6 |
:linenothreshold: 5 |
| 7 |
|
| 8 |
===================== |
| 9 |
SimPy Manual |
| 10 |
===================== |
| 11 |
|
| 12 |
:Authors: - Tony Vignaux <[email protected]> |
| 13 |
- Klaus Muller <[email protected]> |
| 14 |
- Bob Helmbold |
| 15 |
:SimPy release: |release| |
| 16 |
:SimPy Web-site: http://simpy.sourceforge.net/ |
| 17 |
:Python-Version: 2.6 and later |
| 18 |
:Date: |today| |
| 19 |
|
| 20 |
|
| 21 |
.. REPLACEMENTS ============================================== |
| 22 |
.. |yrequest| replace:: ``yield request,self,`` |
| 23 |
.. |rrequest| replace:: ``yield (request,self,``\ *r [,P]*\ ``),`` |
| 24 |
.. |init| replace:: ``__init__`` |
| 25 |
.. =========================================================== |
| 26 |
|
| 27 |
.. contents:: Contents |
| 28 |
:depth: 2 |
| 29 |
|
| 30 |
|
| 31 |
This document describes SimPy version |release|. Changes from the previous |
| 32 |
version are listed in `Appendix A0`_. |
| 33 |
|
| 34 |
|
| 35 |
.. note:: |
| 36 |
|
| 37 |
This document does **not** describe the object oriented (OO) API |
| 38 |
which has been added to SimPy with version 2.0. SimPy 2.0 |
| 39 |
is fully backward compatible with previous versions. The |
| 40 |
procedural API and the OO API co-exist happily in SimPy 2.x. |
| 41 |
|
| 42 |
.. [#] The variable ``version``, imported from ``SimPy.Simulation``, |
| 43 |
contains the revision number and date of the current version. |
| 44 |
|
| 45 |
Introduction |
| 46 |
------------------- |
| 47 |
|
| 48 |
SimPy is a Python-based discrete-event simulation system that models |
| 49 |
active components such as messages, customers, trucks, planes by |
| 50 |
parallel processes. It provides a number of tools for the simulation |
| 51 |
programmer including Processes_ to model active entities, three kinds |
| 52 |
of resource facilities (Resources_, Levels_, and Stores_) and ways of |
| 53 |
recording results by using Monitors_ and Tallys_. |
| 54 |
|
| 55 |
The basic active elements of a SimPy model are process objects (i.e., |
| 56 |
objects of a Process class -- see Processes_). As a general practice |
| 57 |
and for brevity we will often refer to both process objects and their |
| 58 |
classes as "processes." Thus, "process" may refer to a Process class |
| 59 |
or to a process object, depending on context. To avoid ambiguity or |
| 60 |
for added emphasis we often explicitly state whether a class or an |
| 61 |
object is intended. In addition we will use "entity" to refer to |
| 62 |
process objects as this is frequently used in the simulation |
| 63 |
literature. Here, though, we restrict it to process objects and it |
| 64 |
will not be used for any other elements in the simulation. |
| 65 |
|
| 66 |
|
| 67 |
During the simulation, Process objects may be delayed for fixed or |
| 68 |
random times, queued at resource facilities, and may be interrupted by |
| 69 |
or interact in other ways with other processes and components. For |
| 70 |
example, Automobiles in a model of a gas station may have to queue |
| 71 |
while waiting for a pump to become available . Once obtaining a pump it |
| 72 |
takes some time to fill before releasing the pump. |
| 73 |
|
| 74 |
|
| 75 |
A SimPy script contains the declaration of one or more Process classes |
| 76 |
and the creation of process objects (entities) from them. Each |
| 77 |
process object executes its *Process Execution Method* (referred to |
| 78 |
later as a PEM_), a method that determines its actions. Each PEM runs |
| 79 |
in parallel with (and may interact with) the PEMs of other process |
| 80 |
objects. |
| 81 |
|
| 82 |
There are three types of resource facilities (Resources_, Levels_, and |
| 83 |
Stores_). Each type models a congestion point where process objects |
| 84 |
may have to queue while waiting to acquire or, in some cases to |
| 85 |
deposit, a resource. |
| 86 |
|
| 87 |
.. index:: Resources |
| 88 |
|
| 89 |
Resources_ have several *resource units*, each of which may be used by |
| 90 |
process objects. Extending the example above, the gas station might be |
| 91 |
modelled as a resource with its pumps as resource units. On receiving |
| 92 |
a request for a pump from a car, the gas station resource |
| 93 |
automatically queues waiting cars until one becomes available. The |
| 94 |
pump resource unit is held by the car until it is released for |
| 95 |
possible use by another car. |
| 96 |
|
| 97 |
.. index:: Levels; definition |
| 98 |
|
| 99 |
Levels_ model the supply and consumption of a homogeneous |
| 100 |
undifferentiated "material." The Level at any time holds an amount of |
| 101 |
material that is fully described by a scalar (real or integer). This |
| 102 |
can be increased or decreased by process objects. For example, a gas |
| 103 |
(petrol) station stores gas in large storage tanks. The tanks can be |
| 104 |
increased by Tanker deliveries and reduced by cars refuelling. A car |
| 105 |
need not return the gas to the Level in contrast to the requirement |
| 106 |
for Resource units. |
| 107 |
|
| 108 |
.. Note that though a Resource must be released by an entity that has |
| 109 |
finished using it, a Level resource need not be released ever though it may |
| 110 |
be put back if that is wanted in the model. On the other hand it |
| 111 |
might never be released at all. It might be replenished by another entity. |
| 112 |
|
| 113 |
.. index:: Stores; definition |
| 114 |
|
| 115 |
Stores_ model the production and consumption of individual items. A |
| 116 |
store hold a list of items. Process objects can insert or remove |
| 117 |
items from the list. For example, surgical procedures (treated as |
| 118 |
process objects) require specific lists of personnel and equipment |
| 119 |
that may be treated as the items in a Store facility such as a |
| 120 |
clinic or hospital. The items held in a Store can be of any Python |
| 121 |
type. In particular they can be process objects, and this may be |
| 122 |
exploited to facilitate modelling Master/Slave relationships. |
| 123 |
|
| 124 |
In addition to the number of free units or quantities, resource |
| 125 |
facilities all hold queues of waiting process objects which are |
| 126 |
operated automatically by SimPy. They also operate a reneging |
| 127 |
mechanism so that a process object can abandon the wait. |
| 128 |
|
| 129 |
.. index:: Monitor,Tally ; definition |
| 130 |
|
| 131 |
Monitors_ and Tallys_ are used to compile statistics as a function of |
| 132 |
time on variables such as waiting times and queue lengths. These |
| 133 |
statistics consist of simple averages and variances, time-weighted |
| 134 |
averages, or histograms. They can be gathered on the queues associated |
| 135 |
with Resources, Levels and Stores. For example we may collect |
| 136 |
data on the average number of cars waiting at a gas station and the |
| 137 |
distribution of their waiting times. Tallys update the current |
| 138 |
statistics as the simulation progresses, but cannot preserve complete |
| 139 |
time-series records. Monitors can preserve complete time-series |
| 140 |
records that may later be used for more advanced post-simulation |
| 141 |
analyses. |
| 142 |
|
| 143 |
|
| 144 |
Before attempting to use SimPy, you should be able to write Python |
| 145 |
code. In particular, you should be able to define and use classes and |
| 146 |
their objects. Python is free and usable on most platforms. We do not |
| 147 |
expound it here. You can find out more about it and download it from |
| 148 |
the Python_ web-site (http://www.Python.org). SimPy requires *Python* |
| 149 |
2.3 or later. |
| 150 |
|
| 151 |
[Return to Top_ ] |
| 152 |
|
| 153 |
Simulation with SimPy |
| 154 |
------------------------- |
| 155 |
|
| 156 |
To use the SimPy simulation system you must import its ``Simulation`` |
| 157 |
module (or one of the `alternatives`_): |
| 158 |
|
| 159 |
``from SimPy.Simulation import *`` |
| 160 |
|
| 161 |
All discrete-event simulation programs automatically maintain the |
| 162 |
current simulation time in a software clock. This cannot be changed by |
| 163 |
the user directly. In SimPy the current clock value is returned by the |
| 164 |
``now()`` function. |
| 165 |
|
| 166 |
At the start of the simulation the software clock is set to 0.0. |
| 167 |
While the simulation program runs, simulation time steps forward from |
| 168 |
one *event* to the next. An event occurs whenever the state of the |
| 169 |
simulated system changes. For example, an event might be the arrival |
| 170 |
or departure of a car from the gas station. |
| 171 |
|
| 172 |
The following statement initializes global simulation variables and |
| 173 |
sets the software clock to zero. It must appear in the script before |
| 174 |
any SimPy process objects are activated. |
| 175 |
|
| 176 |
``initialize( )`` |
| 177 |
|
| 178 |
This is followed by SimPy statements creating and activating process |
| 179 |
objects. Activation of process objects adds events to the simulation |
| 180 |
schedule. Execution of the simulation itself starts with the following |
| 181 |
statement: |
| 182 |
|
| 183 |
``simulate(until=``\ *endtime*\ ``)`` |
| 184 |
|
| 185 |
The simulation starts, and SimPy seeks and executes the first |
| 186 |
scheduled event. Having executed that event, the simulation seeks and |
| 187 |
executes the next event, and so on. |
| 188 |
|
| 189 |
Typically a simulation is terminated when *endtime* is reached but it |
| 190 |
can be stopped at any time by the command: |
| 191 |
|
| 192 |
``stopSimulation( )`` |
| 193 |
|
| 194 |
``now( )`` will then equal the time when this was called. The |
| 195 |
simulation will also stop if there are no more events to execute (so |
| 196 |
``now()`` equals the time the last scheduled event occurred) |
| 197 |
|
| 198 |
After the simulation has stopped, further statements can be executed. |
| 199 |
``now()`` will retain the time of stopping and data held in Monitors |
| 200 |
will be available for display or further analysis. |
| 201 |
|
| 202 |
|
| 203 |
The following fragment shows only the *main* block in a simulation |
| 204 |
program. (Complete, runnable examples are shown in `Example 1`_ and |
| 205 |
`Example 2`_). Here ``Message`` is a (previously defined) Process |
| 206 |
class and ``m`` is defined as an object of that class, that is, a |
| 207 |
particular message. Activating ``m`` has the effect of scheduling at |
| 208 |
least one event by starting the PEM of ``m`` (here called ``go``). |
| 209 |
The ``simulate(until=1000.0)`` statement starts the simulation itself, |
| 210 |
which immediately jumps to the first scheduled event. It will continue |
| 211 |
until it runs out of events to execute or the simulation time reaches |
| 212 |
``1000.0``. When the simulation stops the (previously written) ``Report`` |
| 213 |
function is called to display the results:: |
| 214 |
|
| 215 |
initialize() |
| 216 |
m = Message() |
| 217 |
activate(m,m.go(),at=0.0) |
| 218 |
simulate(until=1000.0) |
| 219 |
|
| 220 |
Report() # report results when the simulation finishes |
| 221 |
|
| 222 |
.. index:: Object Oriented interface |
| 223 |
|
| 224 |
The object-oriented interface |
| 225 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 226 |
|
| 227 |
An object-oriented API interface was added in SimPy 2.0. It is |
| 228 |
described more fully in ``SimPyOO_API``\. It defines a class of |
| 229 |
*Simulation* objects and makes running multiple simulations cleaner |
| 230 |
and easier. It is compatible with the procedural version described in |
| 231 |
this Manual. Using the object-oriented API, the program fragment listed |
| 232 |
at the end of the previous subsection would look like this:: |
| 233 |
|
| 234 |
|
| 235 |
s=Simulation() |
| 236 |
s.initialize() |
| 237 |
m = Message(sim=s) |
| 238 |
s.activate(m,m.go(),at=0.0) |
| 239 |
s.simulate(until=1000.0) |
| 240 |
|
| 241 |
Report() # report results when the simulation finishes |
| 242 |
|
| 243 |
Further examples of the OO style exist in the *SimPyModels* directory |
| 244 |
and the *Bank Tutorial*. |
| 245 |
|
| 246 |
Alternative SimPy simulation libraries |
| 247 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 248 |
|
| 249 |
In addition to *SimPy.Simulation*, SimPy provides four alternative |
| 250 |
simulation libraries which have the basic ``SimPy.Simulation`` |
| 251 |
capabilities, plus additional facilities: |
| 252 |
|
| 253 |
* *SimPy.SimulationTrace* for program tracing: |
| 254 |
With ``from SimPy.SimulationTrace import *``, any SimPy program automatically |
| 255 |
generates detailed event-by-event tracing output. This makes the library |
| 256 |
ideal for program development/testing and for teaching SimPy. |
| 257 |
|
| 258 |
* *SimPy.SimulationRT* for real time synchronization: |
| 259 |
``from SimPy.SimulationRT import *`` facilitates synchronizing simulation |
| 260 |
time and real (wall-clock) time. This capability can be used to implement, |
| 261 |
e.g., interactive game applications or to demonstrate a model's execution |
| 262 |
in real time. |
| 263 |
|
| 264 |
* *SimPy.SimulationStep* for event-stepping through a simulation: |
| 265 |
The import ``from SimPy.SimulationStep import *`` provides an API for |
| 266 |
stepping through a simulation event by event. This can assist with |
| 267 |
debugging models, interacting with them on an event-by-event basis, |
| 268 |
getting event-by-event output from a model (e.g. for plotting purposes), |
| 269 |
etc. |
| 270 |
|
| 271 |
* *SimPy.SimulationGUIDebug* for event-stepping through a simulation |
| 272 |
with a GUI: ``from SimPy.SimulationGUIDebug import *`` provides an |
| 273 |
API for stepping through a simulation event-by-event, with a GUI |
| 274 |
for user control. The event list, Process and Resource objects are |
| 275 |
shown in windows. This is useful for debugging models and for teaching |
| 276 |
discrete event simulation with SimPy. |
| 277 |
|
| 278 |
[Return to Top_ ] |
| 279 |
|
| 280 |
.. ================================================================== |
| 281 |
|
| 282 |
.. index:: Process |
| 283 |
|
| 284 |
Processes |
| 285 |
------------------- |
| 286 |
|
| 287 |
The active objects for discrete-event simulation in SimPy are process |
| 288 |
objects -- instances of some class that inherits from SimPy's Process |
| 289 |
class. |
| 290 |
|
| 291 |
For example, if we are simulating a computing network we might model |
| 292 |
each message as an object of the class ``Message``. When message |
| 293 |
objects arrive at the computing network they make transitions between |
| 294 |
nodes, wait for service at each one, are served for some time, and |
| 295 |
eventually leave the system. The ``Message`` class specifies all the |
| 296 |
actions of each message in its Process Execution Method (PEM). |
| 297 |
Individual message objects are created as the simulation runs, and |
| 298 |
their evolutions are directed by the ``Message`` class's PEM. |
| 299 |
|
| 300 |
.. index:: Process; defining |
| 301 |
|
| 302 |
Defining a process |
| 303 |
~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 304 |
|
| 305 |
Each Process class inherits from SimPy's ``Process`` class. For example |
| 306 |
the header of the definition of a new ``Message`` Process class would |
| 307 |
be: |
| 308 |
|
| 309 |
``class Message(Process):`` |
| 310 |
|
| 311 |
.. index:: Process Execution Method;PEM |
| 312 |
|
| 313 |
At least one Process Execution Method (PEM) must be defined in each |
| 314 |
Process class [#]_. A PEM may have arguments in addition to the required |
| 315 |
``self`` argument that all methods must have. Naturally, other |
| 316 |
methods and, in particular, an ``__init__`` method, may be defined. |
| 317 |
|
| 318 |
.. [#] More than one can be defined but only one can be executed by |
| 319 |
any process object. |
| 320 |
|
| 321 |
.. Add a paragraph about the standard PEM name ACTIONS |
| 322 |
|
| 323 |
.. _PEM: |
| 324 |
|
| 325 |
* ``A Process Execution Method (PEM)`` defines the actions that are |
| 326 |
performed by its process objects. Each PEM must contain at least one |
| 327 |
of the ``yield`` statements, described later. This makes it a Python |
| 328 |
generator function so that it has resumable execution -- it can be |
| 329 |
restarted again after the yield statement without losing its current |
| 330 |
state. A PEM may have any name of your choice. For example it may |
| 331 |
be called ``execute( )`` or ``run( )``. |
| 332 |
|
| 333 |
.. index:: yield ; definition |
| 334 |
|
| 335 |
"The ``yield`` statements are simulation commands which affect an |
| 336 |
ongoing life-cycle of Process objects. These statements control the |
| 337 |
execution and synchronization of multiple processes. They can delay |
| 338 |
a process, put it to sleep, request a shared resource or provide a |
| 339 |
resource. They can add new events on the simulation event schedule, |
| 340 |
cancel existing ones, or cause processes to wait for a state |
| 341 |
change." |
| 342 |
|
| 343 |
|
| 344 |
For example, here is a the Process Execution Method, ``go(self)``, |
| 345 |
for the ``Message`` class. Upon activation it prints out the current |
| 346 |
time, the message object's identification number and the word |
| 347 |
"Starting". After a simulated delay of 100.0 time units (in the |
| 348 |
``yield hold, ...`` statement) it announces that this message object |
| 349 |
has "Arrived":: |
| 350 |
|
| 351 |
def go(self): |
| 352 |
print now(), self.i, 'Starting' |
| 353 |
yield hold,self,100.0 |
| 354 |
print now(), self.i, 'Arrived' |
| 355 |
|
| 356 |
A process object's PEM starts execution when the object is |
| 357 |
activated, provided the ``simulate(until= ...)`` statement has been |
| 358 |
executed. |
| 359 |
|
| 360 |
|
| 361 |
* **__init__(self, ...)**, where *...* indicates method |
| 362 |
arguments. This method initializes the process object, setting |
| 363 |
values for some or all of its attributes. As for any sub-class in |
| 364 |
Python, the first line of this method must call the ``Process`` class's |
| 365 |
``__init__( )`` method in the form: |
| 366 |
|
| 367 |
``Process.__init__(self)`` |
| 368 |
|
| 369 |
You can then use additional commands to initialize attributes of the |
| 370 |
Process class's objects. You can also override the standard ``name`` |
| 371 |
attribute of the object. |
| 372 |
|
| 373 |
The ``__init__( )`` method is always called whenever you create a |
| 374 |
new process object. If you do not wish to provide for any attributes |
| 375 |
other than a ``name``, the ``__init__`` method may be dispensed |
| 376 |
with. An example of an ``__init__( )`` method is shown in the |
| 377 |
example below. |
| 378 |
|
| 379 |
|
| 380 |
.. index:: entity;creation |
| 381 |
pair: process; object creation |
| 382 |
|
| 383 |
Creating a process object |
| 384 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 385 |
|
| 386 |
An entity (process object) is created in the usual Python manner by |
| 387 |
calling the class. Process classes have a single argument, ``name`` |
| 388 |
which can be specified if no |init| method is defined. It defaults to |
| 389 |
``'a_process'``. It can be over-ridden if an |init| method is defined. |
| 390 |
|
| 391 |
For example to create a new ``Message`` object with a name |
| 392 |
``Message23``: |
| 393 |
|
| 394 |
``m = Message(name="Message23")`` |
| 395 |
|
| 396 |
|
| 397 |
-------- |
| 398 |
|
| 399 |
.. note:: When working through this and all other SimPy manuals, |
| 400 |
the reader is encouraged to type in, run and experiment with |
| 401 |
all examples as she goes. No better way of learning exists |
| 402 |
than **doing**! A suggestion: if you want to see how a SimPy |
| 403 |
model is being executed, *trace* it by replacing `from SimPy.Simulation |
| 404 |
import *` with `from SimPy.SimulationTrace import *`. |
| 405 |
Any Python environment is suitable -- an interactive Python session, |
| 406 |
IDLE, IPython, Scite . . . |
| 407 |
|
| 408 |
.. index:: example;message |
| 409 |
|
| 410 |
.. _`Example 1`: |
| 411 |
|
| 412 |
**Example 1**: This is is a complete, runnable, SimPy script. We |
| 413 |
declare a ``Message`` class and define an ``__init__( )`` method and |
| 414 |
a PEM called ``go( )``. The ``__init__( )`` method provide an |
| 415 |
instance variables of an identification number and message length. |
| 416 |
We do not actually use the ``len`` attribute in this example. |
| 417 |
|
| 418 |
Two ``messages``, ``p1`` and ``p2`` are created. ``p1`` and ``p2`` |
| 419 |
are activated to start at simulation times 0.0 and 6.0, |
| 420 |
respectively. Nothing happens until the ``simulate(until=200)`` |
| 421 |
statement. When both messages have finished (at time |
| 422 |
6.0+100.0=106.0) there will be no more events so the simulation will |
| 423 |
stop at that time: |
| 424 |
|
| 425 |
.. include:: programs/message.py |
| 426 |
:literal: |
| 427 |
|
| 428 |
Running this program gives the following output: |
| 429 |
|
| 430 |
.. include:: programs/message.out |
| 431 |
:literal: |
| 432 |
|
| 433 |
------------ |
| 434 |
|
| 435 |
Elapsing time in a Process |
| 436 |
~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 437 |
|
| 438 |
A PEM_ uses the ``yield hold`` command to temporarily delay a process |
| 439 |
object's operations. |
| 440 |
|
| 441 |
.. index:: yield;hold |
| 442 |
.. index:: hold; yield |
| 443 |
|
| 444 |
yield hold |
| 445 |
++++++++++++ |
| 446 |
|
| 447 |
``yield hold,self,``\ *t* |
| 448 |
|
| 449 |
Causes the process object to delay *t* time units [#]_. After the |
| 450 |
delay, it continues with the next statement in its PEM. During |
| 451 |
the ``hold`` the object's operations are suspended. |
| 452 |
|
| 453 |
.. [#] unless it is further delayed by being interrupted_. |
| 454 |
|
| 455 |
This is used to model any elapsed time an entity might be involved |
| 456 |
in. For example while it is passively being provided with service. |
| 457 |
|
| 458 |
.. |
| 459 |
* ``yield passivate,self`` suspends the process object's operations |
| 460 |
until reactivated by explicit command (which must be issued by a |
| 461 |
different process object). |
| 462 |
|
| 463 |
------ |
| 464 |
|
| 465 |
.. index:: example;shopping |
| 466 |
|
| 467 |
.. _`Example 2`: |
| 468 |
|
| 469 |
**Example 2:** In this example the Process Execution Method, |
| 470 |
``buy``, has an extra argument, ``budget``: |
| 471 |
|
| 472 |
.. include:: programs/shopping.py |
| 473 |
:literal: |
| 474 |
|
| 475 |
------ |
| 476 |
|
| 477 |
.. ================================================================= |
| 478 |
|
| 479 |
Starting and stopping SimPy Process Objects |
| 480 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 481 |
|
| 482 |
A process object is "passive" when first created, i.e., it has no |
| 483 |
scheduled events. It must be *activated* to start its Process |
| 484 |
Execution Method. To activate an instance of a Process class you can |
| 485 |
use either the ``activate`` function or the ``start`` method of the |
| 486 |
Process. (see the Glossary_ for an explanation of the modified Backus-Naur Form (BNF) |
| 487 |
notation used). |
| 488 |
|
| 489 |
.. index:: activate |
| 490 |
single: process object; activation |
| 491 |
|
| 492 |
activate |
| 493 |
+++++++++ |
| 494 |
|
| 495 |
.. |arguments| replace:: \ ``[,{at=now()|delay=0}][,prior=False])`` |
| 496 |
|
| 497 |
.. - ``activate(``\ *p, p.pemname([args])*\ ``[,{at=`` *t* ``|delay=``\ *period*\ ``}][,prior=False])`` |
| 498 |
|
| 499 |
- ``activate(``\ *p, p.pemname([args])*\ |arguments| |
| 500 |
|
| 501 |
activates process object *p*, provides its Process Execution Method |
| 502 |
*p.pemname( )* with arguments *args* and possibly assigns values to the |
| 503 |
other optional parameters. The default is to activate at the current |
| 504 |
time (``at=now( )``) with no delay (``delay=0.0``) and ``prior`` set to |
| 505 |
``False``. You may assign other values to ``at``, ``delay``, and ``prior``. |
| 506 |
|
| 507 |
Example: to activate a process object, ``cust`` with name |
| 508 |
``cust001`` at time 10.0 using a PEM called ``lifetime``:: |
| 509 |
|
| 510 |
activate(cust,cust.lifetime(name='cust001'),at=10.0) |
| 511 |
|
| 512 |
|
| 513 |
However, ``delay`` overrides ``at``, in the sense that when a |
| 514 |
``delay=``\ *period* clause is included, then activation occurs at |
| 515 |
``now( )`` or ``now( )+``\ *period* (whichever is larger), irrespective of |
| 516 |
what value of *t* is assigned in the ``at=``\ *t* clause. This is true |
| 517 |
even when the value of *period* in the delay clause is zero, or |
| 518 |
even negative. So it is better and clearer to choose one (or |
| 519 |
neither) of ``at=``\ *t* and ``delay=``\ *period*, but not both. |
| 520 |
|
| 521 |
If you set ``prior=True``, then process object *p* will be |
| 522 |
activated *before* any others that happen to be scheduled for |
| 523 |
activation at the same time. So, if several process objects are |
| 524 |
scheduled for activation at the same time and all have |
| 525 |
``prior=True``, then the last one scheduled will actually be the |
| 526 |
first to be activated, the next-to-last of those scheduled, the |
| 527 |
second to be activated, and so forth. |
| 528 |
|
| 529 |
Retroactive activations that attempt to activate a process |
| 530 |
object before the current simulation time terminate the |
| 531 |
simulation with an error report. |
| 532 |
|
| 533 |
.. index:: |
| 534 |
single: process object; start |
| 535 |
|
| 536 |
start |
| 537 |
+++++++++ |
| 538 |
|
| 539 |
An alternative to ``activate()`` function is the ``start`` |
| 540 |
method. There are a number of ways of using it: |
| 541 |
|
| 542 |
- *p.*\ ``start(``\ *p.pemname([args])*\ |arguments| |
| 543 |
|
| 544 |
is an alternative to the ``activate`` statement. *p* is a Process |
| 545 |
object. The generator function, *pemname*, can have any |
| 546 |
identifier (such as ``run``, ``life-cycle``, etc). It can have |
| 547 |
parameters. |
| 548 |
|
| 549 |
For example, to activate the process object ``cust`` using the PEM |
| 550 |
with identifier, ``lifetime`` at time 10.0 we would use:: |
| 551 |
|
| 552 |
cust.start(cust.lifetime(name='cust001'),at=10.0) |
| 553 |
|
| 554 |
- *p.*\ ``start([``\ *p.*\ ``ACTIONS()]`` |arguments| |
| 555 |
|
| 556 |
if ``p`` is a Process object and the generator function is given |
| 557 |
the *standard identifier*, ``ACTIONS``. ``ACTIONS``, is |
| 558 |
recognized as a Process Execution Method. It may *not* have |
| 559 |
parameters. The call *p.*\ ``ACTIONS()`` is optional. |
| 560 |
|
| 561 |
For example, to activate the process object ``cust`` with the standard |
| 562 |
PEM identifier ``ACTIONS`` at time 10.0, the following are |
| 563 |
equivalent (and the second version is more convenient):: |
| 564 |
|
| 565 |
cust.start(cust.ACTIONS(), at=10.0) |
| 566 |
cust.start(at=10.0) |
| 567 |
|
| 568 |
|
| 569 |
- An *anonymous* instance of Process class *PR* can be created and |
| 570 |
activated in one command using ``start`` with the standard PEM |
| 571 |
identifier, ``ACTIONS``. |
| 572 |
|
| 573 |
*PR.*\ ``([args]).start(`` |arguments| |
| 574 |
|
| 575 |
Here, *PR* is the identifier for the Process class and not for a |
| 576 |
Process object as was *p*, in the statements above. The generator |
| 577 |
method ``ACTIONS`` may *not* have parameters. |
| 578 |
|
| 579 |
For example, if ``Customer`` is a SimPy Process class we can create |
| 580 |
and activate an anonymous instance at time 10.0:: |
| 581 |
|
| 582 |
Customer(name='cust001').start(at=10.0) |
| 583 |
|
| 584 |
|
| 585 |
You can use the ``passivate``, ``reactivate``, or ``cancel`` commands to |
| 586 |
control Process objects. |
| 587 |
|
| 588 |
.. index:: |
| 589 |
pair: yield;passivate |
| 590 |
single: sleep |
| 591 |
|
| 592 |
passivate |
| 593 |
++++++++++++++ |
| 594 |
|
| 595 |
- ``yield passivate,self`` |
| 596 |
|
| 597 |
suspends the process object itself. It becomes "passive". To get |
| 598 |
it going again another process must ``reactivate`` it. |
| 599 |
|
| 600 |
.. index:: yield;reactivate |
| 601 |
.. index:: reactivate |
| 602 |
|
| 603 |
reactivate |
| 604 |
++++++++++++ |
| 605 |
|
| 606 |
- ``reactivate(``\ *p*\ |arguments| |
| 607 |
|
| 608 |
reactivates a passive process object, *p*. It becomes |
| 609 |
"active". The optional parameters work as for ``activate``. A |
| 610 |
process object cannot reactivate itself. To temporarily suspend |
| 611 |
itself it must use ``yield hold,self,t`` instead. |
| 612 |
|
| 613 |
.. index:: yield;cancel |
| 614 |
.. index:: cancel |
| 615 |
|
| 616 |
cancel |
| 617 |
+++++++++++ |
| 618 |
|
| 619 |
- ``self.cancel(``\ *p*\ ``)`` |
| 620 |
|
| 621 |
deletes all scheduled future events for process object *p*. A |
| 622 |
process cannot ``cancel`` itself. If that is required, use |
| 623 |
``yield passivate,self`` instead. Only "active" process objects |
| 624 |
can be canceled. |
| 625 |
|
| 626 |
A process object is "terminated" after all statements in its process |
| 627 |
execution method have been completed. If the object is still |
| 628 |
referenced by a variable, it becomes just a data container. This can be useful for |
| 629 |
extracting information. Otherwise, it is automatically destroyed. |
| 630 |
|
| 631 |
Even activated process objects will not start operating until the |
| 632 |
``simulate(until=``\ *endtime*\ ``)`` statement is executed. This starts the |
| 633 |
simulation going and it will continue until time *endtime* (unless it runs |
| 634 |
out of events to execute or the command ``stopSimulation( )`` is |
| 635 |
executed). |
| 636 |
|
| 637 |
------------ |
| 638 |
|
| 639 |
.. an example to illustrate yield hold, perhaps. |
| 640 |
|
| 641 |
.. index:: example;firework |
| 642 |
|
| 643 |
.. _`Example 3`: |
| 644 |
|
| 645 |
**Example 3** This simulates a firework with a time fuse. We have put |
| 646 |
in a few extra ``yield hold`` commands for added suspense. |
| 647 |
|
| 648 |
.. include:: programs/firework.py |
| 649 |
:literal: |
| 650 |
|
| 651 |
|
| 652 |
Here is the output. No formatting was attempted so it looks a bit |
| 653 |
ragged: |
| 654 |
|
| 655 |
.. include:: programs/firework.out |
| 656 |
:literal: |
| 657 |
|
| 658 |
|
| 659 |
------------ |
| 660 |
|
| 661 |
.. index:: source;example |
| 662 |
|
| 663 |
A source fragment |
| 664 |
+++++++++++++++++++++ |
| 665 |
|
| 666 |
.. Perhaps move this earlier and use it as a further example of yield |
| 667 |
hold |
| 668 |
|
| 669 |
One useful program pattern is the *source*. This is a process object |
| 670 |
with a Process Execution Method (PEM) that sequentially generates and activates |
| 671 |
other process objects -- it is a source of other process |
| 672 |
objects. Random arrivals can be modelled using random intervals |
| 673 |
between activations. |
| 674 |
|
| 675 |
------------ |
| 676 |
|
| 677 |
.. index:: example;source |
| 678 |
|
| 679 |
.. _`Example 4`: |
| 680 |
|
| 681 |
**Example 4: A source**. Here a source creates and activates a series of |
| 682 |
customers who arrive at regular intervals of 10.0 units of time. This |
| 683 |
continues until the simulation time exceeds the specified ``finishTime`` |
| 684 |
of 33.0. (Of course, to model customers with random inter-arrival |
| 685 |
times the ``yield hold`` statement would use a random variate, such as |
| 686 |
``expovariate( )``, instead of the constant 10.0 inter-arrival time used |
| 687 |
here.) The following example assumes that the ``Customer`` class has |
| 688 |
previously been defined with a PEM called ``run`` that does not require |
| 689 |
any arguments:: |
| 690 |
|
| 691 |
class Source(Process): |
| 692 |
|
| 693 |
def execute(self, finish): |
| 694 |
while now() < finish: |
| 695 |
c = Customer() # create a new customer object, and |
| 696 |
# activate it (using default parameters) |
| 697 |
activate(c, c.run()) |
| 698 |
print('%s %s) % (now(), 'customer') |
| 699 |
yield hold, self, 10.0 |
| 700 |
|
| 701 |
initialize() |
| 702 |
g = Source() # create the Source object, g, |
| 703 |
# and activate it |
| 704 |
activate(g, g.execute(finish=33.0), at=0.0) |
| 705 |
simulate(until=100) |
| 706 |
|
| 707 |
------------ |
| 708 |
|
| 709 |
.. index:: asynchronous; interrupt |
| 710 |
|
| 711 |
Asynchronous interruptions |
| 712 |
~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 713 |
|
| 714 |
An active process object can be interrupted by another but cannot |
| 715 |
interrupt itself. |
| 716 |
|
| 717 |
.. index:: interrupt |
| 718 |
|
| 719 |
interrupt |
| 720 |
+++++++++ |
| 721 |
|
| 722 |
- ``self.interrupt(victim)`` |
| 723 |
|
| 724 |
The *interrupter* process object uses its ``interrupt`` method to |
| 725 |
interrupt the *victim* process object. The interrupt is just a |
| 726 |
*signal*. After this statement, the *interrupter* process object |
| 727 |
continues its PEM. |
| 728 |
|
| 729 |
For the interrupt to have an immediate effect, the *victim* process |
| 730 |
object must be *active* -- that is it must have an event scheduled |
| 731 |
for it (that is, it is "executing" a ``yield hold`` ). If the |
| 732 |
*victim* is not active (that is, it is either *passive* or |
| 733 |
*terminated*) the interrupt has no effect. For example, process |
| 734 |
objects queuing for resource facilities cannot be interrupted |
| 735 |
because they are *passive* during their queuing phase. |
| 736 |
|
| 737 |
If interrupted, the *victim* returns from its ``yield hold`` statement |
| 738 |
prematurely. It must then check to see if it has been interrupted by |
| 739 |
calling: |
| 740 |
|
| 741 |
.. index:: interrupted |
| 742 |
|
| 743 |
interrupted |
| 744 |
+++++++++++++ |
| 745 |
|
| 746 |
- ``self.interrupted( )`` |
| 747 |
|
| 748 |
which returns ``True`` if it has been interrupted. The *victim* can |
| 749 |
then either continue in the current activity or switch to an |
| 750 |
alternative, making sure it tidies up the current state, such as |
| 751 |
releasing any resources it owns. |
| 752 |
|
| 753 |
.. index:: interruptCause |
| 754 |
pair: interrupted;cause |
| 755 |
|
| 756 |
.. index:: interruptedCause |
| 757 |
|
| 758 |
interruptCause |
| 759 |
++++++++++++++++ |
| 760 |
|
| 761 |
- ``self.interruptCause`` |
| 762 |
|
| 763 |
when the *victim* has been interrupted, ``self.interruptCause`` is a |
| 764 |
reference to the *interrupter* object. |
| 765 |
|
| 766 |
.. index:: interruptLeft |
| 767 |
|
| 768 |
interruptLeft |
| 769 |
+++++++++++++ |
| 770 |
|
| 771 |
- ``self.interruptLeft`` |
| 772 |
|
| 773 |
gives the time remaining in the interrupted ``yield hold``. The |
| 774 |
interruption is reset (that is, "turned off") at the *victim's* |
| 775 |
next call to a ``yield hold``. |
| 776 |
|
| 777 |
|
| 778 |
..index:: interruptReset |
| 779 |
|
| 780 |
interruptReset |
| 781 |
++++++++++++++++ |
| 782 |
|
| 783 |
- ``self.interruptReset( )`` |
| 784 |
|
| 785 |
will reset the interruption. |
| 786 |
|
| 787 |
It may be helpful to think of an interruption signal as instructing |
| 788 |
the *victim* to determine whether it should interrupt itself. If the |
| 789 |
*victim* determines that it should interrupt itself, it then becomes |
| 790 |
responsible for making any necessary readjustments -- not only to |
| 791 |
itself but also to any other simulation components that are |
| 792 |
affected. (The *victim* must take responsibility for these |
| 793 |
adjustments, because it is the only simulation component that "knows" |
| 794 |
such details as whether or not it is interrupting itself, when, and |
| 795 |
why.) |
| 796 |
|
| 797 |
----------- |
| 798 |
|
| 799 |
.. index:: example;bus |
| 800 |
.. index:: example;breakdown |
| 801 |
|
| 802 |
.. _`Example 5`: |
| 803 |
|
| 804 |
**Example 5**. A simulation with interrupts. A bus is subject to |
| 805 |
breakdowns that are modelled as interrupts caused by a ``Breakdown`` |
| 806 |
process. Notice that the ``yield hold,self,tripleft`` statement may |
| 807 |
be interrupted, so if the ``self.interrupted()`` test returns ``True`` |
| 808 |
a reaction to it is required. Here, in addition to delaying the bus |
| 809 |
for repairs, the reaction includes scheduling the next breakdown. In |
| 810 |
this example the ``Bus`` Process class does not require an |
| 811 |
``__init__()`` method: |
| 812 |
|
| 813 |
.. include:: programs/breakdown.py |
| 814 |
:literal: |
| 815 |
|
| 816 |
The output from this example: |
| 817 |
|
| 818 |
.. include:: programs/breakdown.out |
| 819 |
:literal: |
| 820 |
|
| 821 |
|
| 822 |
The bus finishes at 1060 but the simulation finished at 1260. Why? The |
| 823 |
``breakdown``\ s PEM consists of a loop, one breakdown following |
| 824 |
another at ``300`` intervals. The last breakdown finishes at 960 and |
| 825 |
then a breakdown event is scheduled for 1260. But the bus finished at |
| 826 |
1060 and is not affected by the breakdown. These details can easily |
| 827 |
be checked by importing from ``SimPy.SimulationTrace`` and re-running |
| 828 |
the program. |
| 829 |
|
| 830 |
------------ |
| 831 |
|
| 832 |
Where interrupts can occur, the victim of interrupts must test for |
| 833 |
interrupt occurrence after every appropriate ``yield hold`` and react |
| 834 |
appropriately to it. A victim holding a resource facility when it gets |
| 835 |
interrupted continues to hold it. |
| 836 |
|
| 837 |
|
| 838 |
Advanced synchronization/scheduling capabilities |
| 839 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 840 |
|
| 841 |
The preceding scheduling constructs all depend on specified time |
| 842 |
values. That is, they delay processes for a specific time, or use |
| 843 |
given time parameters when reactivating them. For a wide range of |
| 844 |
applications this is all that is needed. |
| 845 |
|
| 846 |
However, some applications either require or can profit from an |
| 847 |
ability to activate processes that must wait for other processes to |
| 848 |
complete. For example, models of real-time systems or operating |
| 849 |
systems often use this kind of approach. Event_ Signalling is |
| 850 |
particularly helpful in such situations. Furthermore, some |
| 851 |
applications need to activate processes when certain conditions occur, |
| 852 |
even though when (or if) they will occur may be unknown. SimPy has a |
| 853 |
general `wait until`_ to support clean implementation of this |
| 854 |
approach. |
| 855 |
|
| 856 |
This section describes how SimPy provides event_ Signalling and `wait |
| 857 |
until`_ capabilities. |
| 858 |
|
| 859 |
.. index:: SimEvent; creating |
| 860 |
pair: SimEvent; signalling |
| 861 |
|
| 862 |
.. _Event: |
| 863 |
.. .. _SimEvent: |
| 864 |
|
| 865 |
.. index:: Signalling |
| 866 |
|
| 867 |
Creating and Signalling SimEvents |
| 868 |
+++++++++++++++++++++++++++++++++++ |
| 869 |
|
| 870 |
As mentioned in the Introduction, for ease of expression when no |
| 871 |
confusion can arise we often refer to both process objects and their |
| 872 |
classes as "processes", and mention their object or class status only |
| 873 |
for added clarity or emphasis. Analogously, we will refer to objects |
| 874 |
of SimPy's ``SimEvent`` class as "SimEvents" [#]_ (or, if no confusion |
| 875 |
can arise, simply as "events"). However, we sometimes mention their |
| 876 |
object or class character for clarity or emphasis. |
| 877 |
|
| 878 |
.. [#] The name SimEvent was chosen because "event" is already |
| 879 |
used in Python's standard library. See Python Library Reference |
| 880 |
section *7.5 threading -- Higher-level threading interface*, specifically |
| 881 |
subsection 7.5.5. |
| 882 |
|
| 883 |
SimEvent objects must be created before they can be fired by a |
| 884 |
``signal``. You create the SimEvent object, ``sE``, from SimPy's |
| 885 |
``SimEvent`` class by a statement like the following: |
| 886 |
|
| 887 |
``sE = SimEvent(name='I just had a great new idea!')`` |
| 888 |
|
| 889 |
A SimEvent's ``name`` attribute defaults to ``a_SimEvent`` unless you |
| 890 |
provide your own, as shown here. Its ``occurred`` attribute, |
| 891 |
``sE.occurred``, is a Boolean that defaults to ``False``. It indicates |
| 892 |
whether the event ``sE`` has occurred. |
| 893 |
|
| 894 |
You program a SimEvent to "occur" or "fire" by "signalling" it like this: |
| 895 |
|
| 896 |
``sE.signal(``\ *<payload parameter>*\ ``)`` |
| 897 |
|
| 898 |
This "signal" is "received" by all processes that are either "waiting" |
| 899 |
or "queueing" for this event to occur. What happens when they receive |
| 900 |
this signal is explained in the next section. The *<payload |
| 901 |
parameter>* is optional -- it defaults to ``None``. It can be of any |
| 902 |
Python type. Any process can retrieve it from the event's |
| 903 |
``signalparam`` attribute, for example by: |
| 904 |
|
| 905 |
``message = sE.signalparam`` |
| 906 |
|
| 907 |
.. index:: SimEvents; waiting |
| 908 |
pair: Simevents;queueing |
| 909 |
|
| 910 |
Waiting or Queueing for SimEvents |
| 911 |
'''''''''''''''''''''''''''''''''' |
| 912 |
|
| 913 |
You can program a process either to "wait" or to "queue" for the |
| 914 |
occurrence of SimEvents. The difference is that *all* processes |
| 915 |
"waiting" for some event are reactivated as soon as it occurs. For |
| 916 |
example, all firemen go into action when the alarm sounds. In |
| 917 |
contrast, only the *first* process in the "queue" for some event is |
| 918 |
reactivated when it occurs. That is, the "queue" is FIFO [#FIFO]_. An example |
| 919 |
might be royal succession -- when the present ruler dies: "The king is |
| 920 |
dead. Long live the (new) king!" (And all others in the line of |
| 921 |
succession move up one step.) |
| 922 |
|
| 923 |
.. [#FIFO] "First-in-First-Out" or FCFS, "First-Come-First-Served" |
| 924 |
|
| 925 |
You program a process to ``wait`` for SimEvents by including in its PEM: |
| 926 |
|
| 927 |
.. index:: |
| 928 |
pair: yield; waitenvent |
| 929 |
|
| 930 |
yield waitevent |
| 931 |
++++++++++++++++ |
| 932 |
|
| 933 |
- ``yield waitevent,self,``\ *<events part>* |
| 934 |
|
| 935 |
where *<events part>* can be either: |
| 936 |
|
| 937 |
- one SimEvent object, e.g. ``myEvent``, or |
| 938 |
|
| 939 |
- a tuple of SimEvent objects, e.g. ``(myEvent,myOtherEvent,TimeOut)``, or |
| 940 |
|
| 941 |
- a list of SimEvent objects, e.g. ``[myEvent,myOtherEvent,TimeOut]`` |
| 942 |
|
| 943 |
If none of the events in the *<events part>* have occurred, the process |
| 944 |
is passivated and joined to the list of processes waiting for some |
| 945 |
event in *<events part>* to occur (or to recur). |
| 946 |
|
| 947 |
On the other hand, when *any* of the events in the *<events part>* |
| 948 |
occur, then *all* of the processes "waiting" for those particular |
| 949 |
events are reactivated at the current time. Then the ``occurred`` flag |
| 950 |
of those particular events is reset to ``False``. Resetting their |
| 951 |
``occurred`` flag prevents the waiting processes from being constantly |
| 952 |
reactivated. (For instance, we do not want firemen to keep responding |
| 953 |
to any such "false alarms.") For example, suppose the *<events part>* |
| 954 |
lists events ``a, b`` and ``c`` in that order. If events ``a`` and ``c`` |
| 955 |
occur, then all of the processes waiting for event ``a`` are |
| 956 |
reactivated. So are all processes waiting for event ``c`` but not |
| 957 |
``a``. Then the ``occurred`` flags of events ``a`` and ``c`` are toggled to |
| 958 |
``False``. No direct changes are made to event ``b`` or to any processes |
| 959 |
waiting for it to occur. |
| 960 |
|
| 961 |
You program a process to "queue" for events by including in its PEM: |
| 962 |
|
| 963 |
.. index:: |
| 964 |
pair: yield; queueevent |
| 965 |
|
| 966 |
yield queueevent |
| 967 |
+++++++++++++++++++ |
| 968 |
|
| 969 |
- ``yield queueevent,self,``\ *<events part>* |
| 970 |
|
| 971 |
where the *<events part>* is as described above. |
| 972 |
|
| 973 |
If none of the events in the *<events part>* has occurred, the process |
| 974 |
is passivated and appended to the FIFO queue of processes queuing for |
| 975 |
some event in *<events part>* to occur (or recur). |
| 976 |
|
| 977 |
But when any of the events in *<events part>* occur, the process at |
| 978 |
the head of the "queue" is taken off the queue and reactivated at the |
| 979 |
current time. Then the ``occurred`` flag of those events that occurred |
| 980 |
is reset to ``False`` as in the "waiting" case. |
| 981 |
|
| 982 |
|
| 983 |
.. index:: queued processes; find |
| 984 |
.. index:: waiting processes; find |
| 985 |
.. index:: fired processes; list |
| 986 |
|
| 987 |
Finding Which Processes Are Waiting/Queueing for an Event, and Which Events Fired |
| 988 |
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' |
| 989 |
|
| 990 |
SimPy automatically keeps current lists of what processes are |
| 991 |
"waiting" or "queueing" for SimEvents. They are kept in the ``waits`` |
| 992 |
and ``queues`` attributes of the SimEvent object and can be read by |
| 993 |
commands like the following:: |
| 994 |
|
| 995 |
TheProcessesWaitingFor_myEvent = myEvent.waits |
| 996 |
TheProcessesQueuedFor_myEvent = myEvent.queues |
| 997 |
|
| 998 |
However, you should not attempt to change these attributes yourself. |
| 999 |
|
| 1000 |
Whenever ``myEvent`` occurs, i.e., whenever a ``myEvent.signal(...)`` |
| 1001 |
statement is executed, SimPy does the following: |
| 1002 |
|
| 1003 |
- If there are any processes waiting or queued for that event, it |
| 1004 |
reactivates them as described in the preceding section. |
| 1005 |
|
| 1006 |
- If there are no processes waiting or queued (i.e., ``myEvent.waits`` |
| 1007 |
and ``myEvent.queues`` are both empty), it toggles ``myEvent.occurred`` |
| 1008 |
to ``True``. |
| 1009 |
|
| 1010 |
|
| 1011 |
SimPy also automatically keeps track of which events were fired when a |
| 1012 |
process object was reactivated. For example, you can get a list of the |
| 1013 |
events that were fired when the object ``Godzilla`` was reactivated with |
| 1014 |
a statement like this:: |
| 1015 |
|
| 1016 |
GodzillaRevivedBy = Godzilla.eventsFired |
| 1017 |
|
| 1018 |
|
| 1019 |
------------ |
| 1020 |
|
| 1021 |
.. index:: example;showing waiting, queued and fired processes |
| 1022 |
.. index:: example; wait_or_queue |
| 1023 |
|
| 1024 |
.. _`example 6`: |
| 1025 |
|
| 1026 |
**Example 6**. This complete SimPy script illustrates these |
| 1027 |
constructs. (It also illustrates that a Process class may have more |
| 1028 |
than one PEM. Here the ``Wait_Or_Queue`` class has two PEMs -- |
| 1029 |
``waitup`` and ``queueup``.): |
| 1030 |
|
| 1031 |
.. include:: programs/wait_or_queue.py |
| 1032 |
:literal: |
| 1033 |
|
| 1034 |
|
| 1035 |
This program outputs: |
| 1036 |
|
| 1037 |
.. include:: programs/wait_or_queue.out |
| 1038 |
:literal: |
| 1039 |
|
| 1040 |
|
| 1041 |
Each output line, ``The activating event(s) were ...``, lists the |
| 1042 |
contents of the named object's ``eventsFired`` attribute. One of those |
| 1043 |
events "caused" the object to reactivate at the indicated time. Note |
| 1044 |
that at time 15 objects ``W-0`` and ``W-1`` were not affected by the |
| 1045 |
recurrence of ``event1`` and ``event2`` because they already were |
| 1046 |
active. Also at time 15, even though objects ``W-2``, ``Q-1`` and ``Q-2`` |
| 1047 |
were all waiting for ``event3``, only ``W-2`` and ``Q-1`` were |
| 1048 |
reactivated. Process object ``Q-2`` was not reactivated at that time |
| 1049 |
because it was not first in the queue. Finally, ``Q-2`` was reactivated |
| 1050 |
at time 20, when ``event4`` fired again. |
| 1051 |
|
| 1052 |
------------ |
| 1053 |
|
| 1054 |
.. index:: wait; waituntil |
| 1055 |
|
| 1056 |
.. _`wait until`: |
| 1057 |
|
| 1058 |
"waituntil" synchronization -- waiting for any condition |
| 1059 |
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| 1060 |
|
| 1061 |
SimPy provides the ``waituntil`` feature that makes a process's |
| 1062 |
progress depend on the state of the simulation. This is useful if, for |
| 1063 |
example, you need to reactivate a process when (if ever) the |
| 1064 |
simulation enters the state ``goodWeather OR (nrCustomers>50 AND |
| 1065 |
price<22.50)``. Doing that requires *interrogative* scheduling, |
| 1066 |
while all other SimPy synchronization constructs are *imperative* -- |
| 1067 |
i.e., the condition must be tested after every change in state until |
| 1068 |
it becomes ``True``. |
| 1069 |
|
| 1070 |
This requires that after every change in system state SimPy must run a |
| 1071 |
special (hidden) process that tests and responds appropriately to the |
| 1072 |
condition's truth-value. This clearly takes more run time than SimPy's |
| 1073 |
imperative scheduling constructs. So SimPy activates its interrogative |
| 1074 |
testing process only so long as at least one process is executing a |
| 1075 |
``waituntil`` statement. When this is not the case, the run time overhead |
| 1076 |
is minimal (about 1 percent extra run time). |
| 1077 |
|
| 1078 |
.. index:: yield; waituntil |
| 1079 |
.. index:: waituntil; yield |
| 1080 |
|
| 1081 |
yield waituntil |
| 1082 |
++++++++++++++++ |
| 1083 |
|
| 1084 |
You program a process to wait for a condition to be satisfied by |
| 1085 |
including in its PEM a statement of the form: |
| 1086 |
|
| 1087 |
``yield waituntil, self,``\ *<cond>* |
| 1088 |
|
| 1089 |
where *<cond>* is a reference to a function, without parameters, that |
| 1090 |
returns a Boolean value indicating whether the simulation state or |
| 1091 |
condition to be waited for has occurred. |
| 1092 |
|
| 1093 |
------------ |
| 1094 |
|
| 1095 |
.. index:: example;Romulans |
| 1096 |
|
| 1097 |
.. _Romulans: |
| 1098 |
.. _`example 7`: |
| 1099 |
|
| 1100 |
**Example 7**. This program using the ``yield waituntil ...`` |
| 1101 |
statement. Here the function ``killed()``, in the ``life()`` PEM of |
| 1102 |
the ``Player`` process, defines the condition to be waited for :: |
| 1103 |
|
| 1104 |
from SimPy.Simulation import * |
| 1105 |
import random |
| 1106 |
|
| 1107 |
class Player(Process): |
| 1108 |
|
| 1109 |
def __init__(self,lives=1,name='ImaTarget'): |
| 1110 |
Process.__init__(self,name) |
| 1111 |
self.lives=lives |
| 1112 |
# provide Player objects with a "damage" property |
| 1113 |
self.damage=0 |
| 1114 |
|
| 1115 |
def life(self): |
| 1116 |
self.message='Drat! Some %s survived Federation attack!' %(target.name) |
| 1117 |
|
| 1118 |
def killed(): # function testing for "damage > 5" |
| 1119 |
return self.damage>5 |
| 1120 |
|
| 1121 |
while True: |
| 1122 |
yield waituntil,self,killed |
| 1123 |
self.lives-=1; self.damage=0 |
| 1124 |
if self.lives==0: |
| 1125 |
self.message= '%s wiped out by Federation at \ |
| 1126 |
time %s!' %(target.name,now()) |
| 1127 |
stopSimulation() |
| 1128 |
|
| 1129 |
class Federation(Process): |
| 1130 |
|
| 1131 |
def fight(self): # simulate Federation operations |
| 1132 |
print 'Three %s attempting to escape!' %(target.name) |
| 1133 |
while True: |
| 1134 |
if random.randint(0,10)<2: # check for hit on player |
| 1135 |
target.damage+=1 # hit! increment damage to player |
| 1136 |
if target.damage <= 5: # target survives |
| 1137 |
print 'Ha! %s hit! Damage = %i'%(target.name, target.damage) |
| 1138 |
else: |
| 1139 |
if (target.lives-1)==0: |
| 1140 |
print 'No more %s left!' %(target.name) |
| 1141 |
else: |
| 1142 |
print 'Now only %i %s left!' %(target.lives-1,target.name) |
| 1143 |
|
| 1144 |
yield hold,self,1 |
| 1145 |
|
| 1146 |
initialize() |
| 1147 |
gameOver=100 |
| 1148 |
# create a Player object named "Romulans" |
| 1149 |
target=Player(lives=3,name='Romulans') |
| 1150 |
activate(target,target.life()) |
| 1151 |
# create a Federation object |
| 1152 |
shooter=Federation() |
| 1153 |
activate(shooter,shooter.fight()) |
| 1154 |
simulate(until=gameOver) |
| 1155 |
print target.message |
| 1156 |
|
| 1157 |
|
| 1158 |
One possible output from this program is shown below. Whether the |
| 1159 |
Romulans are wiped out or some escape depends on what simulation |
| 1160 |
states the randomization feature produces:: |
| 1161 |
|
| 1162 |
Three Romulans attempting to escape! |
| 1163 |
Ha! Romulans hit! Damage = 1 |
| 1164 |
Ha! Romulans hit! Damage = 2 |
| 1165 |
Ha! Romulans hit! Damage = 3 |
| 1166 |
Ha! Romulans hit! Damage = 4 |
| 1167 |
Ha! Romulans hit! Damage = 5 |
| 1168 |
Now only 2 Romulans left! |
| 1169 |
Ha! Romulans hit! Damage = 1 |
| 1170 |
Ha! Romulans hit! Damage = 2 |
| 1171 |
Ha! Romulans hit! Damage = 3 |
| 1172 |
Ha! Romulans hit! Damage = 4 |
| 1173 |
Ha! Romulans hit! Damage = 5 |
| 1174 |
Now only 1 Romulans left! |
| 1175 |
Ha! Romulans hit! Damage = 1 |
| 1176 |
Ha! Romulans hit! Damage = 2 |
| 1177 |
Ha! Romulans hit! Damage = 3 |
| 1178 |
Ha! Romulans hit! Damage = 4 |
| 1179 |
Ha! Romulans hit! Damage = 5 |
| 1180 |
No more Romulans left! |
| 1181 |
Romulans wiped out by Federation at time 73! |
| 1182 |
|
| 1183 |
------------ |
| 1184 |
|
| 1185 |
|
| 1186 |
The ``waituntil`` construct is so general that in principle it could |
| 1187 |
replace all the other synchronization approaches (but at a run time |
| 1188 |
cost). |
| 1189 |
|
| 1190 |
[Return to Top_ ] |
| 1191 |
|
| 1192 |
.. ================================================================== |
| 1193 |
|
| 1194 |
.. index:: ! Resources |
| 1195 |
|
| 1196 |
Resources |
| 1197 |
------------------- |
| 1198 |
|
| 1199 |
The three resource facilities provided by SimPy are Resources_, |
| 1200 |
Levels_ and Stores_. Each models a congestion point where process |
| 1201 |
objects may have to queue up to obtain resources. This section |
| 1202 |
describes the Resource type of resource facility. |
| 1203 |
|
| 1204 |
An example of queueing for a Resource might be a manufacturing plant |
| 1205 |
in which a ``Task`` (modelled as a *process object*) needs work done |
| 1206 |
by a ``Machine`` (modelled as a Resource object). If all of the |
| 1207 |
``Machines`` are currently being used, the ``Task`` must wait until |
| 1208 |
one becomes free. A SimPy Resource can have a number of identical |
| 1209 |
``units``, such as a number of identical ``machine`` units. A |
| 1210 |
process obtains a unit of the Resource by ``requesting`` it and, when |
| 1211 |
it is finished, ``releasing`` it. A Resource maintains a list of |
| 1212 |
process objects that have requested but not yet received one of the |
| 1213 |
Resource's units (called the ``waitQ``), and another list of processes |
| 1214 |
that are currently using a unit (the ``activeQ``). SimPy creates and |
| 1215 |
updates these queues itself -- the user can access them, but should |
| 1216 |
not change them. |
| 1217 |
|
| 1218 |
.. index:: Resource; defining object |
| 1219 |
|
| 1220 |
Defining a Resource object |
| 1221 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 1222 |
|
| 1223 |
A Resource object, ``r``, is established by the following statement:: |
| 1224 |
|
| 1225 |
r = Resource(capacity=1, name='a_resource', unitName='units', |
| 1226 |
qType=FIFO, preemptable=False, |
| 1227 |
monitored=False, monitorType=Monitor) |
| 1228 |
|
| 1229 |
where |
| 1230 |
|
| 1231 |
- ``capacity`` is a positive real or integer value that specifies the total |
| 1232 |
number of identical units in Resource object ``r``. |
| 1233 |
|
| 1234 |
- ``name`` is a descriptive name for this Resource object (e.g., |
| 1235 |
``'gasStation'``). |
| 1236 |
|
| 1237 |
- ``unitName`` is a descriptive name for a unit of the resource |
| 1238 |
(e.g., ``'pump'``). |
| 1239 |
|
| 1240 |
- ``qType`` is either ``FIFO`` [#FIFO]_ or ``PriorityQ``. It |
| 1241 |
specifies the queue discipline of the resource's ``waitQ``; |
| 1242 |
typically, this is ``FIFO`` and that is the default value. If |
| 1243 |
``PriorityQ`` is specified, then higher-priority requests waiting |
| 1244 |
for a unit of Resource ``r`` are inserted into the ``waitQ`` ahead |
| 1245 |
of lower priority requests. See `Priority requests for a Resource |
| 1246 |
unit`_ for details. |
| 1247 |
|
| 1248 |
- ``preemptable`` is a Boolean (``False`` or ``True``); typically, |
| 1249 |
this is ``False`` and that is the default value. If it is |
| 1250 |
``True``, then a process requesting a unit of this resource may |
| 1251 |
preempt a lower-priority process in the ``activeQ``, i.e., one that |
| 1252 |
is already using a unit of the resource. See `Preemptive requests |
| 1253 |
for a Resource unit`_ for details. |
| 1254 |
|
| 1255 |
- ``monitored`` is a boolean (``False`` or ``True``). If set to |
| 1256 |
``True``, then information is gathered on the sizes of ``r``'s |
| 1257 |
``waitQ`` and ``activeQ``, otherwise not. |
| 1258 |
|
| 1259 |
- ``monitorType`` is either ``Monitor`` or ``Tally`` and indicates the |
| 1260 |
type of Recorder_ to be used (see `Recording Resource queue lengths`_ for an example and additional |
| 1261 |
discussion). |
| 1262 |
|
| 1263 |
Each Resource object, ``r``, has the following additional attributes: |
| 1264 |
|
| 1265 |
- ``r.n``, the number of units that are currently free. |
| 1266 |
|
| 1267 |
- ``r.waitQ``, a queue (list) of processes that have requested but |
| 1268 |
not yet received a unit of ``r``, so ``len(r.waitQ)`` is the |
| 1269 |
number of process objects currently waiting. |
| 1270 |
|
| 1271 |
- ``r.activeQ``, a queue (list) of process objects currently using |
| 1272 |
one of the Resource's units, so ``len(r.activeQ)`` is the number of |
| 1273 |
units that are currently in use. |
| 1274 |
|
| 1275 |
- ``r.waitMon``, the record (made by a ``Monitor`` or a ``Tally`` |
| 1276 |
whenever ``monitored==True``) of the activity in ``r.waitQ``. So, |
| 1277 |
for example, ``r.waitMon.timeaverage()`` is the average number of |
| 1278 |
processes in ``r.waitQ``. See `Recording Resource queue lengths`_ |
| 1279 |
for an example. |
| 1280 |
|
| 1281 |
- ``r.actMon``, the record (made by a ``Monitor`` or a ``Tally`` whenever |
| 1282 |
``monitored==True``) of the activity in ``r.activeQ``. |
| 1283 |
|
| 1284 |
|
| 1285 |
Requesting and releasing a unit of a Resource |
| 1286 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 1287 |
|
| 1288 |
A process can request and later release a unit of the Resource object, |
| 1289 |
``r``, by using the following yield commands in a Process Execution |
| 1290 |
Method: |
| 1291 |
|
| 1292 |
.. index:: Resource; request |
| 1293 |
pair: yield; request |
| 1294 |
|
| 1295 |
yield request |
| 1296 |
+++++++++++++++ |
| 1297 |
|
| 1298 |
|
| 1299 |
- |yrequest|\ *r [,P=0]* |
| 1300 |
|
| 1301 |
requests a unit of Resource *r* with (optional) real or integer |
| 1302 |
priority value *P*. If no priority is specified, it defaults to 0. |
| 1303 |
Larger values of *P* represent higher priorities. See the following |
| 1304 |
sections on `Queue Order`_ for more information on how priority |
| 1305 |
values are used. Although this form of request can be used for |
| 1306 |
either ``FIFO`` or ``PriorityQ`` priority types, these values are |
| 1307 |
*ignored* when ``qType==FIFO``. |
| 1308 |
|
| 1309 |
.. index:: Resource; release |
| 1310 |
single: yield; release |
| 1311 |
single: release; yield |
| 1312 |
|
| 1313 |
yield release |
| 1314 |
+++++++++++++++ |
| 1315 |
|
| 1316 |
``yield release,self,r`` |
| 1317 |
|
| 1318 |
releases the unit of *r*. |
| 1319 |
|
| 1320 |
|
| 1321 |
.. index:: Resource; queues |
| 1322 |
pair: Resource; waitQ |
| 1323 |
pair: Resource; queue order |
| 1324 |
|
| 1325 |
|
| 1326 |
Queue Order |
| 1327 |
~~~~~~~~~~~~ |
| 1328 |
|
| 1329 |
If a requesting process must wait it is placed into the resource's |
| 1330 |
``waitQ`` in an order determined by settings of the resource's |
| 1331 |
``qType`` and ``preemptable`` attributes and of the priority value it |
| 1332 |
uses in the ``request`` call. |
| 1333 |
|
| 1334 |
|
| 1335 |
.. index:: Resource;non-priority queueing |
| 1336 |
|
| 1337 |
Non-priority queueing |
| 1338 |
++++++++++++++++++++++++ |
| 1339 |
|
| 1340 |
If the ``qType`` is not specified it takes the presumed value of |
| 1341 |
``FIFO`` [#FIFO]_. In that case processes wait in the usual |
| 1342 |
first-come-first-served order. |
| 1343 |
|
| 1344 |
If a Resource unit is free when the request is made, the requesting |
| 1345 |
process takes it and moves on to the next statement in its PEM. If no |
| 1346 |
Resource unit is available when the request is made, then the |
| 1347 |
requesting process is appended to the Resource's ``waitQ`` and |
| 1348 |
suspended. The next time a unit becomes available the first process |
| 1349 |
in the ``r.waitQ`` takes it and continues its execution. All priority |
| 1350 |
assignments are ignored. Moreover, in the FIFO case no preemption is |
| 1351 |
possible, for preemption requires that priority assignments be |
| 1352 |
recognized. (However, see the `Note on preemptive requests with waitQ |
| 1353 |
in FIFO order`_ for one way of simulating such situations.) |
| 1354 |
|
| 1355 |
------------ |
| 1356 |
|
| 1357 |
**Example** In this complete script, the ``server`` Resource object is |
| 1358 |
given two resource units (``capacity=2``). By not specifying its |
| 1359 |
``Qtype`` it takes the default value, ``FIFO``. Here six clients |
| 1360 |
arrive in the order specified by the program. They all request a |
| 1361 |
resource unit from the ``server`` Resource object at the same |
| 1362 |
time. Even though they all specify a priority value in their requests, |
| 1363 |
it is ignored and they get their Resource units in the same order as |
| 1364 |
their requests: |
| 1365 |
|
| 1366 |
.. include:: programs/resource.py |
| 1367 |
:literal: |
| 1368 |
|
| 1369 |
|
| 1370 |
This program results in the following output:: |
| 1371 |
|
| 1372 |
c1 requests 1 unit at t = 0 |
| 1373 |
c2 requests 1 unit at t = 0 |
| 1374 |
c3 requests 1 unit at t = 0 |
| 1375 |
c4 requests 1 unit at t = 0 |
| 1376 |
c5 requests 1 unit at t = 0 |
| 1377 |
c6 requests 1 unit at t = 0 |
| 1378 |
c1 done at time = 100 |
| 1379 |
c2 done at time = 100 |
| 1380 |
c3 done at time = 200 |
| 1381 |
c4 done at time = 200 |
| 1382 |
c5 done at time = 300 |
| 1383 |
c6 done at time = 300 |
| 1384 |
|
| 1385 |
Request order: ['c1', 'c2', 'c3', 'c4', 'c5', 'c6'] |
| 1386 |
Service order: ['c1', 'c2', 'c3', 'c4', 'c5', 'c6'] |
| 1387 |
|
| 1388 |
As illustrated, the clients are served in FIFO order. Clients ``c1`` |
| 1389 |
and ``c2`` each take one Resource unit right away, but the others must |
| 1390 |
wait. When ``c1`` and ``c2`` finish with their resources, clients |
| 1391 |
``c3`` and ``c4`` can each take a unit, and so forth. |
| 1392 |
|
| 1393 |
|
| 1394 |
.. index:: Resource; priority queueing |
| 1395 |
triple: Resource; request; priority |
| 1396 |
pair: Resource; qType |
| 1397 |
pair: Resource; PriorityQ |
| 1398 |
|
| 1399 |
Priority requests for a Resource unit |
| 1400 |
++++++++++++++++++++++++++++++++++++++++ |
| 1401 |
|
| 1402 |
If the Resource ``r`` is defined with ``qType==PriorityQ``, priority |
| 1403 |
values in requests are recognized. If a Resource unit is available |
| 1404 |
when the request is made, the requesting process takes it. If no |
| 1405 |
Resource unit is available when the request is made, the requesting |
| 1406 |
process is inserted into the Resource's ``waitQ`` in order of priority |
| 1407 |
(from high to low) and suspended. For an example where priorities are |
| 1408 |
used, we simply change the preceding example's specification of the |
| 1409 |
``server`` Resource object to:: |
| 1410 |
|
| 1411 |
server=Resource(capacity=2, qType=PriorityQ) |
| 1412 |
|
| 1413 |
where, by not specifying it, we allow ``preemptable`` to take its |
| 1414 |
default value, ``False``. |
| 1415 |
|
| 1416 |
------------ |
| 1417 |
|
| 1418 |
**Example** After this change the program's output becomes:: |
| 1419 |
|
| 1420 |
c1 requests 1 unit at t = 0 |
| 1421 |
c2 requests 1 unit at t = 0 |
| 1422 |
c3 requests 1 unit at t = 0 |
| 1423 |
c4 requests 1 unit at t = 0 |
| 1424 |
c5 requests 1 unit at t = 0 |
| 1425 |
c6 requests 1 unit at t = 0 |
| 1426 |
c1 done at time = 100 |
| 1427 |
c2 done at time = 100 |
| 1428 |
c6 done at time = 200 |
| 1429 |
c5 done at time = 200 |
| 1430 |
c4 done at time = 300 |
| 1431 |
c3 done at time = 300 |
| 1432 |
|
| 1433 |
Request order: ['c1', 'c2', 'c3', 'c4', 'c5', 'c6'] |
| 1434 |
Service order: ['c1', 'c2', 'c6', 'c5', 'c4', 'c3'] |
| 1435 |
|
| 1436 |
Although ``c1`` and ``c2`` have the lowest priority values, each requested |
| 1437 |
and got a ``server`` unit immediately. That was because at the time they |
| 1438 |
made those requests a ``server`` unit was available and the |
| 1439 |
``server.waitQ`` was empty -- it did not start to fill until ``c3`` made |
| 1440 |
its request and found all of the ``server`` units busy. When ``c1`` and |
| 1441 |
``c2`` completed service, ``c6`` and ``c5`` (with the highest priority |
| 1442 |
values of all processes in the ``waitQ``) each got a Resource unit, |
| 1443 |
etc. |
| 1444 |
|
| 1445 |
------------ |
| 1446 |
|
| 1447 |
When some processes in the ``waitQ`` have the same priority level as a |
| 1448 |
process making a priority request, SimPy inserts the requesting |
| 1449 |
process immediately *behind* them. Thus for a given priority value, |
| 1450 |
processes are placed in FIFO order. For example, suppose that when a |
| 1451 |
"priority 3" process makes its priority request the current ``waitQ`` |
| 1452 |
consists of processes with priorities ``[5,4,3a,3b,3c,2a,2b,1]``, |
| 1453 |
where the letters indicate the order in which the equal-priority |
| 1454 |
processes were placed in the queue. Then SimPy inserts this |
| 1455 |
requesting process into the current ``waitQ`` immediately behind its |
| 1456 |
last "priority 3" process. Thus, the new ``waitQ`` will be |
| 1457 |
``[5,4,3a,3b,3c,3d,2a,2b,1]``, where the inserted process is ``3d``. |
| 1458 |
|
| 1459 |
One consequence of this is that, if all priority requests are assigned |
| 1460 |
the same priority value, then the ``waitQ`` will in fact be maintained |
| 1461 |
in ``FIFO`` order. In that case, using a ``FIFO`` instead of a |
| 1462 |
``PriorityQ`` discipline provides some saving in execution time which |
| 1463 |
may be important in simulations where the ``waitQ`` may be long. |
| 1464 |
|
| 1465 |
.. index:: Resource;priority |
| 1466 |
pair: Resource;preemptable |
| 1467 |
|
| 1468 |
Preemptive requests for a Resource unit |
| 1469 |
++++++++++++++++++++++++++++++++++++++++ |
| 1470 |
|
| 1471 |
In some models, higher priority processes can actually *preempt* lower |
| 1472 |
priority processes, i.e., they can take over and use a Resource unit |
| 1473 |
currently being used by a lower priority process whenever no free |
| 1474 |
Resource units are available. A Resource object that allows its units |
| 1475 |
to be preempted is created by setting its properties to |
| 1476 |
``qType==PriorityQ`` and ``preemptable==True``. |
| 1477 |
|
| 1478 |
Whenever a ``preemptable`` Resource unit is free when a request is |
| 1479 |
made, then the requesting process takes it and continues its |
| 1480 |
execution. On the other hand, when a higher priority request finds all |
| 1481 |
the units in a ``preemptable`` Resource in use, then SimPy adopts the |
| 1482 |
following procedure regarding the Resource's ``activeQ`` and |
| 1483 |
``waitQ``: |
| 1484 |
|
| 1485 |
- The process with the lowest priority is removed from the ``activeQ``, |
| 1486 |
suspended, and put at the front of the ``waitQ`` -- so (barring |
| 1487 |
additional preemptions) it will be the next one to get a resource |
| 1488 |
unit. |
| 1489 |
|
| 1490 |
- The preempting process gets the vacated resource unit and is |
| 1491 |
inserted into the ``activeQ`` in order of its priority value. |
| 1492 |
|
| 1493 |
- The time for which the preempted process had the resource unit is |
| 1494 |
taken into account when the process gets into the ``activeQ`` again. |
| 1495 |
Thus, its *total hold time* is always the same, regardless of how |
| 1496 |
many times it has been preempted. |
| 1497 |
|
| 1498 |
.. index:: Resource; preemptive request pattern |
| 1499 |
|
| 1500 |
Warning: SimPy only supports preemption of processes which are |
| 1501 |
implemented in the following pattern:: |
| 1502 |
|
| 1503 |
yield request (one or more request statements) |
| 1504 |
<some code> |
| 1505 |
yield hold (one or more hold statements) |
| 1506 |
<some code> |
| 1507 |
yield release (one or more release statements) |
| 1508 |
|
| 1509 |
Modelling the preemption of a process in any other pattern may lead to |
| 1510 |
errors or exceptions. |
| 1511 |
|
| 1512 |
|
| 1513 |
We emphasize that a process making a ``preemptive`` request to a |
| 1514 |
fully-occupied Resource gets a resource unit if -- but only if -- some |
| 1515 |
process in the current ``activeQ`` has a lower priority. Otherwise, it |
| 1516 |
will be inserted into the ``waitQ`` at a location determined by its |
| 1517 |
priority value and the current contents of the ``waitQ``, using a |
| 1518 |
procedure analogous to that described for priority requests near the |
| 1519 |
end of the preceding section on `Priority requests for a Resource |
| 1520 |
unit`_. This may have the effect of advancing the preempting process |
| 1521 |
ahead of any lower-priority processes that had earlier been preempted |
| 1522 |
and put at the head of the ``waitQ``. In fact, if several preemptions |
| 1523 |
occur before a unit of resource is freed up, then the head of the |
| 1524 |
``waitQ`` will consist of the processes that have been preempted -- in |
| 1525 |
order from the last process preempted to the first of them. |
| 1526 |
|
| 1527 |
------------ |
| 1528 |
|
| 1529 |
.. .. literalinclude:: programs/diffpriority.py |
| 1530 |
:language: python |
| 1531 |
|
| 1532 |
|
| 1533 |
**Example** In this example two clients of different priority compete |
| 1534 |
for the same resource unit:: |
| 1535 |
|
| 1536 |
from SimPy.Simulation import * |
| 1537 |
|
| 1538 |
class Client(Process): |
| 1539 |
def __init__(self,name): |
| 1540 |
Process.__init__(self,name) |
| 1541 |
|
| 1542 |
def getserved(self,servtime,priority,myServer): |
| 1543 |
print self.name, 'requests 1 unit at t=',now() |
| 1544 |
yield request, self, myServer, priority |
| 1545 |
yield hold, self, servtime |
| 1546 |
yield release, self,myServer |
| 1547 |
print self.name,'done at t= ',now() |
| 1548 |
|
| 1549 |
initialize() |
| 1550 |
# create the *server* Resource object |
| 1551 |
server=Resource(capacity=1,qType=PriorityQ,preemptable=1) |
| 1552 |
# create some Client process objects |
| 1553 |
c1=Client(name='c1') |
| 1554 |
c2=Client(name='c2') |
| 1555 |
activate(c1,c1.getserved(servtime=100,priority=1,myServer=server),at=0) |
| 1556 |
activate(c2,c2.getserved(servtime=100,priority=9,myServer=server),at=50) |
| 1557 |
simulate(until=500) |
| 1558 |
|
| 1559 |
|
| 1560 |
The output from this program is:: |
| 1561 |
|
| 1562 |
c1 requests 1 unit at t= 0 |
| 1563 |
c2 requests 1 unit at t= 50 |
| 1564 |
c2 done at t= 150 |
| 1565 |
c1 done at t= 200 |
| 1566 |
|
| 1567 |
Here, ``c1`` is preempted by ``c2`` at ``t=50``. At that time, ``c1`` |
| 1568 |
had held the resource for 50 of its total of 100 time units. When |
| 1569 |
``c2`` finished and released the resource unit at 150, ``c1`` got the |
| 1570 |
resource back and finished the last 50 time units of its service at |
| 1571 |
``t=200``. |
| 1572 |
|
| 1573 |
------------ |
| 1574 |
|
| 1575 |
If preemption occurs when the last few processes in the current |
| 1576 |
``activeQ`` have the same priority value, then the last process in the |
| 1577 |
current ``activeQ`` is the one that will be preempted and inserted |
| 1578 |
into the ``waitQ`` ahead of all others. To describe this, it will be |
| 1579 |
convenient to indicate by an added letter the order in which |
| 1580 |
equal-priority processes have been inserted into a queue. Now, suppose |
| 1581 |
that a "priority 4" process makes a preemptive request when the |
| 1582 |
current ``activeQ`` priorities are ``[5,3a,3b]`` and the current |
| 1583 |
``waitQ`` priorities are ``[2,1,0a,0b]``. Then process ``3b`` will be |
| 1584 |
preempted. After the preemption the ``activeQ`` will be ``[5,4,3a]`` |
| 1585 |
and the ``waitQ`` will be ``[3b,2,1,0a,0b]``. |
| 1586 |
|
| 1587 |
.. To give another example of how this works, consider the following sequence of |
| 1588 |
events, where several preemptive requests are received by a Resource with |
| 1589 |
two Resource units. Throughout this example, we give the ``activeQ`` |
| 1590 |
before the ``waitQ``: |
| 1591 |
|
| 1592 |
1. The current ``activeQ`` and ``waitQ`` are [1a,1b] and [0a,0b], |
| 1593 |
respectively. |
| 1594 |
|
| 1595 |
2. A "priority 5" process makes a preemptive request. Then the queues |
| 1596 |
become: [5,1a] and [1b,0a,0b]. |
| 1597 |
|
| 1598 |
3. A "priority 3" process makes a preemptive request. Then the queues |
| 1599 |
become: [5,3a] and [1a,1b,0a,0b]. |
| 1600 |
|
| 1601 |
4. Another "priority 3" process makes a preemptive request. Then the |
| 1602 |
queues become: [5,3a] and [3b,1a,1b,0a,0b]. |
| 1603 |
|
| 1604 |
5. A "priority 7" process makes a preemptive request. Then the queues |
| 1605 |
become: [7,5] and [3a,3b,1a,1b,0a,0b]. |
| 1606 |
|
| 1607 |
6. The "priority 7" process finishes using its resource unit. Then the |
| 1608 |
queues become: [5,3a] and [3b,1a,1b,0a,0b]. |
| 1609 |
|
| 1610 |
|
| 1611 |
Note on preemptive requests with waitQ in FIFO order |
| 1612 |
+++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| 1613 |
|
| 1614 |
You may consider doing the following to model a system whose queue of |
| 1615 |
items waiting for a resource is to be maintained in FIFO order, but in |
| 1616 |
which preemption is to be possible. It uses SimPy's ``preemptable`` |
| 1617 |
Resource objects, and uses priorities in a way that allows for |
| 1618 |
preempts while maintaining a FIFO ``waitQ`` order. |
| 1619 |
|
| 1620 |
- Set ``qType=PriorityQ`` and ``preemptable=True`` (so that SimPy |
| 1621 |
will process preemptive requests correctly). |
| 1622 |
|
| 1623 |
- Model "system requests that are to be considered as non-preemptive" |
| 1624 |
in SimPy as process objects each of which has exactly the same |
| 1625 |
(low) priority value -- for example, either assign all of them a |
| 1626 |
priority value of 0 (zero) or let it default to that value. (This |
| 1627 |
has the effect of maintaining all of these process objects in the |
| 1628 |
``waitQ`` in FIFO order, as explained at the end of the section on |
| 1629 |
`Priority requests for a Resource unit`_, above.) |
| 1630 |
|
| 1631 |
- Model "system requests that are to be considered as preemptive" in |
| 1632 |
SimPy as process objects each of which is assigned a uniform |
| 1633 |
priority value, but give them a higher value than the one used to |
| 1634 |
model the "non-preemptive system requests" -- for example, assign |
| 1635 |
all of them a priority value of 1 (one). Then they will have a higher |
| 1636 |
priority value than any of the non-preemptive requests. |
| 1637 |
|
| 1638 |
------------ |
| 1639 |
|
| 1640 |
**Example** Here is an example of how this works for a Resource with |
| 1641 |
two Resource units -- we give the ``activeQ`` before the ``waitQ`` |
| 1642 |
throughout this example: |
| 1643 |
|
| 1644 |
1. Suppose that the current ``activeQ`` and ``waitQ`` are ``[0a,0b]`` |
| 1645 |
and ``[0c],`` respectively. |
| 1646 |
|
| 1647 |
2. A "priority 1" process makes a preemptive request. Then the queues |
| 1648 |
become: ``[1a,0a]`` and`` [0b,0c]``. |
| 1649 |
|
| 1650 |
3. Another "priority 1" process makes a preemptive request. Then the |
| 1651 |
queues become: ``[1a,1b]`` and ``[0a,0b,0c]``. |
| 1652 |
|
| 1653 |
4. A third "priority 1" process makes a preemptive request. Then the |
| 1654 |
queues become: ``[1a,1b]`` and ``[1c,0a,0b,0c]``. |
| 1655 |
|
| 1656 |
5. Process ``1a`` finishes using its resource unit. Then the queues |
| 1657 |
become: ``[1b,1c]`` and ``[0a,0b,0c]``. |
| 1658 |
|
| 1659 |
------------ |
| 1660 |
|
| 1661 |
|
| 1662 |
.. index:: Resource; reneging |
| 1663 |
|
| 1664 |
Reneging -- leaving a queue before acquiring a resource |
| 1665 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 1666 |
|
| 1667 |
In most real world situations, people and other items do not wait |
| 1668 |
forever for a requested resource facility to become |
| 1669 |
available. Instead, they leave its queue when their patience is |
| 1670 |
exhausted or when some other condition occurs. This behaviour is |
| 1671 |
called *reneging*, and the reneging person or thing is said to |
| 1672 |
*renege*. |
| 1673 |
|
| 1674 |
SimPy provides an extended (i.e., compound) ``yield request`` statement |
| 1675 |
to handle reneging. |
| 1676 |
|
| 1677 |
.. index:: yield; request with reneging |
| 1678 |
|
| 1679 |
Reneging yield request |
| 1680 |
++++++++++++++++++++++++ |
| 1681 |
|
| 1682 |
There are two types of reneging clause, one for reneging after a |
| 1683 |
certain time and one for reneging when an event has happened. |
| 1684 |
Their general form is |
| 1685 |
|
| 1686 |
|rrequest|\ ``(``\ *<reneging clause>*\ ``)`` |
| 1687 |
|
| 1688 |
to request a unit of Resource *r* (with optional priority *P*, |
| 1689 |
assuming the Resource has been defined as a ``priorityQ``) but with |
| 1690 |
reneging. |
| 1691 |
|
| 1692 |
A SimPy program that models Resource requests with reneging must use |
| 1693 |
the following pattern of statements:: |
| 1694 |
|
| 1695 |
yield (request,self,r),(<reneging clause>) |
| 1696 |
if self.acquired(resource): |
| 1697 |
## process got resource and so did NOT renege |
| 1698 |
. . . . |
| 1699 |
yield release,self,resource |
| 1700 |
else: |
| 1701 |
## process reneged before acquiring resource |
| 1702 |
. . . . . |
| 1703 |
|
| 1704 |
A call to the ``self.acquired(resource)`` method is mandatory after a |
| 1705 |
compound ``yield request`` statement. It not only indicates whether or |
| 1706 |
not the process has acquired the resource, it also removes the |
| 1707 |
reneging process from the resource's ``waitQ``. |
| 1708 |
|
| 1709 |
|
| 1710 |
|
| 1711 |
.. index:: yield; request with reneging after a time limit |
| 1712 |
|
| 1713 |
Reneging after a time limit |
| 1714 |
+++++++++++++++++++++++++++ |
| 1715 |
|
| 1716 |
To make a process give up (renege) after a certain time, use a |
| 1717 |
reneging clause of the following form: |
| 1718 |
|
| 1719 |
|rrequest|\ ``(hold,self,``\ *waittime*\ ``)`` |
| 1720 |
|
| 1721 |
|
| 1722 |
Here the process requests one unit of the resource *r* with optional |
| 1723 |
priority *P*. If a resource unit is available it takes it and continues |
| 1724 |
its PEM. Otherwise, as usual, it is passivated and inserted into *r*\ |
| 1725 |
's ``waitQ``. |
| 1726 |
|
| 1727 |
The process takes a unit if it becomes available before *waittime* |
| 1728 |
expires and continues executing its PEM. If, however, the process has |
| 1729 |
not acquired a unit before the *waittime* has expired it abandons the |
| 1730 |
request (reneges) and leaves the ``waitQ``. |
| 1731 |
|
| 1732 |
------------ |
| 1733 |
|
| 1734 |
**Example**: part of a parking lot simulation:: |
| 1735 |
|
| 1736 |
. . . . |
| 1737 |
parking_lot=Resource(capacity=10) |
| 1738 |
patience=5 # wait no longer than "patience" time units |
| 1739 |
# for a parking space |
| 1740 |
park_time=60 # park for "park_time" time units if get a parking space |
| 1741 |
. . . . |
| 1742 |
yield (request,self,parking_lot),(hold,self,patience) |
| 1743 |
if self.acquired(parking_lot): |
| 1744 |
# park the car |
| 1745 |
yield hold,self,park_time |
| 1746 |
yield release,self,parking_lot |
| 1747 |
else: |
| 1748 |
# patience exhausted, so give up |
| 1749 |
print 'I'm not waiting any longer. I am going home now.' |
| 1750 |
|
| 1751 |
------------ |
| 1752 |
|
| 1753 |
|
| 1754 |
|
| 1755 |
.. index:: yield; request with reneging after an event |
| 1756 |
|
| 1757 |
Reneging when an event has happened |
| 1758 |
+++++++++++++++++++++++++++++++++++ |
| 1759 |
|
| 1760 |
To make a process renege at the occurrence of an event, use a reneging |
| 1761 |
clause having a pattern like the one used for a ``yield waitevent`` |
| 1762 |
statement, namely ``waitevent,self,``\ *events* (see `yield waitevent`_). |
| 1763 |
For example: |
| 1764 |
|
| 1765 |
|rrequest|\ ``(waitevent,self,``\ *events*\ ``)`` |
| 1766 |
|
| 1767 |
Here the process requests one unit of the resource *r* with optional |
| 1768 |
priority *P*. If a resource unit is available it takes it and continues |
| 1769 |
its PEM. Otherwise, as usual, it is passivated and inserted into *r*\ |
| 1770 |
's ``waitQ``. |
| 1771 |
|
| 1772 |
The process takes a unit if it becomes available before any of the |
| 1773 |
*events* occur, and continues executing its PEM. If, however, any of |
| 1774 |
the SimEvents in *events* occur first, it abandons the |
| 1775 |
request (reneges) and leaves the ``waitQ``. (Recall that *events* can be |
| 1776 |
either one event, a list, or a tuple of several SimEvents.) |
| 1777 |
|
| 1778 |
|
| 1779 |
|
| 1780 |
|
| 1781 |
------------ |
| 1782 |
|
| 1783 |
**Example** Queuing for movie tickets (part):: |
| 1784 |
|
| 1785 |
. . . . |
| 1786 |
seats=Resource(capacity=100) |
| 1787 |
sold_out=SimEvent() # signals "out of seats" |
| 1788 |
too_late=SimEvent() # signals "too late for this show" |
| 1789 |
. . . . |
| 1790 |
# Leave the ticket counter queue when movie sold out |
| 1791 |
# or it is too late for the show |
| 1792 |
yield (request,self,seats),(waitevent,self,[sold_out,too_late]) |
| 1793 |
if self.acquired(seats): |
| 1794 |
# watch the movie |
| 1795 |
yield hold,self,120 |
| 1796 |
yield release,self,seats |
| 1797 |
else: |
| 1798 |
# did not get a seat |
| 1799 |
print 'Who needs to see this silly movie anyhow?' |
| 1800 |
|
| 1801 |
------------ |
| 1802 |
|
| 1803 |
|
| 1804 |
Exiting conventions and preemptive queues |
| 1805 |
++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| 1806 |
|
| 1807 |
Many discrete event simulations (including SimPy) adopt the normal |
| 1808 |
"exiting convention", according to which processes that have once |
| 1809 |
started using a Resource unit stay in some Resource queue until their |
| 1810 |
``hold`` time has completed. This is of course automatically the case |
| 1811 |
for FIFO and non-preemptable ``PriorityQ`` disciplines. The point is |
| 1812 |
that the exiting convention is also applied in the ``preemptable`` queue |
| 1813 |
discipline case. Thus, processes remain in some Resource queue until |
| 1814 |
their ``hold`` time has completed, even if they are preempted by higher |
| 1815 |
priority processes. |
| 1816 |
|
| 1817 |
Some real-world situations conform to this convention and some do |
| 1818 |
not. An example of one that does conform can be described as |
| 1819 |
follows. Suppose that at work you are assigned tasks of varying levels |
| 1820 |
of priority. You are to set aside lower priority tasks in order to |
| 1821 |
work on higher priority ones. But you are eventually to complete all |
| 1822 |
of your assigned tasks. So you are operating like a SimPy resource |
| 1823 |
that obeys a ``preemptable`` queue discipline and has one resource |
| 1824 |
unit. With this convention, half-finished low-priority tasks may be |
| 1825 |
postponed indefinitely if they are continually preempted by |
| 1826 |
higher-priority tasks. |
| 1827 |
|
| 1828 |
An example that does not conform to the exiting convention can |
| 1829 |
be described as follows. Suppose again that you are assigned tasks of |
| 1830 |
varying levels of priority and are to set aside lower priority tasks |
| 1831 |
to work on higher priority ones. But you are instructed that any tasks |
| 1832 |
not completed within 24 hours after being assigned are to |
| 1833 |
be sent to another department for completion. Now, suppose |
| 1834 |
that you are assigned Task-A that has a priority level of 3 and will |
| 1835 |
take 10 hours to complete. After working on Task-A for an hour, you |
| 1836 |
are assigned Task-B, which has a priority level of 5 and will take 20 |
| 1837 |
hours to complete. Then, at 11 hours, after working on Task-B for 10 |
| 1838 |
hours, you are assigned Task-C, which has a priority level of 1 and |
| 1839 |
will take 4 hours to complete. (At this point Task-B needs 10 hours to |
| 1840 |
complete, Task-A needs 9 hours to complete, and Task-C needs 4 hours |
| 1841 |
to complete.) At 21 hours you complete Task-B and resume working on |
| 1842 |
Task-A, which at that point needs 9 hours to complete. At 24 hours |
| 1843 |
Task-A still needs another 6 hours to complete, but it has reached the |
| 1844 |
24-hour deadline and so is sent to another department for |
| 1845 |
completion. At the same time, Task-C has been in the waitQ for 13 |
| 1846 |
hours, so you take it up and complete it at hour 28. This queue |
| 1847 |
discipline does not conform to the exiting convention, for under that |
| 1848 |
convention at 24 hours you would continue work on Task-A, |
| 1849 |
complete it at hour 30, and then start on Task-C. |
| 1850 |
|
| 1851 |
|
| 1852 |
.. index:: Resource; monitor queue lengths |
| 1853 |
|
| 1854 |
Recording Resource queue lengths |
| 1855 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 1856 |
|
| 1857 |
Many discrete event models are used mainly to explore the |
| 1858 |
statistical properties of the ``waitQ`` and ``activeQ`` associated with |
| 1859 |
some or all of their simulated resources. SimPy's support for this |
| 1860 |
includes the `Monitor`_ and the `Tally`_. For more information on |
| 1861 |
these and other recording |
| 1862 |
methods, see the section on `Recording Simulation Results`_. |
| 1863 |
|
| 1864 |
|
| 1865 |
If a Resource, ``r``, is defined with ``monitored=True`` SimPy |
| 1866 |
automatically records the length of its associated ``waitQ`` and |
| 1867 |
``activeQ``. These records are kept in the recorder objects called |
| 1868 |
``r.waitMon`` and ``r.actMon``, respectively. This solves a problem, |
| 1869 |
particularly for the ``waitQ`` which cannot easily be recorded |
| 1870 |
externally to the resource. |
| 1871 |
|
| 1872 |
The property ``monitorType`` indicates which variety of recorder is to |
| 1873 |
be used, either Monitor_ or Tally_. The default is ``Monitor``. If |
| 1874 |
this is chosen, complete time series for both queue lengths are |
| 1875 |
maintained and can be used for advanced post-simulation statistical |
| 1876 |
analyses as well as for displaying summary statistics (such as |
| 1877 |
averages, standard deviations, and histograms). If ``Tally`` is chosen |
| 1878 |
summary statistics can be displayed, but complete time series |
| 1879 |
cannot. For more information on these and SimPy's other recording |
| 1880 |
methods, see the section on `Recording Simulation Results`_. |
| 1881 |
|
| 1882 |
------------ |
| 1883 |
|
| 1884 |
**Example** The following program uses a ``Monitor`` to record the |
| 1885 |
``server`` resource's queues. After the simulation ends, it displays |
| 1886 |
some summary statistics for each queue, and then their complete time |
| 1887 |
series: |
| 1888 |
|
| 1889 |
|
| 1890 |
.. include:: programs/resourcemonitor.py |
| 1891 |
:literal: |
| 1892 |
|
| 1893 |
The output from this program is:: |
| 1894 |
|
| 1895 |
c1 requests 1 unit at t = 0 |
| 1896 |
c2 requests 1 unit at t = 0 |
| 1897 |
c3 requests 1 unit at t = 0 |
| 1898 |
c4 requests 1 unit at t = 0 |
| 1899 |
c1 done at t = 100 |
| 1900 |
c2 done at t = 200 |
| 1901 |
c3 done at t = 300 |
| 1902 |
c4 done at t = 400 |
| 1903 |
|
| 1904 |
(Time) Average no. waiting: 1.5 |
| 1905 |
(Number) Average no. waiting: 1.5 |
| 1906 |
(Number) Var of no. waiting: 0.916666666667 |
| 1907 |
(Number) SD of no. waiting: 0.957427107756 |
| 1908 |
(Time) Average no. in service: 1.0 |
| 1909 |
(Number) Average no. in service: 0.5 |
| 1910 |
(Number) Var of no. in service: 0.25 |
| 1911 |
(Number) SD of no. in service: 0.5 |
| 1912 |
======================================== |
| 1913 |
Time history for the 'server' waitQ: |
| 1914 |
[time, waitQ] |
| 1915 |
[0, 1] |
| 1916 |
[0, 2] |
| 1917 |
[0, 3] |
| 1918 |
[100, 2] |
| 1919 |
[200, 1] |
| 1920 |
[300, 0] |
| 1921 |
======================================== |
| 1922 |
Time history for the 'server' activeQ: |
| 1923 |
[time, activeQ] |
| 1924 |
[0, 1] |
| 1925 |
[100, 0] |
| 1926 |
[100, 1] |
| 1927 |
[200, 0] |
| 1928 |
[200, 1] |
| 1929 |
[300, 0] |
| 1930 |
[300, 1] |
| 1931 |
[400, 0] |
| 1932 |
|
| 1933 |
This output illustrates the difference between the *(Time) Average* |
| 1934 |
and the *number statistics*. Here process ``c1`` was in the ``waitQ`` |
| 1935 |
for zero time units, process ``c2`` for 100 time units, and so |
| 1936 |
forth. The total wait time accumulated by all four processes during |
| 1937 |
the entire simulation run, which ended at time 400, amounts to 0 + 100 |
| 1938 |
+ 200 + 300 = 600 time units. Dividing the 600 accumulated time units |
| 1939 |
by the simulation run time of 400 gives 1.5 for the *(Time) Average* |
| 1940 |
number of processes in the ``waitQ``. It is the time-weighted average |
| 1941 |
length of the ``waitQ``, but is almost always called simply the average |
| 1942 |
length of the ``waitQ`` or the average number of items waiting for a |
| 1943 |
resource. |
| 1944 |
|
| 1945 |
It is also the expected number of processes you would find in the |
| 1946 |
``waitQ`` if you took a snapshot of it at a random time during the |
| 1947 |
simulation. The ``activeQ``\ 's time average computation is similar, |
| 1948 |
although in this example the resource is held by some process |
| 1949 |
throughout the simulation. Even though the number in the ``activeQ`` |
| 1950 |
momentarily drops to zero as one process releases the resource and |
| 1951 |
immediately rises to one as the next process acquires it, that occurs |
| 1952 |
instantaneously and so contributes nothing to the *(Time) Average* |
| 1953 |
computation. |
| 1954 |
|
| 1955 |
------------ |
| 1956 |
|
| 1957 |
*Number statistics* such as the Average, Variance, and Standard |
| 1958 |
Deviation are computed differently. At time zero the number of |
| 1959 |
processes in the ``waitQ`` starts at 1, then rises to 2, and then |
| 1960 |
to 3. At time 100 it drops back to two processes, and so forth. The |
| 1961 |
average and standard deviation of the six values [1, 2, 3, 2, 1, 0] is |
| 1962 |
1.5 and 0.9574..., respectively. Number statistics for the ``activeQ`` |
| 1963 |
are computed using the eight values [1, 0, 1, 0, 1, 0, 1, 0] and are |
| 1964 |
as shown in the output. |
| 1965 |
|
| 1966 |
When the ``monitorType`` is changed to ``Tally``, all the output up to |
| 1967 |
and including the lines:: |
| 1968 |
|
| 1969 |
Time history for the 'server' waitQ: |
| 1970 |
[time, waitQ] |
| 1971 |
|
| 1972 |
is displayed. Then the output concludes with an error message |
| 1973 |
indicating a problem with the reference to ``server.waitMon``. Of |
| 1974 |
course, this is because ``Tally`` does not generate complete time |
| 1975 |
series. |
| 1976 |
|
| 1977 |
|
| 1978 |
[Return to Top_ ] |
| 1979 |
|
| 1980 |
.. ========================================================================== |
| 1981 |
|
| 1982 |
|
| 1983 |
.. index:: ! Level |
| 1984 |
|
| 1985 |
Levels |
| 1986 |
----------- |
| 1987 |
|
| 1988 |
The three resource facilities provided by the SimPy system are |
| 1989 |
Resources_, Levels_ and Stores_. Each models a congestion point where |
| 1990 |
process objects may have to queue up to obtain resources. This section |
| 1991 |
describes the Level type of resource facility. |
| 1992 |
|
| 1993 |
Levels model the production and consumption of a homogeneous |
| 1994 |
undifferentiated "material." Thus, the currently-available amount of |
| 1995 |
material in a Level resource facility can be fully described by a |
| 1996 |
scalar (real or integer). Process objects may increase or decrease the |
| 1997 |
currently-available amount of material in a Level facility. |
| 1998 |
|
| 1999 |
For example, a gasoline station stores gas (petrol) in large |
| 2000 |
tanks. Tankers increase, and refuelled cars decrease, the amount of gas |
| 2001 |
in the station's storage tanks. Both getting amounts and putting |
| 2002 |
amounts may be subjected to reneging_ like requesting amounts from a |
| 2003 |
Resource. |
| 2004 |
|
| 2005 |
.. index:: Level; definition |
| 2006 |
|
| 2007 |
Defining a Level |
| 2008 |
~~~~~~~~~~~~~~~~~~ |
| 2009 |
|
| 2010 |
You define the Level resource facility *lev* by a statement like this:: |
| 2011 |
|
| 2012 |
lev = Level(name='a_level', unitName='units', |
| 2013 |
capacity='unbounded', initialBuffered=0, |
| 2014 |
putQType=FIFO, getQType=FIFO, |
| 2015 |
monitored=False, monitorType=Monitor) |
| 2016 |
|
| 2017 |
where |
| 2018 |
|
| 2019 |
- ``name`` (string type) is a descriptive name for the Level object *lev* is |
| 2020 |
known (e.g., ``'inventory'``). |
| 2021 |
- ``unitName`` (string type) is a descriptive name for the units in which the |
| 2022 |
amount of material in *lev* is measured (e.g., ``'kilograms'``). |
| 2023 |
- ``capacity`` (positive real or integer) is the capacity of the Level |
| 2024 |
object *lev*. The default value is set to ``'unbounded'`` which is |
| 2025 |
interpreted as ``sys.maxint``. |
| 2026 |
- ``initialBuffered`` (positive real or integer) is the initial amount of |
| 2027 |
material in the Level object *lev*. |
| 2028 |
- ``putQType`` (``FIFO`` or ``PriorityQ``) is the (producer) queue |
| 2029 |
discipline. |
| 2030 |
- ``getQType`` (``FIFO`` or ``PriorityQ``) is the (consumer) queue |
| 2031 |
discipline. |
| 2032 |
- ``monitored`` (boolean) specifies whether the queues and the amount |
| 2033 |
of material in *lev* will be recorded. |
| 2034 |
- ``monitorType`` (``Monitor`` or ``Tally``) specifies which type of |
| 2035 |
Recorder_ to use. Defaults to ``Monitor``. |
| 2036 |
|
| 2037 |
Every Level resource object, such as ``lev``, also has the following |
| 2038 |
additional attributes: |
| 2039 |
|
| 2040 |
- ``lev.amount`` is the amount currently held in *lev*. |
| 2041 |
|
| 2042 |
- ``lev.putQ`` is the queue of processes waiting to add amounts to *lev*, |
| 2043 |
so ``len(lev.putQ)`` is the number of processes waiting to add |
| 2044 |
amounts. |
| 2045 |
|
| 2046 |
- ``lev.getQ`` is the queue of processes waiting to get amounts from |
| 2047 |
*lev*, so ``len(lev.getQ)`` is the number of processes waiting to |
| 2048 |
get amounts. |
| 2049 |
|
| 2050 |
- ``lev.monitored`` is ``True`` if the queues are to be recorded. In |
| 2051 |
this case ``lev.putQMon``, ``lev.getQMon``, and ``lev.bufferMon`` |
| 2052 |
exist. |
| 2053 |
|
| 2054 |
- ``lev.putQMon`` is a Recorder_ observing ``lev.putQ``. |
| 2055 |
|
| 2056 |
- ``lev.getQMon`` is a Recorder_ observing ``lev.getQ``. |
| 2057 |
|
| 2058 |
- ``lev.bufferMon`` is a Recorder_ observing ``lev.amount``. |
| 2059 |
|
| 2060 |
|
| 2061 |
.. index:: Level; get |
| 2062 |
|
| 2063 |
Getting amounts from a Level |
| 2064 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 2065 |
|
| 2066 |
|
| 2067 |
.. |yget| replace:: ``yield get,self,``\ *lev,ask[,P]* |
| 2068 |
|
| 2069 |
Processes can request amounts from a Level and the same or other |
| 2070 |
processes can offer amounts to it. |
| 2071 |
|
| 2072 |
A process, the *requester*, can request an amount *ask* from the |
| 2073 |
Level resource object *lev* by a ``yield get`` statement.: |
| 2074 |
|
| 2075 |
* ``yield get,self,``\ *lev,ask[,P]* |
| 2076 |
|
| 2077 |
Here *ask* must be a positive real or integer (the amount) and *P* is |
| 2078 |
an optional priority value (real or integer). If *lev* does not hold |
| 2079 |
enough to satisfy the request (that is, *ask > lev*\ ``.amount``) the |
| 2080 |
requesting process is passivated and queued (in *lev*\ ``.getQ``) in order |
| 2081 |
of its priority. Subject to the priority order, it will be reactivated |
| 2082 |
when there is enough to satisfy the request. |
| 2083 |
|
| 2084 |
``self.got`` holds the amount actually received by the requester. |
| 2085 |
|
| 2086 |
|
| 2087 |
..index:: Level; put |
| 2088 |
|
| 2089 |
Putting amounts into a Level |
| 2090 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 2091 |
|
| 2092 |
.. |yput| replace:: ``yield put,self,``\ *lev,give[,P]* |
| 2093 |
|
| 2094 |
|
| 2095 |
A process, the *offerer*, which is usually but not necessarily |
| 2096 |
different from the *requester*, can offer an amount *give* to a Level, |
| 2097 |
*lev*, by a ``yield put`` statement: |
| 2098 |
|
| 2099 |
* ``yield put,self,``\ *lev,give[,P]* |
| 2100 |
|
| 2101 |
Here *give* must be a positive real or integer, and *P* is an optional |
| 2102 |
priority value (real or integer). If the amount offered would lead to |
| 2103 |
an overflow (that is, *lev.*\ ``amount`` + *give > lev.*\ |
| 2104 |
``capacity``) the offering process is passivated and queued (in |
| 2105 |
``lev.putQ``). Subject to the priority order, it will be reactivated |
| 2106 |
when there is enough space to hold the amount offered. |
| 2107 |
|
| 2108 |
The orderings of processes in a Level's ``getQ`` and ``putQ`` behave like |
| 2109 |
those described for the ``waitQ`` under Resources_, except that they are |
| 2110 |
not preemptable. Thus, priority values are ignored when the queue |
| 2111 |
type is FIFO. Otherwise higher priority values have higher priority, |
| 2112 |
etc. |
| 2113 |
|
| 2114 |
.. index:: example; Level |
| 2115 |
|
| 2116 |
------------ |
| 2117 |
|
| 2118 |
**Example**. Suppose that a random demand on an inventory is made each |
| 2119 |
day. Each requested amount is distributed normally with a mean of 1.2 |
| 2120 |
units and a standard deviation of 0.2 units. The inventory (modelled |
| 2121 |
as an object of the Level class) is refilled by 10 units at fixed |
| 2122 |
intervals of 10 days. There are no back-orders, but a accumulated sum |
| 2123 |
of the total stock-out quantities is to be maintained. A trace is to |
| 2124 |
be printed out each day and whenever there is a stock-out: |
| 2125 |
|
| 2126 |
.. include:: programs/levelinventory.py |
| 2127 |
:literal: |
| 2128 |
|
| 2129 |
|
| 2130 |
Here is the last ten day's output from one run of this program:: |
| 2131 |
|
| 2132 |
at 40.0000, add 10.0000 units, now amount = 10.0000 |
| 2133 |
day 40.0000, supplied 0.7490, now amount = 9.2510 |
| 2134 |
day 41.0000, supplied 1.1651, now amount = 8.0858 |
| 2135 |
day 42.0000, supplied 1.1117, now amount = 6.9741 |
| 2136 |
day 43.0000, supplied 1.1535, now amount = 5.8206 |
| 2137 |
day 44.0000, supplied 0.9202, now amount = 4.9004 |
| 2138 |
day 45.0000, supplied 0.8990, now amount = 4.0014 |
| 2139 |
day 46.0000, supplied 1.1448, now amount = 2.8566 |
| 2140 |
day 47.0000, supplied 1.7287, now amount = 1.1279 |
| 2141 |
day 48.0000, supplied 0.9608, now amount = 0.1670 |
| 2142 |
day 49.0000, demand = 0.9837, shortfall = -0.8167 |
| 2143 |
|
| 2144 |
Summary of results through end of day 49.0000: |
| 2145 |
average stock = 4.2720, cumulative stockout = 9.7484 |
| 2146 |
|
| 2147 |
------------ |
| 2148 |
|
| 2149 |
[Return to Top_ ] |
| 2150 |
|
| 2151 |
.. index:: Level; reneging |
| 2152 |
pair: Level; abandoning |
| 2153 |
|
| 2154 |
Reneging |
| 2155 |
~~~~~~~~~~~~~~ |
| 2156 |
|
| 2157 |
.. |ryput| replace:: ``yield (put,self,``\ *lev,ask[,P]*\ ``),`` |
| 2158 |
|
| 2159 |
The ``yield put`` can be subject to reneging_ using one of the compound |
| 2160 |
statements: |
| 2161 |
|
| 2162 |
* |ryput|\ ``(hold,self,``\ *waittime*\ ``)`` |
| 2163 |
|
| 2164 |
where if the process does not acquire the amount before *waittime* is |
| 2165 |
elapsed, the offerer leaves the ``waitQ`` and its execution continues or |
| 2166 |
|
| 2167 |
* |ryput|\ ``(waitevent,self,``\ *events*\ ``)`` |
| 2168 |
|
| 2169 |
where if one of the SimEvents in *events* occurs before enough becomes |
| 2170 |
available, the offerer leaves the ``waitQ`` and its execution |
| 2171 |
continues. |
| 2172 |
|
| 2173 |
In either case if reneging has *not* occurred the quantity will have |
| 2174 |
been put into the Level and ``self.stored(``\ *lev*\ ``)`` will be |
| 2175 |
``True``. This must be tested immediately after the ``yield``:: |
| 2176 |
|
| 2177 |
yield (put,self,lev,ask[,P]),(<reneging clause>) |
| 2178 |
if self.stored(lev): |
| 2179 |
## process did not renege |
| 2180 |
. . . . |
| 2181 |
else: |
| 2182 |
## process reneged before being able to put into the resource |
| 2183 |
|
| 2184 |
|
| 2185 |
The ``yield get`` can also be subject to reneging_ using one of the compound |
| 2186 |
statements: |
| 2187 |
|
| 2188 |
* ``yield (get,self,lev,ask[,P]),(hold,self,waittime)`` |
| 2189 |
|
| 2190 |
where if the process does not acquire the amount before *waittime* is |
| 2191 |
elapsed, the offerer leaves the ``waitQ`` and its execution continues. |
| 2192 |
|
| 2193 |
* ``yield (get,self,lev,ask[,P]),(waitevent,self,events)`` |
| 2194 |
|
| 2195 |
where if one of the SimEvents in *events* occurs before enough becomes |
| 2196 |
available, reneging occurs, the offerer leaves the ``waitQ`` and its execution |
| 2197 |
continues. |
| 2198 |
|
| 2199 |
In either case if reneging has *not* occurred ``self.got == ask`` and |
| 2200 |
``self.acquired(lev)`` will be ``True``. ``self.acquired(lev)`` must be called |
| 2201 |
immediately after the ``yield``:: |
| 2202 |
|
| 2203 |
yield (get,self,lev,ask[,P]),(<reneging clause>) |
| 2204 |
if self.acquired(lev): |
| 2205 |
## process did not renege, self.got == ask |
| 2206 |
. . . . |
| 2207 |
else: |
| 2208 |
## process reneged before being able to put into the resource |
| 2209 |
|
| 2210 |
This test removes the reneging process from the ``getQ``. |
| 2211 |
|
| 2212 |
[Return to Top_ ] |
| 2213 |
|
| 2214 |
.. ================================================================= |
| 2215 |
|
| 2216 |
.. index:: ! Store |
| 2217 |
|
| 2218 |
Stores |
| 2219 |
----------- |
| 2220 |
|
| 2221 |
The three resource facilities provided by the SimPy system are |
| 2222 |
Resources_, Levels_ and Stores_. Each models a congestion point where |
| 2223 |
process objects may have to queue up to obtain resources. This section |
| 2224 |
describes the Store type of resource facility. |
| 2225 |
|
| 2226 |
Stores model the production and consumption of individual items of any |
| 2227 |
Python type. Process objects can insert or remove specific items from |
| 2228 |
the list of items available in a Store. For example, surgical |
| 2229 |
procedures (treated as process objects) require specific lists of |
| 2230 |
personnel and equipment that may be treated as the items available in |
| 2231 |
a Store type of resource facility such as a clinic or hospital. As the |
| 2232 |
items held in a Store may be of any Python type, they may in |
| 2233 |
particular be process objects, and this can be exploited to facilitate |
| 2234 |
modelling Master/Slave relationships. *putting* and *getting* may also |
| 2235 |
be subjected to reneging. |
| 2236 |
|
| 2237 |
.. index:: Store; definition |
| 2238 |
|
| 2239 |
Defining a Store |
| 2240 |
~~~~~~~~~~~~~~~~~~~ |
| 2241 |
|
| 2242 |
The Store object ``sObj`` is established by a statement |
| 2243 |
like the following:: |
| 2244 |
|
| 2245 |
sObj = Store(name='a_store', |
| 2246 |
unitName='units', |
| 2247 |
capacity='unbounded', |
| 2248 |
initialBuffered=None, |
| 2249 |
putQType=FIFO, |
| 2250 |
getQType=FIFO, |
| 2251 |
monitored=False, |
| 2252 |
monitorType=Monitor) |
| 2253 |
|
| 2254 |
where |
| 2255 |
|
| 2256 |
- ``name`` (string type) is a descriptive name for *sObj* (e.g., |
| 2257 |
``'Inventory'``). |
| 2258 |
- ``unitName`` (string type) is a descriptive name for the items |
| 2259 |
in *sObj* (e.g., ``'widgets'``). |
| 2260 |
- ``capacity`` (positive integer) is the maximum number of |
| 2261 |
individual items that can be held in *sObj*. |
| 2262 |
The default value is set to ``'unbounded'`` which is |
| 2263 |
interpreted as ``sys.maxint``. |
| 2264 |
- ``initialBuffered`` (a list of individual items) is *sObj*'s initial content. |
| 2265 |
- ``putQType`` (``FIFO`` or ``PriorityQ``) is the (producer) queue |
| 2266 |
discipline. |
| 2267 |
- ``getQType`` (``FIFO`` or ``PriorityQ``) is the (consumer) queue discipline. |
| 2268 |
- ``monitored`` (boolean) specifies whether *sObj*'s queues and contents |
| 2269 |
are to be recorded. |
| 2270 |
- ``monitorType`` (``Monitor`` or ``Tally``) specifies the type of Recorder_ |
| 2271 |
to be used. Defaults to ``Monitor``. |
| 2272 |
|
| 2273 |
The Store object *sObj* also has the following additional attributes: |
| 2274 |
|
| 2275 |
- ``sObj.theBuffer`` is a queue (list) of the individual items in *sObj*. |
| 2276 |
This list is in FIFO order unless the user stores them in a particular |
| 2277 |
order (see `Storing objects in an order`_ , below). It is |
| 2278 |
read-only and not directly changeable by the user. |
| 2279 |
|
| 2280 |
- ``sObj.nrBuffered`` is the current number of objects in *sObj*. |
| 2281 |
This is read-only and not directly changeable by the user. |
| 2282 |
|
| 2283 |
- ``sObj.putQ`` is the queue of processes waiting to add items to *sObj*, |
| 2284 |
so that ``len(sObj.putQ)`` is the number of processes waiting to add items. |
| 2285 |
|
| 2286 |
- ``sObj.getQ`` is the queue of processes waiting to get items from |
| 2287 |
*sObj*, so that ``len(sObj.getQ)`` is the number of processes waiting to |
| 2288 |
get items. |
| 2289 |
|
| 2290 |
- If ``sObj.monitored`` is ``True`` then the queues are to be recorded. |
| 2291 |
In this case ``sObj.putQMon``, |
| 2292 |
``sObj.getQMon``, and ``sObj.bufferMon`` exist. |
| 2293 |
|
| 2294 |
- ``sObj.putQMon`` is a Recorder_ observing ``sObj.putQ``. |
| 2295 |
|
| 2296 |
- ``sObj.getQMon`` is a Recorder_ observing ``sObj.getQ``. |
| 2297 |
|
| 2298 |
- ``sObj.bufferMon`` is a Recorder_ observing ``sObj.nrBuffered``. |
| 2299 |
|
| 2300 |
|
| 2301 |
.. index:: yield;put |
| 2302 |
|
| 2303 |
Putting objects into a Store |
| 2304 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 2305 |
|
| 2306 |
Processes can request items from a Store and the same or |
| 2307 |
other processes can offer items to it. First look at the simpler of |
| 2308 |
these operations, the ``yield put``. |
| 2309 |
|
| 2310 |
A process, the *offerer*, which is usually but not necessarily |
| 2311 |
different from the *requester*, can offer a list of |
| 2312 |
items to *sObj* by a ``yield put`` statement: |
| 2313 |
|
| 2314 |
* ``yield put,self,sObj,give[,P]`` |
| 2315 |
|
| 2316 |
Here ``give`` is a list of any Python objects. If this statement would |
| 2317 |
lead to an overflow (that is, ``sObj.nrBuffered + len(give) > |
| 2318 |
sObj.capacity``) the putting process is passivated and queued (in |
| 2319 |
``sObj.putQ``) until there is sufficient room. *P* is an optional |
| 2320 |
priority value (real or integer). |
| 2321 |
|
| 2322 |
The ordering of processes in a Store's putQ and getQ behave like those |
| 2323 |
described for the waitQ under Resources_ , except that they are not |
| 2324 |
preemptable. Thus, priority values are ignored when the queue type is |
| 2325 |
FIFO. Otherwise higher priority values indicate higher priority, etc. |
| 2326 |
|
| 2327 |
The items in *sObj* are stored in the form of a queue called |
| 2328 |
``sObj.theBuffer``, which is in FIFO order unless the user has |
| 2329 |
arranged to sort them into a particular order (see `Storing objects in |
| 2330 |
an order`_ below). |
| 2331 |
|
| 2332 |
|
| 2333 |
.. index:: yield; get |
| 2334 |
|
| 2335 |
Getting objects from a Store |
| 2336 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 2337 |
|
| 2338 |
There are two ways of getting objects from a Store. A process, the |
| 2339 |
*requester*, can either extract the first ``n`` objects from *sObj* or a list |
| 2340 |
of items chosen by a *filter function*. |
| 2341 |
|
| 2342 |
Getting *n* items is achieved by the following statement: |
| 2343 |
|
| 2344 |
* ``yield get,self,sObj,n [,P]`` |
| 2345 |
|
| 2346 |
Here *n* must be a positive integer and *P* is an optional priority |
| 2347 |
value (real or integer). If *sObj* does not currently hold enough |
| 2348 |
objects to satisfy this request (that is, ``n > sObj.nrBuffered``) |
| 2349 |
then the requesting process is passivated and queued (in |
| 2350 |
``sObj.getQ``). Subject to the priority ordering, it will be |
| 2351 |
reactivated when the request can be satisfied. |
| 2352 |
|
| 2353 |
The retrieved objects are returned in the list attribute ``got`` of |
| 2354 |
the requesting process. |
| 2355 |
|
| 2356 |
``yield get`` requests with a numerical parameter are honored in |
| 2357 |
priority/FIFO order. Thus, if |
| 2358 |
there are two processes in the Store's ``getQ``, with the first requesting |
| 2359 |
two items and the second one, the second process gets the requested item |
| 2360 |
only after the first process has been given its two items. |
| 2361 |
|
| 2362 |
.. index:: yield;get with filter |
| 2363 |
|
| 2364 |
Using the get filter function |
| 2365 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 2366 |
|
| 2367 |
The second method is to get a list of items chosen by a *filter |
| 2368 |
function*, written by the user. |
| 2369 |
|
| 2370 |
The command, using filter function *ffn* is as follows: |
| 2371 |
|
| 2372 |
* ``yield get,self,sObj,ffn [,P]`` |
| 2373 |
|
| 2374 |
|
| 2375 |
The user provides a filter function that has a single list argument and |
| 2376 |
returns a list. The argument represents the buffer of the Store. The |
| 2377 |
function must search through the objects in the buffer and return a |
| 2378 |
sub-list of those that satisfy the requirement. |
| 2379 |
|
| 2380 |
.. index:: |
| 2381 |
triple: example; Store; yield get with filter |
| 2382 |
|
| 2383 |
------------ |
| 2384 |
|
| 2385 |
**Example** The filter function ``allweight``, shown below, is an example |
| 2386 |
of such a filter. The argument, ``buff``, will be automatically |
| 2387 |
replaced in the execution of |
| 2388 |
``yield get,self,store,allweight`` by the buffer of the Store. In this |
| 2389 |
example the objects in the Store are assumed to have ``weight`` |
| 2390 |
attributes. The function ``allweight`` selects all those that have a |
| 2391 |
weight attribute over a value ``W`` and returns these as a list. The |
| 2392 |
list appears to the calling process as ``self.got``:: |
| 2393 |
|
| 2394 |
def allweight(buff): |
| 2395 |
"""filter: get all items with .weight >=W from store""" |
| 2396 |
result=[] |
| 2397 |
for i in buff: |
| 2398 |
if i.weight>=W: |
| 2399 |
result.append(i) |
| 2400 |
return result |
| 2401 |
|
| 2402 |
This might be used as follows:: |
| 2403 |
|
| 2404 |
yield get,self,sObj,allweight [,P] |
| 2405 |
|
| 2406 |
The retrieved objects are returned in the list attribute ``got`` of |
| 2407 |
the requesting process. |
| 2408 |
|
| 2409 |
------------ |
| 2410 |
|
| 2411 |
**Note:** *``yield get``* requests with a filter function parameter |
| 2412 |
are not necessarily honored in priority/FIFO order, but rather |
| 2413 |
according to the filter function. An example: There are two processes |
| 2414 |
in the Store's ``getQ``, with the first requesting an item with a |
| 2415 |
*weight* attribute less than 2 kilograms and the second one requesting |
| 2416 |
one with a ``weight`` attribute less than 3 kilograms. If there is an |
| 2417 |
item in the Store's buffer with a ``weight`` attribute between 2 and 3 |
| 2418 |
and none with an attribute of less than 2, the second ``get`` requester |
| 2419 |
gets unblocked before the first one. Effectively, the SimPy run time |
| 2420 |
system runs through all processes in the ``getQ`` in sequence and |
| 2421 |
tests their filter functions as long as there are still items in the |
| 2422 |
Store's buffer. |
| 2423 |
|
| 2424 |
------------ |
| 2425 |
|
| 2426 |
**Example** The following program illustrates the use of a Store to |
| 2427 |
model the production and consumption of "widgets". The widgets are |
| 2428 |
distinguished by their weight: |
| 2429 |
|
| 2430 |
.. include:: programs/storewidget.py |
| 2431 |
:literal: |
| 2432 |
|
| 2433 |
|
| 2434 |
This program produces the following outputs |
| 2435 |
(some lines may be formatted differently):: |
| 2436 |
|
| 2437 |
0 Got widget weights [5, 5, 5] |
| 2438 |
0 Got widget weights [5, 5, 5] |
| 2439 |
0 Got widget weights [5, 5, 5] |
| 2440 |
11 Got widget weights [5, 9, 7] |
| 2441 |
11 Got widget weights [9, 7, 9] |
| 2442 |
11 Got widget weights [7, 9, 7] |
| 2443 |
22 Got widget weights [9, 7, 9] |
| 2444 |
22 Got widget weights [7, 9, 7] |
| 2445 |
22 Got widget weights [9, 7, 9] |
| 2446 |
33 Got widget weights [7, 9, 7] |
| 2447 |
33 Got widget weights [9, 7, 9] |
| 2448 |
40 Got widget weights [7, 9, 7] |
| 2449 |
44 Got widget weights [9, 7, 9] |
| 2450 |
50 Got widget weights [7, 9, 7] |
| 2451 |
LenBuffer: [[0, 10], [0, 7], [0, 9], [0, 11], [0, 8], [0, 10], [0, 7], |
| 2452 |
[10, 9], [10, 11], [11, 8], [11, 10], [11, 7], [11, 4], |
| 2453 |
[20, 6], [20, 8], [21, 10], [22, 7], [22, 4], [22, 1], |
| 2454 |
[30, 3], [30, 5], [31, 7], [33, 4], [33, 1], |
| 2455 |
[40, 3], [40, 0], [40, 2], [41, 4], [44, 1], [50, 3], [50, 0], [50, 2]] |
| 2456 |
getQ: [[0, 0], [33, 1], [40, 0], [44, 1], [50, 0]] |
| 2457 |
putQ [[0, 0], [0, 1], [0, 2], [0, 3], [0, 2], [0, 1], [0, 0], [10, 1],\ |
| 2458 |
[11, 0]] |
| 2459 |
|
| 2460 |
-------------- |
| 2461 |
|
| 2462 |
[Return to Top_ ] |
| 2463 |
|
| 2464 |
.. index:: yield; put with reneging |
| 2465 |
|
| 2466 |
|
| 2467 |
Reneging |
| 2468 |
~~~~~~~~~~~~~~ |
| 2469 |
|
| 2470 |
The ``yield put`` can be subject to reneging_ using one of the compound |
| 2471 |
statements: |
| 2472 |
|
| 2473 |
* ``yield (put,self,sObj,give [,P]),(hold,self,waittime)`` |
| 2474 |
|
| 2475 |
where if the process cannot put the list of objects in *give* before *waittime* is |
| 2476 |
elapsed, the offerer leaves the ``putQ`` and its execution continues or |
| 2477 |
|
| 2478 |
* ``yield (put,self,sObj,give [,P]),(waitevent,self,events)`` |
| 2479 |
|
| 2480 |
where if one of the SimEvents in *events* occurs before it can put the |
| 2481 |
list of objects in *give* the offerer leaves the ``putQ`` and its |
| 2482 |
execution continues. |
| 2483 |
|
| 2484 |
In either case if reneging has *not* occurred the list of objects in |
| 2485 |
*give* will have been put into the Store and ``self.stored(Sobj)`` will |
| 2486 |
be ``True``. |
| 2487 |
|
| 2488 |
The mandatory pattern for a ``put`` with reneging is:: |
| 2489 |
|
| 2490 |
yield (put,self,sObj,give [,P]),(<reneging clause>) |
| 2491 |
if self.stored(sObj): |
| 2492 |
## process did not renege |
| 2493 |
. . . . |
| 2494 |
else: |
| 2495 |
## process reneged before being able to put into the resource |
| 2496 |
|
| 2497 |
This is so because ``self.stored( )`` not only tests for reneging, but |
| 2498 |
it also cleanly removes a reneging process from the ``putQ``. |
| 2499 |
|
| 2500 |
The ``yield get`` can be subject to similar reneging_ using one of the compound |
| 2501 |
statements: |
| 2502 |
|
| 2503 |
* ``yield (get,self,sObj,n [,P]),(hold,self,waittime)`` |
| 2504 |
* ``yield (get,self,sObj,ffn [,P]),(hold,self,waittime)`` |
| 2505 |
|
| 2506 |
where if the process does not acquire the amount before *waittime* is |
| 2507 |
elapsed, the offerer leaves the ``waitQ`` and its execution continues. |
| 2508 |
|
| 2509 |
* ``yield (get,self,sObj,n [,P]),(waitevent,self,events)`` |
| 2510 |
* ``yield (get,self,sObj,ffn [,P]),(waitevent,self,events)`` |
| 2511 |
|
| 2512 |
where if one of the SimEvents in *events* occurs before enough becomes |
| 2513 |
available, reneging occurs, the offerer leaves the ``waitQ`` and its execution |
| 2514 |
continues. |
| 2515 |
|
| 2516 |
In either case if reneging has *not* occurred ``self.got`` contains |
| 2517 |
the list of retrieved objects and ``self.acquired(Sobj)`` will be |
| 2518 |
``True``. |
| 2519 |
|
| 2520 |
The mandatory pattern for a ``get`` with reneging is:: |
| 2521 |
|
| 2522 |
yield (get,self,lev,sObj,<n or ffn> [,P]),(<reneging clause>) |
| 2523 |
if self.acquired(sObj): |
| 2524 |
## process did not renege, |
| 2525 |
. . . . |
| 2526 |
else: |
| 2527 |
## process reneged before being able to put into the resource |
| 2528 |
|
| 2529 |
This is so because ``self.acquired( )`` not only tests for reneging, but |
| 2530 |
it also cleanly removes a reneging process from the ``getQ``. |
| 2531 |
|
| 2532 |
[Return to Top_ ] |
| 2533 |
|
| 2534 |
.. index:: yield; put in order |
| 2535 |
pair: yield; get in order |
| 2536 |
|
| 2537 |
Storing objects in an order |
| 2538 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 2539 |
|
| 2540 |
The contents of a Store instance are listed in a queue. By default, |
| 2541 |
this list is kept in FIFO order. However, the list can be kept in a |
| 2542 |
user-defined order. You do this by defining a function for reordering |
| 2543 |
the list and adding it to the Store instance for which you want to |
| 2544 |
change the list order. Subsequently, the SimPy system will |
| 2545 |
automatically call that function after any addition (``put``) to the |
| 2546 |
queue. |
| 2547 |
|
| 2548 |
.. index:: |
| 2549 |
triple: Store; example; parcel |
| 2550 |
|
| 2551 |
------------ |
| 2552 |
|
| 2553 |
**Example** :: |
| 2554 |
|
| 2555 |
class Parcel: |
| 2556 |
def __init__(self,weight): |
| 2557 |
self.weight=weight |
| 2558 |
|
| 2559 |
lightFirst=Store() |
| 2560 |
|
| 2561 |
def getLightFirst(self,par): |
| 2562 |
"""Lighter parcels to front of queue""" |
| 2563 |
tmplist=[(x.weight,x) for x in par] |
| 2564 |
tmplist.sort() |
| 2565 |
return [x for (key,x) in tmplist] |
| 2566 |
|
| 2567 |
lightFirst.addSort(getLightFirst) |
| 2568 |
|
| 2569 |
Now any ``yield get`` will get the lightest parcel in ``lightFirst``'s |
| 2570 |
queue. |
| 2571 |
|
| 2572 |
------------ |
| 2573 |
|
| 2574 |
The ``par`` parameter is automatically given the Store's buffer list as value |
| 2575 |
when the SimPy run time system calls the re-ordering function. |
| 2576 |
|
| 2577 |
*<aStore>.addSort(<reorderFunction>)* adds a re-order function to <aStore>. |
| 2578 |
|
| 2579 |
Note that such function only changes the sorting order of the Store instance, |
| 2580 |
NOT of the Store class. |
| 2581 |
|
| 2582 |
|
| 2583 |
.. index:: |
| 2584 |
triple: Store; example; master/slave |
| 2585 |
|
| 2586 |
Master/Slave modelling with a Store |
| 2587 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 2588 |
|
| 2589 |
The items in a ``Store`` can be of any Python type. In particular, they |
| 2590 |
may be SimPy processes. This can be used to model |
| 2591 |
a Master/Slave situation -- an asymmetrical cooperation between two or |
| 2592 |
more processes, with one process (the Master) being in charge of the |
| 2593 |
cooperation. |
| 2594 |
|
| 2595 |
The consumer (Master) requests one or more Slaves to be added to the |
| 2596 |
Store's contents by the Producer (which may be the same process as the |
| 2597 |
Slave). For Master/Slave cooperation, the Slave has to be passivated |
| 2598 |
(by a ``yield passivate`` or ``yield waitevent`` statement) after it is |
| 2599 |
``put`` and reactivated when it is retrieved and finished with. As this |
| 2600 |
is NOT done automatically by the ``Store``, the Master has to signal the |
| 2601 |
end of the cooperation. This Master/Slave pattern results in the slave process' |
| 2602 |
life-cycle having a hole between the slave process arrival and its departure |
| 2603 |
after having been served. |
| 2604 |
|
| 2605 |
.. index:: |
| 2606 |
triple: example;Store;car wash |
| 2607 |
|
| 2608 |
------------ |
| 2609 |
|
| 2610 |
**Example** Cars arrive randomly at a car wash and add themselves to |
| 2611 |
the ``waitingCars`` queue. They wait (passively) for a ``doneSignal``. |
| 2612 |
There are two ``Carwash`` washers. These ``get`` a car, if one is |
| 2613 |
available, wash it, and then send the ``doneSignal`` to reactivate |
| 2614 |
it. We elect to model the ``Carwash`` as Master and the ``Cars`` as |
| 2615 |
slaves. |
| 2616 |
|
| 2617 |
Four cars are put into the ``waiting`` list and these make up the |
| 2618 |
initial set of cars waiting for service. Additional cars are generated |
| 2619 |
randomly by the ``CarGenerator`` process. Each car ``yield puts`` itself |
| 2620 |
onto the ``waitingCars`` ``Store`` and immediately passivates itself by |
| 2621 |
waiting for a ``doneSignal`` from a car washer. The car washers cycle |
| 2622 |
round ``getting`` the next car on the queue, washing it and then sending |
| 2623 |
a ``doneSignal`` to it when it has finished: |
| 2624 |
|
| 2625 |
.. include:: programs/carwash.py |
| 2626 |
:literal: |
| 2627 |
|
| 2628 |
The output of this program, running to time 30, is:: |
| 2629 |
|
| 2630 |
5 car -1 done by Carwash 0 |
| 2631 |
5 car -2 done by Carwash 1 |
| 2632 |
10 car -3 done by Carwash 0 |
| 2633 |
10 car -4 done by Carwash 1 |
| 2634 |
15 car 0 done by Carwash 0 |
| 2635 |
15 car 1 done by Carwash 1 |
| 2636 |
20 car 2 done by Carwash 0 |
| 2637 |
20 car 3 done by Carwash 1 |
| 2638 |
25 car 4 done by Carwash 0 |
| 2639 |
25 car 5 done by Carwash 1 |
| 2640 |
30 car 6 done by Carwash 0 |
| 2641 |
30 car 7 done by Carwash 1 |
| 2642 |
waitingCars [10, 11, 12, 13, 14] |
| 2643 |
|
| 2644 |
It is also possible to model this car wash with the cars as Master |
| 2645 |
and the ``Carwash`` as Slaves. |
| 2646 |
|
| 2647 |
------------ |
| 2648 |
|
| 2649 |
|
| 2650 |
[Return to Top_ ] |
| 2651 |
|
| 2652 |
.. ========================================================================== |
| 2653 |
|
| 2654 |
.. index:: Random numbers |
| 2655 |
|
| 2656 |
Random Number Generation |
| 2657 |
------------------------- |
| 2658 |
|
| 2659 |
Simulations usually need random numbers. As SimPy does not supply |
| 2660 |
random number generators of its own, users need to import them from |
| 2661 |
some other source. Perhaps the most convenient source is the standard |
| 2662 |
`Python random module`_. It can generate random variates from the |
| 2663 |
following continuous distributions: uniform, beta, exponential, gamma, |
| 2664 |
normal, log-normal, weibull, and vonMises. It can also generate random |
| 2665 |
variates from some discrete distributions. Consult the module's |
| 2666 |
documentation for details. (Excellent brief descriptions of these |
| 2667 |
distributions, and many others, can be found in the `Wikipedia |
| 2668 |
<http://www.wikipedia.com/>`_.) |
| 2669 |
|
| 2670 |
Python's ``random`` module can be used in two ways: you can import the |
| 2671 |
methods directly or you can import the ``Random`` class and make your |
| 2672 |
own random objects. In the second method, each object gives a |
| 2673 |
different random number sequence, thus providing multiple random |
| 2674 |
streams as in Simscript and ModSim. |
| 2675 |
|
| 2676 |
Here the first method is described (and minimally at that). A single |
| 2677 |
pseudo-random sequence is used for all calls. You ``import`` the |
| 2678 |
methods you need from the ``random`` module. For example:: |
| 2679 |
|
| 2680 |
from random import seed, random, expovariate, normalvariate |
| 2681 |
|
| 2682 |
In simulation it is good practice to set the initial ``seed`` for the |
| 2683 |
pseudo-random sequence at the start of each run. Then you have control |
| 2684 |
over the random numbers used. Replications and comparisons are |
| 2685 |
easier and, together with variance reduction techniques, can provide more |
| 2686 |
accurate estimates. In the following code snippet we set the initial |
| 2687 |
seed to 333555. ``X`` and ``Y`` are pseudo-random variates from the |
| 2688 |
two distributions. Both distributions have the same mean:: |
| 2689 |
|
| 2690 |
from random import seed, expovariate, normalvariate |
| 2691 |
|
| 2692 |
seed(333555) |
| 2693 |
X = expovariate(0.1) |
| 2694 |
Y = normalvariate(10.0, 1.0) |
| 2695 |
|
| 2696 |
|
| 2697 |
[Return to Top_ ] |
| 2698 |
|
| 2699 |
.. ============================================================================ |
| 2700 |
|
| 2701 |
.. index:: Monitor,Tally |
| 2702 |
|
| 2703 |
Recording Simulation Results |
| 2704 |
----------------------------- |
| 2705 |
|
| 2706 |
The ``Tally`` and ``Monitor`` class objects enable us to observe a single |
| 2707 |
variable of interest and to return a simple data summary either during |
| 2708 |
or at the completion of a simulation run. |
| 2709 |
|
| 2710 |
Both use the ``observe`` method to record data on one variable. For |
| 2711 |
example we might use a Monitor object to record the waiting times for |
| 2712 |
a sequence of customers and another to record the total number of |
| 2713 |
customers in the shop. In a discrete-event system the number of |
| 2714 |
customers changes only at arrival or departure events and it is at |
| 2715 |
those events that the waiting times and number in the shop must be |
| 2716 |
observed. Monitors and Tallys provide elementary statistics useful |
| 2717 |
either alone or as the start of a more sophisticated statistical |
| 2718 |
analysis and have proved invaluable in many simulations. |
| 2719 |
|
| 2720 |
A few more tools associated with recording results are: |
| 2721 |
|
| 2722 |
- All Monitors are registered automatically in the global list |
| 2723 |
variable ``allMonitors`` and all Tallys in variable |
| 2724 |
``allTallies``. When a simulation is completed results can easily be |
| 2725 |
tabulated and summarized using these lists. |
| 2726 |
|
| 2727 |
- The function ``startCollection()`` can be called to initialize Monitors |
| 2728 |
and Tallys at a certain simulation time. This is helpful when a |
| 2729 |
simulation needs a 'warmup' period to achieve steady state before |
| 2730 |
measurements are started. |
| 2731 |
|
| 2732 |
|
| 2733 |
Defining Tallys and Monitors |
| 2734 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 2735 |
|
| 2736 |
The ''Tally'' class records enough information (such as sums and sums of |
| 2737 |
squares) while the simulation runs to return simple data summaries. |
| 2738 |
This has the advantage of speed and low memory use. Tallys can also |
| 2739 |
furnish data for a histogram. However, they do not preserve a |
| 2740 |
time-series usable in more advanced statistical analysis. When a Tally |
| 2741 |
is defined it is automatically added to the global list ``allTallies``. |
| 2742 |
|
| 2743 |
.. index:: Tally;define |
| 2744 |
|
| 2745 |
To define a new Tally object: |
| 2746 |
|
| 2747 |
* ``m=Tally(name='a_Tally', ylab='y', tlab='t')`` |
| 2748 |
|
| 2749 |
- ``name`` is a descriptive name for the tally object (default='``a_Tally``' ). |
| 2750 |
|
| 2751 |
- ``ylab`` and ``tlab`` are descriptive labels used by the ``SimPy.SimPlot`` |
| 2752 |
package when plotting graphs of the recorded data. They |
| 2753 |
default to ``'y'`` and ``'t'``, respectively. (If a histogram_ is |
| 2754 |
required the method ``setHistogram`` must be called before recording |
| 2755 |
starts). |
| 2756 |
|
| 2757 |
The ``Monitor`` class preserves a complete time-series of the observed |
| 2758 |
data values, *y*, and their associated times, *t*. It calculates the |
| 2759 |
data summaries using these series only when they are needed. It is |
| 2760 |
slower and uses more memory than ``Tally``. In long simulations its |
| 2761 |
memory demands may be a disadvantage. When a Monitor is defined it is |
| 2762 |
automatically added to the global list ``allMonitors``. |
| 2763 |
|
| 2764 |
.. index:: Monitor; define |
| 2765 |
|
| 2766 |
To define a new Monitor object: |
| 2767 |
|
| 2768 |
* ``m=Monitor(name='a_Monitor', ylab='y', tlab='t')`` |
| 2769 |
|
| 2770 |
- ``name`` is a descriptive name for the Monitor object (default='``a_Monitor``'). |
| 2771 |
|
| 2772 |
- ``ylab`` and ``tlab`` are descriptive labels used by the ``SimPy.SimPlot`` |
| 2773 |
package when plotting graphs of the recorded data. They |
| 2774 |
default to ``'y'`` and ``'t'``, respectively. |
| 2775 |
(A histogram_ can be |
| 2776 |
requested at any time). |
| 2777 |
|
| 2778 |
.. _histogram: Histograms_ |
| 2779 |
|
| 2780 |
|
| 2781 |
.. index:: Monitor; observe |
| 2782 |
pair: Tally; observe |
| 2783 |
|
| 2784 |
Observing data |
| 2785 |
~~~~~~~~~~~~~~~~~ |
| 2786 |
|
| 2787 |
Both Tallys and Monitors use the ``observe`` method to record data. |
| 2788 |
Here and in the next section, *r* is either a Tally or a Monitor object: |
| 2789 |
|
| 2790 |
* ``r.observe(y [,t])`` records the current value of the variable, ``y`` |
| 2791 |
and time *t* (or the current time, ``now( )``, if *t* is missing). A |
| 2792 |
Monitor retains the two values as a sub-list ``[t,y]``. A Tally |
| 2793 |
uses them to update the accumulated statistics. |
| 2794 |
|
| 2795 |
To assure that time averages are calculated correctly ``observe`` |
| 2796 |
should be called immediately *after* a change in the variable. For |
| 2797 |
example, if we are using Monitor *r* to record the number *N* |
| 2798 |
of jobs in a system, the correct sequence of commands on an arrival |
| 2799 |
is:: |
| 2800 |
|
| 2801 |
N = N+1 # FIRST, increment the number of jobs |
| 2802 |
r.observe(N) # THEN observe the new value of N using r |
| 2803 |
|
| 2804 |
|
| 2805 |
The recording of data can be ``reset`` to start at any time in the |
| 2806 |
simulation: |
| 2807 |
|
| 2808 |
* ``r.reset([t])`` resets the observations. The recorded data is |
| 2809 |
re-initialized, and the observation starting time is set to *t*, |
| 2810 |
or to the current simulation time, ``now( )``, if *t* |
| 2811 |
is missing. |
| 2812 |
|
| 2813 |
|
| 2814 |
|
| 2815 |
|
| 2816 |
.. index:: Monitor; statistics |
| 2817 |
pair: Tally; statistics |
| 2818 |
|
| 2819 |
Data summaries |
| 2820 |
~~~~~~~~~~~~~~~~~ |
| 2821 |
|
| 2822 |
The following simple data summaries can be obtained from either |
| 2823 |
Monitors or Tallys at any time during or after the simulation run: |
| 2824 |
|
| 2825 |
* ``r.count( )``, the current number of observations. (If *r* is a |
| 2826 |
Monitor this is the same as ``len(r)``). |
| 2827 |
|
| 2828 |
* ``r.total( )``, the sum of the ``y`` values |
| 2829 |
|
| 2830 |
.. index:: Monitor; mean |
| 2831 |
pair: Tally; mean |
| 2832 |
|
| 2833 |
* ``r.mean( )``, the simple average of the observed ``y`` values, |
| 2834 |
ignoring the times at which they were made. This is ``r.total( )/N`` |
| 2835 |
where ``N=r.count( )``. (If there are no observations, the message: |
| 2836 |
"SimPy: No observations for mean" is printed). See |
| 2837 |
`Recording Resource queue lengths`_ for the difference between |
| 2838 |
the simple or numerical average and the time-average. |
| 2839 |
|
| 2840 |
.. figure:: /_static/images/Mon004.* |
| 2841 |
:alt: Standard mean value |
| 2842 |
:align: center |
| 2843 |
:figwidth: 400 |
| 2844 |
|
| 2845 |
``r.mean`` is the simple average of the ``y`` values observed. |
| 2846 |
|
| 2847 |
* ``r.var( )`` the *sample* variance of the observations, ignoring the |
| 2848 |
times at which they were made. If an unbiased estimate of the |
| 2849 |
*population* variance is desired, the sample variance should be |
| 2850 |
multiplied by *n/(n-1)*, where *n = r.count( )*. In either case the |
| 2851 |
standard deviation is, of course, the square-root of the variance |
| 2852 |
(If there are no observations, the message: "SimPy: No observations |
| 2853 |
for sample variance" is printed). |
| 2854 |
|
| 2855 |
.. index:: Monitor; timeAverage |
| 2856 |
pair: Tally; timeAverage |
| 2857 |
|
| 2858 |
* ``r.timeAverage([t])`` the time-weighted average of ``y``, |
| 2859 |
calculated from time 0 (or the last time ``r.reset([t])`` was |
| 2860 |
called) to time *t* (or to the current simulation time, ``now( )``, |
| 2861 |
if *t* is missing). This is determined from the area under the |
| 2862 |
graph shown in the figure, divided by the total time of observation. |
| 2863 |
For accurate time-average results ``y`` most be piecewise constant |
| 2864 |
and ``observed`` just after each change in its value. (If there are |
| 2865 |
no observations, the message "SimPy: No observations for |
| 2866 |
timeAverage" is printed. If no time has elapsed, the message "SimPy: |
| 2867 |
No elapsed time for timeAverage" is printed). |
| 2868 |
|
| 2869 |
.. figure:: /_static/images/Mon005.* |
| 2870 |
:alt: Time Average |
| 2871 |
:align: center |
| 2872 |
:figwidth: 400 |
| 2873 |
|
| 2874 |
``r.timeAverage( )`` is the time-weighted average of the observed |
| 2875 |
``y`` values. Each ``y`` value is weighted by the time for which it |
| 2876 |
exists. The average is the area under the above curve divided by the total |
| 2877 |
time, *t*. |
| 2878 |
|
| 2879 |
* ``r.timeVariance([t])`` the time-weighted variance of the ``y`` |
| 2880 |
values calculated from time 0 (or the last time ``r.reset([t])`` was |
| 2881 |
called) to time *t* (or to the current simulation time, ``now()``, |
| 2882 |
if *t* is missing). |
| 2883 |
|
| 2884 |
* ``r.__str__( )`` is a string that briefly describes the current state |
| 2885 |
of the monitor. This can be used in a print statement. |
| 2886 |
|
| 2887 |
.. index:: Monitor; special methods |
| 2888 |
|
| 2889 |
Special methods for Monitor |
| 2890 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 2891 |
|
| 2892 |
The ``Monitor`` variety of Recorder is a sub-class of ``List`` |
| 2893 |
and has a few extra methods: |
| 2894 |
|
| 2895 |
* ``m[i]`` holds the observation ``i`` as a two-item list, *[ti, yi]* |
| 2896 |
* ``m.yseries( )`` is a list of the recorded data values, *yi* |
| 2897 |
* ``m.tseries( )`` is a list of the recorded times, *ti* |
| 2898 |
|
| 2899 |
|
| 2900 |
.. index:: ! Histograms |
| 2901 |
|
| 2902 |
Histograms |
| 2903 |
~~~~~~~~~~~~~~~~~ |
| 2904 |
|
| 2905 |
A ``Histogram`` is a derived class of ``list`` that counts the |
| 2906 |
observations that fall into a number of specified ranges, called bins. |
| 2907 |
A histogram object can be displayed either by printing it out in text |
| 2908 |
form using ``printHistogram`` method or using the ``plotHistogram`` method in the |
| 2909 |
``SimPy.SimPlot`` package. |
| 2910 |
|
| 2911 |
|
| 2912 |
* ``h = Histogram(low=<float>,high=<float>,nbins=<integer>)`` is a |
| 2913 |
histogram object that counts the |
| 2914 |
number of ``y`` values in each of its bins, based on the |
| 2915 |
recorded ``y`` values. |
| 2916 |
|
| 2917 |
- ``low`` is the nominal lowest value of the histogram (default=0.0) |
| 2918 |
- ``high`` is the nominal highest value of the histogram (default=100.0) |
| 2919 |
|
| 2920 |
- ``nbins`` is the number of bins between ``low`` and ``high`` into which |
| 2921 |
the histogram is to be divided (default=10). |
| 2922 |
SimPy automatically constructs an additional two bins |
| 2923 |
to count the |
| 2924 |
number of ``y`` values ``under`` the ``low`` value and the number |
| 2925 |
``over`` the ``high`` value. Thus, the total number of bins |
| 2926 |
actually used is ``nbins + 2``. The number of ``y`` |
| 2927 |
values in each of these bins is counted and assigned |
| 2928 |
to the appropriate bin. |
| 2929 |
|
| 2930 |
.. figure:: /_static/images/Mon006.* |
| 2931 |
:align: center |
| 2932 |
:alt: Histogram |
| 2933 |
:figwidth: 500 |
| 2934 |
|
| 2935 |
A Histogram contains the number of observed ``y`` values falling |
| 2936 |
into each of its ``nbins+2`` bins. |
| 2937 |
|
| 2938 |
A Histogram, *h*, can be printed out in text form using |
| 2939 |
|
| 2940 |
* ``h.printHistogram(fmt="%s")`` prints out a histogram in a standard |
| 2941 |
format. |
| 2942 |
|
| 2943 |
- ``fmt`` is a python string format for the bin range values. |
| 2944 |
|
| 2945 |
.. THIS MUST BE CLARIFIED. hOW IS IT USED WITH MONITOR? |
| 2946 |
|
| 2947 |
.. index:: Tally; printing a histogram |
| 2948 |
|
| 2949 |
------------ |
| 2950 |
|
| 2951 |
**Example** Printing a histogram from a Tally:: |
| 2952 |
|
| 2953 |
from SimPy.Simulation import * |
| 2954 |
import random as r |
| 2955 |
|
| 2956 |
print version |
| 2957 |
|
| 2958 |
t=Tally(name="myTally",ylab="wait time (sec)") |
| 2959 |
t.setHistogram(low=0.0,high=1.0,nbins=10) |
| 2960 |
for i in range(100000): |
| 2961 |
t.observe(y=r.random()) |
| 2962 |
print t.printHistogram(fmt="%6.4f") |
| 2963 |
|
| 2964 |
This gives a printed histogram like this:: |
| 2965 |
|
| 2966 |
Histogram for myTally: |
| 2967 |
Number of observations: 100000 |
| 2968 |
wait time (sec) < 0.0000: 0 (cum: 0/ 0.0%) |
| 2969 |
0.0000 <= wait time (sec) < 0.1000: 9983 (cum: 9983/ 10.0%) |
| 2970 |
0.1000 <= wait time (sec) < 0.2000: 10121 (cum: 20104/ 20.1%) |
| 2971 |
0.2000 <= wait time (sec) < 0.3000: 9800 (cum: 29904/ 29.9%) |
| 2972 |
0.3000 <= wait time (sec) < 0.4000: 9911 (cum: 39815/ 39.8%) |
| 2973 |
0.4000 <= wait time (sec) < 0.5000: 9996 (cum: 49811/ 49.8%) |
| 2974 |
0.5000 <= wait time (sec) < 0.6000: 9881 (cum: 59692/ 59.7%) |
| 2975 |
0.6000 <= wait time (sec) < 0.7000: 10144 (cum: 69836/ 69.8%) |
| 2976 |
0.7000 <= wait time (sec) < 0.8000: 10029 (cum: 79865/ 79.9%) |
| 2977 |
0.8000 <= wait time (sec) < 0.9000: 10088 (cum: 89953/ 90.0%) |
| 2978 |
0.9000 <= wait time (sec) < 1.0000: 10047 (cum: 100000/100.0%) |
| 2979 |
1.0000 <= wait time (sec) : 0 (cum: 100000/100.0%) |
| 2980 |
|
| 2981 |
--------- |
| 2982 |
|
| 2983 |
|
| 2984 |
Although both Tallys and Monitors can return a histogram of the data, they |
| 2985 |
furnish histogram data in different ways. |
| 2986 |
|
| 2987 |
* The Tally object accumulates the histogram's bin counts as each |
| 2988 |
value is observed during the simulation run. Since none of the |
| 2989 |
individual values are preserved, the ``setHistogram`` method must be |
| 2990 |
called to provide a histogram object to hold the accumulated bin |
| 2991 |
counts before any values are actually observed. |
| 2992 |
|
| 2993 |
* The Monitor object stores all its data, so the accumulated bin |
| 2994 |
counts can be computed whenever they are desired. Thus, the |
| 2995 |
histogram need not be set up until it is needed and this can be done |
| 2996 |
after the data has been gathered. |
| 2997 |
|
| 2998 |
.. index:: |
| 2999 |
triple: Histogram;Tally; establish |
| 3000 |
|
| 3001 |
Setting up a Histogram for a Tally object |
| 3002 |
++++++++++++++++++++++++++++++++++++++++++++ |
| 3003 |
|
| 3004 |
To establish a histogram for a Tally object, ``r``, we call the |
| 3005 |
``setHistogram`` method with appropriate arguments before we observe any |
| 3006 |
data, e.g., |
| 3007 |
|
| 3008 |
* ``r.setHistogram(name = '',low=0.0,high=100.0,nbins=10)`` |
| 3009 |
|
| 3010 |
As usual, ``name`` is a descriptive title for the histogram (defaults to blank). |
| 3011 |
Then, after ``observing`` the data: |
| 3012 |
|
| 3013 |
* ``h=r.getHistogram( )`` returns a completed histogram using the |
| 3014 |
histogram parameters as set up. |
| 3015 |
|
| 3016 |
|
| 3017 |
.. index:: |
| 3018 |
triple: example; Histogram;Tally |
| 3019 |
|
| 3020 |
--------- |
| 3021 |
|
| 3022 |
**Example** In the following example we establish a ``Tally`` recorder |
| 3023 |
to observe values of an exponential random variate. It uses a |
| 3024 |
histogram with 30 bins (plus the under- and over-count bins):: |
| 3025 |
|
| 3026 |
from SimPy.Simulation import * |
| 3027 |
from random import expovariate |
| 3028 |
|
| 3029 |
r = Tally('Tally') # define a tally object, r |
| 3030 |
r.setHistogram(name='exponential', |
| 3031 |
low=0.0,high=20.0,nbins=30) # set before observations |
| 3032 |
|
| 3033 |
for i in range(1000): # make the observations |
| 3034 |
y = expovariate(0.1) |
| 3035 |
r.observe(y) |
| 3036 |
|
| 3037 |
h = r.getHistogram() # return the completed histogram |
| 3038 |
|
| 3039 |
--------- |
| 3040 |
|
| 3041 |
.. index:: |
| 3042 |
triple: Histogram;Monitor; establish |
| 3043 |
|
| 3044 |
Setting up a Histogram for a Monitor object |
| 3045 |
++++++++++++++++++++++++++++++++++++++++++++++ |
| 3046 |
|
| 3047 |
For Monitor objects, a histogram can be set up and returned in |
| 3048 |
a single call, e.g., |
| 3049 |
|
| 3050 |
* ``h = r.histogram(low=0.0,high=100.0,nbins=10)`` |
| 3051 |
|
| 3052 |
This call is equivalent to the following pair: |
| 3053 |
|
| 3054 |
* ``r.setHistogram(name = '',low=0.0,high=100.0,nbins=10)`` |
| 3055 |
* ``h = r.getHistogram( )``, which returns the completed histogram. |
| 3056 |
|
| 3057 |
|
| 3058 |
|
| 3059 |
.. index:: |
| 3060 |
triple: example; Histogram;Monitor |
| 3061 |
|
| 3062 |
--------- |
| 3063 |
|
| 3064 |
**Example** Here we establish a ``Monitor`` to observe values of an |
| 3065 |
exponential random variate. It uses a histogram with 30 bins (plus the |
| 3066 |
under- and over-count bins):: |
| 3067 |
|
| 3068 |
from SimPy.Simulation import * |
| 3069 |
from random import expovariate |
| 3070 |
|
| 3071 |
m = Monitor() # define the Monitor object, m |
| 3072 |
|
| 3073 |
for i in range(1000): # make the observations |
| 3074 |
y = expovariate(0.1) |
| 3075 |
m.observe(y) |
| 3076 |
|
| 3077 |
# set up and return the completed histogram |
| 3078 |
h = m.histogram(low=0.0, high=20, nbins=30) |
| 3079 |
|
| 3080 |
--------- |
| 3081 |
|
| 3082 |
.. ------------------------------------------------------------------------- |
| 3083 |
|
| 3084 |
.. Note: The following methods of the Monitor class are |
| 3085 |
retained for backwards compatibility |
| 3086 |
but are not recommended. They may be removed in future releases of |
| 3087 |
SimPy. |
| 3088 |
|
| 3089 |
* ``r.tally(y)`` records the current value of ``y`` and the current |
| 3090 |
time, ``now( )``. (DO NOT USE) |
| 3091 |
* ``r.accum(y [,t])`` records the current value of ``y`` and time ``t`` |
| 3092 |
(the current time, ``now( )``, if ``t`` is missing). (DO NOT USE) |
| 3093 |
|
| 3094 |
[Return to Top_ ] |
| 3095 |
|
| 3096 |
.. ------------------------------------------------------------------------- |
| 3097 |
|
| 3098 |
Other Links |
| 3099 |
------------------- |
| 3100 |
|
| 3101 |
Several example SimPy models are included with the SimPy code |
| 3102 |
distribution in the file ``SimPyModels``. |
| 3103 |
|
| 3104 |
Klaus Muller and Tony Vignaux, *SimPy: Simulating Systems in Python*, |
| 3105 |
O'Reilly ONLamp.com, 2003-Feb-27, http://www.onlamp.com/pub/a/python/2003/02/27/simpy.html |
| 3106 |
|
| 3107 |
Norman Matloff, *Introduction to the SimPy Discrete-Event Simulation |
| 3108 |
Package*, U Cal: Davis, 2003, |
| 3109 |
http://heather.cs.ucdavis.edu/~matloff/simpy.html |
| 3110 |
|
| 3111 |
David Mertz, *Charming Python: SimPy simplifies complex models*, IBM |
| 3112 |
Developer Works, Dec 2002, |
| 3113 |
http://www-106.ibm.com/developerworks/linux/library/l-simpy.html |
| 3114 |
|
| 3115 |
[Return to Top_ ] |
| 3116 |
|
| 3117 |
Acknowledgments |
| 3118 |
------------------- |
| 3119 |
|
| 3120 |
We thank those users who have sent comments to correct or improve this |
| 3121 |
text. These include: F. Benichu, Bob Helmbold, M. Matti. We will be |
| 3122 |
grateful for further corrections or suggestions. |
| 3123 |
|
| 3124 |
|
| 3125 |
|
| 3126 |
.. =================================================================== |
| 3127 |
|
| 3128 |
Appendices |
| 3129 |
------------- |
| 3130 |
|
| 3131 |
|
| 3132 |
A0. Changes from the previous version of SimPy |
| 3133 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 3134 |
|
| 3135 |
SimPy 2.2b1 differs from version 2.1 in the following ways: |
| 3136 |
|
| 3137 |
**Additions:** |
| 3138 |
|
| 3139 |
|
| 3140 |
|
| 3141 |
**Changes:** |
| 3142 |
|
| 3143 |
- The Unit tests have been rewritten |
| 3144 |
- The directory structure of the release has been simplified |
| 3145 |
- The documentation has had some minor changes |
| 3146 |
|
| 3147 |
|
| 3148 |
.. index:: Error Messages |
| 3149 |
|
| 3150 |
A1. SimPy Error Messages |
| 3151 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 3152 |
|
| 3153 |
.. include:: messages.txt |
| 3154 |
|
| 3155 |
|
| 3156 |
.. index:: SimPy Process States |
| 3157 |
|
| 3158 |
A2. SimPy Process States |
| 3159 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 3160 |
|
| 3161 |
From the viewpoint of the model builder a SimPy process, *p*, |
| 3162 |
can at any time be in one of the following states: |
| 3163 |
|
| 3164 |
- **Active**: Waiting for a scheduled event. This state simulates an |
| 3165 |
activity in the model. Simulated time passes in this |
| 3166 |
state. The process state *p.active( )* returns *True*. |
| 3167 |
|
| 3168 |
- **Passive**: Not active or terminated. Awaiting *(re-)activation* by |
| 3169 |
another process. This state simulates a real world process which |
| 3170 |
has not finished and is waiting for some trigger to continue. Does |
| 3171 |
not change simulation time. *p.passive( )* returns *True*. |
| 3172 |
|
| 3173 |
- **Terminated**: The process has executed all its action statements. |
| 3174 |
If referenced, it serves as a data instance. *p.terminated( )* |
| 3175 |
returns *True* |
| 3176 |
|
| 3177 |
Initially (upon creation of the Process instance), a process returns *passive*. |
| 3178 |
|
| 3179 |
In addition, a SimPy process, *p*, can be in the following (sub)states: |
| 3180 |
|
| 3181 |
- **Interrupted**: Active process has been interrupted by another |
| 3182 |
process. It can immediately respond to the interrupt. This |
| 3183 |
simulates an interruption of a simulated activity before its |
| 3184 |
scheduled completion time. *p.interrupted( )* returns *True*. |
| 3185 |
|
| 3186 |
- **Queuing**: Active process has requested a busy resource and is |
| 3187 |
waiting (passive) to be reactivated upon resource |
| 3188 |
availability. *p.queuing(a_resource)* returns *True*. |
| 3189 |
|
| 3190 |
|
| 3191 |
.. ------------------------------------------------------------------------- |
| 3192 |
|
| 3193 |
|
| 3194 |
A3. SimPlot, The SimPy plotting utility |
| 3195 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 3196 |
|
| 3197 |
``SimPlot`` provides an easy way to graph the results of simulation runs. |
| 3198 |
|
| 3199 |
|
| 3200 |
|
| 3201 |
|
| 3202 |
A4. SimGUI, The SimPy Graphical User Interface |
| 3203 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 3204 |
|
| 3205 |
``SimGUI`` provides a way for users to interact with a SimPy program, |
| 3206 |
changing its parameters and examining the output. |
| 3207 |
|
| 3208 |
|
| 3209 |
|
| 3210 |
|
| 3211 |
A5. SimulationTrace, the SimPy tracing utility |
| 3212 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 3213 |
|
| 3214 |
``SimulationTrace`` has been developed to give users insight into the |
| 3215 |
dynamics of the execution of SimPy simulation programs. It can help |
| 3216 |
developers with testing and users with explaining SimPy models to themselves |
| 3217 |
and others (e.g., for documentation or teaching purposes). |
| 3218 |
|
| 3219 |
|
| 3220 |
|
| 3221 |
A6. SimulationStep, the SimPy event stepping utility |
| 3222 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 3223 |
|
| 3224 |
``SimulationStep`` can assist with debugging models, interacting with them on |
| 3225 |
an event-by-event basis, getting event-by-event output from a model (e.g. |
| 3226 |
for plotting purposes), etc. |
| 3227 |
|
| 3228 |
It caters for: |
| 3229 |
|
| 3230 |
- running a simulation model, while calling a user-defined procedure after every event, |
| 3231 |
- running a simulation model one event at a time by repeated calls, |
| 3232 |
- starting and stopping the event-stepping mode under program control. |
| 3233 |
|
| 3234 |
|
| 3235 |
A7. SimulationRT, a real-time synchronizing utility |
| 3236 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 3237 |
|
| 3238 |
``SimulationRT`` allows synchronizing simulation time and real (wall-clock) time. |
| 3239 |
This capability can be used to implement, e.g., interactive game applications or |
| 3240 |
to demonstrate a model's execution in real time. |
| 3241 |
|
| 3242 |
|
| 3243 |
[Return to Top_ ] |
| 3244 |
|
| 3245 |
.. index:: Glossary |
| 3246 |
|
| 3247 |
.. _glossary: |
| 3248 |
|
| 3249 |
Glossary |
| 3250 |
----------- |
| 3251 |
|
| 3252 |
.. include:: glossary.txt |
| 3253 |
|
| 3254 |
|
| 3255 |
.. ------------------------------------------------------------------------ |
| 3256 |
.. some useful stuff used above |
| 3257 |
|
| 3258 |
|
| 3259 |
.. .. |simpylogo| image:: images/sm_SimPy_Logo.png |
| 3260 |
.. _`simpydownload`: http://sourceforge.net/projects/simpy/ |
| 3261 |
|
| 3262 |
.. _`Python random module`: http://www.python.org/doc/current/lib/module-random.html |
| 3263 |
|
| 3264 |
|
| 3265 |
|
| 3266 |
.. _Top: Contents_ |
| 3267 |
.. _alternatives: `Alternative SimPy simulation libraries`_ |
| 3268 |
.. _Monitor: `Defining Tallys and Monitors`_ |
| 3269 |
.. _Monitors: `Defining Tallys and Monitors`_ |
| 3270 |
.. _Tally: `Defining Tallys and Monitors`_ |
| 3271 |
.. _Tallys: `Defining Tallys and Monitors`_ |
| 3272 |
.. _Recorder: `Recording Simulation Results`_ |
| 3273 |
.. _Recorders: `Recording Simulation Results`_ |
| 3274 |
.. _reneging: `Reneging -- leaving a queue before acquiring a resource`_ |
| 3275 |
.. _interrupted: `Asynchronous interruptions`_ |
| 3276 |
.. _Level: `Levels`_ |
| 3277 |
.. _Store: `Stores`_ |
| 3278 |
.. _Resource: `Resources`_ |
| 3279 |
.. _`Appendix A0`: `A0. Changes from the previous version of SimPy`_ |
| 3280 |
.. _Python: http://www.Python.org |
| 3281 |
|
| 3282 |
|
| 3283 |
.. |
| 3284 |
.. image:: http://sourceforge.net/sflogo.php?group_id=62366&type=4 |
| 3285 |
:width: 125 |
| 3286 |
:height: 37 |
| 3287 |
:alt: SourceForge Logo |
| 3288 |
|
| 3289 |
.. |
| 3290 |
Local Variables: |
| 3291 |
mode: rst |
| 3292 |
indent-tabs-mode: nil |
| 3293 |
sentence-end-double-space: t |
| 3294 |
fill-column: 70 |
| 3295 |
End: |
| 3296 |
|