Package topo :: Package base :: Module simulation :: Class Simulation
[hide private]
[frames] | no frames]

Class Simulation

source code

                       object --+    
                                |    
param.parameterized.Parameterized --+
                                    |
                       object --+   |
                                |   |
                OptionalSingleton --+
                                    |
                                   Simulation

A simulation class that uses a simple sorted event list (instead of e.g. a sched.scheduler object) to manage events and dispatching.

Simulation is a singleton: there is only one instance of Simulation, no matter how many times it is instantiated.

Nested Classes [hide private]

Inherited from param.parameterized.Parameterized: __metaclass__

Instance Methods [hide private]
 
_cleanup(self) source code
 
_set_time(self, time=0)
Set this Simulation's _time to time, using the type specified by the time_type parameter.
source code
 
set_time_type(parameterized_instance, *args, **kw)
Convenience method to allow time_type to be changed easily.
source code
 
__init__(self, *args, **params)
Initialize a Simulation instance.
source code
 
__getitem__(self, item_name)
Return item_name if it exists as an EventProcessor in the Simulation.
source code
 
__setitem__(self, ep_name, ep)
Add ep to the simulation, setting its name to ep_name.
source code
 
__delitem__(self, ep_name)
Dictionary-style deletion of EPs from the simulation; see __delete_ep().
source code
 
__delete_ep(self, ep_name)
Remove the specified EventProcessor from the simulation, plus delete connections that come into it and connections that go from it.
source code
 
__iter__(self) source code
 
time(self)
Return the current simulation time as a FixedPoint object.
source code
 
timestr(self, specified_time=None)
Returns the specified time (or the current time, if none specified) formatted using time_printing_format, which allows users to control how much precision, etc.
source code
 
basename(self)
Return a string suitable for labeling an object created by the current simulation at the current time.
source code
 
run_and_time(self, duration=-1) source code
 
run(self, duration=-1, until=-1)
Process simulation events for the specified duration or until the specified time.
source code
 
sleep(self, delay)
Advance the simulator time by the specified amount.
source code
 
enqueue_event(self, event)
Enqueue an Event at an absolute simulation clock time.
source code
 
schedule_command(self, time, command_string)
Add a command to execute in __main__.__dict__ at the specified time.
source code
 
state_push(self)
Save a copy of the current state of the simulation for later restoration.
source code
 
state_pop(self)
Pop the most recently saved state off the stack.
source code
 
event_push(self)
Save a copy of the events queue for later restoration.
source code
 
event_pop(self)
Pop the most recently saved events queue off the stack.
source code
 
event_clear(self, event_type=<class 'topo.base.simulation.EPConnectionEvent'>)
Clear out all scheduled events of the specified type.
source code
 
connect(self, src, dest, connection_type=<class 'topo.base.simulation.EPConnection'>, **conn_params)
Connect the src EventProcessor to the dest EventProcessor.
source code
 
objects(self, baseclass=<class 'topo.base.simulation.EventProcessor'>)
Return a dictionary of simulation objects having the specified base class.
source code
 
connections(self)
Return a list of all unique connections to or from any object.
source code
 
script_repr(self, imports=[], prefix=' ')
Return a nearly runnable script recreating this simulation.
source code
 
grid_layout(self, objgrid, xstart=100, xstep=150, ystart=100, ystep=150, item_scale=1.0)
Set the layout_location of simulation objects in a grid pattern.
source code

Inherited from param.parameterized.Parameterized: __getstate__, __repr__, __setstate__, __str__, debug, defaults, force_new_dynamic_value, get_param_values, get_value_generator, inspect_value, message, print_param_values, set_dynamic_time_fn, verbose, warning

Inherited from OptionalSingleton: __copy__, __deepcopy__, __getnewargs__

Inherited from object: __delattr__, __getattribute__, __hash__, __reduce__, __reduce_ex__, __setattr__

Class Methods [hide private]

Inherited from param.parameterized.Parameterized: params, print_param_defaults

Static Methods [hide private]
 
__new__(cls, *args, **kw)
staticmethod(function) -> method
source code
Class Variables [hide private]
  time_type = param.Parameter(default= float, constant= True, do...
The numeric type to use for Simulation's time values.
  time_type_args = param.Parameter(default= (), constant= True, ...
Tuple of arguments to give to time_type whenever a new instance of the time_type is being created (e.g.
  register = param.Boolean(default= True, constant= True, doc= ...
Whether or not to register this Simulation.
  startup_commands = param.Parameter(instantiate= True, default=...
List of string commands that will be exec'd in __main__.__dict__ (i.e.
  time_printing_format = param.String("%(_time)09.2f", doc= ...
Format string to be used when the simulation time must be formatted as a string, e.g.
  basename_format = param.String("%(name)s_%(timestr)s", doc= ...
Format string to be used by the basename() function.
  eps_to_start = []
list() -> new list list(sequence) -> new list initialized from sequence's items
  name = param.Parameter(constant= False)
String identifier for this object.
  _inst = Simulation(basename_format='%(name)s_%(timestr)s', nam...
A simulation class that uses a simple sorted event list (instead of e.g.

Inherited from param.parameterized.Parameterized: print_level

Properties [hide private]

Inherited from object: __class__

Method Details [hide private]

__new__(cls, *args, **kw)
Static Method

source code 

staticmethod(function) -> method

Convert a function to be a static method.

A static method does not receive an implicit first argument. To declare a static method, use this idiom:

class C:
def f(arg1, arg2, ...): ... f = staticmethod(f)

It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()). The instance is ignored except for its class.

Static methods in Python are similar to those found in Java or C++. For a more advanced concept, see the classmethod builtin.

Overrides: object.__new__
(inherited documentation)

set_time_type(parameterized_instance, *args, **kw)

source code 
Convenience method to allow time_type to be changed easily.
Decorators:
  • @as_uninitialized

__init__(self, *args, **params)
(Constructor)

source code 
Initialize a Simulation instance.
Overrides: object.__init__

__getitem__(self, item_name)
(Indexing operator)

source code 
Return item_name if it exists as an EventProcessor in the Simulation. See objects().

__setitem__(self, ep_name, ep)
(Index assignment operator)

source code 

Add ep to the simulation, setting its name to ep_name. ep must be an EventProcessor.

If ep_name already exists in the simulation, ep overwrites the original object (as for a dictionary).

Note: EventProcessors do not necessarily have to be added to the simulation to be used, but otherwise they will not receive the start() message. Adding a node to the simulation also sets the backlink node.simulation, so that the node can enqueue events and read the simulation time.

__delitem__(self, ep_name)
(Index deletion operator)

source code 

Dictionary-style deletion of EPs from the simulation; see __delete_ep().

Deletes EP from simulation, plus connections that come into it and connections that go out of it.

__delete_ep(self, ep_name)

source code 

Remove the specified EventProcessor from the simulation, plus delete connections that come into it and connections that go from it.

(Used by 'del sim[ep_name]' (as for a dictionary) to delete an event processor from the simulation.)

time(self)

source code 

Return the current simulation time as a FixedPoint object.

If the time returned will be used in the computation of a floating point variable, it should be cast into a floating point number by float().

timestr(self, specified_time=None)

source code 
Returns the specified time (or the current time, if none specified) formatted using time_printing_format, which allows users to control how much precision, etc. is used for time displays.

basename(self)

source code 
Return a string suitable for labeling an object created by the current simulation at the current time. By default this is simply the name of the simulation + " " + the result from evaluating the time_printing_format parameter.

run(self, duration=-1, until=-1)

source code 

Process simulation events for the specified duration or until the specified time.

Arguments:

duration = length of simulation time to run. Default: run indefinitely while there are still events in the event_queue.

until = maximum simulation time to simulate. Default: run indefinitely while there are still events in the event queue.

If both duration and until are used, the one that is reached first will apply.

Note that duration and until should be specified in a format suitable for conversion (coercion?) into the Simulation's _time_type.

sleep(self, delay)

source code 
Advance the simulator time by the specified amount. By default simply increments the _time value, but subclasses can override this method as they wish, e.g. to wait for an external real time clock to advance first.

schedule_command(self, time, command_string)

source code 

Add a command to execute in __main__.__dict__ at the specified time.

The command should be a string.

state_push(self)

source code 

Save a copy of the current state of the simulation for later restoration.

The saved copy includes all the events on the simulator stack (saved using event_push()). Each EventProcessor is also asked to save its own state. This operation is useful for testing something while being able to roll back to the original state.

Overrides: param.parameterized.Parameterized.state_push

state_pop(self)

source code 

Pop the most recently saved state off the stack.

See state_push() for more details.

Overrides: param.parameterized.Parameterized.state_pop

event_push(self)

source code 

Save a copy of the events queue for later restoration.

Same as state_push(), but does not ask EventProcessors to save their state.

event_pop(self)

source code 

Pop the most recently saved events queue off the stack.

Same as state_pop(), but does not restore EventProcessors' state.

event_clear(self, event_type=<class 'topo.base.simulation.EPConnectionEvent'>)

source code 

Clear out all scheduled events of the specified type.

For instance, with event_type=EPConnectionEvent, this function can be used to ensure that no pending EPConnectionEvents will remain on the queue during some analysis or measurement operation. One will usually want to do a state_push before using this function, then clear out the events that should be deleted, do the measurement or analysis, and then do state_pop to restore the original state.

connect(self, src, dest, connection_type=<class 'topo.base.simulation.EPConnection'>, **conn_params)

source code 

Connect the src EventProcessor to the dest EventProcessor.

The src and dest should be string names of existing EPs. Returns the connection that was created. If the connection hasn't been given a name, it defaults to 'srcTodest'.

objects(self, baseclass=<class 'topo.base.simulation.EventProcessor'>)

source code 

Return a dictionary of simulation objects having the specified base class. All simulation objects have a base class of EventProcessor, and so the baseclass must be either EventProcessor or one of its subclasses.

If there is a simulator called s, you can type e.g. s.objects().keys() to see a list of the names of all objects.

script_repr(self, imports=[], prefix=' ')

source code 

Return a nearly runnable script recreating this simulation.

Needs some work to make the result truly runnable.

Only scheduled commands that have not yet been executed are included, because executed commands are not kept around.

Overrides: param.parameterized.Parameterized.script_repr

grid_layout(self, objgrid, xstart=100, xstep=150, ystart=100, ystep=150, item_scale=1.0)

source code 

Set the layout_location of simulation objects in a grid pattern.

Takes a list of lists of simulation objects, or names of simulation objects, and positions them with layout_locations left-to-right, top-to-bottom, starting at (xstart,ystart) and advancing by xstep and ystep.

The object None can be placed in the grid to skip a grid space.


Class Variable Details [hide private]

time_type


The numeric type to use for Simulation's time values.

Simulation's time type can be set to any numeric type that
supports the usual Python numeric operations, including at
least multiplication, addition, and subtraction.  Most of the
code assumes that fractional values are supported, as they are
for floats, but it may be possible to use an integer type
instead if various default fractional values are overridden.

For instance, one might wish to use arbitrary precision
floating-point time to avoid accumulating rounding errors.
For instance, if stepping through a simulation every 0.05 time
units, after 20 such steps using floats the simulation will
not reach 1.0 exactly, but will instead be slightly higher or
lower.  With an arbitrary precision float type such a series
of steps can be guaranteed to reach 1.0 exactly.
Alternatively, one might wish to use a rational type so that
events can be guaranteed to happen a certain number of times
in a given interval, even if the ratio cannot be expressed as
an even decimal or binary fraction.

Extra arguments can be passed to time_type when it is being used
to create the Simulation's time: see time_type_args.

Some potentially useful number classes::

- gmpy.mpq: gmpy provides Python with access to the fast GNU
  Multi-Precision library (which requires GMP to be built);
  gmpy.mpq is gmpy's rational type.

- fixedpoint.FixedPoint: pure Python fixed-point number, but
  quite slow.

- Python's Decimal class: in the standard library, but also quite
  slow.

Value:
param.Parameter(default= float, constant= True, doc= """
        The numeric type to use for Simulation's time values.
        
        Simulation's time type can be set to any numeric type that
        supports the usual Python numeric operations, including at
        least multiplication, addition, and subtraction.  Most of the
        code assumes that fractional values are supported, as they are
        for floats, but it may be possible to use an integer type
...

time_type_args

Tuple of arguments to give to time_type whenever a new instance of the time_type is being created (e.g. when a Simulation is created).
Value:
param.Parameter(default= (), constant= True, doc= """
        Tuple of arguments to give to time_type whenever a new
        instance of the time_type is being created (e.g. when a
        Simulation is created).""")

register

Whether or not to register this Simulation. If True, this Simulation (when created explicitly or when unpickled) will replace any existing registered Simulation (if one exists). Thus only one Simulation with register=True can exist at any one time, which makes it simpler to handle defining and reloading a series of simulations without polluting the memory space with unused simulations.
Value:
param.Boolean(default= True, constant= True, doc= """
        Whether or not to register this Simulation. If True, this
        Simulation (when created explicitly or when unpickled)
        will replace any existing registered Simulation (if one exists).
        Thus only one Simulation with register=True can exist at
        any one time, which makes it simpler to handle defining
        and reloading a series of simulations without polluting the
        memory space with unused simulations.""")

startup_commands

List of string commands that will be exec'd in __main__.__dict__ (i.e. as if they were entered at the command prompt) every time this simulation is unpickled (and will be executed before the simulation is itself unpickled).

For example, allows items to be imported before scheduled_commands are run.

Value:
param.Parameter(instantiate= True, default= [], doc= """
        List of string commands that will be exec'd in
        __main__.__dict__ (i.e. as if they were entered at the
        command prompt) every time this simulation is unpickled
        (and will be executed before the simulation is itself
        unpickled).

        For example, allows items to be imported before
...

time_printing_format

Format string to be used when the simulation time must be formatted as a string, e.g. for display or for basename(). When the string is evaluated, the time will be available as the attribute '_time'.
Value:
param.String("%(_time)09.2f", doc= """
        Format string to be used when the simulation time must be
        formatted as a string, e.g. for display or for basename().
        When the string is evaluated, the time will be available as
        the attribute '_time'.
        """)

basename_format

Format string to be used by the basename() function. When the string is evaluated, the formatted time from time_printing_format will be available as the attribute 'timestr'.
Value:
param.String("%(name)s_%(timestr)s", doc= """
        Format string to be used by the basename() function.
        When the string is evaluated, the formatted time from
        time_printing_format will be available as the attribute
        'timestr'.
        """)

_inst

A simulation class that uses a simple sorted event list (instead of e.g. a sched.scheduler object) to manage events and dispatching.

Simulation is a singleton: there is only one instance of Simulation, no matter how many times it is instantiated.

Value:
Simulation(basename_format='%(name)s_%(timestr)s', name=None, print_level=100, reg\
ister=True, startup_commands=[], time_printing_format='%(_time)09.2f', time_type=<\
built-in function mpq>, time_type_args=())