2.1. de_sim package

2.1.2. Submodules

2.1.3. de_sim._version module

2.1.4. de_sim.checkpoint module

Checkpointing log

Author

Jonathan Karr <karr@mssm.edu>

Author

Arthur Goldberg <Arthur.Goldberg@mssm.edu>

Date

2017-08-30

Copyright

2016-2018, Karr Lab

License

MIT

class de_sim.checkpoint.Checkpoint(time, state, random_state)[source]

Bases: object

Represents a simulation checkpoint

time[source]

the checkpoint’s simulated time, in simulation time units

Type

float

state[source]

the simulation application’s state at time time

Type

object

random_state[source]

the state of the simulator’s random number generator at time time

Type

object

__eq__(other)[source]

Compare two checkpoints

Assumes that state objects implement the equality comparison operation __eq__()

Parameters

other (checkpoint) – other checkpoint

Returns

true if checkpoints are semantically equal

Return type

bool

__ne__(other)[source]

Compare two checkpoints

Parameters

other (checkpoint) – other checkpoint

Returns

true if checkpoints are semantically unequal

Return type

bool

__str__()[source]

Provide a human readable representation of this Checkpoint

Returns

a human readable representation of this Checkpoint

Return type

str

static get_checkpoint(dirname, time=None)[source]

Get the latest checkpoint in directory dirname with time before or equal to time

For example, consider checkpoints at 1.0 s, 1.5 s, and 2.0 s. If time = 1.5 s, then return the checkpoint from 1.5 s. Return the same checkpoint if time = 1.9 s. If no checkpoint with time <= time exists, then return the first checkpoint. E.g., if time = 0.9 s, the checkpoint from 1.0 s would be returned. Finally, if time is None, return the last checkpoint.

Parameters
  • dirname (str) – directory to read/write checkpoint data

  • time (float, optional) – time in simulated time units of desired checkpoint; if not provided, the most recent checkpoint is returned

Returns

the most recent checkpoint before time time, or the most recent

checkpoint if time is not provided

Return type

Checkpoint

static get_file_name(dirname, time)[source]

Get file name for checkpoint at time time

Parameters
  • dirname (str) – directory to read/write checkpoint data

  • time (float) – time

Returns

file name for checkpoint at time time

Return type

str

static list_checkpoints(dirname, error_if_empty=True)[source]

Get sorted list of times of saved checkpoints in checkpoint directory dirname.

Parameters
  • dirname (str) – directory to read/write checkpoint data

  • error_if_empty (bool, optional) – if set, report an error if no checkpoints found

Returns

sorted list of times of saved checkpoints

Return type

list

Raises

SimulatorError – if dirname doesn’t contain any checkpoints

static set_checkpoint(dirname, checkpoint)[source]

Save a checkpoint to the directory dirname.

Parameters
  • dirname (str) – directory to read/write checkpoint data

  • checkpoint (Checkpoint) – checkpoint

2.1.5. de_sim.errors module

Author

Arthur Goldberg <Arthur.Goldberg@mssm.edu>

Date

2018-01-22

Copyright

2018, Karr Lab

License

MIT

exception de_sim.errors.Error(message=None)[source]

Bases: Exception

Base class for exceptions in de_sim

message[source]

the exception’s message

Type

str

exception de_sim.errors.SimulatorError(message=None)[source]

Bases: de_sim.errors.Error

Exception raised for errors in de_sim

message[source]

the exception’s message

Type

str

2.1.6. de_sim.event module

Simulation event structure

Author

Arthur Goldberg <Arthur.Goldberg@mssm.edu>

Date

2016-05-31

Copyright

2016-2018, Karr Lab

License

MIT

class de_sim.event.Event(creation_time, event_time, sending_object, receiving_object, message)[source]

Bases: object

An object that holds a discrete event simulation (DES) event

Each DES event is scheduled by creating an Event instance and storing it in the simulator’s event queue. To reduce interface errors the message attribute must be structured as specified in the message_types module.

As per David Jefferson’s thinking, the event queue is ordered by data provided by the simulation application, in particular (event time, sub-time), where ‘sub-time’ determines the execution priority among simultaneous messages with the same event time at different simulation objects. This is implemented by the comparison operators for Event below. This ordering achieves deterministic and reproducible simulations. (See Jefferson’s LLNL course.)

creation_time[source]

simulation time when the event is created (aka send_time)

Type

float

event_time[source]

simulation time when the event must be executed (aka receive_time)

Type

float

sending_object[source]

reference to the object that sends the event

Type

SimulationObject

receiving_object[source]

reference to the object that receives (aka executes) the event

Type

SimulationObject

_order_time[source]

the event time, sub-time that’s used to sort events; cached to improve performance

Type

tuple

message[source]

a SimulationMessage carried by the event; its type provides the simulation application’s type for an Event; it may also carry a payload for the Event in its attributes.

Type

SimulationMessage

BASE_HEADERS = ['t(send)', 't(event)', 'Sender', 'Receiver', 'Event type'][source]
__ge__(other)[source]

Does this Event occur later or at the same time as other?

Parameters

other (Event) – another Event

Returns

True if this Event occurs later or at the same time as other

Return type

bool

__gt__(other)[source]

Does this Event occur later than other?

Parameters

other (Event) – another Event

Returns

True if this Event occurs later than other

Return type

bool

__le__(other)[source]

Does this Event occur earlier or at the same time as other?

Parameters

other (Event) – another Event

Returns

True if this Event occurs earlier or at the same time as other

Return type

bool

__lt__(other)[source]

Does this Event occur earlier than other?

Parameters

other (Event) – another Event

Returns

True if this Event occurs earlier than other

Return type

bool

__str__()[source]

Return an Event as a string

Returns

String representation of the Event’s fields, except message,

delimited by tabs

Return type

str

creation_time[source]
custom_header(as_list=False, separator='\t')[source]

Return a header for an Event table containing messages of a particular type

Parameters
  • as_list (bool, optional) – if set, return the header fields in a list

  • separator (str, optional) – the field separator used if the header is returned as a string

Returns

String representation of names of an Event’s fields, or a list

representation if as_list is set

Return type

str

event_time[source]
static header(as_list=False, separator='\t')[source]

Return a header for an Event table

Provide generic header suitable for any type of message in an event.

Parameters
  • as_list (bool, optional) – if set, return the header fields in a list

  • separator (str, optional) – the field separator used if the header is returned as a string

Returns

String representation of names of an Event’s fields, or a list

representation if as_list is set

Return type

str

message[source]
receiving_object[source]
render(round_w_direction=False, annotated=False, as_list=False, separator='\t')[source]

Format the content of an Event

Rendering the content assumes that sending_object and receiving_object have name attributes.

Parameters
  • round_w_direction (bool, optional) – if set, round times to strings indicating the direction of the rounding

  • annotated (bool, optional) – if set, prefix each message field value with its attribute name

  • as_list (bool, optional) – if set, return the Event’s values in a list

  • separator (str, optional) – the field separator used if the values are returned as a string

Returns

String representation of the values of an Event’s fields, or a list

representation if as_list is set

Return type

str

sending_object[source]
de_sim.event.iterable_not_str(obj)[source]

Is an object an iterable, but not a string?

Parameters

obj (object) – an object

Returns

True if obj is an iterable, but not a string

Return type

bool

de_sim.event.nested_elements_to_str(o)[source]

Obtain str() values of all elements of o, recursively, while retaining the same structure

Parameters

o (obj) – an object

Returns

stringified instance of o

Return type

obj

2.1.7. de_sim.shared_state_interface module

An interface that all shared state objects must support

Author

Arthur Goldberg <Arthur.Goldberg@mssm.edu>

Date

2018-02-15

Copyright

2018, Karr Lab

License

MIT

class de_sim.shared_state_interface.SharedStateInterface[source]

Bases: object

An ABC all shared state objects must support so they can participate in logs and checkpoints

abstract get_name()[source]

Get the shared state objects’s name

Returns

the name of a shared state object

Return type

str

abstract get_shared_state(time)[source]

Get the shared state objects’s state

Parameters

time (float) – the simulation time of the state to be returned

Returns

the state of a shared state object, in a human-readable string

Return type

str

2.1.8. de_sim.simulation_checkpoint_object module

A simulation object that produces periodic checkpoints

Author

Arthur Goldberg <Arthur.Goldberg@mssm.edu>

Date

2018-05-03

Copyright

2018, Karr Lab

License

MIT

class de_sim.simulation_checkpoint_object.AbstractCheckpointSimulationObject(name, period)[source]

Bases: de_sim.template_sim_objs.TemplatePeriodicSimulationObject

Abstract class that creates periodic checkpoints

period[source]

interval between checkpoints in simulated time units

Type

float

create_checkpoint()[source]

Create a checkpoint

Derived classes must override this method and actually create a checkpoint

handle_event()[source]

Handle the periodic event

Derived classes must override this method and actually handle the event

metadata = <de_sim.simulation_object.ApplicationSimulationObjectMetadata object>[source]
class de_sim.simulation_checkpoint_object.AccessStateObjectInterface[source]

Bases: object

An abstract base class that all access state objects must support

abstract get_checkpoint_state(time)[source]

Obtain a checkpoint of the simulation application’s state at time time

Returns

a checkpoint of the simulation application’s state

Return type

object

abstract get_random_state()[source]

Obtain a checkpoint of the state of the simulation’s random number generator(s)

Returns

the state of the simulation’s random number generator(s)

Return type

object

class de_sim.simulation_checkpoint_object.CheckpointSimulationObject(name, checkpoint_period, checkpoint_dir, access_state_obj)[source]

Bases: de_sim.simulation_checkpoint_object.AbstractCheckpointSimulationObject

Create periodic checkpoints to files

checkpoint_dir[source]

the directory in which to save checkpoints

Type

str

access_state_obj[source]

an object whose get_checkpoint_state(time) returns the simulation’s state at time time; access_state_obj objects should be derived from AccessStateObjectInterface

Type

AccessStateObjectInterface

create_checkpoint()[source]

Create a checkpoint in the directory self.checkpoint_dir

metadata = <de_sim.simulation_object.ApplicationSimulationObjectMetadata object>[source]

2.1.9. de_sim.simulation_config module

Simulation configuration

Author

Arthur Goldberg <Arthur.Goldberg@mssm.edu>

Author

Jonathan Karr <karr@mssm.edu>

Date

2020-03-16

Copyright

2020, Karr Lab

License

MIT

class de_sim.simulation_config.SimulationConfig(time_max: float, time_init: float = 0.0, stop_condition: object = None, progress: bool = False, output_dir: str = None)[source]

Bases: wc_utils.util.misc.EnhancedDataClass

Configuration information for a simulation run

  • Simulation start time

  • Simulation maximum time

  • Stop condition

  • Progress bar switch

  • Data directory

time_max[source]

maximum simulation time

Type

float

time_init[source]

time at which a simulation starts

Type

float, optional

stop_condition[source]

if provided, a function that takes one argument, the simulation time; a simulation terminates if the function returns True

Type

function, optional

progress[source]

if True, output a bar that dynamically reports the simulation’s progress

Type

bool, optional

output_dir[source]

directory for saving metadata; will be created if it does’t exist; if not provided, then metatdata should be saved before another simulation is run with the same SimulationEngine

Type

str, optional

DO_NOT_PICKLE = ['stop_condition'][source]
__setattr__(name, value)[source]

Validate an attribute when it is changed

output_dir = None[source]
progress = False[source]
stop_condition = None[source]
time_init = 0.0[source]
validate()[source]

Validate a SimulationConfig instance

Validation tests that involve multiple fields must be made in this method. Call it after the SimulationConfig instance is in a consistent state.

Returns

if no error is found

Return type

None

Raises

SimulatorError – if self fails validation

validate_individual_fields()[source]

Validate constraints other than types in individual fields in a SimulationConfig instance

Returns

if no error is found

Return type

None

Raises

SimulatorError – if an attribute of self fails validation

2.1.10. de_sim.simulation_engine module

Discrete event simulation engine

Author

Arthur Goldberg <Arthur.Goldberg@mssm.edu>

Date

2016-06-01

Copyright

2016-2018, Karr Lab

License

MIT

class de_sim.simulation_engine.SimulationEngine(shared_state=None)[source]

Bases: object

A simulation engine

General-purpose simulation mechanisms, including the simulation scheduler. Architected as an OO simulation that could be parallelized.

SimulationEngine contains and manipulates global simulation data. SimulationEngine registers all simulation objects types and all simulation objects. Following simulate() it runs the simulation, scheduling objects to execute events in non-decreasing time order; and generates debugging output.

time[source]

the simulations’s current time

Type

float

simulation_objects[source]

all simulation objects, keyed by name

Type

dict of SimulationObject

shared_state[source]

the shared state of the simulation, needed to log or checkpoint the entire state of a simulation; all objects in shared_state must implement SharedStateInterface

Type

list of object, optional

debug_logs[source]

the debug logs

Type

wc_utils.debug_logs.core.DebugLogsManager

fast_debug_file_logger[source]

a fast logger for debugging messages

Type

FastLogger

fast_plotting_logger[source]

a fast logger for trajectory data for plotting

Type

FastLogger

event_queue[source]

the queue of future events

Type

EventQueue

event_counts[source]

a counter of event types

Type

Counter

sim_config[source]

a simulation run’s configuration

Type

SimulationConfig

sim_metadata[source]

a simulation run’s metadata

Type

SimulationMetadata

author_metadata[source]

information about the person who runs the simulation, if provided by the simulation application

Type

AuthorMetadata

END_TIME_EXCEEDED = ' End time exceeded'[source]
NO_EVENTS_REMAIN = ' No events remain'[source]
TERMINATE_WITH_STOP_CONDITION_SATISFIED = ' Terminate with stop condition satisfied'[source]
add_object(simulation_object)[source]

Add a simulation object instance to this simulation

Parameters

simulation_object (SimulationObject) – a simulation object instance that will be used by this simulation

Raises

SimulatorError – if the simulation object’s name is already in use

add_objects(simulation_objects)[source]

Add many simulation objects into the simulation

Parameters

simulation_objects (iterator of SimulationObject) – an iterator of simulation objects

delete_object(simulation_object)[source]

Delete a simulation object instance from this simulation

Parameters

simulation_object (SimulationObject) – a simulation object instance that is part of this simulation

Raises

SimulatorError – if the simulation object is not part of this simulation

finish_metadata_collection()[source]

Finish metatdata collection

get_object(simulation_object_name)[source]

Get a simulation object instance

Parameters

simulation_object_name (str) – get a simulation object instance that is part of this simulation

Raises

SimulatorError – if the simulation object is not part of this simulation

get_objects()[source]

Get all simulation object instances in the simulation

get_simulation_state()[source]

Get the simulation’s state

init_metadata_collection(sim_config)[source]

Initialize a simulation metatdata object

Call just before a simulation starts, so that correct clock time of start is recorded

Parameters

sim_config (SimulationConfig) – information about the simulation’s configuration (start time, maximum time, etc.)

initialize()[source]

Initialize a simulation

Call send_initial_events() in each simulation object that has been loaded.

Raises

SimulatorError – if the simulation has already been initialized

log_with_time(msg)[source]

Write a debug log message with the simulation time.

message_queues()[source]

Return a string listing all message queues in the simulation

Returns

a list of all message queues in the simulation and their messages

Return type

str

provide_event_counts()[source]

Provide the simulation’s categorized event counts

Returns

the simulation’s categorized event counts, in a tab-separated table

Return type

str

reset()[source]

Reset this SimulationEngine

Delete all objects and reset any prior initialization.

run(time_max=None, sim_config=None, config_dict=None, author_metadata=None)[source]

Alias for simulate

simulate(time_max=None, sim_config=None, config_dict=None, author_metadata=None)[source]

Run a simulation

See _get_sim_config for constraints on arguments

Parameters
  • time_max (float, optional) – the time of the end of the simulation

  • sim_config (SimulationConfig, optional) – the simulation run’s configuration

  • config_dict (dict, optional) – a dictionary with keys chosen from the field names in SimulationConfig

  • author_metadata (AuthorMetadata, optional) – information about the person who runs the simulation

Returns

the number of times a simulation object executes _handle_event(). This may

be smaller than the number of events sent, because simultaneous events at one simulation object are handled together.

Return type

int

Raises

SimulatorError – if the simulation has not been initialized, or has no objects, or has no initial events, or attempts to execute an event that violates non-decreasing time order

2.1.11. de_sim.simulation_message module

Base class for simulation messages

Author

Arthur Goldberg <Arthur.Goldberg@mssm.edu>

Date

2017-03-26

Copyright

2016-2018, Karr Lab

License

MIT

class de_sim.simulation_message.CombinedSimulationMessageMeta(*args, **kwargs)[source]

Bases: de_sim.utilities.ConcreteABCMeta, de_sim.simulation_message.SimulationMessageMeta

class de_sim.simulation_message.SimulationMessage(*args)[source]

Bases: de_sim.simulation_message.SimulationMessageInterface

The simulation message base class

Each simulation event contains a simulation message. All simulation messages are objects. This module supports compact declaration of SimulationMessage types. For example:

class ExampleSimulationMessage1(SimulationMessage):

‘ My docstring ‘ attributes = [‘attr1’, ‘attr2’]

defines the ExampleSimulationMessage1 class with a short docstring and two attributes.

SimulationMessage subclasses must support the comparison operations <, <=, etc. This is provided automatically for attributes that support comparison. Subclasses with message attributes that do not support comparison must override __lt__, __le__, etc.

class de_sim.simulation_message.SimulationMessageInterface(*args)[source]

Bases: object

An abstract base class for simulation messages

The comparison operations (__gt__, __lt__, etc.) order simulation message instances by the tuple (class name, instance attribute values). This enables deterministic sorting of messages by their content, so that simulation messages can be passed in a deterministic order to a simulation object processing them in an event.

__slots__[source]

use __slots__ to save memory because a simulation may contain many messages

Type

list

__ge__(other)[source]

Does this SimulationMessage sort after or equal other?

Parameters

other (SimulationMessage) – another SimulationMessage

Returns

True if this SimulationMessage sorts after or equals other

Return type

bool

__gt__(other)[source]

Does this SimulationMessage sort after other?

Parameters

other (SimulationMessage) – another SimulationMessage

Returns

True if this SimulationMessage sorts after other

Return type

bool

__le__(other)[source]

Does this SimulationMessage sort before or equal other?

Parameters

other (SimulationMessage) – another SimulationMessage

Returns

True if this SimulationMessage sorts before or equals other

Return type

bool

__lt__(other)[source]

Does this SimulationMessage sort before other?

Parameters

other (SimulationMessage) – another SimulationMessage

Returns

True if this SimulationMessage sorts before other

Return type

bool

__str__()[source]

Provide a string representation of a SimulationMessage

attrs()[source]

Provide a list of the attributes names for this SimulationMessage

Returns

the attributes in this SimulationMessage

Return type

list of str

header(as_list=False, separator='\t')[source]

Provide the attribute names for this SimulationMessage

Parameters
  • as_list (bool, optional) – if set, return the attribute names in a list

  • separator (str, optional) – the field separator used if the attribute names are returned as a string

Returns

None if this message has no attributes, or a string representation of

the attribute names for this SimulationMessage, or a list representation if as_list is set

Return type

obj

value_map()[source]

Provide a map from attribute to value, cast to strings, for this SimulationMessage

Uninitialized values are returned as str(None).

Returns

map attribute -> str(attribute value)

Return type

dict

values(annotated=False, as_list=False, separator='\t')[source]

Provide the values in this SimulationMessage

Uninitialized values are returned as str(None).

Parameters
  • annotated (bool, optional) – if set, prefix each value with its attribute name

  • as_list (bool, optional) – if set, return the attribute names in a list

  • separator (str, optional) – the field separator used if the attribute names are returned as a string

Returns

None if this message has no attributes, or a string representation of

the attribute names for this SimulationMessage, or a list representation if as_list is set

Return type

obj

class de_sim.simulation_message.SimulationMessageMeta(*args, **kwargs)[source]

Bases: type

ATTRIBUTES = 'attributes'[source]

2.1.12. de_sim.simulation_metadata module

Classes to represent the metadata of a simulation run

Author

Arthur Goldberg <Arthur.Goldberg@mssm.edu>

Author

Jonathan Karr <karr@mssm.edu>

Date

2017-08-18

Copyright

2016-2018, Karr Lab

License

MIT

class de_sim.simulation_metadata.AuthorMetadata(name: str = None, email: str = None, username: str = None, organization: str = None)[source]

Bases: wc_utils.util.misc.EnhancedDataClass

Represents a simulation’s author

name[source]

authors’ name

Type

str

email[source]

author’s email address

Type

str

username[source]

authors’ username

Type

str

organization[source]

author’s organization

Type

str

__setattr__(name, value)[source]

Validate an attribute when it is changed

email = None[source]
name = None[source]
organization = None[source]
username = None[source]
class de_sim.simulation_metadata.RunMetadata(ip_address: str = None, start_time: datetime.datetime = None, run_time: float = None)[source]

Bases: wc_utils.util.misc.EnhancedDataClass

Represent a simulation’s run

ip_address[source]

ip address of the machine that ran the simulation

Type

str

start_time[source]

simulation clock start time

Type

datetime

run_time[source]

simulation run time in seconds

Type

float

__setattr__(name, value)[source]

Validate an attribute when it is changed

ip_address = None[source]
record_ip_address()[source]
record_run_time()[source]
record_start()[source]
run_time = None[source]
start_time = None[source]
class de_sim.simulation_metadata.SimulationMetadata(simulation_config: de_sim.simulation_config.SimulationConfig, run: de_sim.simulation_metadata.RunMetadata, author: de_sim.simulation_metadata.AuthorMetadata, simulator_repo: wc_utils.util.git.RepositoryMetadata = None)[source]

Bases: wc_utils.util.misc.EnhancedDataClass

Represents the metadata of a discrete event simulation run

simulation_config[source]

information about the simulation’s configuration (e.g. start time, maximum time)

Type

SimulationConfig

run[source]

information about the simulation’s run (e.g. start time, duration)

Type

RunMetadata

author[source]

information about the person who ran the simulation (e.g. name, email)

Type

AuthorMetadata

simulator[source]

metadata about this simulator’s git repository

Type

RepositoryMetadata

__setattr__(name, value)[source]

Validate an attribute when it is changed

static get_pathname(dirname)[source]

See docstring in EnhancedDataClass

simulator_repo = None[source]

2.1.13. de_sim.simulation_object module

Base class for simulation objects and their event queues

Author

Arthur Goldberg <Arthur.Goldberg@mssm.edu>

Date

2016-06-01

Copyright

2016-2018, Karr Lab

License

MIT

class de_sim.simulation_object.AppSimObjAndABCMeta(*args, **kwargs)[source]

Bases: de_sim.simulation_object.ApplicationSimulationObjMeta, de_sim.utilities.ConcreteABCMeta

A concrete class based on two Meta classes to be used as a metaclass for classes derived from both

class de_sim.simulation_object.ApplicationSimulationObjMeta[source]

Bases: type

CLASS_PRIORITY = 'class_priority'[source]
EVENT_HANDLERS = 'event_handlers'[source]
MESSAGES_SENT = 'messages_sent'[source]
static __new__(cls, clsname, superclasses, namespace)[source]
Parameters
  • cls (class) – this class

  • clsname (str) – name of the SimulationObject subclass being created

  • superclasses (tuple) – tuple of superclasses

  • namespace (dict) – namespace of subclass of ApplicationSimulationObject being created

Returns

a new instance of a subclass of SimulationObject

Return type

SimulationObject

Raises

SimulatorError – if class priority is not an int, or if the ApplicationSimulationObject doesn’t define messages_sent or event_handlers, or if handlers in event_handlers don’t refer to methods in the ApplicationSimulationObject, or if event_handlers isn’t an iterator over pairs, or if a message type sent isn’t a subclass of SimulationMessage, or if messages_sent isn’t an iterator over pairs.

class de_sim.simulation_object.ApplicationSimulationObject(name, start_time=0, **kwargs)[source]

Bases: de_sim.simulation_object.SimulationObject, de_sim.simulation_object.ApplicationSimulationObjectInterface

Base class for all simulation objects in a simulation

metadata[source]

metadata for event message sending and handling, initialized by AppSimObjAndABCMeta

Type

ApplicationSimulationObjectMetadata

get_state()[source]
send_initial_events(*args)[source]
classmethod set_class_priority(priority)[source]

Set the execution priority for simulation object classes, class_priority

Use this to set the class_priority of a subclass of SimulationObject after it

has been constructed.

Parameters

priority (SimObjClassPriority) – the desired class_priority for a subclass of SimulationObject

class de_sim.simulation_object.ApplicationSimulationObjectInterface[source]

Bases: object

abstract get_state()[source]
abstract send_initial_events(*args)[source]
class de_sim.simulation_object.ApplicationSimulationObjectMetadata[source]

Bases: object

Metadata for an ApplicationSimulationObject

event_handlers_dict[source]

maps message_type -> event_handler; provides the event handler for each message type for a subclass of SimulationObject

Type

dict

event_handler_priorities[source]

maps message_type -> message_type priority; the highest priority is 0, and priority decreases with increasing priority values.

Type

dict

message_types_sent[source]

the types of messages a subclass of SimulationObject has registered to send

Type

set

class de_sim.simulation_object.EventQueue[source]

Bases: object

A simulation’s event queue

Stores a SimulationEngine’s events in a heap (also known as a priority queue). The heap is a ‘min heap’, which keeps the event with the smallest (event_time, sending_object.name) at the root in heap[0]. This is implemented via comparison operations in Event. Thus, all entries with equal (event_time, sending_object.name) will be popped from the heap adjacently. schedule_event() costs O(log(n)), where n is the size of the heap, while next_events(), which returns all events with the minimum (event_time, sending_object.name), costs O(mlog(n)), where m is the number of events returned.

event_heap[source]

a SimulationEngine’s heap of events

Type

list

debug_logs[source]

a DebugLogsManager

Type

wc_utils.debug_logs.core.DebugLogsManager

__str__()[source]

Return event queue members as a table

empty()[source]

Is the event queue empty?

Returns

return True if the event queue is empty

Return type

bool

log_event(event)[source]

Log an event with its simulation time

Parameters

event (Event) – the Event to log

next_event_obj()[source]

Get the simulation object that receives the next event

Returns

the simulation object that will execute the next event, or None

if no event is scheduled

Return type

SimulationObject)

next_event_time()[source]

Get the time of the next event

Returns

the time of the next event; return infinity if no event is scheduled

Return type

float

next_events()[source]

Get all events at the smallest event time destined for the object whose name sorts earliest

Because multiple events may occur concurrently – that is, have the same simulation time – they must be provided as a collection to the simulation object that executes them.

Handle ‘ties’ properly. That is, since an object may receive multiple events with the same event_time (aka receive_time), pass them all to the object in a list.

Returns

the earliest event(s), sorted by message type priority. If no

events are available the list is empty.

Return type

list of Event

render(sim_obj=None, as_list=False, separator='\t')[source]

Return the content of an EventQueue

Make a human-readable event queue, sorted by non-decreasing event time. Provide a header row and a row for each event. If all events have the same type of message, the header contains event and message fields. Otherwise, the header has event fields and a message field label, and each event labels message fields with their attribute names.

Parameters
  • sim_obj (SimulationObject, optional) – if provided, return only events to be received by sim_obj

  • as_list (bool, optional) – if set, return the EventQueue’s values in a list

  • separator (str, optional) – the field separator used if the values are returned as a string

Returns

String representation of the values of an EventQueue, or a list

representation if as_list is set

Return type

str

reset()[source]
schedule_event(send_time, receive_time, sending_object, receiving_object, message)[source]

Create an event and insert in this event queue, scheduled to execute at receive_time

Simulation object X can sends an event to simulation object Y by invoking

X.send_event(receive_delay, Y, message).

Parameters
  • send_time (float) – the simulation time at which the event was generated (sent)

  • receive_time (float) – the simulation time at which the receiving_object will execute the event

  • sending_object (SimulationObject) – the object sending the event

  • receiving_object (SimulationObject) – the object that will receive the event; when the simulation is parallelized sending_object and receiving_object will need to be global identifiers.

  • message (SimulationMessage) – a SimulationMessage carried by the event; its type provides the simulation application’s type for an Event; it may also carry a payload for the Event in its attributes.

Raises

SimulatorError – if receive_time < send_time, or receive_time or send_time is NaN

class de_sim.simulation_object.SimObjClassPriority[source]

Bases: enum.IntEnum

Simultaneous execution priority for simulation object classes, used in class_priority

EIGHTH = 8[source]
FIFTH = 5[source]
FIRST = 1[source]
FOURTH = 4[source]
HIGH = 1[source]
LOW = 9[source]
MEDIUM = 5[source]
NINTH = 9[source]
SECOND = 2[source]
SEVENTH = 7[source]
SIXTH = 6[source]
THIRD = 3[source]
assign_decreasing_priority = <bound method SimObjClassPriority.assign_decreasing_priority of <enum 'SimObjClassPriority'>>[source]
class de_sim.simulation_object.SimulationObject(name, start_time=0, **kwargs)[source]

Bases: object

Base class for simulation objects.

SimulationObject is a base class for all simulations objects. It provides basic functionality: the object’s name (which must be unique), its simulation time, a queue of received events, and a send_event() method.

name[source]

this simulation object’s name, which is unique across all simulation objects handled by a SimulationEngine

Type

str

time[source]

this simulation object’s current simulation time

Type

float

event_time_tiebreaker[source]

the least significant component of an object’s ‘sub-tme’ priority, which orders simultaneous events received by different instances of the same ApplicationSimulationObject

Type

str

num_events[source]

number of events processed

Type

int

simulator[source]

the SimulationEngine that uses this SimulationObject

Type

int

debug_logs[source]

the debug logs

Type

wc_utils.debug_logs.core.DebugLogsManager

LOG_EVENTS = False[source]
add(simulator)[source]

Add this object to a simulation.

Parameters

simulator (SimulationEngine) – the simulator that will use this SimulationObject

Raises

SimulatorError – if this SimulationObject is already registered with a simulator

property class_event_priority[source]

Get the event priority of this simulation object’s class

Returns

the event priority of this simulation object’s class

Return type

int

delete()[source]

Delete this object from a simulation.

get_receiving_priorities_dict()[source]

Get priorities of message types handled by this SimulationObject’s type

Returns

mapping from message types handled by this SimulationObject to their

execution priorities. The highest priority is 0, and higher values have lower priorities. Execution priorities determine the execution order of concurrent events at a SimulationObject.

Return type

dict

log_with_time(msg)[source]

Write a debug log message with the simulation time.

static register_handlers(subclass, handlers)[source]

Register a SimulationObject’s event handler methods.

The simulation engine vectors execution of a simulation message to the message’s registered event handler method. The priority of message execution in an event containing multiple messages is determined by the sequence of tuples in handlers. These relationships are stored in an ApplicationSimulationObject’s metadata.event_handlers_dict. Each call to register_handlers re-initializes all event handler methods.

Parameters
  • subclass (SimulationObject) – a subclass of SimulationObject that is registering the relationships between the simulation messages it receives and the methods that handle them

  • handlers (list of (SimulationMessage, function)) – a list of tuples, indicating which method should handle which type of SimulationMessage in subclass; ordered in decreasing priority for handling simulation message types

Raises

SimulatorError – if a SimulationMessage appears repeatedly in handlers, or if a method in handlers is not callable

static register_sent_messages(subclass, sent_messages)[source]

Register the messages sent by a SimulationObject subclass

Calling register_sent_messages re-initializes all registered sent message types.

Parameters
  • subclass (SimulationObject) – a subclass of SimulationObject that is registering the types of simulation messages it sends

  • sent_messages (list of SimulationMessage) – a list of the SimulationMessage type’s which can be sent by SimulationObject’s of type subclass

render_event_queue()[source]

Format an event queue as a string

Returns

return a string representation of the simulator’s event queue

Return type

str

send_event(delay, receiving_object, message, copy=False)[source]

Send a simulation event message, specifing the event time as a delay.

Parameters
  • delay (float) – the simulation delay at which receiving_object should execute the event

  • receiving_object (SimulationObject) – the simulation object that will receive and execute the event

  • message (SimulationMessage) – the simulation message which will be carried by the event

  • copy (bool, optional) – if True, copy the message before adding it to the event; set False by default to optimize performance; set True as a safety measure to avoid unexpected changes to shared objects

Raises

SimulatorError – if delay < 0 or delay is NaN, or if the sending object type is not registered to send messages with the type of message, or if the receiving simulation object type is not registered to receive messages with the type of message

send_event_absolute(event_time, receiving_object, message, copy=False)[source]

Send a simulation event message with an absolute event time.

Parameters
  • event_time (float) – the absolute simulation time at which receiving_object will execute the event

  • receiving_object (SimulationObject) – the simulation object that will receive and execute the event

  • message (SimulationMessage) – the simulation message which will be carried by the event

  • copy (bool, optional) – if True, copy the message before adding it to the event; set False by default to optimize performance; set True as a safety measure to avoid unexpected changes to shared objects

Raises

SimulatorError – if event_time < 0, or if the sending object type is not registered to send messages with the type of message, or if the receiving simulation object type is not registered to receive messages with the type of message

2.1.14. de_sim.template_sim_objs module

Template simulation objects

Author

Arthur Goldberg <Arthur.Goldberg@mssm.edu>

Date

2018-05-16

Copyright

2018, Karr Lab

License

MIT

class de_sim.template_sim_objs.TemplatePeriodicSimulationObject(name, period, start_time=0.0)[source]

Bases: de_sim.simulation_object.ApplicationSimulationObject

Template self-clocking ApplicationSimulationObject

Events occur at time start_time, start_time + period, start_time + 2*period, …

To minimize roundoff errors in event times track the number of periods, and multiply by period to determine event times.

period[source]

interval between events, in simulated time units

Type

float

num_periods[source]

number of periods executed

Type

int

start_time[source]

the time of the first periodic event

Type

float, optional

event_handlers = [(<class 'de_sim.simulation_message.NextEvent'>, <function TemplatePeriodicSimulationObject.handle_simulation_event>)][source]
get_state()[source]
handle_event()[source]

Handle the periodic event

Derived classes must override this method and actually handle the event

handle_simulation_event(event)[source]
messages_sent = [<class 'de_sim.simulation_message.NextEvent'>][source]
metadata = <de_sim.simulation_object.ApplicationSimulationObjectMetadata object>[source]
schedule_next_event()[source]

Schedule the next event in self.period simulated time units

send_initial_events()[source]

2.1.15. de_sim.utilities module

Simulation utilities

Author

Arthur Goldberg <Arthur.Goldberg@mssm.edu>

Date

2018-02-26

Copyright

2018, Karr Lab

License

MIT

class de_sim.utilities.ConcreteABCMeta(*args, **kwargs)[source]

Bases: abc.ABCMeta

A concrete subclass of ABCMeta that’s used to combine meta classes

In particular, this makes it easy to create a “most derived metaclass” that includes ABCMetas and a custom Meta, and avoid “TypeError: metaclass conflict”.

See https://docs.python.org/3/reference/datamodel.html#determining-the-appropriate-metaclass, PEP 3119 and https://stackoverflow.com/a/31429212

class de_sim.utilities.FastLogger(logger, level_used)[source]

Bases: object

Cache activity decision to avoid slow logging when not writing logs

active[source]

whether the log is active

Type

bool

method[source]

the logging method being used, debug, info, etc.

Type

method

LOG_LEVELS = {'debug', 'error', 'exception', 'info', 'warning'}[source]
static active_logger(logger, level_used)[source]

Determine whether the logger will write log messages

Parameters
  • logger (logging2.Logger) – a logger

  • level_used (str) – the logging level for this logger

Raises

ValueError – if level_used is not a valid logging level

Returns

return True if the logger is active, False otherwise

Return type

bool

fast_log(msg, **kwargs)[source]

Log, and do it quickly if nothing is being written

Parameters
  • msg (str) – the log message

  • kwargs (dict) – other logging arguments

get_level()[source]

Get the level of this logger

Returns

the level of this logger

Return type

LogLevel

is_active()[source]

Get the cached active state of this logger

Returns

whether this logger is active

Return type

bool

class de_sim.utilities.SimulationProgressBar(use=False)[source]

Bases: object

Simulation progress bar

Shows the progress of a simulation towards the time it is scheduled to end, in simulation time

end()[source]

End the simulation’s progress bar

progress(sim_time)[source]

Advance the simulation’s progress bar

Parameters

sim_time (float) – the simulation time

start(time_max)[source]

Start the simulation’s progress bar

Parameters

time_max (float) – the simulation’s end time

2.1.16. Module contents