3. de_sim package

3.2. Submodules

3.3. de_sim._version module

3.4. de_sim.checkpoint module

Checkpoints for a simulation run

Author

Jonathan Karr <karr@mssm.edu>

Author

Arthur Goldberg <Arthur.Goldberg@mssm.edu>

Date

2017-08-30

Copyright

2016-2020, Karr Lab

License

MIT

class de_sim.checkpoint.AccessCheckpoints(dir_path)[source]

Bases: object

Represent a directory that contains the checkpoints from a simulation run

Checkpoints are saved in pickle files, named t.pickle, where t is the simulation time of the checkpoint.

dir_path[source]

the directory containing simulation checkpoints

Type

str

_last_dir_mod[source]

most recent wall-clock time when the contents of dir_path were modified; used to avoid unnecessary updates to all_checkpoints

Type

str

all_checkpoints[source]

sorted list of the simulation times of all checkpoints in dir_path

Type

list of float

get_checkpoint(time=None)[source]

Get the latest checkpoint in directory dir_path whose time is before or equal to time

However, if no checkpoint with time <= time exists, then return the first checkpoint. If time is None, return the last checkpoint.

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. But, if time = 0.9 s, the checkpoint from 1.0 s would be returned. And if time is None, return the checkpoint from 2.0 s.

Parameters

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

get_filename(time)[source]

Get the filename for the checkpoint at time time

Parameters

time (float) – time

Returns

filename for the checkpoint at time time

Return type

str

list_checkpoints(error_if_empty=True)[source]

Get sorted list of times of saved checkpoints in checkpoint directory dir_path

To enhance performance the list of times is cached in attribute all_checkpoints and refreshed from the contents of directory dir_path if it has been updated.

Parameters

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

Returns

sorted list of times of saved checkpoints

Return type

list of float

Raises

SimulatorError – if dirname doesn’t contain any checkpoints

set_checkpoint(checkpoint)[source]

Save a checkpoint in the directory dir_path

Parameters

checkpoint (Checkpoint) – checkpoint

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

3.5. de_sim.errors module

Author

Arthur Goldberg <Arthur.Goldberg@mssm.edu>

Date

2018-01-22

Copyright

2018-2020, 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

3.6. de_sim.event module

Simulation event class

Author

Arthur Goldberg <Arthur.Goldberg@mssm.edu>

Date

2016-05-31

Copyright

2016-2020, 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.

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. In de_sim, sub-time is a pair: the class priority for the receiving object, and a tiebreaker which is a unique value for each instance of the receiving object’s class. This is implemented by the comparison operators for Event below. This ordering achieves deterministic and reproducible simulations. (For more theory, 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 sent 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]

an EventMessage 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 attribute(s) identified in its slots.

Type

EventMessage

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

a string representation of the names of an Event’s fields, or a list representation if as_list is set

Return type

str or list

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

Provide a header row 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

str: a string representation of names of an Event’s fields, or a list representation if as_list is set

Return type

str or obj

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

Format the contents of an Event

Rendering the contents 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 or list

sending_object[source]

3.7. de_sim.event_message module

Base class for event messages

Author

Arthur Goldberg <Arthur.Goldberg@mssm.edu>

Date

2017-03-26

Copyright

2016-2020, Karr Lab

License

MIT

class de_sim.event_message.CombinedEventMessageMeta(*args, **kwargs)[source]

Bases: de_sim.utilities.ConcreteABCMeta, de_sim.event_message.EventMessageMeta

class de_sim.event_message.EventMessage(*args)[source]

Bases: de_sim.event_message.EventMessageInterface

The event message base class

Each simulation event contains an event message object. This class supports declarative definitions of EventMessage subclasses that automatically define a subclass’ variable attributes. Like Python Data Classes, EventMessages are defined using PEP 526 type annotations. For example:

class ExampleEventMessage(EventMessage):
    "Docstring for ExampleEventMessage"
    attr1: int
    attr2: float = 1.1

defines ExampleEventMessage as an EventMessage with a short docstring and message fields named attr1 and attr2, and this:

example_event_message = ExampleEventMessage(3, 3.14)

creates an instance of the class.

However, as of 2020-10, EventMessage does not use default values or types which may be provided.

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

class de_sim.event_message.EventMessageInterface(*args)[source]

Bases: object

An abstract base class for event messages

The comparison operations (__gt__, __lt__, etc.) order event message instances by the tuple (class name, instance attribute values). When a simulation object executes multiple events simultaneously, this ensures that a list containing these messages can be sorted in a deterministic order, because the events’ messages will have a unique sort order.

__slots__[source]

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

Type

list

__ge__(other)[source]

Does this EventMessage sort after or equal other?

Parameters

other (EventMessage) – another EventMessage

Returns

True if this EventMessage sorts after or equals other

Return type

bool

__gt__(other)[source]

Does this EventMessage sort after other?

Parameters

other (EventMessage) – another EventMessage

Returns

True if this EventMessage sorts after other

Return type

bool

__le__(other)[source]

Does this EventMessage sort before or equal other?

Parameters

other (EventMessage) – another EventMessage

Returns

True if this EventMessage sorts before or equals other

Return type

bool

__lt__(other)[source]

Does this EventMessage sort before other?

Parameters

other (EventMessage) – another EventMessage

Returns

True if this EventMessage sorts before other

Return type

bool

__str__()[source]

Provide a string representation of an EventMessage

attrs()[source]

Provide a list of the field names for this EventMessage

Returns

the names of all attributes in this EventMessage

Return type

list of str

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

Provide the attribute names for this EventMessage

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 EventMessage, or a list representation if as_list is set

Return type

obj

value_map()[source]

Provide a map from each attribute to its value, as a str, for this EventMessage

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 EventMessage

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 str

Returns

None if this message has no attributes, or a str representation of the attribute names for this EventMessage, or a list representation if as_list is set

Return type

obj

class de_sim.event_message.EventMessageMeta(*args, **kwargs)[source]

Bases: type

A custom metaclass that customizes the creation of EventMessage subclasses

3.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-2020, 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(event)[source]

Handle the periodic event

Derived classes which wish to process the event must override this method

Parameters

event (Event) – simulation event; not used

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

Bases: object

An abstract base class interface which any object that obtains a simulation’s checkpoint 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

Periodically write a checkpoint to a file

checkpoint_dir[source]

the directory in which to save checkpoints

Type

str

access_state_obj[source]

an object which obtains the simulation’s state for a checkpoint; access_state_obj objects should be subclasses of AccessStateObjectInterface

Type

AccessStateObjectInterface

create_checkpoint()[source]

Create a checkpoint in the directory self.checkpoint_dir

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

3.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(max_time: float, time_init: float = 0.0, stop_condition: object = None, output_dir: str = None, progress: bool = False, profile: bool = False, object_memory_change_interval: int = 0)[source]

Bases: wc_utils.util.misc.EnhancedDataClass

A dataclass that holds configuration information for a simulation run

  • Simulation maximum time

  • Simulation start time

  • Stop condition

  • Directory for storing simulation metadata

  • Progress bar switch

  • Performance profiling switch

  • Configure profiling of heap memory use

max_time[source]

maximum simulation time

Type

float

time_init[source]

time at which a simulation starts; defaults to 0

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

output_dir[source]

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

Type

str, optional

progress[source]

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

Type

bool, optional

profile[source]

if True, output a profile of the simulation’s performance created by a Python profiler

Type

bool, optional

object_memory_change_interval[source]

number of simulation events between reporting changes in heap object count and memory use; if 0 do not report; defaults to do not report; cannot be used with profile as they run much too slowly

Type

int, optional

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

Validate an attribute in this SimulationConfig when it is changed

Overrides __setattr__ in EnhancedDataClass to report errors as SimulatorErrors

object_memory_change_interval = 0[source]
output_dir = None[source]
profile = False[source]
progress = False[source]
semantically_equal(other)[source]

Are two instances semantically equal with respect to a simulation’s predictions?

Overrides semantically_equal in EnhancedDataClass. The only attributes that are semantically meaningful to a simulation’s predictions are max_time and time_init. Although they’re floats, they are compared exactly because they’re simulation inputs, not computed outputs.

Parameters

other (Object) – other object

Returns

True if other is a SimulationConfig that is semantically equal to self, False otherwise

Return type

bool

stop_condition = None[source]
time_init = 0.0[source]
validate()[source]

Validate a SimulationConfig instance

Validation tests that involve multiple fields are contained in this method.

Returns

None if no error is found

Return type

None

Raises

SimulatorError – if self fails validation

validate_individual_fields()[source]

Validate constraints on individual fields in a SimulationConfig instance

Returns

if no error is found

Return type

None

Raises

SimulatorError – if an attribute of self fails validation

3.10. de_sim.simulation_metadata module

Classes that 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-2020, 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

If possible, the author’s username is obtained automatically. All other attributes must be set manually.

name[source]

the author’s name

Type

str

email[source]

the author’s email address

Type

str

username[source]

the author’s username

Type

str

organization[source]

the 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

All RunMetadata attributes are obtained automatically.

ip_address[source]

IP address of the machine that ran the simulation

Type

str

start_time[source]

clock start time when the simulation started

Type

datetime

run_time[source]

simulation run time in real 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]
semantically_equal(other)[source]

Evaluate whether two instances of RunMetadata are semantically equal

Returns False if other is not a RunMetadata. Otherwise, always returns True , because a simulation’s results do not depend on the data in its RunMetadata.

Parameters

other (Object) – other object

Returns

True if other is a RunMetadata

Return type

bool

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

Represent the metadata of a simulation run; incorporates four types of metadata classes

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 in this SimulationMetadata when it is changed

Overrides __setattr__ in EnhancedDataClass to report errors as SimulatorErrors

static get_pathname(dirname)[source]

Get the pathname for a pickled SimulationMetadata object stored in directory dirname

Parameters

dirname (str) – directory that stores a pickled representation of a SimulationMetadata object

Returns

pathname to a pickled file storing a SimulationMetadata object

Return type

str

semantically_equal(other)[source]

Are two instances semantically equal with respect to a simulation’s predictions?

Overrides semantically_equal in EnhancedDataClass. Ignore run, as a RunMetadata is not semantically meaningful to a simulation’s predictions and depends on a simulation’s performance.

Parameters

other (Object) – other object

Returns

True if other is semantically equal to self, False otherwise

Return type

bool

simulator_repo = None[source]

3.11. de_sim.simulation_object module

Base class for simulation objects

Author

Arthur Goldberg <Arthur.Goldberg@mssm.edu>

Date

2016-06-01

Copyright

2016-2020, Karr Lab

License

MIT

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

Bases: object

Base class for simulation objects.

BaseSimulationObject is a base class for all simulations objects. It provides basic functionality which includes the object’s name (which must be unique), its simulation time, and a send_event() method.

name[source]

this simulation object’s name, which must be unique across all simulation objects handled by a Simulator

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 SimulationObject class

Type

str

num_events[source]

number of events processed

Type

int

simulator[source]

the Simulator that uses this BaseSimulationObject

Type

Simulator

debug_logs[source]

the debug logs

Type

wc_utils.debug_logs.core.DebugLogsManager

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

del_simulator()[source]

Delete this object’s simulator reference

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 BaseSimulationObject’s event handler methods.

The simulator vectors execution of an event 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 a SimulationObject’s metadata.event_handlers_dict. Each call to register_handlers reinitializes all event handler methods.

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

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

Raises

SimulatorError – if an EventMessage 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 BaseSimulationObject subclass

Calling register_sent_messages reinitializes all registered sent message types.

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

Schedule an event containing an event message, specifying the event time as a delay.

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

X.send_event(receive_delay, Y, event_message)

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

  • event_message (EventMessage) – the event 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 event_message, or if the receiving simulation object type is not registered to receive messages with the type of event_message

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

Schedule an event containing an 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 (EventMessage) – the event 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

set_simulator(simulator)[source]

Set this object’s simulator reference

Parameters

simulator (Simulator) – the simulator that will use this BaseSimulationObject

Raises

SimulatorError – if this BaseSimulationObject is already registered with a simulator

class de_sim.simulation_object.SimObjClassPriority[source]

Bases: enum.IntEnum

Priorities for simulation object classes

These are used to order the execution of simultaneous events among objects in different classes

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.SimulationObjMeta[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 BaseSimulationObject subclass being created

  • superclasses (tuple) – tuple of superclasses

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

Returns

a new instance of a subclass of BaseSimulationObject

Return type

SimulationObject

Raises

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

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

Bases: de_sim.simulation_object.BaseSimulationObject, de_sim.simulation_object.SimulationObjectInterface

Base class for all simulation objects in a simulation

metadata[source]

metadata for event message sending and handling, initialized by SimulationObjectAndABCMeta

Type

SimulationObjectMetadata

init_before_run()[source]

Perform initialization before a simulation run

If a simulation object defines init_before_run, it will be called by the simulator just before simulation begins, after all simulation objects have been created and loaded. A simulation object that wishes to schedule initial events for itself or for other objects in the simulation should do so in init_before_run. It can also perform any other initialization in the method.

classmethod set_class_priority(priority)[source]

Set the execution priority for a simulation object class, class_priority

Use this to set the class_priority of a subclass of BaseSimulationObject after it has been constructed.

Parameters

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

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

Bases: de_sim.simulation_object.SimulationObjMeta, 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.SimulationObjectInterface[source]

Bases: object

abstract init_before_run()[source]

Perform initialization before a simulation run

class de_sim.simulation_object.SimulationObjectMetadata[source]

Bases: object

Metadata for a SimulationObject

event_handlers_dict[source]

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

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 BaseSimulationObject has registered to send

Type

set

3.12. de_sim.simulator module

Discrete event simulator

Author

Arthur Goldberg <Arthur.Goldberg@mssm.edu>

Date

2016-06-01

Copyright

2016-2020, Karr Lab

License

MIT

class de_sim.simulator.EventQueue[source]

Bases: object

A simulation’s event queue

Stores a Simulator’s events in a heap (also known as a priority queue). The heap is a ‘min heap’, which keeps the event with the smallest sort order at the root in heap[0]. Events are sorted on their _get_order_time, which provides a pair, (event time, event ‘sub-time’), and is implemented via comparison operations in Event. All entries with equal (event time, event ‘sub-time’) values are popped from the heap by next_events(). schedule_event() costs O(log(n)), where n is the size of the heap, while next_events(), costs O(mlog(n)), where m is the number of events returned.

event_heap[source]

a Simulator’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

len()[source]

Size of the event queue

Returns

number of events in the event queue

Return type

int

log_event(event)[source]

Log an event with its simulation time to the fast_debug_file_logger

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 simulation object with the highest priority

If one event has the smallest event_time, which occurs often, it is returned in a list.

But because multiple events may occur simultaneously – that is, have the same event_time – they are returned in a list that will be passed to the simulation object that will handle them. Specifically, if an EventQueue contains multiple events with the same event_time and they will be received by multiple simulation objects, then the event(s) scheduled for the highest priority simulation object will be returned. Subsequent calls to next_events will return events schedule for simulation object(s) with lower priority(s).

If multiple events are returned, they are sorted by the pair (event message type priority, event message field values).

Returns

the earliest event(s); 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 event time. Events are sorted by the event order tuple provided by Event._get_order_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]

Empty the event queue

schedule_event(send_time, receive_time, sending_object, receiving_object, event_message)[source]

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

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.

  • event_message (EventMessage) – an event message 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.simulator.Simulator[source]

Bases: object

A discrete-event simulator

A general-purpose discrete-event simulation mechanism, including the simulation scheduler. Architected as an object-oriented simulation that could be parallelized.

Simulator contains and manipulates global simulation data. Simulator registers all simulation objects classes and all simulation objects. The simulate() method runs a simulation, scheduling objects to execute events in non-decreasing time order, and generates debugging output.

time[source]

a simulation’s current time

Type

float

simulation_objects[source]

all simulation objects, keyed by their names

Type

dict of SimulationObject

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 that saves trajectory data for plotting

Type

FastLogger

event_queue[source]

the queue of events that will be executed

Type

EventQueue

event_counts[source]

a count of executed events, categorized by the tuple (receiving object class, receiving object name, event message class)

Type

Counter

num_handlers_called[source]

the number of calls a simulation makes to an event handler in a simulation object

Type

int

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

measurements_fh[source]

file handle for debugging measurements file

Type

_io.TextIOWrapper

mem_tracker[source]

a memory use tracker for debugging

Type

pympler.tracker.SummaryTracker

END_TIME_EXCEEDED = ' End time exceeded'[source]
NO_EVENTS_REMAIN = ' No events remain'[source]
NUM_PROFILE_ROWS = 50[source]
class SimulationReturnValue[source]

Bases: tuple

SimulationReturnValue(num_events, profile_stats): the value(s) returned by a simulation run

property num_events[source]

the number of times a simulation object handles an event, which may be smaller than the number of events sent, because simultaneous events at a simulation object are handled together

Type

Alias for field number 0

property profile_stats[source]

if performance is being profiled, a pstats.Stats instance containing the profiling statistics

Type

Alias for field number 1

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 multiple simulation objects to this simulation

Parameters

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

finish_metadata_collection()[source]

Finish metadata collection: record a simulation’s runtime, and write all metadata to disk

get_object(simulation_object_name)[source]

Get a simulation object used by this simulation

Parameters

simulation_object_name (str) – the name of a simulation object

Returns

the simulation object whose name is simulation_object_name

Return type

SimulationObject

Raises
  • SimulatorError – if the simulation object whose name is simulation_object_name

  • is not used by this simulation

get_objects()[source]

Get all simulation object instances in this simulation

Returns

an iterator over all simulation object instances in this simulation

Return type

iterator over SimulationObject

static get_sim_config(max_time=None, sim_config=None, config_dict=None)[source]

External simulate interface

Legal combinations of the three parameters:

  1. Just max_time

  2. Just sim_config, which will contain an entry for max_time

  3. Just config_dict, which must contain an entry for max_time

Other combinations are illegal.

Parameters
  • max_time (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; note that config_dict is not a kwargs argument

Returns

a validated simulation configuration

Return type

SimulationConfig

Raises

SimulatorError – if no arguments are provided, or multiple arguments are provided, or max_time is missing from config_dict

init_metadata_collection(sim_config)[source]

Initialize this simulation’s metadata object

Call just before a simulation runs, so that the correct start time of the simulation is recorded

Parameters
  • sim_config (SimulationConfig) – metadata about the simulation’s

  • configuration (start time, maximum time, etc.) –

initialize()[source]

Initialize a simulation

Call init_before_run() 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, organized by simulation object

Returns

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

Return type

str

provide_event_counts()[source]

Provide the simulation’s event counts, categorized by object type, object name, event type

Returns

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

Return type

str

reset()[source]

Reset this Simulator

Delete all objects, and empty the event queue.

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

Alias for simulate

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

Run a simulation

Exactly one of the arguments max_time, sim_config, and config_dict must be provided. See get_sim_config for additional constraints on these arguments.

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

  • sim_config (SimulationConfig, optional) – a 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; if not provided, then the their username will be obtained automatically

Returns

a SimulationReturnValue whose fields are documented with its definition

Return type

SimulationReturnValue

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

track_obj_mem()[source]

Write memory use tracking data to the measurements file in measurements_fh

3.13. de_sim.template_sim_objs module

Template simulation objects

Author

Arthur Goldberg <Arthur.Goldberg@mssm.edu>

Date

2018-05-16

Copyright

2018-2020, Karr Lab

License

MIT

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

Bases: de_sim.simulation_object.SimulationObject

Template self-clocking SimulationObject

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.event_message.NextEvent'>, <function TemplatePeriodicSimulationObject.handle_simulation_event>)][source]
handle_event(event)[source]

Handle the periodic event

Derived classes which wish to process the event must override this method

Parameters

event (Event) – simulation event; not used

handle_simulation_event(event)[source]

Handle the periodic event

Parameters

event (Event) – the simulation event

Call handle_event and schedule the next event

init_before_run()[source]

Schedule the initial event

messages_sent = [<class 'de_sim.event_message.NextEvent'>][source]
metadata = <de_sim.simulation_object.SimulationObjectMetadata object>[source]
schedule_next_event()[source]

Schedule the next event in self.period simulated time units

3.14. de_sim.utilities module

Simulation utilities

Author

Arthur Goldberg <Arthur.Goldberg@mssm.edu>

Date

2018-02-26

Copyright

2018-2020, 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

Returns

return True if the logger is active, False otherwise

Return type

bool

Raises

ValueError – if level_used is not a valid logging level

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.

A SimulationProgressBar does nothing by default, so that it can be used without an if statement and configured at runtime.

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(max_time)[source]

Start the simulation’s progress bar

Parameters

max_time (float) – the simulation’s end time

3.15. de_sim.visualize module

Visualize a simulation run

Author

Arthur Goldberg <Arthur.Goldberg@mssm.edu>

Date

2020-06-23

Copyright

2020, Karr Lab

License

MIT

class de_sim.visualize.EventCoordinates(sim_obj_id, time): the coordinates of an event: (simulation object id, simulation time)[source]

Bases: tuple

property sim_obj_id[source]

the unique name of a simulation object

Type

Alias for field number 0

property time[source]

the event time of an event

Type

Alias for field number 1

class de_sim.visualize.SimulationEventMessage[source]

Bases: tuple

SimulationEventMessage(message_type, send_coordinates, receive_coordinates): a simulation event message; its type, and send and receive coordinates

property message_type[source]

the class name of a simulation event message

Type

Alias for field number 0

property receive_coordinates[source]

an EventCoordinates: the receive coordinates

Type

Alias for field number 2

property send_coordinates[source]

an EventCoordinates: the send coordinates

Type

Alias for field number 1

class de_sim.visualize.SpaceTime(data=None, plot_params=None)[source]

Bases: object

Generate a space-time plot of a simulation run from a plot log

get_categorized_messages()[source]

Categorize all messages as to self or to other object

get_data(plot_file)[source]

Extract event message data from plot file

Parameters

plot_file (str) – filename of log with event data

Returns

list of all event messages in simulation run

Return type

list of SimulationEventMessage

get_event_locations()[source]

Get a list of the plot coordinates for all simulation events

get_min_max_times()[source]

Get the minimum and maximum event times from the list of event messages

get_obj_x_locations()[source]

Get the x locations of the events for all objects

get_obj_x_locations_map()[source]

Get a map from the ids of all objects to their x locations

get_object_ids()[source]

Get ids of all objects from the list of event messages

plot_data(plot_filename)[source]

Generate space-time diagram

Parameters

plot_filename (str) – pdf filename for plot that is produced

3.16. Module contents