3. de_sim package¶
3.1. Subpackages¶
- 3.1.1. de_sim.config package
- 3.1.2. de_sim.examples package
- 3.1.3. de_sim.testing 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.
-
_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
offloat
-
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
-
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
offloat
- 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
-
__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
-
exception
de_sim.errors.
SimulatorError
(message=None)[source]¶ Bases:
de_sim.errors.Error
Exception raised for errors in de_sim
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.)-
_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 anEvent
; it may also carry a payload for theEvent
in its attribute(s) identified in its slots.- Type
-
__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 alist
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 alist
representation if as_list is set- Return type
str
orlist
-
event_time
[source]
-
static
header
(as_list=False, separator='\t')[source]¶ Provide a header row for an
Event
tableProvide generic header suitable for any type of message in an event.
- Parameters
as_list (
bool
, optional) – if set, return the header fields in alist
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 alist
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 roundingannotated (
bool
, optional) – if set, prefix each message field value with its attribute nameas_list (
bool
, optional) – if set, return theEvent
’s values in alist
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 alist
representation if as_list is set- Return type
str
orlist
-
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,EventMessage
s 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
) – anotherEventMessage
- Returns
True
if thisEventMessage
sorts after or equals other- Return type
bool
-
__gt__
(other)[source]¶ Does this
EventMessage
sort after other?- Parameters
other (
EventMessage
) – anotherEventMessage
- Returns
True
if thisEventMessage
sorts after other- Return type
bool
-
__le__
(other)[source]¶ Does this
EventMessage
sort before or equal other?- Parameters
other (
EventMessage
) – anotherEventMessage
- Returns
True
if thisEventMessage
sorts before or equals other- Return type
bool
-
__lt__
(other)[source]¶ Does this
EventMessage
sort before other?- Parameters
other (
EventMessage
) – anotherEventMessage
- Returns
True
if thisEventMessage
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
ofstr
-
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 alist
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 thisEventMessage
, or alist
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 thisEventMessage
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 nameas_list (
bool
, optional) – if set, return the attribute names in alist
separator (
str
, optional) – the field separator used if the attribute names are returned as astr
- Returns
None if this message has no attributes, or a
str
representation of the attribute names for thisEventMessage
, or alist
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
-
create_checkpoint
()[source]¶ Create a checkpoint
Derived classes must override this method and actually create a checkpoint
-
-
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
-
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
-
access_state_obj
[source]¶ an object which obtains the simulation’s state for a checkpoint; access_state_obj objects should be subclasses of
AccessStateObjectInterface
-
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
-
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
-
__setattr__
(name, value)[source]¶ Validate an attribute in this
SimulationConfig
when it is changedOverrides __setattr__ in
EnhancedDataClass
to report errors asSimulatorError
s
-
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 aSimulationConfig
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.
-
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
= None[source]
-
run_time
= None[source]
-
semantically_equal
(other)[source]¶ Evaluate whether two instances of
RunMetadata
are semantically equalReturns
False
if other is not aRunMetadata
. Otherwise, always returnsTrue
, because a simulation’s results do not depend on the data in itsRunMetadata
.- Parameters
other (
Object
) – other object- Returns
True
if other is aRunMetadata
- 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
information about the person who ran the simulation (e.g. name, email)
- Type
-
__setattr__
(name, value)[source]¶ Validate an attribute in this
SimulationMetadata
when it is changedOverrides __setattr__ in
EnhancedDataClass
to report errors asSimulatorError
s
-
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 aSimulationMetadata
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 aRunMetadata
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
-
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
-
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
-
simulator
[source]¶ the
Simulator
that uses thisBaseSimulationObject
- Type
-
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
-
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 aSimulationObject
.- Return type
dict
-
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 ofBaseSimulationObject
that is registering the relationships between the event messages it receives and the methods that handle themhandlers (
list
of (EventMessage
, method)) – a list of tuples, indicating which method should handle which type ofEventMessage
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
subclassCalling register_sent_messages reinitializes all registered sent message types.
- Parameters
subclass (
BaseSimulationObject
) – a subclass ofBaseSimulationObject
that is registering the types of event messages it sendssent_messages (
list
ofEventMessage
) – a list of theEventMessage
classes which can be sent byBaseSimulationObject
’s of type subclass
-
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 eventreceiving_object (
SimulationObject
) – the simulation object that will receive and execute the eventevent_message (
EventMessage
) – the event message which will be carried by the eventcopy (
bool
, optional) – ifTrue
, copy the message before adding it to the event; setFalse
by default to optimize performance; setTrue
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 eventreceiving_object (
SimulationObject
) – the simulation object that will receive and execute the eventmessage (
EventMessage
) – the event message which will be carried by the eventcopy (
bool
, optional) – ifTrue
, copy the message before adding it to the event; setFalse
by default to optimize performance; setTrue
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 thisBaseSimulationObject
- 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
-
class
de_sim.simulation_object.
SimulationObjMeta
[source]¶ Bases:
type
-
static
__new__
(cls, clsname, superclasses, namespace)[source]¶ - Parameters
cls (
class
) – this classclsname (
str
) – name of theBaseSimulationObject
subclass being createdsuperclasses (
tuple
) – tuple of superclassesnamespace (
dict
) – namespace of subclass ofSimulationObject
being created
- Returns
a new instance of a subclass of
BaseSimulationObject
- Return type
- 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 theSimulationObject
, or if event_handlers isn’t an iterator over pairs, or if a message type sent isn’t a subclass ofEventMessage
, or if messages_sent isn’t an iterator over pairs.
-
static
-
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
-
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 ofBaseSimulationObject
-
-
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.
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].Event
s are sorted on their _get_order_time, which provides a pair, (event time, event ‘sub-time’), and is implemented via comparison operations inEvent
. 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.-
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 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
-
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
ofEvent
-
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_objas_list (
bool
, optional) – if set, return theEventQueue
’s values in alist
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 alist
representation if as_list is set- Return type
str
-
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 eventsending_object (
SimulationObject
) – the object sending the eventreceiving_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 anEvent
; it may also carry a payload for theEvent
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.-
simulation_objects
[source]¶ all simulation objects, keyed by their names
- Type
dict
ofSimulationObject
-
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
information about the person who runs the simulation, if provided by the simulation application
- Type
-
class
SimulationReturnValue
[source]¶ Bases:
tuple
SimulationReturnValue(num_events, profile_stats): the value(s) returned by a simulation run
-
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
ofSimulationObject
) – 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
- 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
overSimulationObject
-
static
get_sim_config
(max_time=None, sim_config=None, config_dict=None)[source]¶ External simulate interface
Legal combinations of the three parameters:
Just max_time
Just sim_config, which will contain an entry for max_time
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 simulationsim_config (
SimulationConfig
, optional) – the simulation run’s configurationconfig_dict (
dict
, optional) – a dictionary with keys chosen from the field names inSimulationConfig
; note that config_dict is not a kwargs argument
- Returns
a validated simulation configuration
- Return type
- 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’sconfiguration (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
-
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
-
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 simulationsim_config (
SimulationConfig
, optional) – a simulation run’s configurationconfig_dict (
dict
, optional) – a dictionary with keys chosen from the field names inSimulationConfig
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
- 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
-
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.
-
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
-
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
-
static
active_logger
(logger, level_used)[source]¶ Determine whether the logger will write log messages
- Parameters
logger (
logging2.Logger
) – a loggerlevel_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 messagekwargs (
dict
) – other logging arguments
-
static
-
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.
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
-
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
-
property
-
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_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
ofSimulationEventMessage
-