SimPy-2.3.1/ 0000755 0000765 0000024 00000000000 11710742263 013164 5 ustar stefan staff 0000000 0000000 SimPy-2.3.1/AUTHORS.txt 0000644 0000765 0000024 00000000567 11641611657 015067 0 ustar stefan staff 0000000 0000000 SimPy was originally created by Klaus G. Müller and Tony Vignaux in 2002.
In 2008, Ontje Lünsdorf and Stefan Scherfke started to contribute to SimPy and
became active maintainers in 2011.
In 2011, Karen Turner came on board to generally help with all the bits and
pieces that may get forgotten :-)
We’d also like to thank:
- Johannes Koomer for a fix for Store._put.
SimPy-2.3.1/CHANGES.txt 0000644 0000765 0000024 00000006342 11710741452 015001 0 ustar stefan staff 0000000 0000000 Changelog for SimPy
==============================
v2.3.1 – 2012-01-28:
--------------------
- [NEW] More improvements on the documentation.
- [FIX] Syntax error in tkconsole.py when installing on Py3.2.
- [FIX] Added *mock* to the dep. list in SimPy.test().
v2.3 – 2011-12-24:
------------------
- [NEW] Support for Python 3.2. Support for Python <= 2.5 has been dropped.
- [NEW] SimPy.test() method to run the tests on the installed version of SimPy.
– [NEW] Tutorials/examples were integrated into the test suite.
– [CHANGE] Even more code clean-up (e.g., removed prints throughout the code,
removed if-main-blocks, ...).
- [CHANGE] Many documentation improvements.
v2.2 – 2011-09-27:
------------------
- [CHANGE] Restructured package layout to be conform to the `Hitchhiker’s Guide
to packaging `_
- [CHANGE] Tests have been ported to pytest.
- [CHANGE] Documentation improvements and clean-ups.
- [FIX] Fixed incorrect behavior of Store._put, thanks to Johannes Koomer for
the fix.
v2.1 – 2010-06-03:
------------------
- [NEW] A function *step* has been added to the API. When called, it executes
the next scheduled event. (*step* is actually a method of *Simulation*.)
- [NEW] Another new function is *peek*. It returns the time of the next event.
By using peek and step together, one can easily write e.g. an interactive
program to step through a simulation event by event.
- [NEW] A simple interactive debugger ``stepping.py`` has been added. It allows
stepping through a simulation, with options to skip to a certain time, skip
to the next event of a given process, or viewing the event list.
- [NEW] Versions of the Bank tutorials (documents and programs) using the
advanced- [NEW] object-oriented API have been added.
- [NEW] A new document describes tools for gaining insight into and debugging
SimPy models.
- [CHANGE] Major re-structuring of SimPy code, resulting in much less SimPy
code – great for the maintainers.
- [CHANGE] Checks have been added which test whether entities belong to the
same Simulation instance.
- [CHANGE] The Monitor and Tally methods timeAverage and timeVariance now
calculate only with the observed time-series. No value is assumed for the
period prior to the first observation.
- [CHANGE] Changed class Lister so that circular references between objects no
longer lead to stack overflow and crash.
- [FIX] Functions *allEventNotices* and *allEventTimes* are working again.
- [FIX] Error messages for methods in SimPy.Lib work again.
v2.0.1 – 2009-04-06:
--------------------
- [NEW] Tests for real time behavior (testRT_Behavior.py and
testRT_Behavior_OO.py in folder SimPy).
- [FIX] Repaired a number of coding errors in several models in the SimPyModels
folder.
- [FIX] Repaired SimulationRT.py bug introduced by recoding for the OO API.
- [FIX] Repaired errors in sample programs in documents:
- Simulation with SimPy - In Depth Manual
- SimPy’s Object Oriented API Manual
- Simulation With Real Time Synchronization Manual
- SimPlot Manual
- Publication-quality Plot Production With Matplotlib Manual
v2.0.0 - 2009-01-26:
--------------------
- [NEW] In addition to its existing API, SimPy now also has an object oriented
API.
SimPy-2.3.1/LICENSE.txt 0000644 0000765 0000024 00000063645 11641611657 015032 0 ustar stefan staff 0000000 0000000 GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
Copyright (C)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!
SimPy-2.3.1/PKG-INFO 0000644 0000765 0000024 00000007341 11710742263 014266 0 ustar stefan staff 0000000 0000000 Metadata-Version: 1.0
Name: SimPy
Version: 2.3.1
Summary: Event discrete, process based simulation for Python.
Home-page: http://simpy.sourceforge.net/
Author: Klaus Muller, Tony Vignaux, Ontje Lünsdorf, Stefan Scherfke
Author-email: vignaux at user.sourceforge.net; kgmuller at users.sourceforge.net; the_com at gmx.de; stefan at sofa-rockers.org
License: GNU LGPL
Download-URL: https://sourceforge.net/projects/simpy/files/
Description: SimPy
=====
SimPy is a process-based discrete-event simulation language based on standard
Python and released under the GNU LGPL.
It provides the modeller with components of a simulation model. These include
processes for active components like customers, messages and vehicles as well
as resources for passive components that form limited capacity congestion
points (like servers, checkout counters and tunnels). It also provides monitor
variables to aid in gathering statistics. SimPy comes with extensive plotting
capabilities.
The distribution contains in-depth documentation, tutorials, and a large number
of simulation models.
Simulation model developers are encouraged to share their SimPy modeling
techniques with the SimPy community. Please post a message to the SimPy-Users
mailing list: http://lists.sourceforge.net/lists/listinfo/simpy-users
Software developers are also encouraged to interface SimPy with other Python-
accessible packages, such as GUI, database or mapping and to share these new
capabilities with the community under the GNU LGPL.
Installation
------------
SimPy requires Python 2.6 or above (including Python 3).
You can install SimPy easily via `PIP `_::
$ pip install -U SimPy
You can also download and install SimPy manually::
$ cd where/you/put/simpy/
$ python setup.py install
To run SimPy’s test suite on your installation, execute::
$ python -c "import SimPy; SimPy.test()"
Getting started
---------------
You can also run one or more of the programs under *docs/examples/* to see
whether Python finds the SimPy module. If you get an error message like
*ImportError: No module named SimPy*, check if the SimPy packages exists in
your site-packages folder (like /Lib/site-packages).
The tutorial and manuals are in the *docs/html* folder. Many users have
commented that the Bank tutorials are valuable in getting users started on
building their own simple models. Even a few lines of Python and SimPy can
model significant real systems.
For more help, contact the `SimPy-Users mailing list
`_. SimPy users are pretty helpful.
Enjoy simulation programming in SimPy!
Platform: UNKNOWN
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 2
Classifier: Programming Language :: Python :: 2.6
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.2
Classifier: Programming Language :: Python :: Implementation :: PyPy
Classifier: Operating System :: OS Independent
Classifier: License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Science/Research
Classifier: Topic :: Scientific/Engineering
SimPy-2.3.1/README.txt 0000644 0000765 0000024 00000004250 11675344306 014671 0 ustar stefan staff 0000000 0000000 SimPy
=====
SimPy is a process-based discrete-event simulation language based on standard
Python and released under the GNU LGPL.
It provides the modeller with components of a simulation model. These include
processes for active components like customers, messages and vehicles as well
as resources for passive components that form limited capacity congestion
points (like servers, checkout counters and tunnels). It also provides monitor
variables to aid in gathering statistics. SimPy comes with extensive plotting
capabilities.
The distribution contains in-depth documentation, tutorials, and a large number
of simulation models.
Simulation model developers are encouraged to share their SimPy modeling
techniques with the SimPy community. Please post a message to the SimPy-Users
mailing list: http://lists.sourceforge.net/lists/listinfo/simpy-users
Software developers are also encouraged to interface SimPy with other Python-
accessible packages, such as GUI, database or mapping and to share these new
capabilities with the community under the GNU LGPL.
Installation
------------
SimPy requires Python 2.6 or above (including Python 3).
You can install SimPy easily via `PIP `_::
$ pip install -U SimPy
You can also download and install SimPy manually::
$ cd where/you/put/simpy/
$ python setup.py install
To run SimPy’s test suite on your installation, execute::
$ python -c "import SimPy; SimPy.test()"
Getting started
---------------
You can also run one or more of the programs under *docs/examples/* to see
whether Python finds the SimPy module. If you get an error message like
*ImportError: No module named SimPy*, check if the SimPy packages exists in
your site-packages folder (like /Lib/site-packages).
The tutorial and manuals are in the *docs/html* folder. Many users have
commented that the Bank tutorials are valuable in getting users started on
building their own simple models. Even a few lines of Python and SimPy can
model significant real systems.
For more help, contact the `SimPy-Users mailing list
`_. SimPy users are pretty helpful.
Enjoy simulation programming in SimPy!
SimPy-2.3.1/SimPy/ 0000755 0000765 0000024 00000000000 11710742263 014225 5 ustar stefan staff 0000000 0000000 SimPy-2.3.1/SimPy/GUIDebug.py 0000644 0000765 0000024 00000032301 11650343201 016161 0 ustar stefan staff 0000000 0000000 try: # Python 3
from tkinter import *
except: # Python 2
from Tkinter import *
from SimPy.SimulationStep import now,Globals
import warnings
warnings.warn('This module be removed in SimPy 3.', DeprecationWarning)
# Creates and controls the GUI of the program
class GUIController(object):
def __init__(self):
self.root = Tk()
self.root.withdraw()
self.saveNextEvent()
self.eventWin = EventWindow(self)
self.wlist = []
self.plist = []
self.rlist = []
# Adds a new Window to the GUI
def addNewWindow(self,obj,name,hook):
self.wlist += [GenericWindow(obj,hook,self,name)]
# Adds a new Process to the GUI
def addNewProcess(self,obj,name,hook):
self.plist += [ProcessWindow(obj,hook,self,name)]
# Adds a new Resource to the GUI
def addNewResource(self,obj,name,hook):
self.rlist += [ResourceWindow(obj,hook,self,name)]
# Updates all the windows currently up
def updateAllWindows(self):
for w in self.wlist: w.update()
for p in self.plist: p.update()
for r in self.rlist: r.update()
if self.eventWin.window: self.eventWin.update()
self.organizeWindows()
self.saveNextEvent()
# removes all instances of window in lists
def removeWindow(self, w):
f = lambda win: win is not w
self.wlist = list(filter(f, self.wlist))
self.plist = list(filter(f, self.plist))
self.rlist = list(filter(f, self.rlist))
# save next event to be run
def saveNextEvent(self):
#from SimPy.SimulationTrace import _e
tempList=[]
tempList[:]=Globals.sim._timestamps
tempList.sort()
for ev in tempList:
# return only event notices which are not cancelled
if ev[3]: continue
# save next event
self.nextEvent = ev
return
self.nextEvent = (None,None,None,None)
def organizeWindows(self):
# event window
eventWindowHeight = 0
# only organize event window only if it exists
if self.eventWin.window:
eventWindowHeight = 40 + 20 * self.eventWin.table.size()
self.eventWin.setWindowSize(500, eventWindowHeight ,20,40)
# generic windows
count = -1
for win in self.wlist:
count += 1
(w,h,x,y) = win.getWindowSize()
win.setWindowSize(w, h, 20, 40 + eventWindowHeight + 40 )
eventWindowHeight += h + 40
# process windows
xCount = -1
yCount = 0
for p in self.plist:
xCount += 1
yCoord = 40 + 150 * xCount
xCoord = 550 + 210 * yCount
p.setWindowSize(200,120, xCoord, yCoord )
if yCoord >= 600:
xCount = -1
yCount += 1
# resource windows
count = -1
for r in self.rlist:
count += 1
windowHeight = 0
windowHeight += 20 # capacity title
windowHeight += 105 # empty table sizes
windowHeight += (r.activeT.size() + r.waitT.size()) * 17 # add size for each row
r.setWindowSize(200, windowHeight , 20 + 220 * count , 40 + eventWindowHeight + 40)
# Creates a basic window that shows a user made hook.
class GenericWindow(object):
def __init__(self, obj, hook, guiCtrl, title=None):
self.window = Toplevel()
self.window.protocol("WM_DELETE_WINDOW", self._destroyWindow)
self.obj = obj
self.hook = hook
self.guiCtrl = guiCtrl
if not title:
self.title = "%s%s" % (type(obj),id(obj))
else:
self.title = title
self.initGUI()
def setWindowSize(self,w,h,x,y):
newG = "%dx%d+%d+%d" % (w,h,x,y)
self.window.geometry(newG)
def setWindowOrigin(self,x,y):
(w,h,xx,yy) = self.getWindowSize()
newG = "%dx%d+%d+%d" % (w,h,x,y)
self.window.geometry(newG)
def getWindowSize(self):
g = self.window.geometry()
return [int(i) for i in g.replace('+','x').split('x')]
def _destroyWindow(self):
self.window.destroy()
self.window = None
self.guiCtrl.removeWindow(self)
# Creates the window
def initGUI(self):
self.window.title(self.title)
txt = self.hook()
if txt != "": txt += '\n'
self.hookTxt = Label(self.window,text=txt,justify=LEFT)
self.hookTxt.pack()
# Updates the window
def update(self):
txt = self.hook()
if txt != "": txt += '\n'
self.hookTxt["text"] = txt
# Class that creates the event window for the simulation that
# displays the time and event.
class EventWindow(GenericWindow):
def __init__(self, guiCtrl):
self.window = Toplevel()
self.window.protocol("WM_DELETE_WINDOW", self._destroyWindow)
self.guiCtrl = guiCtrl
self.initGUI()
# Creates the initial window using a two column window with a
# status bar on the bottom
def initGUI(self):
self.window.title("Event List")
# Creates the table
self.table = MultiListbox(self.window,(('', 1), ('Time',15),
('Process',20),('Next Line',5)))
# Adds the status bar to display the current simulation time
self.status = StatusBar(self.window)
self.status.pack(side=TOP, fill=X)
self.update()
# Updates the window
def update(self):
self.updateETable()
self.updateStatus()
# Updates the status bar
def updateStatus(self):
self.status.set(" Current Time: %s",now())
# Updates the table
def updateETable(self):
#from SimPy.SimulationStep import _e
self.table.delete(0,self.table.size())
tempList=[]
tempList[:]=Globals.sim._timestamps
tempList.sort()
ev = self.guiCtrl.nextEvent
nextLine = 0
if( ev[2] ):
if( ev[2]._nextpoint ):
nextLine = ev[2]._nextpoint.gi_frame.f_lineno
if ev[0]:
self.table.insert(END,(' >>',
str(ev[0]), ev[2].name, nextLine ))
count = -1
for ev in tempList:
# return only event notices which are not cancelled
if ev[3]: continue
count += 1
currentEvent = ''
#if count == 0 and now() == ev[0]:
# currentEvent = ' >>'
nextLine = 0
if( ev[2] ):
if( ev[2]._nextpoint ):
nextLine = ev[2]._nextpoint.gi_frame.f_lineno
self.table.insert(END,(currentEvent,
str(ev[0]), ev[2].name, nextLine ))
self.table.pack(expand=YES,fill=BOTH)
# Creates a Process Window that shows the status, Next Event time,
# if the Process is currently interupted, and an optional user hook.
class ProcessWindow(GenericWindow):
def __init__(self, obj, hook, guiCtrl, name):
self.proc = obj
if name:
obj.name = name
GenericWindow.__init__(self, obj, hook, guiCtrl, "Process")
# Initializes the window
def initGUI(self):
Label(self.window,text="%s" % (self.proc.name)).pack()
# Creates the table
self.table = MultiListbox(self.window,((None,10),(None,15)))
self.status = StatusBar(self.window)
self.status.pack(side=BOTTOM, fill=X)
GenericWindow.initGUI(self)
self.setWindowSize(0,0,-1000,-1000)
self.update()
# Updates the window
def update(self):
# If the process has been terminated close the window
if self.proc.terminated():
self._destroyWindow()
return
if self.isRunning():
self.status.label["text"] = "Running!"
self.status.label["fg"] = "red"#"green"
else:
self.status.label["text"] = ""
self.status.label["fg"] = "white"
self.table.delete(0,self.table.size())
if self.proc.active() == False:
status = "Passive"
else:
status = "Active"
if self.proc._nextTime:
nextEvent = self.proc._nextTime
else:
nextEvent = ""
if self.proc.interrupted() == True:
interrupted = "True"
else:
interrupted = "False"
self.table.insert(END,(" Status:", status))
self.table.insert(END,(" Next Event:", nextEvent))
self.table.insert(END,(" Interrupted:", interrupted ))
self.table.pack(expand=YES,fill=BOTH)
GenericWindow.update(self)
def isRunning(self):
return self.guiCtrl.nextEvent[2] is self.proc
# Creates a Resource Window that displays the capacity, waitQ,
# activeQ and an optional user hook
class ResourceWindow(GenericWindow):
def __init__(self,obj,hook,guiCtrl,name):
self.resource = obj
if name:
obj.name = name
GenericWindow.__init__(self,obj,hook, guiCtrl,"Resource")
# Initializes the window with the two tables for the waitQ and activeQ
def initGUI(self):
Label(self.window,text="%s\tCapacity: %d" % (self.resource.name,self.resource.capacity)).pack()
self.activeT = MultiListbox(self.window,(('#',5),('ActiveQ',20)))
self.waitT = MultiListbox(self.window,(('#',5),('WaitQ',20)))
self.updateQTables()
GenericWindow.initGUI(self)
self.setWindowSize(0,0,-1000,-1000)
# Updates the window
def update(self):
GenericWindow.update(self)
self.updateQTables()
# Updates the waitQ and activeQ tables
def updateQTables(self):
self.activeT.delete(0,END)
self.waitT.delete(0,END)
# Update the activeQ
for i in range(len(self.resource.activeQ)):
col1 = '%d' % (i+1)
col2 = self.resource.activeQ[i].name
self.activeT.insert(END,(" " + col1,col2))
# Update the waitQ
for i in range(len(self.resource.waitQ)):
col1 = '%d' % (i+1)
col2 = self.resource.waitQ[i].name
self.waitT.insert(END,(" " + col1,col2))
self.activeT.pack(expand=YES,fill=BOTH)
self.waitT.pack(expand=YES,fill=BOTH)
self.window.update()
# A class that creates a multilistbox with a scrollbar
class MultiListbox(Frame):
def __init__(self, master, lists):
Frame.__init__(self, master)
self.lists = []
for l,w in lists:
frame = Frame(self); frame.pack(side=LEFT, expand=YES, fill=BOTH)
if l is None:
None
elif l is '':
Label(frame, text='', borderwidth=1, relief=FLAT).pack(fill=X)
else:
Label(frame, text=l, borderwidth=1, relief=SOLID).pack(fill=X)
lb = Listbox(frame, width=w, height=0, borderwidth=0, selectborderwidth=0,
relief=FLAT, exportselection=FALSE)
lb.pack(expand=YES, fill=BOTH)
self.lists.append(lb)
frame = Frame(self); frame.pack(side=LEFT, fill=Y)
Label(frame, borderwidth=1, relief=RAISED).pack(fill=X)
sb = Scrollbar(frame, orient=VERTICAL, command=self._scroll)
sb.pack(expand=YES, fill=Y)
self.lists[0]['yscrollcommand']=sb.set
def _select(self, y):
row = self.lists[0].nearest(y)
self.selection_clear(0, END)
self.selection_set(row)
return 'break'
def _button2(self, x, y):
for l in self.lists: l.scan_mark(x, y)
return 'break'
def _b2motion(self, x, y):
for l in self.lists: l.scan_dragto(x, y)
return 'break'
def _scroll(self, *args):
for l in self.lists:
l.yview(*args)
def curselection(self):
return self.lists[0].curselection()
def delete(self, first, last=None):
for l in self.lists:
l.delete(first, last)
def get(self, first, last=None):
result = []
for l in self.lists:
result.append(l.get(first,last))
if last: return list(map(*[None] + result))
return result
def index(self, index):
self.lists[0].index(index)
def insert(self, index, *elements):
for e in elements:
i = 0
for l in self.lists:
l.insert(index, e[i])
i = i + 1
def size(self):
return self.lists[0].size()
def see(self, index):
for l in self.lists:
l.see(index)
def selection_anchor(self, index):
for l in self.lists:
l.selection_anchor(index)
def selection_clear(self, first, last=None):
for l in self.lists:
l.selection_clear(first, last)
def selection_includes(self, index):
return self.lists[0].selection_includes(index)
def selection_set(self, first, last=None):
for l in self.lists:
l.selection_set(first, last)
# Creates a statusbar
class StatusBar(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.label = Label(self, bd=1, relief=SUNKEN, anchor=W)
self.label.pack(fill=X)
def set(self, format, *args):
self.label.config(text=format % args)
self.label.update_idletasks()
def clear(self):
self.label.config(text="")
self.label.update_idletasks()
SimPy-2.3.1/SimPy/Globals.py 0000644 0000765 0000024 00000003324 11650347456 016174 0 ustar stefan staff 0000000 0000000 # coding=utf-8
"""
This file provides a global Simulation object and the global simulation methods
used by SimPy up to version 1.9.1.
"""
global sim
sim = None
def initialize():
sim.initialize()
def now():
return sim.now()
def stopSimulation():
"""Application function to stop simulation run"""
sim.stopSimulation()
def allEventNotices():
"""Returns string with eventlist as;
t1: processname, processname2
t2: processname4, processname5, . . .
. . . .
"""
return sim.allEventNotices()
def allEventTimes():
"""Returns list of all times for which events are scheduled.
"""
return sim.allEventTimes()
def startCollection(when = 0.0, monitors = None, tallies = None):
"""Starts data collection of all designated Monitor and Tally objects
(default = all) at time 'when'.
"""
sim.startCollection( when = when, monitors = monitors, tallies = tallies)
def _startWUStepping():
"""Application function to start stepping through simulation for waituntil
construct."""
sim._startWUStepping()
def _stopWUStepping():
"""Application function to stop stepping through simulation."""
sim._stopWUStepping()
def activate(obj, process, at = 'undefined', delay = 'undefined',
prior = False):
"""Application function to activate passive process."""
sim.activate(obj, process, at = at, delay = delay, prior = prior)
def reactivate(obj, at = 'undefined', delay = 'undefined', prior = False):
"""Application function to reactivate a process which is active,
suspended or passive."""
sim.reactivate(obj, at = at, delay = delay, prior = prior)
def simulate(until = 0):
return sim.simulate(until = until)
SimPy-2.3.1/SimPy/Lib.py 0000644 0000765 0000024 00000121331 11672177337 015321 0 ustar stefan staff 0000000 0000000 # coding=utf-8
"""
This file contains Simerror, FatalSimerror, Process, SimEvent, the resources
Resource, Level and Storage as well as their dependencies Buffer, Queue, FIFO
and PriorityQ.
"""
import inspect
import sys
import types
from SimPy.Lister import Lister
from SimPy.Recording import Monitor, Tally
# Required for backward compatiblity
import SimPy.Globals as Globals
class Simerror(Exception):
""" SimPy error which terminates "simulate" with an error message"""
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class FatalSimerror(Simerror):
""" SimPy error which terminates script execution with an exception"""
def __init__(self, value):
Simerror.__init__(self, value)
self.value = value
class Process(Lister):
"""Superclass of classes which may use generator functions"""
def __init__(self, name = 'a_process', sim = None):
if sim is None: sim = Globals.sim # Use global simulation object if sim is None
self.sim = sim
#the reference to this Process instances single process (==generator)
self._nextpoint = None
if isinstance(name, str) or (sys.version_info.major == 2 and
isinstance(name, basestring)):
self.name = name
else:
raise FatalSimerror("Process name parameter '%s' is not a string"%name)
self._nextTime = None #next activation time
self._remainService = 0
self._preempted = 0
self._priority={}
self._getpriority={}
self._putpriority={}
self._terminated = False
self._inInterrupt = False
self.eventsFired = [] #which events process waited / queued for occurred
if hasattr(sim, 'trace'):
self._doTracing = True
else:
self._doTracing = False
def active(self):
return self._nextTime != None and not self._inInterrupt
def passive(self):
return self._nextTime is None and not self._terminated
def terminated(self):
return self._terminated
def interrupted(self):
return self._inInterrupt and not self._terminated
def queuing(self, resource):
return self in resource.waitQ
def cancel(self, victim):
"""Application function to cancel all event notices for this Process
instance;(should be all event notices for the _generator_)."""
self.sim._unpost(whom = victim)
def start(self, pem = None, at = 'undefined', delay = 'undefined', prior = False):
"""Activates PEM of this Process.
p.start(p.pemname([args])[,{at = t | delay = period}][, prior = False]) or
p.start([p.ACTIONS()][,{at = t | delay = period}][, prior = False]) (ACTIONS
parameter optional)
"""
if pem is None:
try:
pem = self.ACTIONS()
except AttributeError:
raise FatalSimerror\
('no generator function to activate')
else:
pass
if not (type(pem) == types.GeneratorType):
raise FatalSimerror('activating function which'+
' is not a generator (contains no \'yield\')')
if not self._terminated and not self._nextTime:
#store generator reference in object; needed for reactivation
self._nextpoint = pem
if at == 'undefined':
at = self.sim._t
if delay == 'undefined':
zeit = max(self.sim._t, at)
else:
zeit = max(self.sim._t, self.sim._t + delay)
if self._doTracing:
self.sim.trace.recordActivate(who = self, when = zeit,
prior = prior)
self.sim._post(what = self, at = zeit, prior = prior)
def _hold(self, a):
if len(a[0]) == 3: ## yield hold,self,delay
delay = a[0][2]
if delay < 0:
raise FatalSimerror('hold: delay time negative: %s, in %s' % (
delay, str(a[0][1])))
else: ## yield hold,self
delay = 0
who = a[1]
self.interruptLeft = delay
self._inInterrupt = False
self.interruptCause = None
self.sim._post(what = who, at = self.sim._t + delay)
def _passivate(self, a):
a[0][1]._nextTime = None
def interrupt(self, victim):
"""Application function to interrupt active processes"""
# can't interrupt terminated / passive / interrupted process
if victim.active():
if self._doTracing:
save = self.sim.trace._comment
self.sim.trace._comment = None
victim.interruptCause = self # self causes interrupt
left = victim._nextTime - self.sim._t
victim.interruptLeft = left # time left in current 'hold'
victim._inInterrupt = True
self.sim.reactivate(victim)
if self._doTracing:
self.sim.trace._comment = save
self.sim.trace.recordInterrupt(self, victim)
return left
else: #victim not active -- can't interrupt
return None
def interruptReset(self):
"""
Application function for an interrupt victim to get out of
'interrupted' state.
"""
self._inInterrupt = False
def acquired(self, res):
"""Multi - functional test for reneging for 'request' and 'get':
(1)If res of type Resource:
Tests whether resource res was acquired when proces reactivated.
If yes, the parallel wakeup process is killed.
If not, process is removed from res.waitQ (reneging).
(2)If res of type Store:
Tests whether item(s) gotten from Store res.
If yes, the parallel wakeup process is killed.
If no, process is removed from res.getQ
(3)If res of type Level:
Tests whether units gotten from Level res.
If yes, the parallel wakeup process is killed.
If no, process is removed from res.getQ.
"""
if isinstance(res, Resource):
test = self in res.activeQ
if test:
self.cancel(self._holder)
else:
res.waitQ.remove(self)
if res.monitored:
res.waitMon.observe(len(res.waitQ),t = self.sim.now())
return test
elif isinstance(res, Store):
test = len(self.got)
if test:
self.cancel(self._holder)
else:
res.getQ.remove(self)
if res.monitored:
res.getQMon.observe(len(res.getQ),t = self.sim.now())
return test
elif isinstance(res, Level):
test = not (self.got is None)
if test:
self.cancel(self._holder)
else:
res.getQ.remove(self)
if res.monitored:
res.getQMon.observe(len(res.getQ),t = self.sim.now())
return test
def stored(self, buffer):
"""Test for reneging for 'yield put . . .' compound statement (Level and
Store. Returns True if not reneged.
If self not in buffer.putQ, kill wakeup process, else take self out of
buffer.putQ (reneged)"""
test = self in buffer.putQ
if test: #reneged
buffer.putQ.remove(self)
if buffer.monitored:
buffer.putQMon.observe(len(buffer.putQ),t = self.sim.now())
else:
self.cancel(self._holder)
return not test
class SimEvent(Lister):
"""Supports one - shot signalling between processes. All processes waiting for an event to occur
get activated when its occurrence is signalled. From the processes queuing for an event, only
the first gets activated.
"""
def __init__(self, name = 'a_SimEvent', sim = None):
if sim is None: sim = Globals.sim # Use global simulation if sim is None
self.sim = sim
self.name = name
self.waits = []
self.queues = []
self.occurred = False
self.signalparam = None
if hasattr(sim, 'trace'):
self._doTracing = True
else:
self._doTracing = False
def signal(self, param = None):
"""Produces a signal to self;
Fires this event (makes it occur).
Reactivates ALL processes waiting for this event. (Cleanup waits lists
of other events if wait was for an event - group (OR).)
Reactivates the first process for which event(s) it is queuing for
have fired. (Cleanup queues of other events if wait was for an event - group (OR).)
"""
self.signalparam = param
if self._doTracing:
self.sim.trace.recordSignal(self)
if not self.waits and not self.queues:
self.occurred = True
else:
#reactivate all waiting processes
for p in self.waits:
p[0].eventsFired.append(self)
self.sim.reactivate(p[0], prior = True)
#delete waits entries for this process in other events
for ev in p[1]:
if ev != self:
if ev.occurred:
p[0].eventsFired.append(ev)
for iev in ev.waits:
if iev[0] == p[0]:
ev.waits.remove(iev)
break
self.waits = []
if self.queues:
proc = self.queues.pop(0)[0]
proc.eventsFired.append(self)
self.sim.reactivate(proc)
def _wait(self, par):
"""Consumes a signal if it has occurred, otherwise process 'proc'
waits for this event.
"""
proc = par[0][1] #the process issuing the yield waitevent command
# test that process and SimEvent belong to same Simulation instance
if __debug__:
if not (proc.sim == self.sim):
raise FatalSimerror("waitevent: Process %s, SimEvent %s not in "
"same Simulation instance" % (proc.name,self.name))
proc.eventsFired = []
if not self.occurred:
self.waits.append([proc, [self]])
proc._nextTime = None #passivate calling process
else:
proc.eventsFired.append(self)
self.occurred = False
self.sim._post(proc, at = self.sim._t, prior = 1)
def _waitOR(self, par):
"""Handles waiting for an OR of events in a tuple / list.
"""
proc = par[0][1]
evlist = par[0][2]
proc.eventsFired = []
anyoccur = False
for ev in evlist:
# test that process and SimEvent belong to same Simulation instance
if __debug__:
if not (proc.sim == ev.sim):
raise FatalSimerror(
"waitevent: Process %s, SimEvent %s not in "\
"same Simulation instance"%(proc.name,ev.name))
if ev.occurred:
anyoccur = True
proc.eventsFired.append(ev)
ev.occurred = False
if anyoccur: #at least one event has fired; continue process
self.sim._post(proc, at = self.sim._t, prior = 1)
else: #no event in list has fired, enter process in all 'waits' lists
proc.eventsFired = []
proc._nextTime = None #passivate calling process
for ev in evlist:
ev.waits.append([proc, evlist])
def _queue(self, par):
"""Consumes a signal if it has occurred, otherwise process 'proc'
queues for this event.
"""
proc = par[0][1] #the process issuing the yield queueevent command
proc.eventsFired = []
# test that process and SimEvent belong to same Simulation instance
if __debug__:
if not (proc.sim == self.sim):
raise FatalSimerror("queueevent: Process %s, SimEvent %s not in "
"same Simulation instance"%(proc.name,self.name))
if not self.occurred:
self.queues.append([proc, [self]])
proc._nextTime = None #passivate calling process
else:
proc.eventsFired.append(self)
self.occurred = False
self.sim._post(proc, at = self.sim._t, prior = 1)
def _queueOR(self, par):
"""Handles queueing for an OR of events in a tuple / list.
"""
proc = par[0][1]
evlist = par[0][2]
proc.eventsFired = []
anyoccur = False
for ev in evlist:
# test that process and SimEvent belong to same Simulation instance
if __debug__:
if not (proc.sim == ev.sim):
raise FatalSimerror("yield queueevent: Process %s, SimEvent %s not in "
"same Simulation instance"%(proc.name,ev.name))
if ev.occurred:
anyoccur = True
proc.eventsFired.append(ev)
ev.occurred = False
if anyoccur: #at least one event has fired; continue process
self.sim._post(proc, at = self.sim._t, prior = 1)
else: #no event in list has fired, enter process in all 'waits' lists
proc.eventsFired = []
proc._nextTime = None #passivate calling process
for ev in evlist:
ev.queues.append([proc, evlist])
class Queue(list):
def __init__(self, res, moni):
if not moni is None: #moni == []:
self.monit = True # True if a type of Monitor / Tally attached
else:
self.monit = False
self.moni = moni # The Monitor / Tally
self.resource = res # the resource / buffer this queue belongs to
def enter(self, obj):
pass
def leave(self):
pass
def takeout(self, obj):
self.remove(obj)
if self.monit:
self.moni.observe(len(self), t = self.moni.sim.now())
class FIFO(Queue):
def __init__(self, res, moni):
Queue.__init__(self, res, moni)
def enter(self, obj):
self.append(obj)
if self.monit:
self.moni.observe(len(self),t = self.moni.sim.now())
def enterGet(self, obj):
self.enter(obj)
def enterPut(self, obj):
self.enter(obj)
def leave(self):
a = self.pop(0)
if self.monit:
self.moni.observe(len(self),t = self.moni.sim.now())
return a
class PriorityQ(FIFO):
"""Queue is always ordered according to priority.
Higher value of priority attribute == higher priority.
"""
def __init__(self, res, moni):
FIFO.__init__(self, res, moni)
def enter(self, obj):
"""Handles request queue for Resource"""
if len(self):
ix = self.resource
if self[-1]._priority[ix] >= obj._priority[ix]:
self.append(obj)
else:
z = 0
while self[z]._priority[ix] >= obj._priority[ix]:
z += 1
self.insert(z, obj)
else:
self.append(obj)
if self.monit:
self.moni.observe(len(self),t = self.moni.sim.now())
def enterGet(self, obj):
"""Handles getQ in Buffer"""
if len(self):
ix = self.resource
if self[-1]._getpriority[ix] >= obj._getpriority[ix]:
self.append(obj)
else:
z = 0
while self[z]._getpriority[ix] >= obj._getpriority[ix]:
z += 1
self.insert(z, obj)
else:
self.append(obj)
if self.monit:
self.moni.observe(len(self),t = self.moni.sim.now())
def enterPut(self, obj):
"""Handles putQ in Buffer"""
if len(self):
ix = self.resource
if self[-1]._putpriority[ix] >= obj._putpriority[ix]:
self.append(obj)
else:
z = 0
while self[z]._putpriority[ix] >= obj._putpriority[ix]:
z += 1
self.insert(z, obj)
else:
self.append(obj)
if self.monit:
self.moni.observe(len(self),t = self.moni.sim.now())
class Resource(Lister):
"""Models shared, limited capacity resources with queuing;
FIFO is default queuing discipline.
"""
def __init__(self, capacity = 1, name = 'a_resource', unitName = 'units',
qType = FIFO, preemptable = 0, monitored = False,
monitorType = Monitor,sim = None):
"""
monitorType={Monitor(default) | Tally}
"""
if capacity < 0:
raise ValueError('capacity should be >= 0, but is: %s' % capacity)
if sim is None: sim = Globals.sim # Use global simulation if sim is Non
self.sim = sim
self.name = name # resource name
self.capacity = capacity # resource units in this resource
self.unitName = unitName # type name of resource units
self.n = capacity # uncommitted resource units
self.monitored = monitored
if self.monitored: # Monitor waitQ, activeQ
self.actMon = monitorType(name = 'Active Queue Monitor %s'%self.name,
ylab = 'nr in queue', tlab = 'time',
sim = self.sim)
monact = self.actMon
self.waitMon = monitorType(name = 'Wait Queue Monitor %s'%self.name,
ylab = 'nr in queue', tlab = 'time',
sim = self.sim)
monwait = self.waitMon
else:
monwait = None
monact = None
self.waitQ = qType(self, monwait)
self.preemptable = preemptable
self.activeQ = qType(self, monact)
self.priority_default = 0
# Initialize monitors
if self.monitored:
monact.observe(t = self.sim.now(), y = len(self.activeQ))
monwait.observe(t = self.sim.now(), y = len(self.waitQ))
def _request(self, arg):
"""Process request event for this resource"""
obj = arg[1]
# test that process and Resource belong to same Simulation instance
if __debug__:
if not (obj.sim == self.sim):
raise FatalSimerror("yield request: Process %s, Resource %s not in "\
"same Simulation instance"%(obj.name,self.name))
if len(arg[0]) == 4: # yield request, self, resource, priority
obj._priority[self] = arg[0][3]
else: # yield request, self, resource
obj._priority[self] = self.priority_default
if self.preemptable and self.n == 0: # No free resource
# test for preemption condition
preempt = obj._priority[self] > self.activeQ[-1]._priority[self]
# If yes:
if preempt:
z = self.activeQ[-1]
# Keep track of preempt level
z._preempted += 1
# suspend lowest priority process being served
# record remaining service time at first preempt only
if z._preempted == 1:
z._remainService = z._nextTime - self.sim._t
# cancel only at first preempt
Process(sim=self.sim).cancel(z)
# remove from activeQ
self.activeQ.remove(z)
# put into front of waitQ
self.waitQ.insert(0, z)
# if self is monitored, update waitQ monitor
if self.monitored:
self.waitMon.observe(len(self.waitQ), self.sim.now())
# passivate re - queued process
z._nextTime = None
# assign resource unit to preemptor
self.activeQ.enter(obj)
# post event notice for preempting process
self.sim._post(obj, at = self.sim._t, prior = 1)
else:
self.waitQ.enter(obj)
# passivate queuing process
obj._nextTime = None
else: # treat non - preemption case
if self.n == 0:
self.waitQ.enter(obj)
# passivate queuing process
obj._nextTime = None
else:
self.n -= 1
self.activeQ.enter(obj)
self.sim._post(obj, at = self.sim._t, prior = 1)
def _release(self, arg):
"""Process release request for this resource"""
actor = arg[1]
self.n += 1
self.activeQ.remove(arg[1])
if self.monitored:
self.actMon.observe(len(self.activeQ),t = self.sim.now())
#reactivate first waiting requestor if any; assign Resource to it
if self.waitQ:
obj = self.waitQ.leave()
self.n -= 1 #assign 1 resource unit to object
self.activeQ.enter(obj)
# if resource preemptable:
if self.preemptable:
# if object had been preempted:
if obj._preempted:
# keep track of preempt level
obj._preempted -= 1
# reactivate object delay = remaining service time
# but only, if all other preempts are over
if obj._preempted == 0:
self.sim.reactivate(obj, delay = obj._remainService,
prior = 1)
# else reactivate right away
else:
self.sim.reactivate(obj, delay = 0, prior = 1)
# else:
else:
self.sim.reactivate(obj, delay = 0, prior = 1)
self.sim._post(arg[1], at = self.sim._t, prior = 1)
class Buffer(Lister):
"""Abstract class for buffers
Blocks a process when a put would cause buffer overflow or a get would cause
buffer underflow.
Default queuing discipline for blocked processes is FIFO."""
priorityDefault = 0
def __init__(self, name = None, capacity = 'unbounded', unitName = 'units',
putQType = FIFO, getQType = FIFO,
monitored = False, monitorType = Monitor, initialBuffered = None,
sim = None):
if sim is None: sim = Globals.sim # Use global simulation if sim is None
self.sim = sim
if capacity == 'unbounded':
capacity = sys.maxsize
elif capacity < 0:
raise ValueError('capacity should be >= 0, but is: %s' % capacity)
self.capacity = capacity
self.name = name
self.putQType = putQType
self.getQType = getQType
self.monitored = monitored
self.initialBuffered = initialBuffered
self.unitName = unitName
if self.monitored:
## monitor for Producer processes' queue
self.putQMon = monitorType(name = 'Producer Queue Monitor %s'%self.name,
ylab = 'nr in queue', tlab = 'time',
sim=self.sim)
## monitor for Consumer processes' queue
self.getQMon = monitorType(name = 'Consumer Queue Monitor %s'%self.name,
ylab = 'nr in queue', tlab = 'time',
sim=self.sim)
## monitor for nr items in buffer
self.bufferMon = monitorType(name = 'Buffer Monitor %s'%self.name,
ylab = 'nr in buffer', tlab = 'time',
sim=self.sim)
else:
self.putQMon = None
self.getQMon = None
self.bufferMon = None
self.putQ = self.putQType(res = self, moni = self.putQMon)
self.getQ = self.getQType(res = self, moni = self.getQMon)
if self.monitored:
self.putQMon.observe(y = len(self.putQ),t = self.sim.now())
self.getQMon.observe(y = len(self.getQ),t = self.sim.now())
self._putpriority={}
self._getpriority={}
def _put(self):
pass
def _get(self):
pass
class Level(Buffer):
"""Models buffers for processes putting / getting un - distinguishable items.
"""
def getamount(self):
return self.nrBuffered
def gettheBuffer(self):
return self.nrBuffered
theBuffer = property(gettheBuffer)
def __init__(self,**pars):
Buffer.__init__(self,**pars)
if self.name is None:
self.name = 'a_level' ## default name
if (type(self.capacity) != type(1.0) and\
type(self.capacity) != type(1)) or\
self.capacity < 0:
raise FatalSimerror('Level: capacity parameter not a positive number: %s'\
%self.initialBuffered)
if type(self.initialBuffered) == type(1.0) or\
type(self.initialBuffered) == type(1):
if self.initialBuffered > self.capacity:
raise FatalSimerror('initialBuffered exceeds capacity')
if self.initialBuffered >= 0:
self.nrBuffered = self.initialBuffered ## nr items initially in buffer
## buffer is just a counter (int type)
else:
raise FatalSimerror('initialBuffered param of Level negative: %s'\
%self.initialBuffered)
elif self.initialBuffered is None:
self.initialBuffered = 0
self.nrBuffered = 0
else:
raise FatalSimerror('Level: wrong type of initialBuffered (parameter=%s)'\
%self.initialBuffered)
if self.monitored:
self.bufferMon.observe(y = self.amount, t = self.sim.now())
amount = property(getamount)
def _put(self, arg):
"""Handles put requests for Level instances"""
obj = arg[1]
whichSim=self.sim
# test that process and Level belong to same Simulation instance
if __debug__:
if not (obj.sim == self.sim):
raise FatalSimerror(
"put: Process %s, Level %s not in "\
"same Simulation instance"%(obj.name,self.name))
if len(arg[0]) == 5: # yield put, self, buff, whattoput, priority
obj._putpriority[self] = arg[0][4]
whatToPut = arg[0][3]
elif len(arg[0]) == 4: # yield get, self, buff, whattoput
obj._putpriority[self] = Buffer.priorityDefault #default
whatToPut = arg[0][3]
else: # yield get, self, buff
obj._putpriority[self] = Buffer.priorityDefault #default
whatToPut = 1
if type(whatToPut) != type(1) and type(whatToPut) != type(1.0):
raise FatalSimerror('Level: put parameter not a number')
if not whatToPut >= 0.0:
raise FatalSimerror('Level: put parameter not positive number')
whatToPutNr = whatToPut
if whatToPutNr + self.amount > self.capacity:
obj._nextTime = None #passivate put requestor
obj._whatToPut = whatToPutNr
self.putQ.enterPut(obj) #and queue, with size of put
else:
self.nrBuffered += whatToPutNr
if self.monitored:
self.bufferMon.observe(y = self.amount, t = self.sim.now())
# service any getters waiting
# service in queue - order; do not serve second in queue before first
# has been served
while len(self.getQ) and self.amount > 0:
proc = self.getQ[0]
if proc._nrToGet <= self.amount:
proc.got = proc._nrToGet
self.nrBuffered -= proc.got
if self.monitored:
self.bufferMon.observe(y = self.amount, t = self.sim.now())
self.getQ.takeout(proc) # get requestor's record out of queue
whichSim._post(proc, at = whichSim._t) # continue a blocked get requestor
else:
break
whichSim._post(obj, at = whichSim._t, prior = 1) # continue the put requestor
def _get(self, arg):
"""Handles get requests for Level instances"""
obj = arg[1]
# test that process and Store belong to same Simulation instance
if __debug__:
if not (obj.sim == self.sim):
raise FatalSimerror(
"get: Process %s, Level %s not in "\
"same Simulation instance"%(obj.name,self.name))
obj.got = None
if len(arg[0]) == 5: # yield get, self, buff, whattoget, priority
obj._getpriority[self] = arg[0][4]
nrToGet = arg[0][3]
elif len(arg[0]) == 4: # yield get, self, buff, whattoget
obj._getpriority[self] = Buffer.priorityDefault #default
nrToGet = arg[0][3]
else: # yield get, self, buff
obj._getpriority[self] = Buffer.priorityDefault
nrToGet = 1
if type(nrToGet) != type(1.0) and type(nrToGet) != type(1):
raise FatalSimerror('Level: get parameter not a number: %s'%nrToGet)
if nrToGet < 0:
raise FatalSimerror('Level: get parameter not positive number: %s'%nrToGet)
if self.amount < nrToGet:
obj._nrToGet = nrToGet
self.getQ.enterGet(obj)
# passivate queuing process
obj._nextTime = None
else:
obj.got = nrToGet
self.nrBuffered -= nrToGet
if self.monitored:
self.bufferMon.observe(y = self.amount, t = self.sim.now())
self.sim._post(obj, at = self.sim._t, prior = 1)
# reactivate any put requestors for which space is now available
# service in queue - order; do not serve second in queue before first
# has been served
while len(self.putQ): #test for queued producers
proc = self.putQ[0]
if proc._whatToPut + self.amount <= self.capacity:
self.nrBuffered += proc._whatToPut
if self.monitored:
self.bufferMon.observe(y = self.amount, t = self.sim.now())
self.putQ.takeout(proc)#requestor's record out of queue
self.sim._post(proc, at = self.sim._t) # continue a blocked put requestor
else:
break
class Store(Buffer):
"""Models buffers for processes coupled by putting / getting distinguishable
items.
Blocks a process when a put would cause buffer overflow or a get would cause
buffer underflow.
Default queuing discipline for blocked processes is priority FIFO.
"""
def getnrBuffered(self):
return len(self.theBuffer)
nrBuffered = property(getnrBuffered)
def getbuffered(self):
return self.theBuffer
buffered = property(getbuffered)
def __init__(self,**pars):
Buffer.__init__(self,**pars)
self.theBuffer = []
if self.name is None:
self.name = 'a_store' ## default name
if type(self.capacity) != type(1) or self.capacity <= 0:
raise FatalSimerror\
('Store: capacity parameter not a positive integer: %s'\
%self.capacity)
if type(self.initialBuffered) == type([]):
if len(self.initialBuffered) > self.capacity:
raise FatalSimerror\
('Store: number initialBuffered exceeds capacity')
else:
## buffer receives list of objects
self.theBuffer[:] = self.initialBuffered
elif self.initialBuffered is None:
self.theBuffer = []
else:
raise FatalSimerror\
('Store: initialBuffered not a list')
if self.monitored:
self.bufferMon.observe(y = self.nrBuffered, t = self.sim.now())
self._sort = None
def addSort(self, sortFunc):
"""Adds buffer sorting to this instance of Store. It maintains
theBuffer sorted by the sortAttr attribute of the objects in the
buffer.
The user - provided 'sortFunc' must look like this:
def mySort(self, par):
tmplist = [(x.sortAttr, x) for x in par]
tmplist.sort()
return [x for (key, x) in tmplist]
"""
self._sort = sortFunc.__get__(self, self.__class__)
self.theBuffer = self._sort(self.theBuffer)
def _put(self, arg):
"""Handles put requests for Store instances"""
obj = arg[1]
# test that process and Store belong to same Simulation instance
if __debug__:
if not (obj.sim == self.sim):
raise FatalSimerror(
"put: Process %s, Store %s not in "\
"same Simulation instance"%(obj.name,self.name))
whichSim=self.sim
if len(arg[0]) == 5: # yield put, self, buff, whattoput, priority
obj._putpriority[self] = arg[0][4]
whatToPut = arg[0][3]
elif len(arg[0]) == 4: # yield put, self, buff, whattoput
obj._putpriority[self] = Buffer.priorityDefault #default
whatToPut = arg[0][3]
else: # error, whattoput missing
raise FatalSimerror('Item to put missing in yield put stmt')
if type(whatToPut) != type([]):
raise FatalSimerror('put parameter is not a list')
whatToPutNr = len(whatToPut)
if whatToPutNr + self.nrBuffered > self.capacity:
obj._nextTime = None #passivate put requestor
obj._whatToPut = whatToPut
self.putQ.enterPut(obj) #and queue, with items to put
else:
self.theBuffer.extend(whatToPut)
if not(self._sort is None):
self.theBuffer = self._sort(self.theBuffer)
if self.monitored:
self.bufferMon.observe(y = self.nrBuffered, t = whichSim.now())
# service any waiting getters
# service in queue order: do not serve second in queue before first
# has been served
#
# [jkoomen@xeroxlabs.com / 2011-08-16]
# Documentation says that
# "yield get requests with a numerical parameter are honored in priority/FIFO order"
# but
# "yield get requests with a filter function parameter are not necessarily honored in priority/FIFO order, but rather according to the filter function."
# while self.nrBuffered > 0 and len(self.getQ):
idx = 0
while self.nrBuffered > 0 and idx < len(self.getQ):
proc = self.getQ[idx]
if inspect.isfunction(proc._nrToGet):
movCand = proc._nrToGet(self.theBuffer) #predicate parameter
if movCand:
proc.got = movCand[:]
for i in movCand:
self.theBuffer.remove(i)
self.getQ.takeout(proc)
if self.monitored:
self.bufferMon.observe(
y = self.nrBuffered, t = whichSim._t)
whichSim._post(what = proc, at = whichSim._t) # continue a blocked get requestor
else:
# break
idx += 1
else: #numerical parameter
if proc._nrToGet <= self.nrBuffered:
nrToGet = proc._nrToGet
proc.got = []
proc.got[:] = self.theBuffer[0:nrToGet]
self.theBuffer[:] = self.theBuffer[nrToGet:]
if self.monitored:
self.bufferMon.observe(
y = self.nrBuffered, t = whichSim._t)
# take this get requestor's record out of queue:
self.getQ.takeout(proc)
whichSim._post(what = proc, at = whichSim._t) # continue a blocked get requestor
else:
break
whichSim._post(what = obj, at = whichSim._t, prior = 1) # continue the put requestor
def _get(self, arg):
"""Handles get requests"""
filtfunc = None
obj = arg[1]
# test that process and Store belong to same Simulation instance
if __debug__:
if not (obj.sim == self.sim):
raise FatalSimerror(
"get: Process %s, Store %s not in "\
"same Simulation instance"%(obj.name,self.name))
whichSim=obj.sim
obj.got = [] # the list of items retrieved by 'get'
if len(arg[0]) == 5: # yield get, self, buff, whattoget, priority
obj._getpriority[self] = arg[0][4]
if inspect.isfunction(arg[0][3]):
filtfunc = arg[0][3]
else:
nrToGet = arg[0][3]
elif len(arg[0]) == 4: # yield get, self, buff, whattoget
obj._getpriority[self] = Buffer.priorityDefault #default
if inspect.isfunction(arg[0][3]):
filtfunc = arg[0][3]
else:
nrToGet = arg[0][3]
else: # yield get, self, buff
obj._getpriority[self] = Buffer.priorityDefault
nrToGet = 1
if not filtfunc: #number specifies nr items to get
if nrToGet < 0:
raise FatalSimerror\
('Store: get parameter not positive number: %s'%nrToGet)
if self.nrBuffered < nrToGet:
obj._nrToGet = nrToGet
self.getQ.enterGet(obj)
# passivate / block queuing 'get' process
obj._nextTime = None
else:
for i in range(nrToGet):
obj.got.append(self.theBuffer.pop(0)) # move items from
# buffer to requesting process
if self.monitored:
self.bufferMon.observe(y = self.nrBuffered, t = whichSim.now())
whichSim._post(obj, at = whichSim._t, prior = 1)
# reactivate any put requestors for which space is now available
# serve in queue order: do not serve second in queue before first
# has been served
while len(self.putQ):
proc = self.putQ[0]
if len(proc._whatToPut) + self.nrBuffered <= self.capacity:
for i in proc._whatToPut:
self.theBuffer.append(i) #move items to buffer
if not(self._sort is None):
self.theBuffer = self._sort(self.theBuffer)
if self.monitored:
self.bufferMon.observe(
y = self.nrBuffered, t = whichSim.now())
self.putQ.takeout(proc) # dequeue requestor's record
whichSim._post(proc, at = whichSim._t) # continue a blocked put requestor
else:
break
else: # items to get determined by filtfunc
movCand = filtfunc(self.theBuffer)
if movCand: # get succeded
whichSim._post(obj, at = whichSim._t, prior = 1)
obj.got = movCand[:]
for item in movCand:
self.theBuffer.remove(item)
if self.monitored:
self.bufferMon.observe(y = self.nrBuffered, t = whichSim.now())
# reactivate any put requestors for which space is now available
# serve in queue order: do not serve second in queue before first
# has been served
while len(self.putQ):
proc = self.putQ[0]
if len(proc._whatToPut) + self.nrBuffered <= self.capacity:
for i in proc._whatToPut:
self.theBuffer.append(i) #move items to buffer
if not(self._sort is None):
self.theBuffer = self._sort(self.theBuffer)
if self.monitored:
self.bufferMon.observe(
y = self.nrBuffered, t = whichSim.now())
self.putQ.takeout(proc) # dequeue requestor's record
whichSim._post(proc, at = whichSim._t) # continue a blocked put requestor
else:
break
else: # get did not succeed, block
obj._nrToGet = filtfunc
self.getQ.enterGet(obj)
# passivate / block queuing 'get' process
obj._nextTime = None
SimPy-2.3.1/SimPy/Lister.py 0000644 0000765 0000024 00000001642 11650347474 016054 0 ustar stefan staff 0000000 0000000 # coding=utf-8
"""
Pretty-printer for SimPy class objects
"""
class Lister(object):
indent = 0
def __str__(self):
Lister.indent += 1
if Lister.indent > 3:
# In case of recursion, avoid infinite loop
result = ' ... '
else:
result = '< Instance of %s, id %s:\n%s%s>' % (
self.__class__.__name__,
id(self),
self.attrnames(),
'\t' * (Lister.indent - 1),
)
Lister.indent -= 1
return result
def attrnames(self):
result = ''
for attr in self.__dict__:
# Ignore built-in and private attributes
if not (attr[:2] == '__' or attr[0] == '_'):
result += '\t' * Lister.indent + '.%s=%s\n' % (attr,
self.__dict__[attr])
return result
def __repr__(self):
return self.__str__()
SimPy-2.3.1/SimPy/Recording.py 0000644 0000765 0000024 00000035025 11650341271 016515 0 ustar stefan staff 0000000 0000000 # coding=utf-8
"""
This file contains the classes for recording simulation results, Histogram,
Monitor and Tally.
"""
# Required for backward compatibility
import SimPy.Globals as Globals
class Histogram(list):
""" A histogram gathering and sampling class"""
def __init__(self, name = '', low = 0.0, high = 100.0, nbins = 10):
list.__init__(self)
self.name = name
self.low = float(low)
self.high = float(high)
self.nbins = nbins
self.binsize = (self.high - self.low) / nbins
self._nrObs = 0
self._sum = 0
self[:] = [[low + (i - 1) * self.binsize, 0] for i in range(self.nbins + 2)]
def addIn(self, y):
""" add a value into the correct bin"""
self._nrObs += 1
self._sum += y
b = int((y - self.low + self.binsize) / self.binsize)
if b < 0: b = 0
if b > self.nbins + 1: b = self.nbins + 1
assert 0 <= b <=self.nbins + 1, 'Histogram.addIn: b out of range: %s'%b
self[b][1] += 1
def __str__(self):
histo = self
ylab = 'value'
nrObs = self._nrObs
width = len(str(nrObs))
res = []
res.append(' < Histogram %s:'%self.name)
res.append('\nNumber of observations: %s'%nrObs)
if nrObs:
su = self._sum
cum = histo[0][1]
fmt = '%s'
line = '\n%s <= %s < %s: %s (cum: %s/%s%s)'\
%(fmt, '%s', fmt, '%s', '%s', '%5.1f', '%s')
line1 = '\n%s%s < %s: %s (cum: %s/%s%s)'\
%('%s', '%s', fmt, '%s', '%s', '%5.1f', '%s')
l1width = len(('%s <= '%fmt)%histo[1][0])
res.append(line1\
%(' ' * l1width, ylab, histo[1][0], str(histo[0][1]).rjust(width),\
str(cum).rjust(width),(float(cum) / nrObs) * 100, '%')
)
for i in range(1, len(histo) - 1):
cum += histo[i][1]
res.append(line\
%(histo[i][0], ylab, histo[i + 1][0], str(histo[i][1]).rjust(width),\
str(cum).rjust(width),(float(cum) / nrObs) * 100, '%')
)
cum += histo[-1][1]
linen = '\n%s <= %s %s : %s (cum: %s/%s%s)'\
%(fmt, '%s', '%s', '%s', '%s', '%5.1f', '%s')
lnwidth = len(('<%s'%fmt)%histo[1][0])
res.append(linen\
%(histo[-1][0], ylab, ' ' * lnwidth, str(histo[-1][1]).rjust(width),\
str(cum).rjust(width),(float(cum) / nrObs) * 100, '%')
)
res.append('\n > ')
return ' '.join(res)
class Monitor(list):
""" Monitored variables
A Class for monitored variables, that is, variables that allow one
to gather simple statistics. A Monitor is a subclass of list and
list operations can be performed on it. An object is established
using m = Monitor(name = '..'). It can be given a
unique name for use in debugging and in tracing and ylab and tlab
strings for labelling graphs.
"""
def __init__(self, name = 'a_Monitor', ylab = 'y', tlab = 't', sim = None):
list.__init__(self)
if not sim: sim = Globals.sim # Use global simulation if sim is None
self.sim = sim
self.startTime = 0.0
self.name = name
self.ylab = ylab
self.tlab = tlab
self.sim.allMonitors.append(self)
def setHistogram(self, name = '', low = 0.0, high = 100.0, nbins = 10):
"""Sets histogram parameters.
Must be called before call to getHistogram"""
if name == '':
histname = self.name
else:
histname = name
self.histo = Histogram(name = histname, low = low, high = high, nbins = nbins)
def observe(self, y,t = None):
"""record y and t"""
if t is None: t = self.sim.now()
self.append([t, y])
def tally(self, y):
""" deprecated: tally for backward compatibility"""
self.observe(y, 0)
def accum(self, y,t = None):
""" deprecated: accum for backward compatibility"""
self.observe(y, t)
def reset(self, t = None):
"""reset the sums and counts for the monitored variable """
self[:] = []
if t is None: t = self.sim.now()
self.startTime = t
def tseries(self):
""" the series of measured times"""
return list(zip(*self))[0]
def yseries(self):
""" the series of measured values"""
return list(zip(*self))[1]
def count(self):
""" deprecated: the number of observations made """
return self.__len__()
def total(self):
""" the sum of the y"""
if self.__len__() == 0: return 0
else:
sum = 0.0
for i in range(self.__len__()):
sum += self[i][1]
return sum # replace by sum() later
def mean(self):
""" the simple average of the monitored variable"""
try:
return 1.0 * self.total() / self.__len__()
except ZeroDivisionError:
raise ZeroDivisionError('SimPy: No observations for mean')
def var(self):
""" the sample variance of the monitored variable """
n = len(self)
tot = self.total()
ssq = 0.0
for i in range(self.__len__()):
ssq += self[i][1] ** 2 # replace by sum() eventually
try:
return (ssq - float(tot * tot) / n) / n
except:
raise ZeroDivisionError(
'SimPy: No observations for sample variance')
def timeAverage(self, t = None):
"""
The time-weighted average of the monitored variable.
If t is used it is assumed to be the current time,
otherwise t = self.sim.now()
"""
N = self.__len__()
if N == 0:
return None
if t is None: t = self.sim.now()
sum = 0.0
tlast = self[0][0]
ylast = self[0][1]
for i in range(N):
ti, yi = self[i]
sum += ylast * (ti - tlast)
tlast = ti
ylast = yi
sum += ylast * (t - tlast)
T = t - self[0][0]
if T == 0:
return None
return sum / float(T)
def timeVariance(self, t = None):
""" the time - weighted Variance of the monitored variable.
If t is used it is assumed to be the current time,
otherwise t = self.sim.now()
"""
N = self.__len__()
if N == 0:
return None
if t is None: t = self.sim.now()
sm = 0.0
ssq = 0.0
tlast = self[0][0]
# print 'DEBUG: 1 twVar ', t, tlast
ylast = self[0][1]
for i in range(N):
ti, yi = self[i]
sm += ylast * (ti - tlast)
ssq += ylast * ylast * (ti - tlast)
tlast = ti
ylast = yi
sm += ylast * (t - tlast)
ssq += ylast * ylast * (t - tlast)
T = t - self[0][0]
if T == 0:
return None
mn = sm / float(T)
return ssq / float(T) - mn * mn
def histogram(self, low = 0.0, high = 100.0, nbins = 10):
""" A histogram of the monitored y data values.
"""
h = Histogram(name = self.name, low = low, high = high, nbins = nbins)
ys = self.yseries()
for y in ys: h.addIn(y)
return h
def getHistogram(self):
"""Returns a histogram based on the parameters provided in
preceding call to setHistogram.
"""
ys = self.yseries()
h = self.histo
for y in ys: h.addIn(y)
return h
def printHistogram(self, fmt = '%s'):
"""Returns formatted frequency distribution table string from Monitor.
Precondition: setHistogram must have been called.
fmt == format of bin range values
"""
try:
histo = self.getHistogram()
except:
raise FatalSimerror('histogramTable: call setHistogram first'\
' for Monitor %s'%self.name)
ylab = self.ylab
nrObs = self.count()
width = len(str(nrObs))
res = []
res.append('\nHistogram for %s:'%histo.name)
res.append('\nNumber of observations: %s'%nrObs)
su = sum(self.yseries())
cum = histo[0][1]
line = '\n%s <= %s < %s: %s (cum: %s/%s%s)'\
%(fmt, '%s', fmt, '%s', '%s', '%5.1f', '%s')
line1 = '\n%s%s < %s: %s (cum: %s/%s%s)'\
%('%s', '%s', fmt, '%s', '%s', '%5.1f', '%s')
l1width = len(('%s <= '%fmt)%histo[1][0])
res.append(line1\
%(' ' * l1width, ylab, histo[1][0], str(histo[0][1]).rjust(width),\
str(cum).rjust(width),(float(cum) / nrObs) * 100, '%')
)
for i in range(1, len(histo) - 1):
cum += histo[i][1]
res.append(line\
%(histo[i][0], ylab, histo[i + 1][0], str(histo[i][1]).rjust(width),\
str(cum).rjust(width),(float(cum) / nrObs) * 100, '%')
)
cum += histo[-1][1]
linen = '\n%s <= %s %s : %s (cum: %s/%s%s)'\
%(fmt, '%s', '%s', '%s', '%s', '%5.1f', '%s')
lnwidth = len(('<%s'%fmt)%histo[1][0])
res.append(linen\
%(histo[-1][0], ylab, ' ' * lnwidth, str(histo[-1][1]).rjust(width),\
str(cum).rjust(width),(float(cum) / nrObs) * 100, '%')
)
return ' '.join(res)
class Tally:
def __init__(self, name = 'a_Tally', ylab = 'y', tlab = 't', sim = None):
if not sim: sim = Globals.sim # use global simulation if sim is None
self.sim = sim
self.name = name
self.ylab = ylab
self.tlab = tlab
self.reset()
self.startTime = 0.0
self.histo = None
self.sum = 0.0
self._sum_of_squares = 0
self._integral = 0.0 # time - weighted sum
self._integral2 = 0.0 # time - weighted sum of squares
self.sim.allTallies.append(self)
def setHistogram(self, name = '', low = 0.0, high = 100.0, nbins = 10):
"""Sets histogram parameters.
Must be called to prior to observations initiate data collection
for histogram.
"""
if name == '':
hname = self.name
else:
hname = name
self.histo = Histogram(name = hname, low = low, high = high, nbins = nbins)
def observe(self, y, t = None):
if t is None:
t = self.sim.now()
self._integral += (t - self._last_timestamp) * self._last_observation
yy = self._last_observation * self._last_observation
self._integral2 += (t - self._last_timestamp) * yy
self._last_timestamp = t
self._last_observation = y
self._total += y
self._count += 1
self._sum += y
self._sum_of_squares += y * y
if self.histo:
self.histo.addIn(y)
def reset(self, t = None):
if t is None:
t = self.sim.now()
self.startTime = t
self._last_timestamp = t
self._last_observation = 0.0
self._count = 0
self._total = 0.0
self._integral = 0.0
self._integral2 = 0.0
self._sum = 0.0
self._sum_of_squares = 0.0
def count(self):
return self._count
def total(self):
return self._total
def mean(self):
return 1.0 * self._total / self._count
def timeAverage(self, t = None):
if t is None:
t = self.sim.now()
integ = self._integral + (t - self._last_timestamp) * self._last_observation
if (t > self.startTime):
return 1.0 * integ / (t - self.startTime)
else:
return None
def var(self):
return 1.0 * (self._sum_of_squares - (1.0 * (self._sum * self._sum)\
/ self._count)) / (self._count)
def timeVariance(self, t = None):
""" the time - weighted Variance of the Tallied variable.
If t is used it is assumed to be the current time,
otherwise t = self.sim.now()
"""
if t is None:
t = self.sim.now()
twAve = self.timeAverage(t)
#print 'Tally timeVariance DEBUG: twave:', twAve
last = self._last_observation
twinteg2 = self._integral2 + (t - self._last_timestamp) * last * last
#print 'Tally timeVariance DEBUG:tinteg2:', twinteg2
if (t > self.startTime):
return 1.0 * twinteg2 / (t - self.startTime) - twAve * twAve
else:
return None
def __len__(self):
return self._count
def __eq__(self, l):
return len(l) == self._count
def getHistogram(self):
return self.histo
def printHistogram(self, fmt = '%s'):
"""Returns formatted frequency distribution table string from Tally.
Precondition: setHistogram must have been called.
fmt == format of bin range values
"""
try:
histo = self.getHistogram()
except:
raise FatalSimerror('histogramTable: call setHistogram first'\
' for Tally %s'%self.name)
ylab = self.ylab
nrObs = self.count()
width = len(str(nrObs))
res = []
res.append('\nHistogram for %s:'%histo.name)
res.append('\nNumber of observations: %s'%nrObs)
su = self.total()
cum = histo[0][1]
line = '\n%s <= %s < %s: %s (cum: %s/%s%s)'\
%(fmt, '%s', fmt, '%s', '%s', '%5.1f', '%s')
line1 = '\n%s%s < %s: %s (cum: %s/%s%s)'\
%('%s', '%s', fmt, '%s', '%s', '%5.1f', '%s')
l1width = len(('%s <= '%fmt)%histo[1][0])
res.append(line1\
%(' ' * l1width, ylab, histo[1][0], str(histo[0][1]).rjust(width),\
str(cum).rjust(width),(float(cum) / nrObs) * 100, '%')
)
for i in range(1, len(histo) - 1):
cum += histo[i][1]
res.append(line\
%(histo[i][0], ylab, histo[i + 1][0], str(histo[i][1]).rjust(width),\
str(cum).rjust(width),(float(cum) / nrObs) * 100, '%')
)
cum += histo[-1][1]
linen = '\n%s <= %s %s : %s (cum: %s/%s%s)'\
%(fmt, '%s', '%s', '%s', '%s', '%5.1f', '%s')
lnwidth = len(('<%s'%fmt)%histo[1][0])
res.append(linen\
%(histo[-1][0], ylab, ' ' * lnwidth, str(histo[-1][1]).rjust(width),\
str(cum).rjust(width),(float(cum) / nrObs) * 100, '%')
)
return ' '.join(res)
SimPy-2.3.1/SimPy/SimGUI.py 0000644 0000765 0000024 00000035175 11650343277 015714 0 ustar stefan staff 0000000 0000000 # coding=utf-8
"""
SimGUI 2.1 Provides a Tk / Tkinter - based framework for SimPy simulation
models.
"""
try: # Python 3
from tkinter import *
from tkinter.messagebox import *
except: # Python 2
from Tkinter import *
from tkMessageBox import *
from Canvas import Line, CanvasText, Rectangle
from SimPy import tkconsole as tkcons
from SimPy import __version__
import warnings
warnings.warn('This module be removed in SimPy 3.', DeprecationWarning)
class SimGUI(object):
def __init__(self, win, title = 'SimGUI', doc = 'No doc string found', consoleHeight = 50):
self.root = win
self.doc = doc
self.title = title
win.title(title)
self.win = self.root
self.noRunYet = True
self.makeMenu()
self.makeConsole(consoleHeight)
def mainloop(self):
self.root.mainloop()
def makeMenu(self):
self.top = Menu(self.win) #win = top - level window
self.win.config(menu = self.top)
self.makeFileMenu()
self.makeEditMenu()
self.makeRunMenu()
self.makeViewMenu()
self.makeHelpMenu()
def makeFileMenu(self):
self.file = Menu(self.top)
self.file.add_command(label = 'Save console content',
command = self.saveConsole, underline = 0)
self.file.add_command(label = 'Quit',
command = self.win.quit, underline = 0)
self.top.add_cascade(label = 'File', menu = self.file, underline = 0)
def makeEditMenu(self):
self.edit = Menu(self.top)
self.edit.add_command(label = 'Change parameters',
command = self.changeParameters, underline = 0)
self.edit.add_command(label = 'Clear console',
command = self.clearConsole, underline = 1)
self.top.add_cascade(label = 'Edit',
menu = self.edit, underline = 0)
def makeRunMenu(self):
self.run = Menu(self.top)
self.top.add_cascade(label = 'Run',
menu = self.run, underline = 0)
def makeViewMenu(self):
self.view = Menu(self.top)
self.view.add_command(label = 'Collected data',
command = self.showMonitors, underline = 0)
self.top.add_cascade(label = 'View',
menu = self.view, underline = 0)
def makeHelpMenu(self):
self.help = Menu(self.top)
self.help.add_command(label = 'About SimGUI',
command = self._aboutSimGUI, underline = 6)
self.help.add_command(label = 'Model description',
command = self.about, underline = 6)
self.help.add_command(label = 'Model code',
command = self.showcode, underline = 6)
self.help.add_command(label = 'Python interpreter',
command = self.makeInterpreter, underline = 0)
self.top.add_cascade(label = 'Help', menu = self.help, underline = 0)
def makeConsole(self, height):
scrollbar = Scrollbar(self.root)
scrollbar.pack(side = RIGHT, fill = Y)
textOutput = Frame(self.root)
# the status - line
self.topconsole = Label(textOutput, text = '')
self.topconsole.pack()
# the console
self.console = Text(textOutput, height = height, wrap = WORD, yscrollcommand = scrollbar.set)
self.console.pack()
scrollbar.config(command = self.console.yview)
textOutput.pack()
def writeConsole(self, text = ' '):
self.console.insert(END, '%s\n'%text)
self.root.update()
def writeStatusLine(self, text = ''):
self.topconsole.config(text = text)
self.root.update()
def saveConsole(self):
try: # Python 3
from tkinter.filedialog import asksaveasfilename
except: # Python 2
from tkFileDialog import asksaveasfilename
#get the Console content
content = self.console.get('1.0', END + ' - 1c')
#get a file name to save to
filename = asksaveasfilename()
if not filename[-4:] == '.txt':
filename += '.txt'
fi = open(filename, 'wb')
fi.write(content)
fi.close()
def clearConsole(self):
self.console.delete('1.0', END)
def showcode(self):
'Show SimPy / Python code of this program'
import sys
tl = Toplevel()
tl.title(self.title + ' - Code')
t = Text(tl, width = 80)
scroll = Scrollbar(tl, command = t.yview)
t.configure(yscrollcommand = scroll.set)
sourcefile = sys.argv[0]
source = ''
for i in open(sourcefile).readlines():
source = source + i
t.insert(END, source)
t.pack(side = LEFT)
scroll.pack(side = RIGHT, fill = Y)
def about(self):
self.showTextBox(width = 80, height = 30, text = self.doc,
title = self.title + ' - Model information')
def _aboutSimGUI(self):
t = Toplevel()
t.title('About SimGUI')
tx = Text(t, width = 60, height = 7)
txt = 'SimGUI version %s\n\nSimGUI is a framework for SimPy - based simulations. '%__version__+\
'It has been developed by Klaus Muller, Simon Frost and Tony Vignaux. \n'+\
'\n\nHomepage and download: simpy.sourceforge.net\n'
tx.insert(END, txt)
tx.pack()
def notdone(self):
showerror('Not implemented', 'Not yet available')
def showTextBox(self, width = 60, height = 10, text = ' ', title = ' '):
tl = Toplevel()
tl.title(title)
txt = text
t = Text(tl, width = width, height = height, wrap = WORD)
t.insert(END, txt)
t.pack()
def findMonitors(self):
self._monitors = []
for k in self.__dict__:
a = self.__dict__[k]
if isinstance(a, list) and hasattr(a, 'tseries') and hasattr(a, 'yseries'):
self._monitors.append(a)
def showMonitors(self):
if self.noRunYet:
showwarning('SimGUI warning', 'Run simulation first!')
return
self.findMonitors()
if not self._monitors:
showwarning('SimGUI warning', 'No Monitor instances found')
for m in self._monitors:
self.writeConsole('\nMonitor \'%s\':\n' % m.name)
dat = m
try:
xlab = m.tlab
except:
xlab = 'x'
try:
ylab = m.ylab
except:
ylab = 'y'
sep = ',\t'
self.writeConsole('%s%s%s' % (xlab, sep, ylab))
for this in dat:
self.writeConsole('%s%s%s' % (this[0],sep, this[1]))
self.writeConsole()
def findParameters(self):
"""Finds the instance of Parameters (there may only be one)
and associates it with self._parameters"""
self._parameters = None
for k in self.__dict__:
a = self.__dict__[k]
if isinstance(a, Parameters):
self._parameters = a
def changeParameters(self):
"""Offers entry fields for parameter change"""
self.findParameters()
if not self._parameters:
showwarning('SimGUI warning', 'No Parameters instance found.')
return
t1 = Toplevel(self.root)
top = Frame(t1)
self.lbl={}
self.ent={}
i = 1
for p in self._parameters.__dict__:
self.lbl[p] = Label(top, text = p)
self.lbl[p].grid(row = i, column = 0)
self.ent[p] = Entry(top)
self.ent[p].grid(row = i, column = 1)
self.ent[p].insert(0, self._parameters.__dict__[p])
i += 1
top.pack(side = TOP, fill = BOTH, expand = YES)
commitBut = Button(top, text = 'Change parameters', command = self.commit)
commitBut.grid(row = i, column = 1)
def commit(self):
"""Commits parameter changes, i.e. updates self._parameters"""
for p in self._parameters.__dict__:
this = self._parameters.__dict__
tipo = type(this[p])
if tipo == type(1):
try:
this[p] = int(self.ent[p].get())
except:
showerror(title = 'Input error',
message = 'Type Error; correct parameter \'%s\' to %s' % (p, tipo))
elif tipo == type(1.1):
try:
this[p] = float(self.ent[p].get())
except:
showerror(title = 'Input error',
message = 'Type Error; correct parameter \'%s\' to %s' % (p, tipo))
elif tipo == type('abc'):
try:
this[p] = self.ent[p].get()
except:
showerror(title = 'Input error',
message = 'Type Error; correct parameter \'%s\' to %s' % (p, tipo))
elif tipo == type([]):
try:
a = eval(self.ent[p].get())
if type(a) == type([]):
this[p] = a
except:
showerror(title = 'Input error',
message = 'Type Error; correct parameter \'%s\' to %s' % (p, tipo))
else:
showerror(title = 'Application program error',
message = 'Parameter %s has unsupported type'%p)
self.noRunYet = True
def makeInterpreter(self):
i = Toplevel(self.root)
interpreter = tkcons.Console(parent = i)
interpreter.dict['SimPy'] = self
interpreter.pack(fill = BOTH, expand = 1)
class Parameters:
def __init__(self,**kwds):
self.__dict__.update(kwds)
def __repr__(self):
return str(self.__dict__)
def __str__(self):
return str(self.__dict__)
def show(self):
res = []
for i in self.__dict__:
res.append('%s : %s\n' % (i, self.__dict__[i]))
return "".join(res)
if __name__ == '__main__':
print('SimGUI.py')
from SimPy.Simulation import *
from random import Random
class Source(Process):
""" Source generates customers randomly"""
def __init__(self, seed = 333):
Process.__init__(self)
self.SEED = seed
def generate(self, number, interval):
rv = Random(self.SEED)
for i in range(number):
c = Customer(name = 'Customer%02d' % (i,))
activate(c, c.visit(timeInBank = 12.0))
t = rv.expovariate(1.0 / interval)
yield hold, self, t
def NoInSystem(R):
""" The number of customers in the resource R
in waitQ and active Q"""
return (len(R.waitQ) + len(R.activeQ))
class Customer(Process):
""" Customer arrives, is served and leaves """
def __init__(self, name):
Process.__init__(self)
self.name = name
def visit(self, timeInBank = 0):
arrive = now()
Qlength = [NoInSystem(counter[i]) for i in range(Nc)]
##print '%7.4f %s: Here I am. %s '%(now(),self.name, Qlength)
for i in range(Nc):
if Qlength[i] == 0 or Qlength[i] == min(Qlength): join = i ; break
yield request, self, counter[join]
wait = now() - arrive
waitMonitor.observe(wait, t = now())
##print '%7.4f %s: Waited %6.3f' % (now(),self.name, wait)
tib = counterRV.expovariate(1.0 / timeInBank)
yield hold, self, tib
yield release, self, counter[join]
serviceMonitor.observe(now() - arrive, t = now())
if trace:
gui.writeConsole('Customer leaves at %.1d'%now())
def model():
global Nc, counter, counterRV, waitMonitor, serviceMonitor, trace, lastLeave, noRunYet, initialized
counterRV = Random(gui.params.counterseed)
sourceseed = gui.params.sourceseed
nrRuns = gui.params.nrRuns
lastLeave = 0
gui.noRunYet = True
for runNr in range(nrRuns):
gui.noRunYet = False
trace = gui.params.trace
if trace:
gui.writeConsole(text = '\n ** Run %s' % (runNr + 1))
Nc = 2
counter = [Resource(name = 'Clerk0'),Resource(name = 'Clerk1')]
gui.waitMon = waitMonitor = Monitor(name = 'Waiting Times')
waitMonitor.tlab = 'Time'
waitMonitor.ylab = 'Customer waiting time'
gui.serviceMon = serviceMonitor = Monitor(name = 'Service Times')
serviceMonitor.xlab = 'Time'
serviceMonitor.ylab = 'Total service time = wait + service'
initialize()
source = Source(seed = sourceseed)
activate(source, source.generate(gui.params.numberCustomers, gui.params.interval),0.0)
result = simulate(until = gui.params.endtime)
lastLeave += now()
gui.writeConsole('%s simulation run(s) completed\n'%nrRuns)
gui.writeConsole('Parameters:\n%s'%gui.params.show())
gui.writeStatusLine('Time: %.2f '%now())
def statistics():
if gui.noRunYet:
showwarning(title = 'Model warning',
message = 'Run simulation first -- no data available.')
return
aver = lastLeave / gui.params.nrRuns
gui.writeConsole(text = 'Average time for %s customers to get through bank: %.1f\n(%s runs)\n'\
%(gui.params.numberCustomers, aver, gui.params.nrRuns))
__doc__ = """
Modified bank11.py (from Bank Tutorial) with GUI.
Model: Simulate customers arriving at random, using a Source, requesting service
from two counters each with their own queue with random servicetime.
Uses Monitor objects to record waiting times and total service times."""
def showAuthors():
gui.showTextBox(text = 'Tony Vignaux\nKlaus Muller', title = 'Author information')
class MyGUI(SimGUI):
def __init__(self, win,**p):
SimGUI.__init__(self, win,**p)
self.help.add_command(label = 'Author(s)',
command = showAuthors, underline = 0)
self.view.add_command(label = 'Statistics',
command = statistics, underline = 0)
self.run.add_command(label = 'Run',
command = model, underline = 0)
root = Tk()
gui = MyGUI(root, title = 'SimPy GUI example', doc = __doc__, consoleHeight = 40)
gui.params = Parameters(endtime = 2000,
sourceseed = 1133,
counterseed = 3939393,
numberCustomers = 50,
interval = 10.0,
trace = 0,
nrRuns = 1)
gui.mainloop()
SimPy-2.3.1/SimPy/SimPlot.py 0000644 0000765 0000024 00000104671 11650343117 016175 0 ustar stefan staff 0000000 0000000 # coding=utf-8
"""
SimPlot 2.1 Provides basic plotting services based on Tk / Tkinter.
"""
try: # Python 3
from tkinter import *
from tkinter.messagebox import *
from tkinter.simpledialog import askinteger, askstring, askfloat
from tkinter.filedialog import *
except: # Python 2
from Tkinter import *
from tkMessageBox import *
from tkSimpleDialog import askinteger, askstring, askfloat
from tkFileDialog import *
from Canvas import Line, CanvasText, Rectangle
import string, math
from math import pi
from SimPy.Simulation import Monitor
import warnings
warnings.warn('This module be removed in SimPy 3.', DeprecationWarning)
def minCoordinate(clist):
if len(clist) < 2: return clist[0]
try:
x, y = clist[0]
for x1, y1 in clist[1:]:
if x1 <= x or y1 <= y:
x, y = x1, y1
except:
x, y = 0, 0
return x, y
def maxCoordinate(clist):
if len(clist) < 2: return clist[0]
try:
x, y = clist[0]
for x1, y1 in clist[1:]:
if x1 >= x or y1 >= y:
x, y = x1, y1
except:
x, y = 0, 0
return x, y
def minBound(clist):
x = 10000000
y = 10000000
for x1, y1 in clist:
if x1 < x: x = x1
if y1 < y: y = y1
return x, y
def maxBound(clist):
x = -10000000
y = -10000000
for x1, y1 in clist:
if x1 > x: x = x1
if y1 > y: y = y1
return x, y
class SimPlot(object):
def __init__(self, root = Tk()):
self.root = root
pass
def mainloop(self):
self.root.mainloop()
def makeLine(self, points,**attr):
return GraphLine(points, **attr)
def makeStep(self, points, **attr):
#convert data list to steps
step0 = points[:]
step1 = [[0, 0]] * 2*len(step0)
prev = [step0[0][0],0]
for x in range(len(step0)):
step1[2 * x] = [step0[x][0],prev[1]]
step1[2 * x + 1] = step0[x]
prev = step0[x]
#draw the line
return self.makeLine(step1, smooth = False, **attr)
def makeHistogram(self, points,**attr):
"""Makes a histogram graph. 'points' must be a Histogram - like
object.
"""
#convert data list to bars
step0 = points[:]
step1 = [[0, 0]] * 3*len(step0)
prev = [step0[0][0],0]
for x in range(len(step0)):
step1[3 * x] = [step0[x][0],prev[1]]
step1[3 * x + 1] = [step0[x][0],0.0]
step1[3 * x + 2] = step0[x]
prev = step0[x]
deltax = step0[1][0] - step0[0][0]
step1.append([prev[0] + deltax, prev[1]])
step1.append([prev[0] + deltax, 0])
#make the line
return self.makeLine(step1, smooth = False,
xaxis = (step1[0][0],step1[-1][0]),
**attr)
def makeSymbols(self, points,**attr):
return GraphSymbols(points,**attr)
def makeBars(self, points,**attr):
return GraphBars(points,**attr)
def makeGraphObjects(self, objects):
return GraphObjects(objects)
def makeGraphBase(self, master, width, height,
background = 'white', title = '', xtitle = '', ytitle = '', **kw):
return GraphBase(master, width, height,
background, title, xtitle, ytitle,**kw)
def graphMenu(self, root, graph):
"""To provide a File menu (postscript output, more to come)
to the plotxxxx plots"""
mainMenu = Menu(root)
root.config(menu = mainMenu)
def postscriptout():
graph.postscr()
file = Menu(mainMenu)
file.add_command(label = 'Postscript', command = postscriptout)
mainMenu.add_cascade(label = 'File', menu = file, underline = 0)
def plotLine(self, points, windowsize = (500, 300),title = '', width = 1, color = 'black',
smooth = 0, background = 'white', xlab = 'x', ylab = 'y',
xaxis = 'automatic', yaxis = 'automatic'):
"""Generates a line chart, with menu to save as Postscript file.
'points' can be a Monitor instance.
"""
if points != []:
root = Toplevel()
f = Frame(root)
try: #if it is like a Monitor, take xlab, ylab from it
ylab = points.ylab
xlab = points.tlab
if not title: title = points.name
except:
pass
line = self.makeLine(points, width = width, color = color, smooth = smooth)
gr = self.makeGraphObjects([line])
graph = self.makeGraphBase(f, windowsize[0], windowsize[1],
title = title, xtitle = xlab,
ytitle = ylab, background = background)
graph.pack(side = LEFT, fill = BOTH, expand = YES)
graph.draw(gr, xaxis = xaxis, yaxis = yaxis)
#File menu
self.graphMenu(root, graph)
f.pack()
return graph
else:
print('SimPlot.plotline: dataset empty, no plot.')
return None
def plotStep(self, points, windowsize = (500, 300),title = '', width = 1, color = 'black',
background = 'white', xlab = 'x', ylab = 'y',
xaxis = 'automatic', yaxis = 'automatic'):
"""Generates a step chart, with menu to save as Postscript file.
'points' can be a Monitor instance.
"""
if points != []:
#convert data list to steps
step0 = points[:]
step1 = [[0, 0]] * 2*len(step0)
prev = [step0[0][0],0]
for x in range(len(step0)):
step1[2 * x] = [step0[x][0],prev[1]]
step1[2 * x + 1] = step0[x]
prev = step0[x]
#treat monitor case
try: #if it is like a Monitor, take xlab, ylab from it
ylab = points.ylab
xlab = points.tlab
if not title: title = points.name
except:
pass
#draw the line
smooth = False
return self.plotLine(step1, windowsize, title, width, color,
smooth, background, xlab, ylab,
xaxis, yaxis)
else:
print('SimPlot.plotStep: dataset empty, no plot.')
return None
def plotHistogram(self, points, windowsize = (500, 300),title = '', width = 1, color = 'black',
background = 'white', xlab = 'x', ylab = 'y',
xaxis = 'automatic', yaxis = 'automatic'):
"""Makes a histogram plot. 'points' can be a Monitor instance.
"""
if points != []:
#convert data list to bars
step0 = points[:]
step1 = [[0, 0]] * 3*len(step0)
prev = [step0[0][0],0]
for x in range(len(step0)):
step1[3 * x] = [step0[x][0],prev[1]]
step1[3 * x + 1] = [step0[x][0],0.0]
step1[3 * x + 2] = step0[x]
prev = step0[x]
deltax = step0[1][0] - step0[0][0]
step1.append([prev[0] + deltax, prev[1]])
step1.append([prev[0] + deltax, 0])
#treat monitor case
try: #if it is like a Monitor, take xlab, ylab from it
ylab = points.ylab
xlab = points.tlab
if not title: title = points.name
except:
pass
#draw the line
smooth = False
return self.plotLine(step1, windowsize = windowsize, title = title, width = width,
color = color, smooth = smooth, background = background,
xlab = xlab, ylab = ylab, xaxis = (step1[0][0],step1[-1][0]),
yaxis = yaxis)
else:
print('SimPlot.plotHistogram: dataset empty, no plot.')
return None
def plotBars(self, points, windowsize = (500, 300),title = '', color = 'black',
width = 1, size = 3, fillcolor = 'black', fillstyle = '',
outline = 'black', background = 'white', xlab = 'x', ylab = 'y',
xaxis = 'automatic', yaxis = 'automatic', anchor = 0.0):
"""Generates a bar chart, with menu to save as Postscript file.
'points' can be a Monitor instance.
"""
if points != []:
root = Toplevel()
f = Frame(root)
try: #if it is like a Monitor, take xlab, ylab from it
ylab = points.ylab
xlab = points.tlab
if not title: title = points.name
except:
pass
bars = self.makeBars(points, width = width, size = size, color = color,
fillcolor = fillcolor, fillstyle = fillstyle,
outline = outline, anchor = anchor)
gr = self.makeGraphObjects([bars])
graph = self.makeGraphBase(f, windowsize[0],windowsize[1],
title = title, xtitle = xlab,
ytitle = ylab, background = background)
graph.pack(side = LEFT, fill = BOTH, expand = YES)
graph.draw(gr, xaxis = xaxis, yaxis = yaxis)
#File menu
self.graphMenu(root, graph)
f.pack()
return graph
else:
print('SimPlot.plotBars dataset empty, no plot.')
return None
def plotScatter(self, points, windowsize = (500, 300),title = '', width = 1, color = 'black',
fillcolor = 'black', size = 2, fillstyle = '',
outline = 'black', marker = 'circle',
background = 'white', xlab = 'x', ylab = 'y',
xaxis = 'automatic', yaxis = 'automatic'):
if points != []:
root = Toplevel()
f = Frame(root)
try: #if it is like a Monitor, take xlab, ylab from it
ylab = points.ylab
xlab = points.tlab
if not title: title = points.name
except:
pass
scat = self.makeSymbols(points, width = width, color = color, size = size,
marker = marker, fillcolor = fillcolor,
fillstyle = fillstyle, outline = outline)
gr = self.makeGraphObjects([scat])
graph = self.makeGraphBase(f, windowsize[0],windowsize[1],
title = title, xtitle = xlab,
ytitle = ylab, background = background)
graph.pack(side = LEFT, fill = BOTH, expand = YES)
graph.draw(gr, xaxis = xaxis, yaxis = yaxis)
#File menu
self.graphMenu(root, graph)
f.pack()
return graph
else:
print('SimPlot.plotScatter: dataset empty, no plot.')
return None
def mainloop(self):
self.root.mainloop()
class GraphPoints:
def __init__(self, points, attr):
self.points = points
self.scaled = self.points
self.attributes = {}
for name, value in self._attributes.items():
try:
value = attr[name]
except KeyError: pass
self.attributes[name] = value
def boundingBox(self):
return minBound(self.points), maxBound(self.points)
def fitToScale(self, scale = (1, 1), shift = (0, 0)):
self.scaled = []
for x, y in self.points:
self.scaled.append(((scale[0] * x) + shift[0],\
(scale[1] * y) + shift[1]))
self.attributes.get('anchor', 0.0)
self.anchor = scale[1] * self.attributes.get('anchor', 0.0)+\
shift[1]
class GraphLine(GraphPoints):
def __init__(self, points, **attr):
GraphPoints.__init__(self, points, attr)
_attributes = {'color': 'black',
'width': 1,
'smooth': 0,
'splinesteps': 12}
def draw(self, canvas):
color = self.attributes['color']
width = self.attributes['width']
smooth = self.attributes['smooth']
steps = self.attributes['splinesteps']
arguments = (canvas,)
if smooth:
for i in range(len(self.points)):
x1, y1 = self.scaled[i]
arguments = arguments + (x1, y1)
else:
for i in range(len(self.points) - 1):
x1, y1 = self.scaled[i]
x2, y2 = self.scaled[i + 1]
arguments = arguments + (x1, y1, x2, y2)
Line(*arguments, **{'fill': color, 'width': width,
'smooth': smooth, 'splinesteps':steps})
class GraphSymbols(GraphPoints):
def __init__(self, points, **attr):
GraphPoints.__init__(self, points, attr)
_attributes = {'color': 'black',
'width': 1,
'fillcolor': 'black',
'size': 2,
'fillstyle': '',
'outline': 'black',
'marker': 'circle'}
def draw(self, canvas):
color = self.attributes['color']
size = self.attributes['size']
fillcolor = self.attributes['fillcolor']
marker = self.attributes['marker']
fillstyle = self.attributes['fillstyle']
self._drawmarkers(canvas, self.scaled, marker, color,
fillstyle, fillcolor, size)
def _drawmarkers(self, c, coords, marker = 'circle', color = 'black',
fillstyle = '', fillcolor = '', size = 2):
l = []
f = eval('self._' + marker)
for xc, yc in coords:
id = f(c, xc, yc, outline = color, size = size,
fill = fillcolor, fillstyle = fillstyle)
if type(id) is type(()):
for item in id: l.append(item)
else:
l.append(id)
return l
def _circle(self, c, xc, yc, size = 1, fill = '', outline = 'black',
fillstyle = ''):
id = c.create_oval(xc - 0.5, yc - 0.5, xc + 0.5, yc + 0.5,
fill = fill, outline = outline,
stipple = fillstyle)
c.scale(id, xc, yc, size * 5, size * 5)
return id
def _dot(self, c, xc, yc, size = 1, fill = '', outline = 'black',
fillstyle = ''):
id = c.create_oval(xc - 0.5, yc - 0.5, xc + 0.5, yc + 0.5,
fill = fill, outline = outline,
stipple = fillstyle)
c.scale(id, xc, yc, size * 2.5, size * 2.5)
return id
def _square(self, c, xc, yc, size = 1, fill = '', outline = 'black',
fillstyle = ''):
id = c.create_rectangle(xc - 0.5, yc - 0.5, xc + 0.5, yc + 0.5,
fill = fill, outline = outline,
stipple = fillstyle)
c.scale(id, xc, yc, size * 5, size * 5)
return id
def _triangle(self, c, xc, yc, size = 1, fill = '', outline = 'black',
fillstyle = ''):
id = c.create_polygon(-0.5, 0.288675134595,
0.5, 0.288675134595,
0.0, -0.577350269189, fill = fill,
outline = outline, stipple = fillstyle)
c.move(id, xc, yc)
c.scale(id, xc, yc, size * 5, size * 5)
return id
def _triangle_down(self, c, xc, yc, size = 1, fill = '',
outline = 'black', fillstyle = ''):
id = c.create_polygon(-0.5, -0.288675134595,
0.5, -0.288675134595,
0.0, 0.577350269189, fill = fill,
outline = outline, stipple = fillstyle)
c.move(id, xc, yc)
c.scale(id, xc, yc, size * 5, size * 5)
return id
def _cross(self, c, xc, yc, size = 1, fill = 'black', outline = None,
fillstyle = ''):
if outline: fill = outline
id1 = c.create_line(xc - 0.5, yc - 0.5, xc + 0.5, yc + 0.5,
fill = fill)
id2 = c.create_line(xc - 0.5, yc + 0.5, xc + 0.5, yc - 0.5,
fill = fill)
c.scale(id1, xc, yc, size * 5, size * 5)
c.scale(id2, xc, yc, size * 5, size * 5)
return id1, id2
def _plus(self, c, xc, yc, size = 1, fill = 'black', outline = None,
fillstyle = ''):
if outline: fill = outline
id1 = c.create_line(xc - 0.5, yc, xc + 0.5, yc, fill = fill)
id2 = c.create_line(xc, yc + 0.5, xc, yc - 0.5, fill = fill)
c.scale(id1, xc, yc, size * 5, size * 5)
c.scale(id2, xc, yc, size * 5, size * 5)
return id1, id2
class GraphBars(GraphPoints):
def __init__(self, points, **attr):
GraphPoints.__init__(self, points, attr)
_attributes = {'color': 'black',
'width': 1,
'fillcolor': 'black',
'size': 3,
'fillstyle': '',
'outline': 'black'}
def draw(self, canvas):
color = self.attributes['color']
width = self.attributes['width']
fillstyle = self.attributes['fillstyle']
outline = self.attributes['outline']
spread = self.attributes['size']
arguments = (canvas,)
p1, p2 = self.boundingBox()
for i in range(len(self.points)):
x1, y1 = self.scaled[i]
canvas.create_rectangle(x1 - spread, y1, x1 + spread,
self.anchor, fill = color,
width = width, outline = outline,
stipple = fillstyle)
class GraphObjects:
def __init__(self, objects):
self.objects = objects
def boundingBox(self):
c1, c2 = self.objects[0].boundingBox()
for object in self.objects[1:]:
c1o, c2o = object.boundingBox()
c1 = minBound([c1, c1o])
c2 = maxBound([c2, c2o])
return c1, c2
def fitToScale(self, scale = (1, 1), shift = (0, 0)):
for object in self.objects:
object.fitToScale(scale, shift)
def draw(self, canvas):
for object in self.objects:
object.draw(canvas)
class GraphBase(Frame):
def __init__(self, master, width, height,
background = 'white', title = '', xtitle = '', ytitle = '', **kw):
Frame.__init__(self, master, **kw)
self.title = title
self.xtitle = xtitle
self.ytitle = ytitle
self.canvas = Canvas(self, width = width, height = height,
background = background)
self.canvas.pack(fill = BOTH, expand = YES)
border_w = self.canvas.winfo_reqwidth() - \
string.atoi(self.canvas.cget('width'))
border_h = self.canvas.winfo_reqheight() - \
string.atoi(self.canvas.cget('height'))
self.border = (border_w, border_h)
self.canvas.bind('', self.configure)
self.plotarea_size = [None, None]
self._setsize()
self.last_drawn = None
self.font = ('Verdana', 10)
def configure(self, event):
new_width = event.width - self.border[0]
new_height = event.height - self.border[1]
width = string.atoi(self.canvas.cget('width'))
height = string.atoi(self.canvas.cget('height'))
if new_width == width and new_height == height:
return
self.canvas.configure(width = new_width, height = new_height)
self._setsize()
self.clear()
self.replot()
def bind(self, *args):
self.canvas.bind(*args)
def _setsize(self):
self.width = string.atoi(self.canvas.cget('width'))
self.height = string.atoi(self.canvas.cget('height'))
#self.plotarea_size[0] = 0.90 * self.width
#self.plotarea_size[1] = 0.90 * -self.height
self.plotarea_size[0] = 0.90 * self.width
self.plotarea_size[1] = 0.90 * -self.height
xo = 0.5 * (self.width - self.plotarea_size[0])
yo = self.height - 0.5 * (self.height + self.plotarea_size[1])
self.plotarea_origin = (xo, yo)
def draw(self, graphics, xaxis = 'automatic', yaxis = 'automatic'):
self.last_drawn = (graphics, xaxis, yaxis)
p1, p2 = graphics.boundingBox()
xaxis = self._axisInterval(xaxis, p1[0], p2[0])
yaxis = self._axisInterval(yaxis, p1[1], p2[1])
text_width = [0., 0.]
text_height = [0., 0.]
if xaxis is not None:
p1 = xaxis[0], p1[1]
p2 = xaxis[1], p2[1]
xticks = self._ticks(xaxis[0], xaxis[1])
bb = self._textBoundingBox(xticks[0][1])
text_height[1] = bb[3] - bb[1]
text_width[0] = 0.5 * (bb[2] - bb[0])
bb = self._textBoundingBox(xticks[-1][1])
text_width[1] = 0.5 * (bb[2] - bb[0])
else:
xticks = None
if yaxis is not None:
p1 = p1[0], yaxis[0]
p2 = p2[0], yaxis[1]
yticks = self._ticks(yaxis[0], yaxis[1])
for y in yticks:
bb = self._textBoundingBox(y[1])
w = bb[2] - bb[0]
text_width[0] = max(text_width[0], w)
h = 0.5 * (bb[3] - bb[1])
text_height[0] = h
text_height[1] = max(text_height[1], h)
else:
yticks = None
text1 = [text_width[0], -text_height[1]]
text2 = [text_width[1], -text_height[0]]
scale = ((self.plotarea_size[0] - text1[0] - text2[0]) / \
(p2[0] - p1[0]),
(self.plotarea_size[1] - text1[1] - text2[1]) / \
(p2[1] - p1[1]))
shift = ((-p1[0] * scale[0]) + self.plotarea_origin[0] + \
text1[0],
(-p1[1] * scale[1]) + self.plotarea_origin[1] + \
text1[1])
self._drawAxes(self.canvas, xaxis, yaxis, p1, p2,
scale, shift, xticks, yticks)
graphics.fitToScale(scale, shift)
graphics.draw(self.canvas)
def _axisInterval(self, spec, lower, upper):
if spec is None:
return None
if spec == 'minimal':
if lower == upper:
return lower - 0.5, upper + 0.5
else:
return lower, upper
if spec == 'automatic':
range = upper - lower
if range == 0.:
return lower - 0.5, upper + 0.5
log = math.log10(range)
power = math.floor(log)
fraction = log - power
if fraction <= 0.05:
power = power - 1
grid = 10.**power
lower = lower - lower % grid
mod = upper % grid
if mod != 0:
upper = upper - mod + grid
return lower, upper
if type(spec) == type(()):
lower, upper = spec
if lower <= upper:
return lower, upper
else:
return upper, lower
raise ValueError(str(spec) + ': illegal axis specification')
def _drawAxes(self, canvas, xaxis, yaxis,
bb1, bb2, scale, shift, xticks, yticks):
dict = {'anchor': N, 'fill': 'black'}
if self.font is not None:
dict['font'] = self.font
if xaxis is not None:
#draw x - axis
lower, upper = xaxis
text = 1
once = 1
for y, d in [(bb1[1], -3), (bb2[1], 3)]:
#d=.5 of tick - length
p1 = (scale[0] * lower) + shift[0], (scale[1] * y) + shift[1]
if once: pp1 = p1
p2 = (scale[0] * upper) + shift[0], (scale[1] * y) + shift[1]
if once: pp2 = p2
once = 0
Line(self.canvas, p1[0], p1[1], p2[0], p2[1],
fill = 'black', width = 1)
if xticks:
for x, label in xticks:
p = (scale[0] * x) + shift[0], \
(scale[1] * y) + shift[1]
Line(self.canvas, p[0], p[1], p[0], p[1] + d,
fill = 'black', width = 1)
if text:
dict['text'] = label
CanvasText(self.canvas, p[0],
p[1] + 2, **dict) ##KGM 14 Aug 03
text = 0
#write x - axis title
CanvasText(self.canvas,(pp2[0] - pp1[0]) / 2.+pp1[0],pp1[1] + 22, text = self.xtitle)
#write graph title
CanvasText(self.canvas,(pp2[0] - pp1[0]) / 2.+pp1[0],7, text = self.title)
dict['anchor'] = E
if yaxis is not None:
#draw y - axis
lower, upper = yaxis
text = 1
once = 1
for x, d in [(bb1[0], -3), (bb2[0], 3)]:
p1 = (scale[0] * x) + shift[0], (scale[1] * lower) + shift[1]
p2 = (scale[0] * x) + shift[0], (scale[1] * upper) + shift[1]
if once: pp1 = p1 ;pp2 = p2
once = 0
Line(self.canvas, p1[0], p1[1], p2[0], p2[1],
fill = 'black', width = 1)
if yticks:
for y, label in yticks:
p = (scale[0] * x) + shift[0], \
(scale[1] * y) + shift[1]
Line(self.canvas, p[0], p[1], p[0] - d, p[1],
fill = 'black', width = 1)
if text:
dict['text'] = label
CanvasText(self.canvas,
p[0] - 4, p[1] + 2, **dict)
text = 0
#write y - axis title
CanvasText(self.canvas, pp2[0],pp2[1] - 10, text = self.ytitle)
def _ticks(self, lower, upper):
ideal = (upper - lower) / 7.
log = math.log10(ideal)
power = math.floor(log)
fraction = log - power
factor = 1.
error = fraction
for f, lf in self._multiples:
e = math.fabs(fraction - lf)
if e < error:
error = e
factor = f
grid = factor * 10.**power
if power > 3 or power < -3:
format = '%+7.0e'
elif power >= 0:
digits = max(1, int(power))
format = '%' + repr(digits)+'.0f'
else:
digits = -int(power)
format = '%'+repr(digits + 2)+'.'+repr(digits)+'f'
ticks = []
t = -grid * math.floor(-lower / grid)
while t <= upper and len(ticks) < 200:
ticks.append((t, format % (t,)))
t = t + grid
return ticks
_multiples = [(2., math.log10(2.)), (5., math.log10(5.))]
def _textBoundingBox(self, text):
bg = self.canvas.cget('background')
dict = {'anchor': NW, 'text': text, 'fill': bg}
if self.font is not None:
dict['font'] = self.font
item = CanvasText(self.canvas, 0., 0., **dict)
bb = self.canvas.bbox(item)
self.canvas.delete(item)
return bb
def replot(self):
if self.last_drawn is not None:
self.draw(self.last_drawn)
def clear(self):
self.canvas.delete('all')
def postscr(self, filename = None):
"""Write to Postscript file given by 'filename'. If none provided,
ask user.
"""
try: # Python 3
from tkinter.filedialog import asksaveasfilename
except: # Python 2
from tkFileDialog import asksaveasfilename
if not filename:
filename = asksaveasfilename()
if filename:
if not filename[-3:] == '.ps':
filename += '.ps'
self.canvas.postscript(width = self.width, height = self.height, file = filename)
class TextBox(Frame):
def __init__(self, master, width, height,
background = 'white', boxtext = '', **kw):
Frame.__init__(self, master, **kw)
self.width = width
self.height = height
self.canvas = Canvas(self, width = width, height = height,
background = background)
self.canvas.pack(fill = BOTH, expand = YES)
#CanvasText(self.canvas, text = boxtext)
def postscr(self):
#select output file
#from tkFileDialog import asksaveasfilename
filename = asksaveasfilename()
if filename:
if not filename[-3:] == '.ps':
filename += '.ps'
self.canvas.postscript(width = self.width, height = self.height, file = filename)
if __name__ == '__main__':
print('SimPlot.py')
root = Tk()
plt = SimPlot()
root.title('SimPlot example - First frame')
root1 = Tk()
root1.title('SimPlot example - Second frame')
"""PARAMETER DEFAULTS:
GraphBase
---------
background = 'white',
title = '',
xtitle = '',
ytitle = ''
GraphBase.draw
--------------
xaxis = 'automatic',
yaxis = 'automatic')
GraphLine
---------
color: 'black',
width: 1,
smooth: 0,
splinesteps: 12
GraphSymbols:
-------------
color: 'black',
width: 1,
fillcolor: 'black',
size: 2,
fillstyle: '',
outline: 'black',
marker: 'circle'}
GraphBars
---------
color: 'black',
width: 1,
fillcolor: 'black',
size: 3,
fillstyle: '',
outline: 'black'
"""
# Plot 1 -- smooth line + filled bars
di = 5.0 * pi / 40.
data = []
for i in range(40):
data.append((float(i) * di,
(math.sin(float(i) * di) - math.cos(float(i) * di))))
line1 = plt.makeLine(data, color = 'black', width = 1,
smooth = 1)
line1a = plt.makeBars(data[1:], color = 'blue', fillstyle = 'gray25',
anchor = 0.0)
graphObject = plt.makeGraphObjects([line1a, line1])
#Second panel -- Narrow bars
line2 = plt.makeBars([(0, 0),(1, 145),(2,-90),(3, 147),(4, 22),(5, 31),
(6, 77),(7, 125),(8, 220),(9, 550),(10, 560),(11, 0)],
outline = 'green', color = 'red', size = 7)
graphObject2 = plt.makeGraphObjects([line2])
# Third plot -- Smooth line and unsmoothed line
line3 = plt.makeLine([(1, 145 + 100),(2, 151 + 100),(3, 147 + 100),(4, 22 + 100),(5, 31 + 100),
(6, 77 + 100),(7, 125 + 100),(8, 220 + 100),(9, 550 + 100),(10, 560 + 100)],
color = 'blue', width = 2, smooth = 1)
line3a = plt.makeLine([(1, 145),(2, 151),(3, 147),(4, 22),(5, 31),
(6, 77),(7, 125),(8, 220),(9, 550),(10, 560)],
color = 'green', width = 2, smooth = 0)
line3b = plt.makeStep([(1, 145 + 100),(2, 151 + 100),(3, 147 + 100),(4, 22 + 100),(5, 31 + 100),
(6, 77 + 100),(7, 125 + 100),(8, 220 + 100),(9, 550 + 100),(10, 560 + 100)],
color = 'red', width = 2)
graphObject3 = plt.makeGraphObjects([line3, line3a, line3b])
# Fourth plot -- lines with all available symbols with different
# outline colors / fill colors / sizes
line4 = plt.makeSymbols([(1, 100),(2, 100),(3, 100),(4, 100),(5, 100),
(6, 100),(7, 100),(8, 100),(9, 100),(10, 100)],
color = 'black', fillcolor = 'red', width = 2, marker = 'triangle')
line5 = plt.makeSymbols([(1, 200),(2, 200),(3, 200),(4, 200),(5, 200),
(6, 200),(7, 200),(8, 200),(9, 200),(10, 200)],
color = 'red', width = 2, marker = 'circle')
line6 = plt.makeSymbols([(1, 300),(2, 300),(3, 300),(4, 300),(5, 300),
(6, 300),(7, 300),(8, 300),(9, 300),(10, 300)],
color = 'green', width = 2, marker = 'dot')
line7 = plt.makeSymbols([(1, 400),(2, 400),(3, 400),(4, 400),(5, 400),
(6, 400),(7, 400),(8, 400),(9, 400),(10, 400)],
color = 'blue', fillcolor = 'white',
size = 2, width = 2, marker = 'square')
line8 = plt.makeSymbols([(1, 500),(2, 500),(3, 500),(4, 500),(5, 500),
(6, 500),(7, 500),(8, 500),(9, 500),(10, 500)],
color = 'yellow', width = 2, marker = 'triangle')
line9 = plt.makeSymbols([(1, 600),(2, 600),(3, 600),(4, 600),(5, 600),
(6, 600),(7, 600),(8, 600),(9, 600),(10, 600)],
color = 'magenta', width = 2, marker = 'cross')
line10 = plt.makeSymbols([(1, 700),(2, 700),(3, 700),(4, 700),(5, 700),
(6, 700),(7, 700),(8, 700),(9, 700),(10, 700)],
color = 'brown', width = 2, marker = 'plus')
line11 = plt.makeSymbols([(1, 800),(2, 800),(3, 800),(4, 800),(5, 800),
(6, 800),(7, 800),(8, 800),(9, 800),(10, 800)],
color = 'black', fillcolor = 'orange',
width = 2, marker = 'triangle_down')
graphObject4 = GraphObjects([line4, line5, line6, line7, line8,
line9, line10, line11])
# Two panels
f1 = Frame(root)
f2 = Frame(root1)
graph={}
# Plots 1 and 2 in panel f1, side by side
graph[1] = plt.makeGraphBase(f1, 500, 300, title = 'Plot 1: 1 makeLine call, 1 makeBars call',
xtitle = 'the x-axis', ytitle = 'the y-axis')
graph[1].pack(side = LEFT, fill = BOTH, expand = YES)
graph[1].draw(graphObject, xaxis = 'minimal', yaxis = 'minimal')
graph[2] = plt.makeGraphBase(f1, 500, 300, title = 'Plot 2: 1 makeBars call',
xtitle = 'time', ytitle = 'pulse [volt]')
# Set side - by - side plots
graph[2].pack(side = LEFT, fill = BOTH, expand = YES)
graph[2].draw(graphObject2, 'minimal', 'automatic')
# Pack panel 1 to make it visible
f1.pack()
# Plots 2 and 3 in panel f2, one under the other
graph[3] = plt.makeGraphBase(f2, 500, 300,
title = 'Plot 3: 2 makeLine call (smooth, not smooth); 1 makeStep call')
graph[3].pack(side = TOP, fill = BOTH, expand = YES)
graph[3].draw(graphObject3)
graph[4] = plt.makeGraphBase(f2, 500, 300, border = 3, title = 'Plot 4: 8 makeSymbols calls')
# Set one - over - other configuration of plots
graph[4].pack(side = TOP, fill = BOTH, expand = YES)
graph[4].draw(graphObject4)
# Pack panel 2 to make it visible
f2.pack()
# Save graph[1] to Postscript file (user selects filename)
graph[1].postscr()
# end plotting stuff
#### Very Important -- get Tk going by starting event loop
plt.mainloop()
SimPy-2.3.1/SimPy/Simulation.py 0000644 0000765 0000024 00000050751 11675036575 016747 0 ustar stefan staff 0000000 0000000 # coding=utf-8
"""
Simulation implements SimPy Processes, Resources, Buffers, and the backbone simulation
scheduling by coroutine calls. Provides data collection through classes
Monitor and Tally.
Based on generators
"""
import random
import sys
import types
from heapq import heappush, heappop
from SimPy.Lister import Lister
from SimPy.Recording import Monitor, Tally
from SimPy.Lib import Process, SimEvent, PriorityQ, Resource, Level, \
Store, Simerror, FatalSimerror, FIFO
# Required for backward compatibility
import SimPy
import SimPy.Globals as Globals
from SimPy.Globals import initialize, simulate, now, stopSimulation, \
allEventNotices, allEventTimes, startCollection,\
_startWUStepping, _stopWUStepping, activate, reactivate
# yield keywords
hold = 1
passivate = 2
request = 3
release = 4
waitevent = 5
queueevent = 6
waituntil = 7
get = 8
put = 9
class Infinity(object):
def __cmp__(self, other):
return 1
infinity = Infinity()
def holdfunc(a):
a[0][1]._hold(a)
def requestfunc(a):
"""Handles 'yield request, self, res' and
'yield (request, self, res),(,self, par)'.
can be 'hold' or 'waitevent'.
"""
if type(a[0][0]) == tuple:
## Compound yield request statement
## first tuple in ((request, self, res),(xx, self, yy))
b = a[0][0]
## b[2] == res (the resource requested)
##process the first part of the compound yield statement
##a[1] is the Process instance
b[2]._request(arg = (b, a[1]))
##deal with add - on condition to command
##Trigger processes for reneging
class _Holder(Process):
"""Provides timeout process"""
def __init__(self,name,sim=None):
Process.__init__(self,name=name,sim=sim)
def trigger(self, delay):
yield hold, self, delay
if not proc in b[2].activeQ:
proc.sim.reactivate(proc)
class _EventWait(Process):
"""Provides event waiting process"""
def __init__(self,name,sim=None):
Process.__init__(self,name=name,sim=sim)
def trigger(self, event):
yield waitevent, self, event
if not proc in b[2].activeQ:
proc.eventsFired = self.eventsFired
proc.sim.reactivate(proc)
#activate it
proc = a[0][0][1] # the process to be woken up
actCode = a[0][1][0]
if actCode == hold:
proc._holder = _Holder(name = 'RENEGE - hold for %s'%proc.name,
sim=proc.sim)
## the timeout delay
proc.sim.activate(proc._holder, proc._holder.trigger(a[0][1][2]))
elif actCode == waituntil:
raise FatalSimerror('Illegal code for reneging: waituntil')
elif actCode == waitevent:
proc._holder = _EventWait(name = 'RENEGE - waitevent for %s'\
%proc.name,sim=proc.sim)
## the event
proc.sim.activate(proc._holder, proc._holder.trigger(a[0][1][2]))
elif actCode == queueevent:
raise FatalSimerror('Illegal code for reneging: queueevent')
else:
raise FatalSimerror('Illegal code for reneging %s'%actCode)
else:
## Simple yield request command
a[0][2]._request(a)
def releasefunc(a):
a[0][2]._release(a)
def passivatefunc(a):
a[0][1]._passivate(a)
def waitevfunc(a):
#if waiting for one event only (not a tuple or list)
evtpar = a[0][2]
if isinstance(evtpar, SimEvent):
a[0][2]._wait(a)
# else, if waiting for an OR of events (list / tuple):
else: #it should be a list / tuple of events
# call _waitOR for first event
evtpar[0]._waitOR(a)
def queueevfunc(a):
#if queueing for one event only (not a tuple or list)
evtpar = a[0][2]
if isinstance(evtpar, SimEvent):
a[0][2]._queue(a)
#else, if queueing for an OR of events (list / tuple):
else: #it should be a list / tuple of events
# call _queueOR for first event
evtpar[0]._queueOR(a)
def waituntilfunc(par):
par[0][1].sim._waitUntilFunc(par[0][1], par[0][2])
def getfunc(a):
"""Handles 'yield get, self, buffer, what, priority' and
'yield (get, self, buffer, what, priority),(,self, par)'.
can be 'hold' or 'waitevent'.
"""
if type(a[0][0]) == tuple:
## Compound yield request statement
## first tuple in ((request, self, res),(xx, self, yy))
b = a[0][0]
## b[2] == res (the resource requested)
##process the first part of the compound yield statement
##a[1] is the Process instance
b[2]._get(arg = (b, a[1]))
##deal with add - on condition to command
##Trigger processes for reneging
class _Holder(Process):
"""Provides timeout process"""
def __init__(self,**par):
Process.__init__(self,**par)
def trigger(self, delay):
yield hold, self, delay
#if not proc in b[2].activeQ:
if proc in b[2].getQ:
a[1].sim.reactivate(proc)
class _EventWait(Process):
"""Provides event waiting process"""
def __init__(self,**par):
Process.__init__(self,**par)
def trigger(self, event):
yield waitevent, self, event
if proc in b[2].getQ:
a[1].eventsFired = self.eventsFired
a[1].sim.reactivate(proc)
#activate it
proc = a[0][0][1] # the process to be woken up
actCode = a[0][1][0]
if actCode == hold:
proc._holder = _Holder(name='RENEGE - hold for %s'%proc.name,
sim=proc.sim)
## the timeout delay
a[1].sim.activate(proc._holder, proc._holder.trigger(a[0][1][2]))
elif actCode == waituntil:
raise FatalSimerror('waituntil: Illegal code for reneging: waituntil')
elif actCode == waitevent:
proc._holder = _EventWait(name="RENEGE - waitevent for%s"\
%proc.name,sim=proc.sim)
## the event
a[1].sim.activate(proc._holder, proc._holder.trigger(a[0][1][2]))
elif actCode == queueevent:
raise FatalSimerror('Illegal code for reneging: queueevent')
else:
raise FatalSimerror('Illegal code for reneging %s'%actCode)
else:
## Simple yield request command
a[0][2]._get(a)
def putfunc(a):
"""Handles 'yield put' (simple and compound hold / waitevent)
"""
if type(a[0][0]) == tuple:
## Compound yield request statement
## first tuple in ((request, self, res),(xx, self, yy))
b = a[0][0]
## b[2] == res (the resource requested)
##process the first part of the compound yield statement
##a[1] is the Process instance
b[2]._put(arg = (b, a[1]))
##deal with add - on condition to command
##Trigger processes for reneging
class _Holder(Process):
"""Provides timeout process"""
def __init__(self,**par):
Process.__init__(self,**par)
def trigger(self, delay):
yield hold, self, delay
#if not proc in b[2].activeQ:
if proc in b[2].putQ:
a[1].sim.reactivate(proc)
class _EventWait(Process):
"""Provides event waiting process"""
def __init__(self,**par):
Process.__init__(self,**par)
def trigger(self, event):
yield waitevent, self, event
if proc in b[2].putQ:
a[1].eventsFired = self.eventsFired
a[1].sim.reactivate(proc)
#activate it
proc = a[0][0][1] # the process to be woken up
actCode = a[0][1][0]
if actCode == hold:
proc._holder = _Holder(name='RENEGE - hold for %s'%proc.name,
sim=proc.sim)
## the timeout delay
a[1].sim.activate(proc._holder, proc._holder.trigger(a[0][1][2]))
elif actCode == waituntil:
raise FatalSimerror('Illegal code for reneging: waituntil')
elif actCode == waitevent:
proc._holder = _EventWait(name='RENEGE - waitevent for %s'\
%proc.name,sim=proc.sim)
## the event
a[1].sim.activate(proc._holder, proc._holder.trigger(a[0][1][2]))
elif actCode == queueevent:
raise FatalSimerror('Illegal code for reneging: queueevent')
else:
raise FatalSimerror('Illegal code for reneging %s'%actCode)
else:
## Simple yield request command
a[0][2]._put(a)
class Simulation(object):
_dispatch = {
hold: holdfunc, request: requestfunc, release: releasefunc,
passivate: passivatefunc, waitevent: waitevfunc,
queueevent: queueevfunc, waituntil: waituntilfunc, get: getfunc,
put: putfunc,
}
_commandcodes = list(_dispatch.keys())
_commandwords = {
hold: 'hold', request: 'request', release: 'release',
passivate: 'passivate', waitevent: 'waitevent',
queueevent: 'queueevent', waituntil: 'waituntil', get: 'get',
put: 'put'
}
def __init__(self):
self.initialize()
def initialize(self):
self._t = 0
self.next_time = 0
# Eventqueue stuff.
self._timestamps = []
self._sortpr = 0
self._start = False
self._stop = False
self.condQ = []
self.allMonitors = []
self.allTallies = []
def now(self):
return self._t
def stopSimulation(self):
"""Application function to stop simulation run"""
self._stop = True
def _post(self, what, at, prior = False):
"""Post an event notice for process what for time at"""
# event notices are Process instances
if at < self._t:
raise FatalSimerror('Attempt to schedule event in the past')
what._nextTime = at
self._sortpr -= 1
if prior:
# before all other event notices at this time
# heappush with highest priority value so far (negative of
# monotonely decreasing number)
# store event notice in process instance
what._rec = [at, self._sortpr, what, False]
# make event list refer to it
heappush(self._timestamps, what._rec)
else:
# heappush with lowest priority
# store event notice in process instance
what._rec = [at,-self._sortpr, what, False]
# make event list refer to it
heappush(self._timestamps, what._rec)
def _unpost(self, whom):
"""
Mark event notice for whom as cancelled if whom is a suspended process
"""
if whom._nextTime is not None: # check if whom was actually active
whom._rec[3] = True ## Mark as cancelled
whom._nextTime = None
def allEventNotices(self):
"""Returns string with eventlist as;
t1: processname, processname2
t2: processname4, processname5, . . .
. . . .
"""
ret = ''
tempList = []
tempList[:] = self._timestamps
tempList.sort()
# return only event notices which are not cancelled
tempList = [[x[0],x[2].name] for x in tempList if not x[3]]
tprev = -1
for t in tempList:
# if new time, new line
if t[0] == tprev:
# continue line
ret += ', %s'%t[1]
else:
# new time
if tprev == -1:
ret = '%s: %s' % (t[0],t[1])
else:
ret += '\n%s: %s' % (t[0],t[1])
tprev = t[0]
return ret + '\n'
def allEventTimes(self):
"""Returns list of all times for which events are scheduled.
"""
r = []
r[:] = self._timestamps
r.sort()
# return only event times of not cancelled event notices
r1 = [x[0] for x in r if not x[3]]
tprev = -1
ret = []
for t in r1:
if t == tprev:
#skip time, already in list
pass
else:
ret.append(t)
tprev = t
return ret
def activate(self, obj, process, at = 'undefined', delay = 'undefined',
prior = False):
"""Application function to activate passive process."""
if __debug__:
if not (obj.sim == self):
raise FatalSimerror('activate: Process %s not in activating '
'Simulation instance' % obj.name)
if not (type(process) == types.GeneratorType):
raise FatalSimerror('Activating function which'+
' is not a generator (contains no \'yield\')')
if not obj._terminated and not obj._nextTime:
#store generator reference in object; needed for reactivation
obj._nextpoint = process
if at == 'undefined':
at = self._t
if delay == 'undefined':
zeit = max(self._t, at)
else:
zeit = max(self._t, self._t + delay)
self._post(obj, at = zeit, prior = prior)
def reactivate(self, obj, at = 'undefined', delay = 'undefined',
prior = False):
"""Application function to reactivate a process which is active,
suspended or passive."""
# Object may be active, suspended or passive
if not obj._terminated:
a = Process('SimPysystem',sim=self)
a.cancel(obj)
# object now passive
if at == 'undefined':
at = self._t
if delay == 'undefined':
zeit = max(self._t, at)
else:
zeit = max(self._t, self._t + delay)
self._post(obj, at = zeit, prior = prior)
def startCollection(self, when = 0.0, monitors = None, tallies = None):
"""Starts data collection of all designated Monitor and Tally objects
(default = all) at time 'when'.
"""
class Starter(Process):
def collect(self, monitors, tallies):
for m in monitors:
m.reset()
for t in tallies:
t.reset()
yield hold, self
if monitors is None:
monitors = self.allMonitors
if tallies is None:
tallies = self.allTallies
if when == 0.0:
for m in monitors:
try:
ylast = m[-1][1]
empty = False
except IndexError:
empty = True
m.reset()
if not empty:
m.observe(t = now(), y = ylast)
for t in tallies:
t.reset()
else:
s = Starter(sim = self)
self.activate(s, s.collect(monitors = monitors, tallies = tallies),\
at = when, prior = True)
def _waitUntilFunc(self, proc, cond):
"""
Puts a process 'proc' waiting for a condition into a waiting queue.
'cond' is a predicate function which returns True if the condition is
satisfied.
"""
if not cond():
self.condQ.append(proc)
proc.cond = cond
# passivate calling process
proc._nextTime = None
else:
#schedule continuation of calling process
self._post(proc, at = self._t, prior = 1)
def _terminate(self, process):
"""Marks a process as terminated."""
process._nextpoint = None
process._terminated = True
process._nextTime = None
def has_events(self):
"""
Checks if there are events which can be processed. Returns ``True`` if
there are events and the simulation has not been stopped.
"""
return not self._stop and self._timestamps
def peek(self):
"""
Returns the time of the next event or infinity, if no
more events are scheduled.
"""
if not self._timestamps:
return infinity
else:
return self._timestamps[0][0]
def step(self):
"""
Executes the next uncancelled event in the eventqueue.
"""
# Fetch next process and advance its process execution method.
noActiveNotice = True
# Get an uncancelled event
while noActiveNotice:
if self._timestamps:
_tnotice, p, proc, cancelled = heappop(self._timestamps)
noActiveNotice = cancelled
else:
return None
# Advance simulation time.
proc._rec = None
self._t = _tnotice
# Execute the event. This will advance the process execution method.
try:
resultTuple = next(proc._nextpoint)
# Process the command function which has been yielded by the
# process.
if type(resultTuple[0]) == tuple:
# allowing for reneges, e.g.:
# >>> yield (request, self, res),(waituntil, self, cond)
command = resultTuple[0][0]
else:
command = resultTuple[0]
if __debug__:
if not command in self._commandcodes:
raise FatalSimerror('Illegal command: yield %s'%command)
self._dispatch[command]((resultTuple, proc))
except StopIteration:
# Process execution method has terminated.
self._terminate(proc)
# Test the conditions for all waiting processes if there are any at
# all. Where condition are satisfied, reactivate that process
# immediately and remove it from queue.
# Always test the wait conditions. They might be triggered by on a
# terminating process execution method (e.g. the above next() call
# raises the StopIteration exception)
if self.condQ:
i = 0
while i < len(self.condQ):
proc = self.condQ[i]
if proc.cond():
self.condQ.pop(i)
self.reactivate(proc)
else:
i += 1
# Return time of the next scheduled event.
#return self._timestamps[0][0] if self._timestamps else None
if self._timestamps:
return self._timestamps[0][0]
else:
return None
def simulate(self, until=0):
"""
Start the simulation and run its loop until the timeout ``until`` is
reached, stopSimulation is called, or no more events are scheduled.
"""
try:
if not self._timestamps:
return 'SimPy: No activities scheduled'
# Some speedups. Storing these values in local variables prevents
# the self-lookup. Note that this can't be done for _stop because
# this variable will get overwritten, bools are immutable.
step = self.step
timestamps = self._timestamps
while not self._stop and timestamps and timestamps[0][0] <= until:
step()
if not self._stop and timestamps:
# Timestamps left, simulation not stopped
self._t = until
return 'SimPy: Normal exit at time %s' % self._t
elif not timestamps:
# No more timestamps
return 'SimPy: No more events at time %s' % self._t
else:
# Stopped by call of stopSimulation
return 'SimPy: Run stopped at time %s' % self._t
# Delete the excepts?
except FatalSimerror as error:
raise FatalSimerror('SimPy: ' + error.value)
except Simerror as error:
return 'SimPy: ' + error.value
finally:
self._stop = True
# For backward compatibility
Globals.sim = Simulation()
peek = Globals.sim.peek
step = Globals.sim.step
allMonitors = Globals.sim.allMonitors
allTallies = Globals.sim.allTallies
# End backward compatibility
SimPy-2.3.1/SimPy/SimulationGUIDebug.py 0000644 0000765 0000024 00000011255 11650343144 020241 0 ustar stefan staff 0000000 0000000 import sys
from SimPy.SimulationStep import *
try: # Python 3
from tkinter import *
except:
from Tkinter import *
import SimPy.SimulationStep, GUIDebug
import warnings
warnings.warn('This module be removed in SimPy 3.', DeprecationWarning)
# global variables
_breakpoints = []
_until = 0
_callback = None
_lastCommandIssued = ""
_simStarted = False
_registeredClasses = []
_runMode = None
# run modes
STEP = 1
NO_STEP = 2
# register new object for windowing
def register(obj,hook=lambda :"",name=None):
global _registeredClasses
# if process subclass is given register it
if type(obj) == TypeType and issubclass(obj, Process):
_registeredClasses += [(obj,name,hook)]
# if instance of process is given register it
elif issubclass(type(obj), Process):
_guiCtrl.addNewProcess(obj,name,hook)
# if instance of Resource is given register it
elif issubclass(type(obj), Resource):
_guiCtrl.addNewResource(obj,name,hook)
# else create a generic window with hook
else:
_guiCtrl.addNewWindow(obj,name,hook)
# override activate to catch registered class instances
def activate(obj,process,at="undefined",delay="undefined",prior=False):
global _registeredClasses
SimPy.SimulationStep.activate(obj,process,at,delay,prior)
# if obj is instance of the class register it
for c,n,h in _registeredClasses:
if isinstance(obj, c):
_guiCtrl.addNewProcess(obj,n,h)
# add to breakpoints
def newBreakpoint(newBpt):
global _breakpoints
_breakpoints.append(newBpt)
_breakpoints.sort()
# set the current run mode of simulation
def setRunMode(runMode):
global _runMode
_runMode = runMode
# initialize the simulation and the GUI
def initialize():
SimPy.SimulationStep.initialize()
# create gui controller
global _guiCtrl
_guiCtrl = GUIDebug.GUIController()
# initialize run mode if not already set
global _runMode
if not _runMode:
_runMode = STEP
# simulation function
def simulate(callback=lambda :None, until=0):
global _runMode
# print usage
if( _runMode == STEP ):
print("Breakpoint Usage:")
print(" [c] Continue simulation")
print(" [s] Step to next event")
print(" [b #] Add new breakpoint")
print()
print(" [q] Quit debugger")
print()
# set global variables
global _until
_until = until
global _callback
_callback = callback
# initialize to step command
global _lastCommandIssued
_lastCommandIssued = "s"
# only prompt user if we are in STEP mode
if( _runMode == STEP): promptUser()
# quit if user entered 'q'
if( _lastCommandIssued == 'q'):
return
# begin simulation
global _simStarted
_simStarted = True
startStepping()
SimPy.SimulationStep.simulate(callback=callbackFunction,until=_until)
# check for breakpoints
def callbackFunction():
global _breakpoints,_runMode,_guiCtrl
# NO_STEP mode means we update windows and take no breaks
# this is used for compatibility with REAL debuggers
if( _runMode == NO_STEP ):
_guiCtrl.updateAllWindows()
return
if( 0 == len(_breakpoints) ):
return
# this is a breakpoint
if( now() >= _breakpoints[0] ):
# update gui
_guiCtrl.updateAllWindows()
# remove past times from breakpoints list
while( 0 != len(_breakpoints) and now() >= _breakpoints[0] ):
_breakpoints.pop(0)
# call user's callback function
global _callback
_callback()
promptUser()
# prompt user for next command
def promptUser():
global _simStarted
# set prompt text
prompt = '(SimDB) > '
# pause for breakpoint
while( 1 ):
if sys.version_info.major == 2:
input = raw_input
user_input = input( prompt )
# take a look at the last command issued
global _lastCommandIssued
if 0 == len(user_input):
user_input = _lastCommandIssued
_lastCommandIssued = user_input
# continue
if( "c" == user_input ):
break
# step
elif( "s" == user_input ):
global _breakpoints
_breakpoints.insert(0,0)
break
# add breakpoint
elif( 0 == user_input.find("b")):
try:
for i in eval( user_input[1:] + "," ):
newBreakpoint( int(i) )
except SyntaxError:
print("missing breakpoint values")
# quit
elif( "q" == user_input ):
SimPy.SimulationStep.stopSimulation()
return
else:
print(" unknown command")
SimPy-2.3.1/SimPy/SimulationRT.py 0000644 0000765 0000024 00000005005 11650344776 017203 0 ustar stefan staff 0000000 0000000 # coding=utf-8
"""
SimulationRT provides synchronization of real time and SimPy simulation time.
Implements SimPy Processes, resources, and the backbone simulation scheduling
by coroutine calls.
Based on generators.
"""
import time
from SimPy.Simulation import *
import SimPy
class SimulationRT(Simulation):
def __init__(self):
if sys.platform == 'win32': #take care of differences in clock accuracy
self.wallclock = time.clock
else:
self.wallclock = time.time
Simulation.__init__(self)
def rtnow(self):
return self.wallclock() - self.rtstart
def rtset(self, rel_speed=1):
"""
Resets the ratio simulation time over clock time(seconds).
"""
# Ensure relative speed is a float.
self.rel_speed = float(rel_speed)
def simulate(self, until=0, real_time=False, rel_speed=1):
"""
Simulates until simulation time reaches ``until``. If ``real_time`` is
``True`` a simulation time unit is matched with real time by the factor
1 / ``rel_speed``.
"""
try:
self.rtstart = self.wallclock()
self.rtset(rel_speed)
while self._timestamps and not self._stop:
next_event_time = self.peek()
if next_event_time > until: break
if real_time:
delay = (
next_event_time / self.rel_speed -
(self.wallclock() - self.rtstart)
)
if delay > 0: time.sleep(delay)
self.step()
# There are still events in the timestamps list and the simulation
# has not been manually stopped. This means we have reached the stop
# time.
if not self._stop and self._timestamps:
self._t = until
return 'SimPy: Normal exit'
else:
return 'SimPy: No activities scheduled'
except Simerror as error:
return 'SimPy: ' + error.value
finally:
self._stop = True
# For backward compatibility
Globals.sim = SimulationRT()
def rtnow():
return Globals.sim.rtnow()
rtset = Globals.sim.rtset
def simulate(until = 0, real_time = False, rel_speed = 1):
return Globals.sim.simulate(until = until, real_time = real_time, rel_speed = rel_speed)
wallclock = Globals.sim.wallclock
allMonitors = Globals.sim.allMonitors
allTallies = Globals.sim.allTallies
# End backward compatibility
SimPy-2.3.1/SimPy/SimulationStep.py 0000644 0000765 0000024 00000003007 11650345130 017552 0 ustar stefan staff 0000000 0000000 # coding=utf-8
"""
SimulationStep supports stepping through SimPy simulation event - by - event.
Based on generators.
"""
from SimPy.Simulation import *
_step = False
class SimulationStep(Simulation):
def __init__(self):
Simulation.__init__(self)
self._step = False
def initialize(self):
Simulation.initialize(self)
self._step = False
def startStepping(self):
"""Application function to start stepping through simulation."""
self._step = True
def stopStepping(self):
"""Application function to stop stepping through simulation."""
self._step = False
def step(self):
Simulation.step(self)
if self._step: self.callback()
def simulate(self, callback=lambda: None, until=0):
"""
Simulates until simulation time reaches ``until``. After processing each
event, ``callback`` will be invoked if stepping has been enabled with
:meth:`~SimPy.SimulationStep.startStepping`.
"""
self.callback = callback
return Simulation.simulate(self, until)
# For backward compatibility
Globals.sim = SimulationStep()
def startStepping():
Globals.sim.startStepping()
def stopStepping():
Globals.sim.stopStepping()
peek = Globals.sim.peek
step = Globals.sim.step
allMonitors = Globals.sim.allMonitors
allTallies = Globals.sim.allTallies
def simulate(callback = lambda :None, until = 0):
return Globals.sim.simulate(callback = callback, until = until)
# End backward compatibility
SimPy-2.3.1/SimPy/SimulationTrace.py 0000644 0000765 0000024 00000027325 11667110252 017711 0 ustar stefan staff 0000000 0000000 # coding=utf-8
"""
SimulationTrace 2.1 Traces execution of SimPy models.
Implements SimPy Processes, Resources, Buffers, and the backbone simulation
scheduling by coroutine calls. Provides data collection through classes
Monitor and Tally.
Based on generators.
"""
from __future__ import print_function
from SimPy.Lister import *
from SimPy.Simulation import *
def trace_dispatch(trace, command, func):
"""
Returns a wrapper for ``func`` which will record the dispatch in the trace
log.
"""
def dispatch(event):
func(event)
trace.recordEvent(command, event)
return dispatch
class SimulationTrace(Simulation):
def __init__(self):
Simulation.__init__(self)
self.trace = Trace(sim=self)
# Trace method to be called on _post calls.
self._post_tracing = None
# We use our own instance of the command dictionary.
self._dispatch = dict(Simulation._dispatch)
# Now wrap all commands in a tracing call.
for command, func in self._dispatch.items():
self._dispatch[command] = trace_dispatch(self.trace, command, func)
def initialize(self):
Simulation.initialize(self)
def _post(self, what, at, prior=False):
if self._post_tracing is not None: self._post_tracing(what, at, prior)
Simulation._post(self, what, at, prior)
def activate(
self, obj, process, at='undefined', delay='undefined', prior=False):
# Activate _post tracing.
self._post_tracing = self.trace.recordActivate
Simulation.activate(self, obj, process, at, delay, prior)
self._post_tracing = None
def reactivate(
self, obj, at='undefined', delay='undefined', prior=False):
# Activate _post tracing.
self._post_tracing = self.trace.recordReactivate
Simulation.reactivate(self, obj, at, delay, prior)
self._post_tracing = None
def _terminate(self, process):
self.trace.tterminated(process)
Simulation._terminate(self, process)
def simulate(self, until=0):
try:
return Simulation.simulate(self, until)
finally:
if not(self.trace.outfile is sys.stdout):
self.trace.outfile.close()
class Trace(Lister):
commands={hold:'hold', passivate:'passivate', request:'request', release:'release',
waitevent:'waitevent', queueevent:'queueevent', waituntil:'waituntil',
get:'get', put:'put'}
def __init__(self, start = 0, end = 10000000000, toTrace=\
['hold', 'activate', 'cancel', 'reactivate', 'passivate', 'request',
'release', 'interrupt', 'terminated', 'waitevent', 'queueevent',
'signal', 'waituntil', 'put', 'get'
],outfile = sys.stdout,sim=None):
Trace.commandsproc={hold:Trace.thold, passivate:Trace.tpassivate,
request:Trace.trequest, release:Trace.trelease,
waitevent:Trace.twaitevent,
queueevent:Trace.tqueueevent,
waituntil:Trace.twaituntil,
get:Trace.tget, put:Trace.tput}
if sim is None: sim=Globals.sim
self.sim=sim
self.start = start
self.end = end
self.toTrace = toTrace
self.tracego = True
self.outfile = outfile
self._comment = None
def treset(self):
Trace.commandsproc={hold:Trace.thold, passivate:Trace.tpassivate,
request:Trace.trequest, release:Trace.trelease,
waitevent:Trace.twaitevent,
queueevent:Trace.tqueueevent,
waituntil:Trace.twaituntil,
get:Trace.tget, put:Trace.tput}
self.start = 0
self.end = 10000000000
self.toTrace = ['hold', 'activate', 'cancel', 'reactivate', 'passivate', 'request',
'release', 'interrupt', 'terminated', 'waitevent', 'queueevent',
'signal', 'waituntil', 'put', 'get']
self.tracego = True
self.outfile = sys.stdout
self._comment = None
def tchange(self,**kmvar):
for v in kmvar:
if v == 'start':
self.start = kmvar[v]
elif v == 'end':
self.end = kmvar[v]
elif v == 'toTrace':
self.toTrace = kmvar[v]
elif v == 'outfile':
self.outfile = kmvar[v]
def tstart(self):
self.tracego = True
def tstop(self):
self.tracego = False
def ifTrace(self, cond):
if self.tracego and (self.start <= self.sim.now() <= self.end)\
and cond:
return True
def thold(self, par):
try:
return 'delay: %s' % par[0][2]
except:
return 'delay: 0'
thold = classmethod(thold)
def trequest(self, par):
res = par[0][2]
if len(par[0]) == 4:
priority = 'priority: ' + str(par[0][3])
else:
priority = 'priority: default'
wQ = [x.name for x in res.waitQ]
aQ = [x.name for x in res.activeQ]
return '<%s> %s\n. . .waitQ: %s\n. . .activeQ: %s' % (res.name, priority, wQ, aQ)
trequest = classmethod(trequest)
def trelease(self, par):
res = par[0][2]
wQ = [x.name for x in res.waitQ]
aQ = [x.name for x in res.activeQ]
return '<%s>\n. . .waitQ: %s\n. . .activeQ: %s' % (res.name, wQ, aQ)
trelease = classmethod(trelease)
def tpassivate(self, par):
return ""
tpassivate = classmethod(tpassivate)
def tactivate(self, par):
pass
tactivate = classmethod(tactivate)
def twaitevent(self, par):
evt = par[0][2]
if type(evt) == list or type(evt) == tuple:
enames = [x.name for x in evt]
return 'waits for events <%s> '%enames
else:
return 'waits for event <%s> '%evt.name
twaitevent = classmethod(twaitevent)
def tqueueevent(self, par):
evt = par[0][2]
if type(evt) == list or type(evt) == tuple:
enames = [x.name for x in evt]
return 'queues for events <%s> '%enames
else:
return 'queues for event <%s> '%evt.name
tqueueevent = classmethod(tqueueevent)
def tsignal(self, evt):
wQ = [x.name for x in evt.waits]
qQ = [x.name for x in evt.queues]
return '<%s> \n. . . occurred: %s\n. . . waiting: %s\n. . . queueing: %s'\
%(evt.name, evt.occurred, wQ, qQ)
pass
tsignal = classmethod(tsignal)
def twaituntil(self, par):
condition = par[0][2]
return 'for condition <%s> '%condition.__name__
twaituntil = classmethod(twaituntil)
def tget(self, par):
buff = par[0][2]
if len(par[0]) == 5:
priority = 'priority: ' + str(par[0][4])
else:
priority = 'priority: default'
if len(par[0]) == 3:
nrToGet = 1
else:
nrToGet = par[0][3]
toGet = 'to get: %s %s from' % (nrToGet, buff.unitName)
getQ = [x.name for x in buff.getQ]
putQ = [x.name for x in buff.putQ]
try:
inBuffer = buff.amount
except:
inBuffer = buff.nrBuffered
return '%s <%s> %s \n. . .getQ: %s \n. . .putQ: %s \n. . .in buffer: %s'\
%(toGet, buff.name, priority, getQ, putQ, inBuffer)
tget = classmethod(tget)
def tput(self, par):
buff = par[0][2]
if len(par[0]) == 5:
priority = 'priority: ' + str(par[0][4])
else:
priority = 'priority: default'
if len(par[0]) == 3:
nrToPut = 1
else:
if type(par[0][3]) == type([]):
nrToPut = len(par[0][3])
else:
nrToPut = par[0][3]
getQ = [x.name for x in buff.getQ]
putQ = [x.name for x in buff.putQ]
toPut = 'to put: %s %s into' % (nrToPut, buff.unitName)
try:
inBuffer = buff.amount
except:
inBuffer = buff.nrBuffered
return '%s <%s> %s \n. . .getQ: %s \n. . .putQ: %s \n. . .in buffer: %s'\
%(toPut, buff.name, priority, getQ, putQ, inBuffer)
tput = classmethod(tput)
def recordEvent(self, command, whole):
if self.ifTrace(Trace.commands[command] in self.toTrace):
if not type(whole[0][0]) == tuple:
print(whole[0][1].sim.now(),\
Trace.commands[command],\
'<' + whole[0][1].name + '>',\
Trace.commandsproc[command](whole), file=self.outfile)
if self._comment:
print('----', self._comment, file=self.outfile)
else:
print(whole[0][0][1].sim.now(),\
Trace.commands[command],\
'<' + whole[0][0][1].name + '>'+\
Trace.commandsproc[command](whole[0]), file=self.outfile)
print('|| RENEGE COMMAND:', file=self.outfile)
command1 = whole[0][1][0]
print('||\t', Trace.commands[command1],\
'<' + whole[0][1][1].name + '>',\
Trace.commandsproc[command1]((whole[0][1],)), file=self.outfile)
if self._comment:
print('----', self._comment, file=self.outfile)
self._comment = None
def recordInterrupt(self, who, victim):
if self.ifTrace('interrupt' in self.toTrace):
print('%s interrupt by: <%s> of: <%s>'\
%(who.sim.now(),who.name, victim.name), file=self.outfile)
if self._comment:
print('----', self._comment, file=self.outfile)
self._comment = None
def recordCancel(self, who, victim):
if self.ifTrace('cancel' in self.toTrace):
print('%s cancel by: <%s> of: <%s> '\
%(who.sim.now(),who.name, victim.name), file=self.outfile)
if self._comment:
print('----', self._comment, file=self.outfile)
self._comment = None
def recordActivate(self, who, when, prior):
if self.ifTrace('activate' in self.toTrace):
print('%s activate <%s> at time: %s prior: %s'\
%(who.sim.now(),who.name,when, prior), file=self.outfile)
if self._comment:
print('----', self._comment, file=self.outfile)
self._comment = None
def recordReactivate(self, who, when, prior):
if self.ifTrace('reactivate' in self.toTrace):
print('%s reactivate <%s> time: %s prior: %s'\
%(who.sim.now(),who.name,when, prior), file=self.outfile)
if self._comment:
print('----', self._comment, file=self.outfile)
self._comment = None
def recordSignal(self, evt):
if self.ifTrace('signal' in self.toTrace):
print('%s event <%s> is signalled' \
%(evt.sim.now(),evt.name), file=self.outfile)
if self._comment:
print('----', self._comment, file=self.outfile)
self._comment = None
def tterminated(self, who):
if self.ifTrace('terminated' in self.toTrace):
print('%s <%s> terminated'\
%(who.sim.now(),who.name), file=self.outfile)
if self._comment:
print('----', self._comment, file=self.outfile)
self._comment = None
def ttext(self, par):
self._comment = par
# For backward compatibility
Globals.sim = SimulationTrace()
trace = Globals.sim.trace
step = Globals.sim.step
peek = Globals.sim.peek
allMonitors = Globals.sim.allMonitors
allTallies = Globals.sim.allTallies
# End backward compatibility
SimPy-2.3.1/SimPy/__init__.py 0000644 0000765 0000024 00000002232 11710741444 016335 0 ustar stefan staff 0000000 0000000 # coding=utf-8
"""
SimPy, a process - based simulation package in Python
Contains the following modules:
Lib - module with all base classes of SimPy
Globals - module providing a global Simulation object
Simulation - module implementing processes and resources
Monitor - dummy module for backward compatibility
SimulationTrace - module implementing event tracing
SimulationRT - module for simulation speed control
SimulationStep - module for stepping through simulation event by event
SimPlot - Tk - based plotting module
SimGui - Tk - based SimPy GUI module
Lister - module for prettyprinting class instances
Lib - module containing SimPy entity classes (Process etc.)
Recording - module containing SimPy classes for recording results (Monitor,
Tally)
Globals - module providing global Simulation object and the global
simulation methods
stepping - a simple interactive debugger
"""
__version__ = '2.3.1'
def test():
import os.path
try:
import pytest
except ImportError:
print('You need pytest and mock to run the tests. '
'Try "pip install pytest mock".')
else:
pytest.main([os.path.dirname(__file__)])
SimPy-2.3.1/SimPy/stepping.py 0000644 0000765 0000024 00000003533 11650345562 016440 0 ustar stefan staff 0000000 0000000 # coding=utf-8
"""
This is a small utility for interactively stepping through a simulation.
Usage:
import stepping
(simulation model)
stepping.stepping(Globals) # instead of 'simulate(until = endtime)
"""
import sys
def stepping(glob):
asim = glob.sim
help = {'s':"next event",'r':"run to end",'e':"end run",
'