pydevs¶
This is the documentation of pydevs, a Python wrapper of adevs, a C++ library implementing the Discrete Event System Specification (DEVS).
- Release: 0.1.8
- Date: December 03, 2016
- Author: Andreas Sorge <as@asorge.de>
- Author of adevs: Jim Nutaro <nutarojj@ornl.gov>
- Documentation: http://pydevs.readthedocs.org
- Repository: http://github.com/andsor/pydevs
Contents¶
pydevs Quickstart¶
See Modeling and simulation with Adevs for a comprehensive introduction into modeling and simulation with adevs/pydevs.
Here we merely demonstrate how to set up a simple DEVS network model (adevs Digraph model) in Python.
import logging
import devs
logger = logging.getLogger('quickstart')
logger.setLevel(logging.DEBUG)
#logging.getLogger('devs').setLevel(logging.WARNING)
A Source – Processor – Observer model (M/M/1 Queue)¶
import collections
import random
class Source(devs.AtomicBase):
arrival_port = 0
def __init__(self, arrival_rate=1.0, **kwds):
super().__init__(**kwds)
self.logger = logging.getLogger('quickstart.Source')
self.logger.info('Initialize source with arrival rate {}'.format(arrival_rate))
self.arrival_rate = arrival_rate
self.inter_arrival_time = random.expovariate(self.arrival_rate)
self.job_id = 0
def ta(self):
self.logger.debug('Next arrival in {} time units'.format(self.inter_arrival_time))
return self.inter_arrival_time
def delta_int(self):
self.job_id += 1
self.inter_arrival_time = random.expovariate(self.arrival_rate)
def output_func(self):
self.logger.info('Generate job {}'.format(self.job_id))
return self.arrival_port, self.job_id
class Server(devs.AtomicBase):
arrival_port = 0
departure_port = 1
def __init__(self, service_rate=1.0, **kwds):
super().__init__(**kwds)
self.logger = logging.getLogger('quickstart.Server')
self.logger.info('Initialize server with service rate {}'.format(service_rate))
self.service_rate = service_rate
self.remaining_service_time = devs.infinity
self.queue = collections.deque()
self.job_in_service = None
def ta(self):
if self.job_in_service is None:
self.logger.debug('Server is idle')
return devs.infinity
return self.remaining_service_time
def start_next_job(self):
self.job_in_service = self.queue.popleft()
self.remaining_service_time = random.expovariate(self.service_rate)
self.logger.info('Start processing job {} with service time {}'.format(self.job_in_service, self.remaining_service_time))
def delta_int(self):
# service finished
self.logger.info('Finished processing job {}'.format(self.job_in_service))
if len(self.queue):
# jobs waiting, start to process immediately
self.start_next_job()
else:
# no more jobs, switch to idle
self.logger.info('Queue empty, server turns idle')
self.job_in_service = None
def delta_ext(self, e, xb):
if self.job_in_service is not None:
self.remaining_service_time -= e
# new job(s) arriving
for port, job_id in xb:
self.logger.info('New job {} arrives'.format(job_id))
self.queue.append(job_id)
if self.job_in_service is None:
# queue empty, start immediately
self.start_next_job()
else:
# server busy
self.logger.debug('Server busy, enqueueing job {}'.format(job_id))
self.logger.debug('Remaining service time for job {}: {} time units'.format(self.job_in_service, self.remaining_service_time))
def delta_conf(xb):
# treat incoming jobs first
self.delta_ext(self.ta(), xb)
self.delta_int()
def output_func(self):
# service finished
return self.departure_port, self.job_in_service
class Observer(devs.AtomicBase):
arrival_port = 0
departure_port = 1
def __init__(self, time=0.0, **kwds):
super().__init__(**kwds)
self.logger = logging.getLogger('quickstart.Observer')
self.logger.info('Initialize observer at time {}'.format(time))
self.time = time
self.arrivals = list()
self.departures = list()
def delta_ext(self, e, xb):
self.time += e
for port, job_id in xb:
if port == self.arrival_port:
self.logger.info('Job {} arrives at time {}'.format(job_id, self.time))
self.arrivals.append(self.time)
elif port == self.departure_port:
self.logger.info('Job {} departs at time {}'.format(job_id, self.time))
self.departures.append(self.time)
source = Source(1.0)
server = Server(1.0)
observer = Observer()
INFO:quickstart.Source:Initialize source with arrival rate 1.0
INFO:quickstart.Server:Initialize server with service rate 1.0
INFO:quickstart.Observer:Initialize observer at time 0.0
digraph = devs.Digraph()
digraph.add(source)
digraph.add(server)
digraph.add(observer)
digraph.couple(source, source.arrival_port, server, server.arrival_port)
digraph.couple(source, source.arrival_port, observer, observer.arrival_port)
digraph.couple(server, server.departure_port, observer, observer.departure_port)
simulator = devs.Simulator(digraph)
DEBUG:quickstart.Server:Server is idle
WARNING:devs.devs.AtomicBase:ta not implemented, return devs.infinity
-c:1: UserWarning: ta not implemented, return devs.infinity
DEBUG:quickstart.Source:Next arrival in 0.1652953524349517 time units
simulator.execute_until(5.0)
INFO:quickstart.Source:Generate job 0
INFO:quickstart.Server:New job 0 arrives
INFO:quickstart.Server:Start processing job 0 with service time 3.5509846975085804
DEBUG:quickstart.Server:Remaining service time for job 0: 3.5509846975085804 time units
INFO:quickstart.Observer:Job 0 arrives at time 0.1652953524349517
DEBUG:quickstart.Source:Next arrival in 1.0903431091204843 time units
WARNING:devs.devs.AtomicBase:ta not implemented, return devs.infinity
INFO:quickstart.Source:Generate job 1
INFO:quickstart.Server:New job 1 arrives
DEBUG:quickstart.Server:Server busy, enqueueing job 1
DEBUG:quickstart.Server:Remaining service time for job 0: 2.4606415883880963 time units
INFO:quickstart.Observer:Job 1 arrives at time 1.255638461555436
DEBUG:quickstart.Source:Next arrival in 2.3049818738267307 time units
WARNING:devs.devs.AtomicBase:ta not implemented, return devs.infinity
INFO:quickstart.Source:Generate job 2
INFO:quickstart.Server:New job 2 arrives
DEBUG:quickstart.Server:Server busy, enqueueing job 2
DEBUG:quickstart.Server:Remaining service time for job 0: 0.15565971456136563 time units
INFO:quickstart.Observer:Job 2 arrives at time 3.5606203353821666
DEBUG:quickstart.Source:Next arrival in 2.937090534560785 time units
WARNING:devs.devs.AtomicBase:ta not implemented, return devs.infinity
INFO:quickstart.Server:Finished processing job 0
INFO:quickstart.Server:Start processing job 1 with service time 0.9782561195217124
INFO:quickstart.Observer:Job 0 departs at time 3.7162800499435322
WARNING:devs.devs.AtomicBase:ta not implemented, return devs.infinity
INFO:quickstart.Server:Finished processing job 1
INFO:quickstart.Server:Start processing job 2 with service time 0.404069818122655
INFO:quickstart.Observer:Job 1 departs at time 4.694536169465245
WARNING:devs.devs.AtomicBase:ta not implemented, return devs.infinity
observer.arrivals, observer.departures
([0.1652953524349517, 1.255638461555436, 3.5606203353821666],
[3.7162800499435322, 4.694536169465245])
logger.setLevel(logging.ERROR)
logging.getLogger('devs').setLevel(logging.ERROR)
simulator.execute_until(100000.0)
len(observer.arrivals), len(observer.departures), len(server.queue)
(100015, 99697, 317)
License¶
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
devs¶
devs package¶
Submodules¶
devs.devs module¶
-
class
devs.devs.
AtomicBase
¶ Bases:
object
Python extension type, base type for DEVS Atomic Model
Python modules subclass this type and overwrite the methods
When initialized, the constructor (__init__) creates a new instance of the underlying C++ wrapper class Atomic (defined in the C++ header file). The C++ wrapper class Atomic inherits from adevs::Atomic and implements all the virtual functions. The C++ wrapper instance receives the function pointers to the cy_* helper functions defined here, as well as a pointer to the Python extension type instance. Whenever adevs calls one of the virtual functions of the C++ wrapper instance, the C++ wrapper instance routes it via the function pointer to the corresponding cy_* helper function. The cy_* helper function calls the corresponding method of the instance of the Python extension type.
http://stackoverflow.com/a/12700121/2366781 https://bitbucket.org/binet/cy-cxxfwk/src
When initialized, the constructor (__init__) creates a new instance of the underlying C++ wrapper class Atomic (defined in the C++ header file). Upon adding the model to a Digraph, the Digraph increases the reference count to this Python object, and decreases the reference count upon destruction. Note that the adevs C++ Digraph instance assumes ownership of the C++ wrapper instances. The C++ Digraph instance deletes all C++ wrapper instances upon destruction. So the Python object might still exist even though the C++ wrapper instance is long gone. When adevs deletes the C++ wrapper instance, the Python object is not deleted, when it is still referenced in the Python scope, but we can live with that.
The port type is integer. The value type is a generic Python object. This Python wrapper class abstracts away the underlying adevs C++ PortValue type.
adevs creates (copies) the C++ PortValue instance. https://github.com/smiz/adevs/blob/aae196ba660259ac32fc254bad810f4b4185d52f/include/adevs_digraph.h#L194 https://github.com/smiz/adevs/blob/aae196ba660259ac32fc254bad810f4b4185d52f/include/adevs_bag.h#L156
The only interface we need is to iterate over input (InputBag) in delta_ext and delta_conf, and to add output events (OutputBag) in output_func. Adding output events, the instance of this Python wrapper class increases the reference counter of the value Python object. The C++ wrapper class decreases the reference counter upon adevs’ call to the gc_output garbage collection function.
We deliberately break the adevs interface for the output_func method. In adevs, a reference to a Bag is supplied to the method returning void. Here, we choose the Pythonic way and take the return value of the method as the output bag. This is converted automatically by the cy_output_func helper function. output_func can either return
None (no output), a tuple (of length 2: port, value), or an iterable (of tuples of length 2: port, value).For example, output_func can be implemented as a generator expression.
Similarly, the cy_delta_ext and cy_delta_conf helper functions convert the input bag to a Python list of port, value tuples.
-
delta_conf
()¶
-
delta_ext
()¶
-
delta_int
()¶
-
output_func
()¶
-
ta
()¶
-
-
class
devs.devs.
Digraph
¶ Bases:
object
Python extension type that wraps the C++ wrapper class for the adevs Digraph class
For now, we only provide Atomic models. I.e. nested network models are not supported yet.
An instance of the C++ Digraph class takes ownership of added components, i.e. deletes the components at the end of its lifetime. This is why we increase the reference count to the Python object as soon as we add it to the Digraph. Upon deletion of the Digraph, the reference count is decreased. https://github.com/smiz/adevs/blob/aae196ba660259ac32fc254bad810f4b4185d52f/include/adevs_digraph.h#L205
-
add
()¶
-
couple
()¶
-
-
class
devs.devs.
IOBag
¶ Bases:
object
Python extension base type that wraps an existing C++ I/O bag
For constant bags, only the internal pointer _thisconstptr is used. For non-const bags, both internal pointers _thisconstptr and _thisptr are used.
-
empty
()¶
-
size
()¶
-
-
class
devs.devs.
InputBag
¶ Bases:
devs.devs.IOBag
Python extension type that wraps an existing C++ I/O bag
-
class
devs.devs.
OutputBag
¶ Bases:
devs.devs.IOBag
Python extension type that wraps an existing C++ I/O bag
To construct an instance in Cython, use the CreateOutputBag factory function.
When inserting port/values, increase the reference counter for Python objects.
-
insert
()¶
-
-
class
devs.devs.
Simulator
¶ Bases:
object
Python extension type that wraps the adevs C++ Simulator class
Note that the adevc C++ Simulator class does not assume ownership of the model. Hence, when using a Python wrapper Simulator instance, we need to keep the Python wrapper Digraph or AtomicBase-subclassed instance in scope as well. When the model Python instance goes out of scope, the internal C++ pointer gets deleted, rendering the Simulator defunct.
-
execute_next_event
()¶
-
execute_until
()¶
-
next_event_time
()¶
-
Module contents¶
Copyright 2014 The pydevs Developers
Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.