2.1. de_sim package

2.1.2. Submodules

2.1.3. 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 sec

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 seconds 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 in seconds

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.4. 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.5. 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.6. 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.7. de_sim.sim_metadata module

Classes to represent the metadata of a simulation run

Author

Jonathan Karr <karr@mssm.edu>

Author

Arthur Goldberg <Arthur.Goldberg@mssm.edu>

Date

2017-08-18

Copyright

2016-2018, Karr Lab

License

MIT

class de_sim.sim_metadata.AuthorMetadata(name, email, username, organization)[source]

Bases: object

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

ATTRIBUTES = ['name', 'email', 'username', 'organization'][source]
__eq__(other)[source]

Compare two author metadata objects

Parameters

other (AuthorMetadata) – other author metadata object

Returns

true if author metadata objects are semantically equal

Return type

bool

__ne__(other)[source]

Compare two author metadata objects

Parameters

other (AuthorMetadata) – other author metadata object

Returns

true if author metadata objects are semantically unequal

Return type

bool

__str__()[source]

Provide a readable representation of this AuthorMetadata

Returns

a readable representation of this AuthorMetadata

Return type

str

class de_sim.sim_metadata.Comparable[source]

Bases: abc.ABC

Interface to an object that can be compared, for simulation metadata elements

abstract __eq__(other)[source]

Compare two simulation metadata elements

Parameters

other (Comparable) – other simulation metadata element

Returns

true if simulation metadata elements are semantically equal

Return type

bool

abstract __ne__(other)[source]

Compare two simulation metadata elements

Parameters

other (Comparable) – other simulation metadata element

Returns

true if simulation metadata objects are semantically unequal

Return type

bool

class de_sim.sim_metadata.RunMetadata(start_time=None, run_time=None, ip_address=None)[source]

Bases: object

Represent a simulation’s run

start_time[source]

simulation start time

Type

datetime.datetime

run_time[source]

simulation run time in seconds

Type

float

ip_address[source]

ip address of the machine that ran the simulation

Type

str

ATTRIBUTES = ['start_time', 'run_time', 'ip_address'][source]
__eq__(other)[source]

Compare two run metadata objects

Parameters

other (RunMetadata) – other run metadata object

Returns

true if run metadata objects are semantically equal

Return type

bool

__ne__(other)[source]

Compare two run metadata objects

Parameters

other (RunMetadata) – other run metadata object

Returns

true if run metadata objects are semantically unequal

Return type

bool

__str__()[source]

Provide a readable representation of this RunMetadata

Returns

a readable representation of this RunMetadata

Return type

str

record_end()[source]
record_ip_address()[source]
record_start()[source]
class de_sim.sim_metadata.SimulationMetadata(model, simulation, run, author)[source]

Bases: object

Represents the metadata of a simulation run

model[source]

Metadata about the model’s git repository

Type

wc_utils.util.git.RepositoryMetadata

simulation[source]

Information about the simulation’s configuration (e.g. perturbations, random seed)

Type

object

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

ATTRIBUTES = ['model', 'simulation', 'run', 'author'][source]
__eq__(other)[source]

Compare two simulation metadata objects

Parameters

other (SimulationMetadata) – other simulation metadata object

Returns

true if simulation metadata objects are semantically equal

Return type

bool

__ne__(other)[source]

Compare two simulation metadata objects

Parameters

other (SimulationMetadata) – other simulation metadata object

Returns

true if simulation metadata objects are semantically unequal

Return type

bool

__str__()[source]

Provide a readable representation of this SimulationMetadata

Returns

a readable representation of this SimulationMetadata

Return type

str

get_file_name()[source]

Get file name for simulation metadata stored in directory dirname

Parameters

dirname (str) – directory for holding the metadata

Returns

file name for simulation metadata

Return type

str

static read_metadata(dirname)[source]

Read a simulation metadata object from the directory dirname

Parameters

dirname (str) – directory for holding the metadata

static write_metadata(simulation_metadata, dirname)[source]

Save a simulation metadata object to the directory dirname

Parameters
  • simulation_metadata (SimulationMetadata) – a simulation metadata instance

  • dirname (str) – directory for holding the metadata

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 seconds

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_engine module

Core 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, stop_condition=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

progress[source]

a real-time progress bar

Type

SimulationProgressBar

stop_condition[source]

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

Type

function, optional

event_counts[source]

a counter of event types

Type

Counter

__initialized[source]

whether the simulation has been initialized

Type

bool

Raises[source]

SimulatorError: if the stop_condition is not callable

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

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

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

Set simulation time to 0, delete all objects, and reset any prior initialization.

run(end_time, **kwargs)[source]

Alias for simulate

set_stop_condition(stop_condition)[source]

Set the simulation engine’s stop condition

stop_condition[source]

a function that takes one argument time; stop_condition is executed and tested before each simulation event. If it returns True a simulation is terminated.

Type

function

Raises[source]

SimulatorError: if the stop_condition is not callable

simulate(end_time, stop_condition=None, progress=False)[source]

Run the simulation

Parameters
  • end_time (float) – the time of the end of the simulation

  • stop_condition (function, optional) – if provided, a function that takes one argument time; a simulation terminates if the function returns True

  • progress (bool, optional) – if True, print a bar that dynamically reports the simulation’s progress

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

2.1.10. 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.11. 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, **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, **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.12. 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)[source]

Bases: de_sim.simulation_object.ApplicationSimulationObject

Template self-clocking ApplicationSimulationObject

Events occur at time 0, period, 2 x period, …

To avoid roundoff errors in event times get them from a UniformSequence.

period[source]

interval between events, in simulated seconds

Type

float

event_time_sequence[source]

a uniform sequence generator

Type

UniformSequence

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 seconds

send_initial_events()[source]

2.1.13. 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(end_time)[source]

Start the simulation’s progress bar

Parameters

end_time (float) – the simulation’s end time

2.1.14. Module contents