2.1. wc_sim package¶
2.1.1. Subpackages¶
- 2.1.1.1. wc_sim.config package
- 2.1.1.2. wc_sim.on_ROSS package
- 2.1.1.2.1. Subpackages
- 2.1.1.2.1.1. wc_sim.on_ROSS.try_c_and_python package
- 2.1.1.2.1.1.1. Submodules
- 2.1.1.2.1.1.2. wc_sim.on_ROSS.try_c_and_python.python_call_c module
- 2.1.1.2.1.1.3. wc_sim.on_ROSS.try_c_and_python.python_with_c_callback module
- 2.1.1.2.1.1.4. wc_sim.on_ROSS.try_c_and_python.setup_python_call_c module
- 2.1.1.2.1.1.5. wc_sim.on_ROSS.try_c_and_python.setup_python_with_c_callback module
- 2.1.1.2.1.1.6. Module contents
- 2.1.1.2.1.1. wc_sim.on_ROSS.try_c_and_python package
- 2.1.1.2.2. Module contents
- 2.1.1.2.1. Subpackages
- 2.1.1.3. wc_sim.submodels package
2.1.2. Submodules¶
2.1.3. wc_sim.__main__ module¶
Command line programs for simulating whole-cell models
- Author
Jonathan Karr <karr@mssm.edu>
- Author
Arthur Goldberg <Arthur.Goldberg@mssm.edu>
- Date
2018-05-15
- Copyright
2018, Karr Lab
- License
MIT
-
class
wc_sim.__main__.
App
(label=None, **kw)[source]¶ Bases:
cement.core.foundation.App
Command line application
-
class
Meta
[source]¶ Bases:
object
-
handlers
= [<class 'wc_sim.__main__.BaseController'>, <class 'wc_sim.__main__.SimController'>, <class 'obj_tables.migrate.CementControllers.DataSchemaMigrationConfigController'>, <class 'obj_tables.migrate.CementControllers.MigrateController'>, <class 'obj_tables.migrate.CementControllers.MigrateFileController'>][source]¶
-
-
class
-
class
wc_sim.__main__.
BaseController
(*args, **kw)[source]¶ Bases:
cement.ext.ext_argparse.ArgparseController
Base controller for command line application
-
class
wc_sim.__main__.
SimController
(*args, **kw)[source]¶ Bases:
cement.ext.ext_argparse.ArgparseController
-
class
Meta
[source]¶ Bases:
object
-
arguments
= [(['model_file'], {'type': <class 'str'>, 'help': 'an Excel file containing a model, or a glob matching tab- or comma-delimited files storing a model'}), (['max_time'], {'type': <class 'float'>, 'help': 'maximum time for the simulation (sec)'}), (['--results-dir'], {'type': <class 'str'>, 'help': 'store simulation results in results-dir, including an HDF5 file combining all run results'}), (['--checkpoint-period'], {'type': <class 'float'>, 'default': 10.0, 'help': 'checkpointing period (sec)'}), (['--dfba-time-step'], {'type': <class 'float'>, 'default': 1.0, 'help': 'timestep for dFBA submodel(s) (sec)'}), (['-p', '--profile'], {'default': False, 'action': 'store_true', 'help': "profile the simulation's performance; saved in results-dir if provided, else on stdout"}), (['-m', '--memory_profile'], {'type': <class 'float'>, 'default': 0, 'help': 'event interval in a memory profile of the simulation; saved in results-dir if provided, else on stdout'}), (['-v', '--verbose'], {'default': False, 'action': 'store_true', 'help': 'verbose output'})][source]¶
-
-
class
2.1.4. wc_sim._version module¶
2.1.5. wc_sim.aggregate_distributed_props module¶
Compute distributed properties of multi-algorithmic whole-cell model simulations.
- Author
Arthur Goldberg <Arthur.Goldberg@mssm.edu>
- Date
2017-03-15
- Copyright
2016-2018, Karr Lab
- License
MIT
-
class
wc_sim.aggregate_distributed_props.
AggregateDistributedProps
(name)[source]¶ Bases:
de_sim.simulation_object.SimulationObject
Obtain and provide properties of a multi-algorithmic whole-cell model simulation that require retrieving distributed data.
Computing an aggregate distributed property is driven by the data in a DistributedProperty. The current mechanism determines each distributed property periodically, at an interval provided by the DistributedProperty. It is obtained by requesting values from SimulationObject’s that store parts of the property.
A AggregateDistributedProps manages multiple distributed properties.
Event messages used to obtain properties:
- AggregateProperty: aggregate a property. Events sent by an AggregateDistributedProps to itself,
regulating a distributed property’s periodicity.
- GetHistoricalProperty: request a property. A GetHistoricalProperty message sent to an AggregateDistributedProps
requests the aggregate property. One sent to another object requests the local property.
GiveProperty: a response to a GetHistoricalProperty message, containing the property’s value.
-
properties
[source]¶ map: property.name -> property; properties managed by this AggregateDistributedProps
- Type
dict
-
SENT_MESSAGE_TYPES
= [<class 'de_sim.event_message.AggregateProperty'>, <class 'de_sim.event_message.GiveProperty'>, <class 'de_sim.event_message.GetHistoricalProperty'>][source]¶
-
add_property
(distributed_property)[source]¶ Add a DistributedProperty
- Parameters
distributed_property (
DistributedProperty
) – a DistributedProperty that will be managed by this AggregateDistributedProps
-
event_handlers
= [(<class 'de_sim.event_message.AggregateProperty'>, <function AggregateDistributedProps.handle_aggregate_property_event>), (<class 'de_sim.event_message.GiveProperty'>, <function AggregateDistributedProps.handle_give_property_event>), (<class 'de_sim.event_message.GetHistoricalProperty'>, <function AggregateDistributedProps.handle_get_historical_property_event>)][source]¶
-
get_property
(event)[source]¶ Obtain an event’s property_name
- Parameters
event (
Event
) – an event message about a DistributedProperty
-
handle_aggregate_property_event
(event)[source]¶ Process an event message AggregateProperty
- Parameters
event (
Event
) – an event message about a DistributedProperty
-
handle_get_historical_property_event
(event)[source]¶ Provide an aggregate property value to a requestor
- Parameters
event (
Event
) – an event message about a DistributedProperty- Raises
ValueError – if the DistributedProperty is not available at the requested time
-
handle_give_property_event
(event)[source]¶ Record a property value from a contributor
- Parameters
event (
Event
) – an event message about a DistributedProperty
-
class
wc_sim.aggregate_distributed_props.
DistributedProperty
(name, period, contributors, aggregation_function, **kwargs)[source]¶ Bases:
object
A distributed property
Maintain the state of an aggregate distributed property. The property is a single value, collected periodically from a set of contributing SimulationObject’s.
-
num_periods
[source]¶ the number of periods for which this property has been collected; used by AggregateDistributedProps to create event times that equal integral numbers of periods
- Type
int
-
contributors
[source]¶ SimulationObject’s which must be queried to establish this property
- Type
list
ofSimulationObject
-
value_history
[source]¶ time -> dict: SimulationObject -> value; history of distributed values for this property
- Type
dict
-
aggregate_value_history
[source]¶ time -> value; history of aggregated values for this property
- Type
dict
-
aggregate_values
(time)[source]¶ Aggregate the value of this distributed property at time time
Use this distributed property’s aggregation function (aggregation_function) to perform the aggregation.
- Parameters
time (
float
) – the value’s time
-
get_aggregate_value
(time)[source]¶ Obtain a DistributedProperty’s value from the local value history
- Parameters
time (
float
) – the value’s time- Raises
ValueError – if the DistributedProperty is not available at time
-
record_value
(contributor, time, value)[source]¶ Record a contributed value of a distributed property
Also aggregate the property if values have been received from all contributors at time.
- Parameters
contributor (
float
) – theSimulationObject
contributing the valuetime (
float
) – the value’s timevalue (
float
) – the value from contributor at time
-
request_values
(the_aggregate_distributed_props, time)[source]¶ Request a DistributedProperty’s value from all objects that contribute to the value
- Parameters
the_aggregate_distributed_props (
SimulationObject
) – the AggregateDistributedProps requesting the valuestime (
float
) – the time of the values
- Raises
ValueError – if the DistributedProperty is not available at the requested time
-
-
class
wc_sim.aggregate_distributed_props.
DistributedPropertyFactory
[source]¶ Bases:
object
-
static
make_distributed_property
(property_name, distributed_property_name, period, aggregation_function, **kwargs)[source]¶ Create a partially instantiated DistributedProperty
- Parameters
property_name (
str
) – the property’s name, an ALL CAPS constant in this moduledistributed_property_name (
str
) – the distributed property’s nameperiod (
float
) – the periodicity at which the property is aggregatedaggregation_function (
method
) – static method that aggregates values for this propertykwargs (
dict
) – arguments keyword arguments for aggregation_function
- Raises
ValueError – if the aggregation function is not callable or is unknown
-
static
2.1.6. wc_sim.debug_logs module¶
Setup multialgorithm configuration
- Author
Arthur Goldberg <Arthur.Goldberg@mssm.edu>
- Date
2016-10-03
- Copyright
2016-2018, Karr Lab
- License
MIT
2.1.7. wc_sim.distributed_properties module¶
Define distributed properties of multi-algorithmic DES simulations of whole-cell models
- Author
Arthur Goldberg <Arthur.Goldberg@mssm.edu>
- Date
2017-05-30
- Copyright
2016-2018, Karr Lab
- License
MIT
2.1.8. wc_sim.dynamic_components module¶
Dynamic components of a multialgorithm simulation
- Author
Arthur Goldberg <Arthur.Goldberg@mssm.edu>
- Author
Jonathan Karr <karr@mssm.edu>
- Date
2018-02-07
- Copyright
2017-2019, Karr Lab
- License
MIT
-
class
wc_sim.dynamic_components.
CacheManager
(caching_active=None, cache_invalidation=None)[source]¶ Bases:
object
Represent a RAM cache of DynamicExpression.eval() values
This is a centralized cache for all DynamicExpression values and DynamicCompartment accounted_mass values. Caching may speed up a simulation substantially, or may slow it down. All caching is controlled by the multialgorithm configuration file. The expression_caching attribute determines whether caching is active. The cache_invalidation attribute selects the cache invalidation approach.
The event_based invalidation approach invalidates (flushes) the entire cache at the start of each simulation event which changes species populations, that is, that executes a reaction. Thus, all expressions used during the event must be recalculated. This approach will boost performance if many expressions are used repeatedly during a single event, as occurs when many rate laws that share functions are evaluated.
The reaction_dependency_based invalidation approach invalidates (flushes) individual cache entries that depend on the execution of a particular reaction. The dependencies of DynamicExpressions on species populations and the reactions that alter the populations are computed at initialization.
Under the reaction_dependency_based approach, when a reaction executes all cached values of the DynamicExpressions that depend on the reaction are invalidated. This approach will be superior if a typical reaction execution changes populations of species that are used, directly or indirectly, by only a small fraction of the cached values of the DynamicExpressions.
In addition, since the populations of species modeled by continuous integration algorithms, such as ODEs and dFBA, vary continuously, DynamicExpressions that depend on them must always be invalidated whenever simulation time advances.
-
__contains__
(expression)[source]¶ Indicate whether the cache contains an expression
- Parameters
expression (
object
) – a dynamic expression- Returns
- return
True
if caching is enabled and expression is in the cache, False
otherwise
- return
- Return type
bool
-
cache_stats_table
()[source]¶ Provide the caching stats
- Returns
the caching stats in a table
- Return type
str
-
empty
()[source]¶ Determine whether the cache is empty
- Returns
return
True
if the cache is empty,False
otherwise- Return type
bool
-
flush
(expressions)[source]¶ Invalidate the cache entries for all dynamic expressions in expressions
Missing cache entries are ignored.
- Parameters
expressions (
list
ofobj
) – iterator over dynamic expression instances
-
get
(expression)[source]¶ If caching is enabled, get the value of expression from the cache if it’s stored
Also maintain caching statistics.
- Parameters
expression (
object
) – a dynamic expression- Returns
the cached value of expression
- Return type
object
- Raises
MultialgorithmError – if the cache does not contain an entry for expression
-
invalidate
(expressions=None)[source]¶ Invalidate the cache entries for all dynamic expressions in expressions
Missing cache entries are ignored. Does nothing if caching is not enabled.
- Parameters
expressions (
set
ofobj
) – iterator over dynamic expression instances
-
invalidation_approach
()[source]¶ Provide the invalidation approach
- Returns
the invalidation approach
- Return type
-
set
(expression, value)[source]¶ If caching is enabled, set a value for expression in the cache
- Parameters
expression (
object
) – a dynamic expressionvalue (
object
) – value of the dynamic expression
-
-
class
wc_sim.dynamic_components.
CachingEvents
[source]¶ Bases:
enum.Enum
Types of caching events, used to maintain caching statistics
-
class
wc_sim.dynamic_components.
DynamicCompartment
(dynamic_model, random_state, wc_lang_compartment, species_ids=None)[source]¶ Bases:
wc_sim.dynamic_components.DynamicComponent
A dynamic compartment
A
DynamicCompartment
tracks the dynamic aggregate state of a compartment. ADynamicCompartment
is created for each wc_lang Compartment in a whole-cell model.-
id
[source]¶ id of this
DynamicCompartment
, copied from the wc_lang Compartment- Type
str
-
biological_type
[source]¶ biological type of this
DynamicCompartment
, copied from the Compartment- Type
pronto.term.Term
-
physical_type
[source]¶ physical type of this
DynamicCompartment
, copied from the Compartment- Type
pronto.term.Term
-
init_volume
[source]¶ initial volume, sampled from the distribution specified in the wc_lang model
- Type
float
-
init_mass
[source]¶ initial mass, including the mass not accounted for by explicit species
- Type
float
-
init_density
[source]¶ the initial density of this
DynamicCompartment
, as specified by the model; this is the constant density of the compartment- Type
float
-
accounted_fraction
[source]¶ the fraction of the initial mass or density accounted for by initial species; assumed to be constant throughout a dynamical model
- Type
float
-
species_ids
[source]¶ the IDs of the species stored in this
DynamicCompartment
; if None, use the IDs of all species in species_population- Type
list
ofstr
-
__str__
()[source]¶ Provide a string representation of this
DynamicCompartment
- Returns
a string representation of this compartment at the current simulation time
- Return type
str
-
accounted_mass
(time=None)[source]¶ Provide the total current mass of all species in this
DynamicCompartment
- Parameters
time (
Rational
, optional) – the current simulation time- Returns
the total current mass of all species (g)
- Return type
float
-
accounted_volume
(time=None)[source]¶ Provide the current volume occupied by all species in this
DynamicCompartment
- Parameters
time (
Rational
, optional) – the current simulation time- Returns
the current volume of all species (l)
- Return type
float
-
eval
(time=None)[source]¶ Provide the mass of this
DynamicCompartment
- Parameters
time (
Rational
, optional) – the current simulation time- Returns
this compartment’s current mass (g)
- Return type
float
-
fold_change_total_mass
(time=None)[source]¶ Provide the fold change of the total mass of this
DynamicCompartment
- Parameters
time (
Rational
, optional) – the current simulation time- Returns
the fold change of the total mass of this compartment
- Return type
float
-
fold_change_total_volume
(time=None)[source]¶ Provide the fold change of the total volume of this
DynamicCompartment
- Parameters
time (
Rational
, optional) – the current simulation time- Returns
the fold change of the total volume of this compartment
- Return type
float
-
initialize_mass_and_density
(species_population)[source]¶ Initialize the species populations and the mass accounted for by species.
Also initialize the fraction of density accounted for by species, self.accounted_fraction.
- Parameters
species_population (
LocalSpeciesPopulation
) – the simulation’s species population store- Raises
MultialgorithmError – if accounted_fraction == 0 or if MAX_ALLOWED_INIT_ACCOUNTED_FRACTION < accounted_fraction
-
mass
(time=None)[source]¶ Provide the total current mass of this
DynamicCompartment
This mass includes the mass not accounted for by explicit species, as determined by the initial specified density, specified volume, and mass accounted for by species.
- Parameters
time (
Rational
, optional) – the current simulation time- Returns
this compartment’s total current mass (g)
- Return type
float
-
volume
(time=None)[source]¶ Provide the current volume of this
DynamicCompartment
This volume includes the volume not accounted for by explicit species, as determined by the ratio of the specified initial density to the initial density accounted for by species.
- Parameters
time (
Rational
, optional) – the current simulation time- Returns
this compartment’s current volume (l)
- Return type
float
-
-
class
wc_sim.dynamic_components.
DynamicComponent
(dynamic_model, local_species_population, wc_lang_model)[source]¶ Bases:
object
Component of a simulation
-
local_species_population
[source]¶ the simulation’s species population store
- Type
LocalSpeciesPopulation
-
__str__
()[source]¶ Provide a readable representation of this DynamicComponent
- Returns
a readable representation of this DynamicComponent
- Return type
str
-
static
get_dynamic_component
(model_type, id)[source]¶ Get a simulation’s dynamic component
- Parameters
model_type (
type
) – the subclass of DynamicComponent (or obj_tables.Model) being retrievedid (
str
) – the dynamic component’s id
- Returns
the dynamic component
- Return type
- Raises
MultialgorithmError – if the dynamic component cannot be found
-
static
get_dynamic_model_type
(model_type)[source]¶ Get a simulation’s dynamic component type
Obtain a dynamic component type from a corresponding wc_lang Model type, instance or string name.
- Parameters
model_type (
Object
) – a wc_lang Model type represented by a subclass of obj_tables.Model, an instance of obj_tables.Model, or a string name for a obj_tables.Model- Returns
the dynamic component
- Return type
type
- Raises
MultialgorithmError – if the corresponding dynamic component type cannot be determined
-
-
class
wc_sim.dynamic_components.
DynamicDfbaObjective
(*args)[source]¶ Bases:
wc_sim.dynamic_components.DynamicExpression
The dynamic representation of a
wc_lang.DfbaObjective
-
class
wc_sim.dynamic_components.
DynamicExpression
(dynamic_model, local_species_population, wc_lang_model, wc_lang_expression)[source]¶ Bases:
wc_sim.dynamic_components.DynamicComponent
Simulation representation of a mathematical expression, based on
ParsedExpression
-
wc_sim_tokens
[source]¶ a tokenized, compressed representation of expression
- Type
list
ofWcSimToken
-
expr_substrings
[source]¶ strings which are joined to form the string which is ‘eval’ed
- Type
list
ofstr
-
NON_LANG_OBJ_ID_TOKENS
= {<ObjTablesTokenCodes.math_func_id: 2>, <ObjTablesTokenCodes.number: 3>, <ObjTablesTokenCodes.op: 4>, <ObjTablesTokenCodes.other: 5>}[source]¶
-
__str__
()[source]¶ Provide a readable representation of this DynamicExpression
- Returns
a readable representation of this DynamicExpression
- Return type
str
-
eval
(time)[source]¶ Evaluate this mathematical expression
- Approach:
Replace references to related Models in self.wc_sim_tokens with their values
Join the elements of self.wc_sim_tokens into a Python expression
eval the Python expression
- Parameters
time (
float
) – the simulation time at which the expression should be evaluated- Returns
the value of this
DynamicExpression
at time time- Return type
float
orbool
- Raises
MultialgorithmError – if Python eval raises an exception
-
prepare
()[source]¶ Prepare this dynamic expression for simulation
Because they refer to each other, all
DynamicExpression
s must be created before any of them are prepared.- Raises
MultialgorithmError – if a Python function used in wc_lang_expression does not exist
-
-
class
wc_sim.dynamic_components.
DynamicFunction
(*args)[source]¶ Bases:
wc_sim.dynamic_components.DynamicExpression
The dynamic representation of a
wc_lang.Function
-
class
wc_sim.dynamic_components.
DynamicModel
(model, species_population, dynamic_compartments)[source]¶ Bases:
object
Represent and access the dynamics of a whole-cell model simulation
A DynamicModel provides access to dynamical components of the simulation, and determines aggregate properties that are not provided by other, more specific, dynamical components like species populations, submodels, and dynamic compartments.
-
dynamic_compartments
[source]¶ map from compartment ID to
DynamicCompartment
; the simulation’sDynamicCompartment
s, one for each compartment in model- Type
dict
-
dynamic_submodels
[source]¶ the simulation’s dynamic submodels, indexed by their ids
- Type
dict
of DynamicSubmodel
-
dynamic_species
[source]¶ the simulation’s dynamic species, indexed by their ids
- Type
dict
of DynamicSpecies
-
dynamic_parameters
[source]¶ the simulation’s parameters, indexed by their ids
- Type
dict
of DynamicParameter
-
dynamic_observables
[source]¶ the simulation’s dynamic observables, indexed by their ids
- Type
dict
of DynamicObservable
-
dynamic_functions
[source]¶ the simulation’s dynamic functions, indexed by their ids
- Type
dict
of DynamicFunction
-
dynamic_stop_conditions
[source]¶ the simulation’s stop conditions, indexed by their ids
- Type
dict
of DynamicStopCondition
-
dynamic_rate_laws
[source]¶ the simulation’s rate laws, indexed by their ids
- Type
dict
of DynamicRateLaw
-
dynamic_dfba_objectives
[source]¶ the simulation’s dFBA Objective, indexed by their ids
- Type
dict
of DynamicDfbaObjective
-
cache_manager
[source]¶ a cache for potentially expensive expression evaluations that get repeated
- Type
-
rxn_expression_dependencies
[source]¶ map from reactions to lists of expressions whose values depend on species with non-zero stoichiometry in the reaction
- Type
dict
-
# TODO
OPTIMIZE DFBA CACHING: describe dFBA caching optimization
- Type
APG
-
continuous_rxn_dependencies
[source]¶ map from ids of continuous submodels to sets identifying expressions whose values depend on species with non-zero stoichiometry in reaction(s) modeled by the submodel
- Type
dict
-
cell_accounted_mass
()[source]¶ Provide the total current mass of all species in the cell
Sum the current mass of all species in cellular
DynamicCompartment
s.- Returns
the current mass of all species in the cell (g)
- Return type
float
-
cell_accounted_volume
()[source]¶ Provide the current volume occupied by all species in the cell
Sum the current volume occupied by all species in cellular
DynamicCompartment
s.- Returns
the current volume occupied by all species in the cell (l)
- Return type
float
-
cell_growth
()[source]¶ Report the cell’s growth in cell/s, relative to the cell’s initial volume
- Returns
growth in cell/s, relative to the cell’s initial volume
- Return type
float
-
cell_mass
()[source]¶ Provide the cell’s current mass
Sum the mass of all cellular
DynamicCompartment
s.- Returns
the cell’s current mass (g)
- Return type
float
-
cell_volume
()[source]¶ Provide the cell’s current volume
Sum the volume of all cellular
DynamicCompartment
s.- Returns
the cell’s current volume (l)
- Return type
float
-
continuous_reaction_dependencies
()[source]¶ Get the expressions that depend on species used by reactions modeled by continuous submodels
Caching uses these dependencies to determine the expressions that should be invalidated when species populations change or time advances.
- Returns
- map from ids of continuous submodels to lists of expressions
whose values depend on species with non-zero stoichiometry in reaction(s) modeled by the submodel
- Return type
(
dict
)
-
continuous_submodel_flush_after_populations_change
(dynamic_submodel_id)[source]¶ Invalidate cache entries that depend on reactions modeled by a continuous submodel
Only used when caching is enabled. Runs when a continuous submodel advances time or changes species populations.
- Parameters
dynamic_submodel_id (
str
) – the id of the continuous submodel that’s running
-
eval_dynamic_functions
(time, functions_to_eval=None)[source]¶ Evaluate some dynamic functions at time time
- Parameters
time (
float
) – the simulation timefunctions_to_eval (
list
ofstr
, optional) – if provided, ids of the functions to evaluate; otherwise, evaluate all functions
- Returns
- map from the IDs of dynamic functions in functions_to_eval to their
values at simulation time time
- Return type
dict
-
eval_dynamic_observables
(time, observables_to_eval=None)[source]¶ Evaluate some dynamic observables at time time
- Parameters
time (
float
) – the simulation timeobservables_to_eval (
list
ofstr
, optional) – if provided, ids of the observables to evaluate; otherwise, evaluate all observables
- Returns
- map from the IDs of dynamic observables in observables_to_eval to their
values at simulation time time
- Return type
dict
-
eval_dynamic_rate_laws
(time)[source]¶ Evaluate all dynamic rate laws at time time
Does not consider whether a rate law’s reaction is enabled.
- Parameters
time (
float
) – the simulation time- Returns
map from the IDs of dynamic rate laws to their values at simulation time time
- Return type
dict
-
flush_after_reaction
(reaction)[source]¶ If caching is enabled, invalidate cache entries when time advances and a reaction executes
- Parameters
reaction (
Reaction
) – the reaction that executed
-
flush_compartment_masses
()[source]¶ If caching is enabled, invalidate cache entries for compartmental masses
Run whenever populations change or time advances
-
get_aggregate_state
()[source]¶ Report the cell’s aggregate state
- Returns
the cell’s aggregate state
- Return type
dict
-
get_num_submodels
()[source]¶ Provide the number of submodels
- Returns
the number of submodels
- Return type
int
-
get_reaction_fluxes
()[source]¶ Obtain the most recent flux for all reactions modeled by dFBA submodels
- Returns
map from the IDs of reactions modeled by dFBA submodels to their most recent fluxes
- Return type
dict
-
get_species_count_array
(now)[source]¶ Map current species counts into an numpy array
- Parameters
now (
float
) – the current simulation time- Returns
numpy array, #species x # compartments, containing count of species in compartment
-
get_stop_condition
()[source]¶ Provide a simulation’s stop condition
A simulation’s stop condition is constructed as a logical ‘or’ of all
StopConditions
in a model.- Returns
- a function which computes the logical ‘or’ of all
StopConditions
, or None if no stop condition are defined
- a function which computes the logical ‘or’ of all
- Return type
function
-
obtain_dependencies
(model)[source]¶ Obtain the dependencies of expressions on reactions in a WC Lang model
An expression depends on a reaction if the expression uses any species whose population changes when the reaction executes, or the expression uses an expression that depends on the reaction.
When caching is active, these dependencies identify which cached expressions to invalidate. They’re also used by the Next Reaction Method to determine which rate laws must be evaluated after a reaction executes.
obtain_dependencies is memory and compute intensive because it builds and walks an in-memory DAG that represents the dependency relationships among the WC-Lang models used by a whole-cell model. If a simulation fails with the error “killed” and no other information, then it is probably running on a system or in a container which does not have sufficient memory to complete this function. Try running on a system with more memory, simulating a smaller model, or disabling caching in wc_sim.cfg.
- Parameters
model (
Model
) – the description of the whole-cell model in wc_lang- Returns
- the dependencies of expressions on reactions, which maps each
reaction to a list of expressions
- Return type
dict
oflist
-
-
class
wc_sim.dynamic_components.
DynamicObservable
(*args)[source]¶ Bases:
wc_sim.dynamic_components.DynamicExpression
The dynamic representation of an
wc_lang.Observable
-
class
wc_sim.dynamic_components.
DynamicParameter
(dynamic_model, local_species_population, wc_lang_model, value)[source]¶ Bases:
wc_sim.dynamic_components.DynamicComponent
The dynamic representation of a
wc_lang.Parameter
-
class
wc_sim.dynamic_components.
DynamicRateLaw
(*args)[source]¶ Bases:
wc_sim.dynamic_components.DynamicExpression
The dynamic representation of a
wc_lang.RateLaw
-
class
wc_sim.dynamic_components.
DynamicSpecies
(dynamic_model, local_species_population, wc_lang_model)[source]¶ Bases:
wc_sim.dynamic_components.DynamicComponent
The dynamic representation of a
wc_lang.Species
-
class
wc_sim.dynamic_components.
DynamicStopCondition
(*args)[source]¶ Bases:
wc_sim.dynamic_components.DynamicExpression
The dynamic representation of a
wc_lang.StopCondition
-
class
wc_sim.dynamic_components.
SimTokCodes
[source]¶ Bases:
int
,wc_utils.util.enumerate.CaseInsensitiveEnum
Token codes used in WcSimTokens
2.1.9. wc_sim.future_multialgorithm_simulation module¶
Future improvements to wc_sim/multialgorithm_simulation.py; useful later
- Author
Arthur Goldberg <Arthur.Goldberg@mssm.edu>
- Date
2019-10-02
- Copyright
2016-2019, Karr Lab
- License
MIT
-
class
wc_sim.future_multialgorithm_simulation.
MultialgorithmSimulation
(model, args, shared_species_store_name='SHARED_SPECIES_STORE')[source]¶ Bases:
object
Initialize a multialgorithm simulation from a language model and run-time parameters
the name for the shared species store
- Type
str
-
species_pop_objs
[source]¶ shared species populations used by SimulationObject’s; not currently used
- Type
dict
of SpeciesPopSimObject
-
private_species
[source]¶ map from DynamicSubmodel to a set of the species modeled by only the submodel; not currently used
- Type
dict
of set
the shared species
- Type
set
-
create_access_species_pop
(lang_submodel)[source]¶ Create a LocalSpeciesPopulations for a submodel and wrap it in an AccessSpeciesPopulations
- Parameters
lang_submodel (
Submodel
) – description of a submodel- Returns
an AccessSpeciesPopulations for the lang_submodel
- Return type
AccessSpeciesPopulations
Create the shared species object.
- Returns
dict mapping id to SpeciesPopSimObject objects for the simulation
- Return type
dict
2.1.10. wc_sim.message_types module¶
A static set of message types and their content for multialgorithmic whole-cell simulations
- Author
Arthur Goldberg <Arthur.Goldberg@mssm.edu>
- Date
2016-06-10
- Copyright
2016-2018, Karr Lab
- License
MIT
Event message types are subclasses of EventMessage. Every simulation event message contains a typed EventMessage.
- Declare
For each message type which has an message, a class that represents the body
Event message types, bodies and reply message:
- AdjustPopulationByDiscreteSubmodel
a discrete (stochastic) model increases or decreases some species copy numbers: data: dict: species_name -> population_change; no reply message
- AdjustPopulationByContinuousSubmodel
a continuous model integrated by a time-step simulation increases or decreases some species copy numbers: data: dict: species_name -> (population_change, population_change_rate); no reply message
- GetPopulation
set of species whose population is needed; data: set: species_name(s)
- GivePopulation
response to GetPopulation; dict: species_name -> population
Define a class that stores the body of each message type. This avoids confusing the structure of a message body. These classes should be used by all message senders and receivers. It is enforced by checking class names against message body types.
For this sequential simulator, event messages are stored as a copy of or reference to sender’s data structure # TODO(Arthur): for parallel simulation, serialize and deserialize message bodies, perhaps with Pickle
-
class
wc_sim.message_types.
ContinuousChange
[source]¶ Bases:
wc_sim.message_types.ContinuousChange_namedtuple
A namedtuple to be used in the body of an AdjustPopulationByContinuousSubmodel message
2.1.11. wc_sim.metadata module¶
Store metadata about a WC simulation run
- Author
Arthur Goldberg <Arthur.Goldberg@mssm.edu>
- Date
2020-03-29
- Copyright
2020, Karr Lab
- License
MIT
-
class
wc_sim.metadata.
WCSimulationMetadata
(wc_sim_config: wc_sim.sim_config.WCSimulationConfig, wc_simulator_repo: wc_utils.util.git.RepositoryMetadata = None, wc_model_repo: wc_utils.util.git.RepositoryMetadata = None)[source]¶ Bases:
wc_utils.util.misc.EnhancedDataClass
Represent a WC simulation’s metatdata
-
wc_simulator_repo
[source]¶ Git repository repo metadata about the WC simulator
- Type
RepositoryMetadata
, optional
-
wc_model_repo
[source]¶ Git repository repo metadata about the WC repo storing the WC model being simulated
- Type
RepositoryMetadata
, optional
-
semantically_equal
(other)[source]¶ Are two instances semantically equal with respect to a simulation’s predictions?
Overrides semantically_equal in
EnhancedDataClass
. Ignore verbose, changes, and perturbations. verbose does not influence a simulation’s predictions and changes and perturbations are not currently used.- Parameters
other (
Object
) – other object- Returns
True
if other is semantically equal to self,False
otherwise- Return type
bool
-
set_wc_model_repo
(model_path)[source]¶ Set the value of wc_model_repo if it can be obtained from model_path
- Parameters
model_path (
str
) – path to a file in the model’s Git repository
-
wc_model_repo
= None[source]
-
wc_simulator_repo
= None[source]
-
2.1.12. wc_sim.model_utilities module¶
A set of static methods that help prepare Models for simulation.
- Author
Arthur Goldberg <Arthur.Goldberg@mssm.edu>
- Date
2017-04-10
- Copyright
2016-2018, Karr Lab
- License
MIT
-
class
wc_sim.model_utilities.
ModelUtilities
[source]¶ Bases:
object
A set of static methods that help prepare Models for simulation.
-
static
find_private_species
(model, return_ids=False)[source]¶ Identify a model’s species that are private to a submodel.
Find the species in a model that are modeled privately by a single submodel. This analysis relies on the observation that a submodel can only access species that participate in reactions that occurs in the submodel. (It might not access some of these species too, if they’re initialized with concentration=0 and the reactions in which they participate never fire. However, that cannot be determined statically.)
- Parameters
model (
Model
) – a Model instancereturn_ids (
boolean
, optional) – if set, return object ids rather than references
- Returns
- a dict that maps each submodel to a set containing the species
modeled by only the submodel.
- Return type
dict
Identify the model’s species that are shared by multiple submodels.
Find the species in a model that are modeled by multiple submodels.
- Parameters
model (
Model
) – a Model instancereturn_ids (
boolean
, optional) – if set, return object ids rather than references
- Returns
a set containing the shared species.
- Return type
set
-
static
get_species_types
(species_ids)[source]¶ Get the specie types from an iterator that provides specie ids
Deterministic – that is, given a sequence of specie ids provided by species_ids will always return the same list of specie type ids
- Parameters
species_ids (
iterator
) – an iterator that provides specie ids- Returns
an iterator over the specie type ids in species_ids
- Return type
list
-
static
non_neg_normal_sample
(random_state, mean, std, max_iters=100)[source]¶ Obtain a non-negative sample from a normal distribution
The distribution returned is 0 for x < 0 and normal for 0 <= x
- Parameters
random_state (
numpy.random.RandomState
) – a random statemean (
float
) – mean of the normal dist. to samplestd (
float
) – std of the normal dist. to samplemax_iters (
int
, optional) – maximum number of draws of the true normal distribution
- Returns
a normal sample that is not negative
- Return type
float
- Raises
ValueError – if taking max_iters normal sample does not obtain one that is not negative
-
static
parse_species_id
(species_id)[source]¶ Fast species id parser
- Parameters
species_id (
str
) – species identifier- Returns
species type id, compartment id
- Return type
tuple
of (str
,str
)- Raises
ValueError – if species_id is not of the form species_type_id[compartment_id]
-
static
sample_copy_num_from_concentration
(species, volume, random_state)[source]¶ Provide the initial copy number of species from its specified value
The initial copy number is sampled from a specified distribution whose mean is given in molecules or molarity.
- Parameters
species (
Species
) – a Species instance; the species.concentration.units must be an instance of unit_registry.Unit and in species.concentration.units.choicesvolume (
float
) – volume for calculating copy numbersrandom_state (
RandomState
) – random state for sampling from distribution of initial concentrations
- Returns
the species’ copy number
- Return type
float
- Raises
ValueError – if the concentration uses illegal or unsupported units
-
static
2.1.13. wc_sim.multialgorithm_checkpointing module¶
Take periodic checkpoints in a multialgorithmic simulation
- Author
Arthur Goldberg <Arthur.Goldberg@mssm.edu>
- Author
Jonathan Karr <karr@mssm.edu>
- Date
2018-05-08
- Copyright
2018, Karr Lab
- License
MIT
-
class
wc_sim.multialgorithm_checkpointing.
AccessState
(local_species_population, dynamic_model, multialgorithm_simulation)[source]¶ Bases:
de_sim.simulation_checkpoint_object.AccessStateObjectInterface
Obtain checkpoints of a multialgorithm simulation’s biological state and random state
-
local_species_population
[source]¶ provide a simulation’s species populations
- Type
LocalSpeciesPopulation
-
get_checkpoint_state
(time)[source]¶ Obtain a checkpoint of the biological state
- Parameters
time (
float
) – the simulation time of the checkpoing being created- Returns
- dictionaries containing the simulation’s state:
population has the simulation’s species populations, observables contains all of its observables, functions contains all of its functions, rate_laws contains the values of all of its rate laws, dfba_reaction_fluxes contains the most recent fluxes of all dFBA reactions, and aggregate_state contains its aggregrate compartment states.
- Return type
dict
of dict
-
-
class
wc_sim.multialgorithm_checkpointing.
MultialgorithmCheckpoint
(time, state, random_state)[source]¶ Bases:
de_sim.checkpoint.Checkpoint
Checkpoint class that holds multialgorithmic checkpoints
-
class
wc_sim.multialgorithm_checkpointing.
MultialgorithmicCheckpointingSimObj
(name, checkpoint_period, checkpoint_dir, local_species_population, dynamic_model, multialgorithm_simulation)[source]¶ Bases:
de_sim.simulation_checkpoint_object.CheckpointSimulationObject
A checkpointing simulation object for a multialgorithmic simulation
2.1.14. wc_sim.multialgorithm_errors module¶
Define multi-algoritmic simulation errors.
- Author
Arthur Goldberg <Arthur.Goldberg@mssm.edu>
- Date
2016-12-12
- Copyright
2016-2018, Karr Lab
- License
MIT
-
exception
wc_sim.multialgorithm_errors.
DynamicFrozenSimulationError
(time, message=None)[source]¶ Bases:
wc_sim.multialgorithm_errors.DynamicMultialgorithmError
Exception raised by an SSA submodel when it is the only submodel and total propensities == 0
A simulation in this state cannot progress.
-
exception
wc_sim.multialgorithm_errors.
DynamicMultialgorithmError
(time, message=None)[source]¶ Bases:
wc_sim.multialgorithm_errors.Error
Exception raised for errors in package wc_sim that occur during a simulation
-
exception
wc_sim.multialgorithm_errors.
DynamicNegativePopulationError
(time, method, species, last_population, population_decrease, delta_time=None)[source]¶ Bases:
wc_sim.multialgorithm_errors.DynamicMultialgorithmError
Exception raised when a negative species population is predicted
The sum of last_population and population_decrease equals the predicted negative population.
-
exception
wc_sim.multialgorithm_errors.
DynamicSpeciesPopulationError
(time, message=None)[source]¶ Bases:
wc_sim.multialgorithm_errors.DynamicMultialgorithmError
Exception raised when species population management encounters a problem during a simulation
-
exception
wc_sim.multialgorithm_errors.
Error
(message=None)[source]¶ Bases:
Exception
Base class for exceptions involving multi-algoritmic simulation
-
exception
wc_sim.multialgorithm_errors.
MultialgorithmError
(message=None)[source]¶ Bases:
wc_sim.multialgorithm_errors.Error
Exception raised for errors in package wc_sim
-
exception
wc_sim.multialgorithm_errors.
MultialgorithmWarning
[source]¶ Bases:
UserWarning
wc_sim multialgorithm warning
-
exception
wc_sim.multialgorithm_errors.
SpeciesPopulationError
(message=None)[source]¶ Bases:
wc_sim.multialgorithm_errors.Error
Exception raised when species population management encounters a problem
2.1.15. wc_sim.multialgorithm_simulation module¶
Initialize a multialgorithm simulation from a language model and run-time parameters
- Author
Arthur Goldberg <Arthur.Goldberg@mssm.edu>
- Date
2017-02-07
- Copyright
2016-2019, Karr Lab
- License
MIT
-
class
wc_sim.multialgorithm_simulation.
MultialgorithmSimulation
(model, wc_sim_config, options=None)[source]¶ Bases:
object
Initialize a multialgorithm simulation from a language model and run-time parameters
Create a simulation from a model described by a wc_lang Model.
-
args
[source]¶ parameters for the simulation; if results_dir is an entry in args, then checkpoint_period must also be included
- Type
dict
-
checkpointing_sim_obj
[source]¶ the checkpointing object; None if absent
- Type
MultialgorithmicCheckpointingSimObj
-
init_populations
[source]¶ the initial populations of species, derived from the specification in model
- Type
dict
from species id to population
-
local_species_population
[source]¶ a shared species population for the multialgorithm simulation
- Type
LocalSpeciesPopulation
-
temp_dynamic_compartments
[source]¶ the simulation’s DynamicCompartment`s, one for each compartment in `model; temporary attribute used until
DynamicModel
is made- Type
dict
-
__str__
()[source]¶ Provide a readable representation of this MultialgorithmSimulation
- Returns
a readable representation of this MultialgorithmSimulation
- Return type
str
-
build_simulation
(prepare_model=True)[source]¶ Prepare a multialgorithm simulation
- Parameters
prepare_model (
boolean
, optional) – if set, prepare the model; unset as needed testing- Returns
- an initialized simulation and its
dynamic model
- Return type
tuple
of (Simulator
,DynamicModel
)
-
create_dynamic_submodels
()[source]¶ Create dynamic submodels that access shared species
- Returns
list of the simulation’s DynamicSubmodels
- Return type
list
- Raises
MultialgorithmError – if a submodel cannot be created
-
create_multialgorithm_checkpointing
(checkpoints_dir, checkpoint_period)[source]¶ Create a multialgorithm checkpointing object for this simulation
- Parameters
checkpoints_dir (
str
) – the directory that will contain checkpointscheckpoint_period (
float
) – interval between checkpoints, in simulated seconds
- Returns
the checkpointing object
- Return type
MultialgorithmicCheckpointingSimObj
-
get_dynamic_compartments
(submodel)[source]¶ Get the
DynamicCompartment
s for Submodel submodel- Parameters
submodel (
Submodel
) – the wc_lang submodel being compiled into a DynamicSubmodel- Returns
- mapping: compartment id -> DynamicCompartment for the
DynamicCompartment`(s) that a new `DynamicSubmodel needs
- Return type
dict
-
init_species_pop_from_distribution
()[source]¶ Initialize the species populations
Uses the dynamic compartment volume previously sampled from its distribution
-
make_local_species_population
(retain_history=True)[source]¶ Create a
LocalSpeciesPopulation
that contains all the species in a modelInstantiate a
LocalSpeciesPopulation
as the centralized store of a model’s species population.- Parameters
retain_history (
bool
, optional) – whether theLocalSpeciesPopulation
should retain species population history- Returns
a
LocalSpeciesPopulation
for the model- Return type
LocalSpeciesPopulation
-
molecular_weights_for_species
(species=None)[source]¶ Obtain the molecular weights for species with specified ids
A weight of NaN is returned for species whose species_types do not have a structure.
- Parameters
species (
iterator
, optional) – an iterator over species ids; if not initialized, obtain weights for all species in the model- Returns
species_type_id -> molecular weight
- Return type
dict
-
prepare
()[source]¶ Prepare and validate the model
- Raises
MultialgorithmError – if the model is invalid
-
prepare_skipped_submodels
()[source]¶ Prepare the IDs of the submodels that will not be run
- Returns
the IDs of submodels that will not run
- Return type
set
ofstr
-
2.1.16. wc_sim.run_results module¶
Store and retrieve combined results of a multialgorithmic simulation run
- Author
Arthur Goldberg <Arthur.Goldberg@mssm.edu>
- Author
Jonathan Karr <karr@mssm.edu>
- Date
2018-05-20
- Copyright
2018-2019, Karr Lab
- License
MIT
-
class
wc_sim.run_results.
MakeDataFrame
(times, columns)[source]¶ Bases:
object
Efficiently make a Pandas dataframe that contains a 2D numpy.ndarray
-
class
wc_sim.run_results.
RunResults
(results_dir)[source]¶ Bases:
object
Store and retrieve combined results of a multialgorithmic simulation run
HDF5 uses attributes to store “self-describing” data. The official HDF5 way to store metadata is in the attribute field attached to each data object. Since a simulation’s metadata applies to all
RunResults
components, it is stored in a metadata Group object in the HDF5 file.-
results_dir
[source]¶ pathname of a directory containing a simulation run’s checkpoints and/or HDF5 file storing the combined results
- Type
str
-
COMPONENTS
= {'aggregate_states', 'dfba_reaction_fluxes', 'functions', 'observables', 'populations', 'random_states', 'rate_laws'}[source]¶
-
COMPUTED_COMPONENTS
= {'masses': <function RunResults.get_masses>, 'volumes': <function RunResults.get_volumes>}[source]¶
-
METADATA_CLASS_TO_NAME
= {<class 'de_sim.simulation_metadata.SimulationMetadata'>: 'de_sim_metadata', <class 'wc_sim.metadata.WCSimulationMetadata'>: 'wc_sim_metadata'}[source]¶
-
aggregate_state_properties
()[source]¶ Get the names of the aggregate state properties
- Returns
the names of the aggregate state properties in a RunResults
- Return type
set
-
convert_checkpoints
()[source]¶ Convert the data in saved checkpoints into pandas dataframes for loading into hdf
- Returns
- dataframes of the components of a simulation checkpoint history
population_df, observables_df, functions_df, rate_laws_df, dfba_reaction_fluxes_df, aggregate_states_df, random_states_s
- Return type
tuple
of pandas objects
-
convert_metadata
(metadata_class)[source]¶ Convert the saved simulation metadata into HDF5 attributes on a metadata Group
- Parameters
metadata_class (
EnhancedDataClass
) – the class that stored the metadata
-
static
dataframes_are_close
(df1, df2, rtol=None, atol=None)[source]¶ Indicate whether two Pandas DataFrames that contain floats are almost equal
- Args:
df1 (
pandas.DataFrame
): one DataFrame df2 (pandas.DataFrame
): another DataFrame rtol (float
, optional): relative tolerance; if provided, passed to numpy.allclose()which compares DataFrame values
- atol (
float
, optional): absolute tolerance, if provided, passed to numpy.allclose() which compares DataFrame values
- atol (
- Returns:
bool
:True
if theDataFrame
s are semantically equal, i.e.,if rows and columns are identical and values are all close
- Raises
ValueError – if either argument is not a
pandas.DataFrame
-
get
(component)[source]¶ Provide the specified component
- Parameters
component (
str
) – the name of the component to return- Returns
- an object containing a component of this RunResults, as specified by component;
simulation time series data are
pandas.DataFrame
or pandas.Series instances; simulation metadata aredict
instances.
- Return type
object
- Raises
MultialgorithmError – if component is not an element of RunResults.COMPONENTS or RunResults.COMPUTED_COMPONENTS
-
get_concentrations
(compartment_id=None)[source]¶ Get species concentrations at checkpoint times
- Parameters
compartment_id (
str
, optional) – if provided, obtain concentrations for species in compartment_id; otherwise, return the concentrations of all species- Returns
- the concentrations of species at checkpoint times, filtered
by compartment_id if it’s provided
- Return type
pandas.DataFrame
- Raises
MultialgorithmError – if no species are in the compartment
-
get_masses
(compartment_id=None)[source]¶ Get the compartment masses at checkpoint times
- Parameters
compartment_id (
str
, optional) – if provided, return the compartment’s masses; otherwise, return the masses of all compartments- Returns
the masses of a compartment or all compartments at all checkpoint times
- Return type
pandas.DataFrame
-
get_metadata
()[source]¶ Get simulation metadata from the HDF5 file
- Returns
- a nested dictionary of metadata corresponding to the attributes in
SimulationMetadata
andWCSimulationMetadata
- Return type
dict
-
get_properties
(compartment_id, property=None)[source]¶ Get a compartment’s aggregate state properties or property at checkpoint times
- Parameters
compartment_id (
str
) – the id of the compartmentproperty (
str
, optional) – if provided, the property to return; otherwise, return all properties
- Returns
a compartment’s properties or property at all checkpoint times
- Return type
pandas.DataFrame
-
get_times
()[source]¶ Get simulation times of results data
- Returns
simulation times of results data
- Return type
numpy.ndarray
-
get_volumes
(compartment_id=None)[source]¶ Get the compartment volumes at checkpoint times
- Parameters
compartment_id (
str
, optional) – if provided, return the compartment’s volumes; otherwise, return the volumes of all compartments- Returns
the volumes of one compartment or all compartments at all checkpoint times
- Return type
pandas.DataFrame
-
semantically_equal
(other, debug=False)[source]¶ Are the predictions and metadata in two
RunResults
objects semantically equal?Uses numpy.allclose() to compare predictions. Uses semantically_equal to ignore semantically insignificant metadata, such as the timestamp of a simulation’s execution or its runtime. Compares all RunResults.COMPONENTS except ‘random_states’, which is ignored.
- Parameters
other (
Object
) – other objectdebug (
bool
) – whether to output debugging info when the objects are not semantically equal
- Returns
True
if self and other are semantically equal,False
otherwise- Return type
bool
-
2.1.17. wc_sim.sim_config module¶
Classes to represent WC simulation configurations and import/export configurations to/from SED-ML
- Author
Jonathan Karr <karr@mssm.edu>
- Author
Arthur Goldberg <Arthur.Goldberg@mssm.edu>
- Date
2017-08-19
- Copyright
2016-2018, Karr Lab
- License
MIT
-
class
wc_sim.sim_config.
Perturbation
(change, start_time, end_time=nan)[source]¶ Bases:
object
Represents a perturbation to simulate:
Change: desired value for a target (state/parameter)
Start time: time in seconds when the target should be perturbed
End time: optional, time in seconds when the perturbation should end. That is, the target will be held to the desired value from the start to the end time.
-
class
wc_sim.sim_config.
SedMl
[source]¶ Bases:
object
Reads and writes simulation configurations to/from SED-ML.
-
static
read
(file_name)[source]¶ Imports simulation configuration from SED-ML file
- Parameters
file_name (
str
) – path to SED-ML file from which to import simulation configuration- Returns
simulation configuration
- Return type
-
static
write
(cfg, file_name)[source]¶ Exports simulation configuration to SED-ML file
- Parameters
cfg (
WCSimulationConfig
) – simulation configurationfile_name (
str
) – path to write SED-ML file
-
static
-
class
wc_sim.sim_config.
WCSimulationConfig
(de_simulation_config: object, random_seed: int = None, ode_time_step: float = None, dfba_time_step: float = None, checkpoint_period: float = None, submodels_to_skip: list = None, verbose: bool = False, merge_like_submodels: bool = True, changes: list = None, perturbations: list = None)[source]¶ Bases:
wc_utils.util.misc.EnhancedDataClass
Whole-cell simulation configuration
A simulation configuration for DE-Sim
Random number generator seed
ODE and dFBA timesteps
Checkpoint period
Submodels to skip
Whether to produce verbose output
Whether to merge algorithmically-like submodels into individual submodels
Model changes: Instructions to change parameter values and add or remove model components. These instructions are executed before the initial conditions are calculated
External perturbations: Instructions to set parameter values or state at specific time points or time ranges
-
de_simulation_config
[source]¶ a simulation configuration for DE-Sim, needed for validation
- Type
SimulationConfig
-
submodels_to_skip
[source]¶ submodels that should not be run, identified by their ids
- Type
list
ofstr
, optional
-
merge_like_submodels
[source]¶ whether to merge algorithmically-like submodels into individual submodels
- Type
bool
, optional
-
changes
[source]¶ list of desired model changes (e.g. modified parameter values, additional species/reactions, removed species/reactions)
- Type
list
, optional
-
perturbations
[source]¶ list of desired simulated perturbations (e.g. set state to a value at a specified time or time range)
- Type
list
, optional
-
apply_changes
(model)[source]¶ Applies changes to model
- Parameters
model (
wc.sim.model.Model
) – model
-
apply_perturbations
(model)[source]¶ Applies perturbations to model
- Parameters
model (
wc.sim.model.Model
) – model
-
changes
= None[source]
-
check_periodic_timestep
(periodic_attr)[source]¶ Check that simulation duration is an integral multiple of a periodic activity’s timestep
- Parameters
periodic_attr (
str
) – name of an attribute storing the duration of a periodic activity- Returns
if no error is found
- Return type
None
- Raises
MultialgorithmError – if the simulation duration is not an integral multiple of the periodic activity’s timestep
-
checkpoint_period
= None[source]
-
dfba_time_step
= None[source]
-
get_num_time_steps
()[source]¶ Calculate number of simulation timesteps
- Returns
number of simulation timesteps
- Return type
int
-
merge_like_submodels
= True[source]
-
ode_time_step
= None[source]
-
perturbations
= None[source]
-
random_seed
= None[source]
-
semantically_equal
(other)[source]¶ Are two instances semantically equal with respect to a simulation’s predictions?
Overrides semantically_equal in
EnhancedDataClass
. Ignore verbose, changes, and perturbations. verbose does not influence a simulation’s predictions and changes and perturbations are not currently used.- Parameters
other (
Object
) – other object- Returns
True
if other is semantically equal to self,False
otherwise- Return type
bool
-
submodels_to_skip
= None[source]
-
validate
()[source]¶ Fully validate a WCSimulationConfig instance
- Returns
if no error is found
- Return type
None
- Raises
MultialgorithmError – if validation fails
-
validate_individual_fields
()[source]¶ Validate individual fields in a WCSimulationConfig instance
- Returns
if no error is found
- Return type
None
- Raises
MultialgorithmError – if an attribute fails validation
-
verbose
= False[source]
2.1.18. wc_sim.simulation module¶
Simulate a multialgorithm model
- Author
Arthur Goldberg <Arthur.Goldberg@mssm.edu>
- Date
2018-05-25
- Copyright
2018, Karr Lab
- License
MIT
-
class
wc_sim.simulation.
Simulation
(model)[source]¶ Bases:
object
Simulate a multialgorithm model
metadata about the author of a whole-cell simulation run
- Type
AuthorMetadata
-
class
SimulationReturnValue
[source]¶ Bases:
tuple
SimulationReturnValue(num_events, results_dir, profile_stats): Value returned by a simulation run
-
get_simulator
()[source]¶ Provide the simulation’s simulation engine
- Returns
the simulation’s simulation engine
- Return type
Simulator
-
provide_event_counts
()[source]¶ Provide the last simulation’s categorized event counts
- Returns
the last simulation’s categorized event counts, in a tab-separated table
- Return type
str
-
run
(max_time, results_dir=None, progress_bar=True, checkpoint_period=None, seed=None, ode_time_step=None, dfba_time_step=None, profile=False, submodels_to_skip=None, verbose=True, object_memory_change_interval=0, options=None)[source]¶ Run one simulation
- Parameters
max_time (
float
) – the maximum time of a simulation; a stop condition may end it earlier (sec)results_dir (
str
, optional) – path to a directory in which results are storedprogress_bar (
bool
, optional) – whether to show the progress of a simulation in in a real-time bar on a terminalcheckpoint_period (
float
, optional) – the period between simulation state checkpoints (sec)ode_time_step (
float
, optional) – time step length of ODE submodel (sec)dfba_time_step (
float
, optional) – time step length of dFBA submodel (sec)profile (
bool
, optional) – whether to output a profile of the simulation’s performance created by a Python profilerseed (
object
, optional) – a seed for the simulation’s numpy.random.RandomState; if provided, seed will reseed the simulator’s PRNGsubmodels_to_skip (
list
ofstr
, optional) – submodels that should not be run, identified by their idsverbose (
bool
, optional) – whether to print success outputobject_memory_change_interval (
int
, optional) – event interval between memory profiles of the simulation; default of 0 indicates no profileoptions (
dict
, optional) – options for submodels, keyed by submodel class name; are passed toMultialgorithmSimulation
- Returns
- containing 1) an
int
holding the number of simulation events, 2) if results_dir is provided, a
str
containing the pathname of the directory containing the results, and 3) if profile is True, profile stats for the simulation
- containing 1) an
- Return type
- Raises
MultialgorithmError – if the simulation raises an exception
-
run_batch
(results_dir, checkpoint_period)[source]¶ Run all simulations specified by the simulation configuration
- Parameters
results_dir (
str
) – path to a directory in which results should be storedcheckpoint_period (
float
) – the period between simulation state checkpoints (sec)
- Returns
- number of simulation events, pathname of directory
containing the results
- Return type
tuple
of (int, str)
-
wc_sim.simulation.
config_multialgorithm
= {'abs_ode_solver_tolerance': 1e-10, 'cache_invalidation': 'reaction_dependency_based', 'checkpoint_period': 10.0, 'checkpointing_sim_obj_name': 'CHECKPOINTING_SIM_OBJ', 'default_center_of_mass': 10, 'default_rounding': True, 'dfba_time_step': 1.0, 'expression_caching': True, 'initial_ssa_wait_ema': 1, 'interpolate': True, 'max_allowed_init_accounted_fraction': 1.5, 'mean_to_std_dev_ratio': 10.0, 'minimum_allowed_population': -0.001, 'num_ssa_verification_sim_runs': 20, 'output_directory': '.', 'rel_ode_solver_tolerance': 1e-08, 'run_time_error_checking': False, 'ssa_event_logging_spacing': 100}[source]¶ put in docstring usage:
from wc_sim.simulation import Simulation from wc_sim.run_results import RunResults
- one run:
model = … model object or model file simulation = Simulation(model) events, results_dir = simulation.run(max_time, results_dir, checkpoint_period) run_results = RunResults(results_dir)
- batch run:
model = … model object or model file sim_config = SimulationConfig(…) simulation = Simulation(model, sim_config) events_array, results_dir = simulation.run_batch()
- Type
TODO
2.1.19. wc_sim.species_populations module¶
Store species populations, and partition them among submodel private species and shared species
- Author
Arthur Goldberg <Arthur.Goldberg@mssm.edu>
- Author
Jonathan Karr <karr@mssm.edu>
- Author
Arthur Goldberg, Arthur.Goldberg@mssm.edu
- Date
2017-02-04
- Copyright
2016-2018, Karr Lab
- License
MIT
-
class
wc_sim.species_populations.
AccessSpeciesPopulationInterface
[source]¶ Bases:
object
An abstract base class defining the interface between a submodel and its species population store(s)
A submodel in a WC simulation can interact with multiple components that store the population of the species it models. This architecture is needed to simulate a model in parallel. All these stores must implement this interface which defines read and write operations on the species in a store. Both write operations have the prefix adjust in their names because they adjust a store’s population. All operations require a time argument that indicates the simulation time at which the operation executes in the store.
-
abstract
adjust_continuously
(time, cont_submodel_id, population_slopes, time_step=None)[source]¶ A continuous submodel adjusts the rate of change of a set of species at a particular simulation time
-
abstract
adjust_discretely
(time, adjustments)[source]¶ A discrete submodel adjusts the population of a set of species at a particular simulation time
-
abstract
-
class
wc_sim.species_populations.
AccessSpeciesPopulations
(local_pop_store, remote_pop_stores)[source]¶ Bases:
wc_sim.species_populations.AccessSpeciesPopulationInterface
Interface a submodel with the components that store the species populations it models
Each submodel is a distinct simulation object. In the current population-based model, species are represented by their populations. (A hybrid instance-population model would change that.) Each submodel accesses a subset of the species in a model. A submodel’s species can be partitioned into those that are accessed ONLY by the submodel and those that it shares with other submodels. These are respectively stored in a local LocalSpeciesPopulation which is private to this submodel, and a set of SpeciesPopSimObjects which are shared with other submodels. LocalSpeciesPopulation objects are accessed via local memory operations whereas SpeciesPopSimObjects, which are distinct simulation objects, are accessed via simulation event messages.
AccessSpeciesPopulations enables a submodel to access all of the species populations that it uses through a single convenient interface. The submodel simply indicates the species being used and the operation type. This object then maps the species to the entity or entities storing them, and executes the operation on each entity.
Essentially, an AccessSpeciesPopulations multiplexes a submodel’s access to multiple population stores.
-
submodel
[source]¶ the submodel that’s using this
AccessSpeciesPopulations
- Type
DynamicSubmodel
-
species_locations
[source]¶ a map indicating the store for each species used by the submodel using this object, that is, the local submodel.
- Type
dict
of str
-
remote_pop_stores
[source]¶ a map from store name to a system identifier for the remote population store(s) that the local submodel uses. For a shared memory implementation system identifiers can be object references; for a distributed implementation they must be network object identifiers.
- Type
dict
of identifiers of SpeciesPopSimObject
-
species_population_cache
[source]¶ a cache of populations for species that are stored remotely in the SpeciesPopSimObjects in remote_pop_stores; values for remote populations are pre-fetched at the right simulation time (via GetPopulation and GivePopulation messages) into this cache and then read from it when needed.
-
__str__
()[source]¶ Provide readable AccessSpeciesPopulations state
Provide the submodel’s name, the name of the local_pop_store, and the id and store name of each species accessed by this AccessSpeciesPopulations.
- Returns
a multi-line string describing this AccessSpeciesPopulations’ state.
- Return type
str
-
add_species_locations
(store_name, species_ids, replace=False)[source]¶ Add species locations to the species location map
Record that the species listed in species_ids are stored by the species population store identified by store_name. To replace existing location map values without raising an exception, set replace to True.
- Parameters
store_name (
str
) – the globally unique name of a species population store. LOCAL_POP_STORE is a special name that identifies the local population store for private speciesspecies_ids (
list
ofstr
) – a list of species ids
- Raises
SpeciesPopulationError – if store store_name is unknown
SpeciesPopulationError – if replace is False and any species_id in species_ids is already mapped to a different store than store_name.
-
adjust_continuously
(time, adjustments)[source]¶ A continuous submodel adjusts the population of a set of species at the time time
- Parameters
time (
float
) – the time at which the population is being adjustedadjustments (
dict
of tuple) – map: species_ids -> population_slope; adjustments to be made to some species populations.
See the description for adjust_discretely above.
- Returns
the names of the stores for the species whose populations are adjusted.
- Return type
list
-
adjust_discretely
(time, adjustments)[source]¶ A discrete submodel adjusts the population of a set of species at the time time
Distribute the adjustments among the population stores managed by this object. Iterate through the components that store the population of species listed in adjustments. Update the local population store immediately and send AdjustPopulationByDiscreteSubmodel messages to the remote stores. Since these messages are asynchronous, this method returns as soon as they are sent.
- Parameters
time (
float
) – the time at which the population is being adjustedadjustments (
dict
offloat
) – map: species_ids -> population_adjustment; adjustments to be made to some species populations
- Returns
the names of the stores for the species whose populations are adjusted
- Return type
list
-
del_species_locations
(species_ids, force=False)[source]¶ Delete entries from the species location map
Remove species location mappings for the species in species_ids. To avoid raising an exception when a species is not in the location map, set force to True.
- Parameters
species_ids (
list
of species_ids) – a list of species idsforce (
boolean
, optional) – if set, do not raise an exception if a species_id in species_ids is not found in the species location map.
- Raises
SpeciesPopulationError – if force is False and any species_id in species_ids is not in the species location map.
-
locate_species
(species_ids)[source]¶ Locate the component(s) that store a set of species
Given a list of species identifiers in species_ids, partition them into the storage component(s) that store their populations. This method is widely used by code that accesses species. It returns a dictionary that maps from store name to the ids of species whose populations are modeled by the store.
The special name LOCAL_POP_STORE represents a special store, the local
wc_sim.local_species_population.LocalSpeciesPopulation
instance. Each other store is identified by the name of a remotewc_sim.species_pop_sim_object.SpeciesPopSimObject
instance.- Parameters
species_ids (
list
ofstr
) – a list of species identifiers- Returns
- a map from store_name -> a set of species_ids whose populations are stored
by component store_name.
- Return type
dict
- Raises
SpeciesPopulationError – if a store cannot be found for a species_id in species_ids
-
prefetch
(delay, species_ids)[source]¶ Obtain species populations from remote stores when they will be needed in the future
Generate GetPopulation queries that obtain species populations whose primary stores are remote at delay in the future. The primary stores (SpeciesPopSimObject objects) will respond to the GetPopulation queries with GivePopulation responses.
To ensure that the remote store object executes the GetPopulation at an earlier simulation time than the submodel will need the data, decrease the event time of the GetPopulation event to the previous floating point value.
- Parameters
delay (
float
) – the populations will be needed at now + delayspecies_ids (
list
of species_ids) – a list of species ids
- Returns
the names of the stores for the species whose populations are adjusted.
- Return type
list
-
read
(time, species_ids)[source]¶ Obtain the population of the species identified in species_ids at the time time
Obtain the species from the local_pop_store and/or the species_population_cache. If some of the species’ primary stores are remote_pop_stores, then their populations should be in the cache because they should have been prefetched.
- Parameters
time (
float
) – the time at which the population should be obtainedspecies_ids (set) – identifiers of the species whose populations will be obtained.
- Returns
species_id -> population; the predicted population of all requested species at time time.
- Return type
dict
- Raises
SpeciesPopulationError – if a store cannot be found for a species_id in species_ids
SpeciesPopulationError – if any of the species were cached at a time that differs from time
-
read_one
(time, species_id)[source]¶ Obtain the predicted population of species`species_id` at the time time
If the species is stored in the local_pop_store, obtain its population there. Otherwise obtain the population from the species_population_cache. If the species’ primary store is a remote_pop_store, then its population should be in the cache because the population should have been prefetched.
- Parameters
time (
float
) – the time at which the population should be obtainedspecies_id (
str
) – identifier of the species whose population will be obtained.
- Returns
the predicted population of species_id at simulation time time.
- Return type
float
- Raises
SpeciesPopulationError – if species_id is an unknown species
-
-
class
wc_sim.species_populations.
DynamicSpeciesState
(species_name, random_state, initial_population, cont_submodel_ids=None, record_history=False, default_rounding=None)[source]¶ Bases:
object
Track the population of a single species in a multi-algorithmic model
A
DynamicSpeciesState
is a shared object that can be accessed by multiple submodels in a multi-algorithmic model. We call it a dynamic species. The accesses to a dynamic species can be categorized into ‘write’ and ‘read’ types. Write accesses, called adjustments, change a dynamic species’ state. The read accesses, continuous_change() and get_population(), retrieve information from a dynamic species’ state but do not change the state. In order to satisfy temporal causality a sequence of accesses of a DynamicSpeciesState instance must satisfy the following synchronization constraints:Write accesses must occur in non-decreasing time order
- Every read access must occur at a time greater than or equal to the largest time of all
preceeding write accesses
- Every write access must occur at a time greater than or equal to the largest time of all
preceeding read accesses
The _validate_adjustment_time() and _validate_read_time() methods enforce these constraints.
Note that these rules allow multiple simultaneous accesses, with causal relationships that depend on the execution order that occur at a particular time. For example, at time t a reaction modeled by a discrete SSA submodel might update a species population, and then use the updated population to compute a reaction’s rate law.
Consider a multi-algorithmic model that contains both submodels that execute discrete-time algorithms, like the stochastic simulation algorithm (SSA), and submodels that execute continuous-time integration algorithms, like ODE and dFBA. Discrete-time algorithms change system state at discrete time instants. Continuous-time algorithms approximate species populations as continuous variables, and obtain the predicted rate-of-change of a species at time instants determined by the algorithm. We assume this behavior.
A dynamic species’ state in a multi-algorithmic model may be modeled by multiple submodels that model reactions in which the species participates. These can be multiple discrete-time submodels and multiple continuous-time submodels. Discrete-time and continuous-time models adjust the state of a species by the methods discrete_adjustment() and continuous_adjustment(), respectively. These adjustments take the following forms,
discrete_adjustment(time, population_change)
continuous_adjustment(time, continuous_submodel_id, population_slope)
where time is the time at which that change takes place, population_change is the increase or decrease in the species’ population, continuous_submodel_id is the id of the continuous submodel making the adjustment, and population_slope is the predicted future rate of change of the population.
To improve the accuracy of multi-algorithmic models, we linearally interpolate population predictions for species modeled by continuous-time submodels. Interpolated predictions are based on the latest population slope predictions made by the continuous submodels modeling a species. Thus, we assume that a species population modeled by continuous models is adjusted sufficiently frequently that the latest adjustments accurately estimate population slopes.
A species instance stores the most recent value of the species’ population in last_population, which is initialized when the instance is created. If a species is modeled by one or more continuous-time submodels, it also stores the species’ latest rate of change for each continuous-time submodel in population_slopes and the time of the most recent continuous_adjustment in continuous_time. Interpolation determines the population prediction p at time t as:
interpolation = 0 if modeled_continuously: interpolation = (t - continuous_time) * sum(population_slopes) p = last_population + interpolation
This approach is completely general, and can be applied to any simulation value whose dynamics are predicted by a multi-algorithmic model.
Population values returned by methods in
DynamicSpeciesState
use stochastic rounding by default to provide integer values and avoid systematic rounding bias. See more detail in get_population’s docstring.-
species_name
[source]¶ the species’ name; not logically needed, but helpful for error reporting, logging, debugging, etc.
- Type
str
-
compartment_id
[source]¶ the species’ compartment’s id; optimization to avoid parsing species id at run-time
- Type
str
-
random_state
[source]¶ a shared PRNG, used to round populations to integers
- Type
wc_utils.rand.RandomState
-
population_slopes
[source]¶ if continuous submodel(s) are modeling the species, a map from continuous submodel id to the rate of change of the population provided by the most recent adjustment by the continuous submodel
- Type
dict
-
continuous_time
[source]¶ if a continuous submodel is modeling the species, the time of the most recent adjustment by any continuous model; initialized to None to indicate that no continuous adjustment has been made
- Type
float
-
last_adjustment_time
[source]¶ the time of the latest adjustment; used to prevent reads in the past
- Type
float
-
default_rounding
[source]¶ whether species populations are rounded when rounding isn’t specified
- Type
bool
, optional
-
class
HistoryRecord
[source]¶ Bases:
tuple
HistoryRecord(time, operation, argument): entry in a DynamicSpeciesState history
-
class
Operation
[source]¶ Bases:
enum.Enum
Types of operations on DynamicSpeciesState, for use in history
-
compartment_id
[source]
-
continuous_adjustment
(time, cont_submodel_id, population_slope, time_step=None)[source]¶ A continuous-time submodel adjusts the species’ state
A continuous-time submodel, such as an ordinary differential equation (ODE) or a dynamic flux balance analysis (FBA) model, uses this method to adjust the species’ state. Each integration of a continuous-time model must predict a species’ population change and the population’s short-term future rate of change, i.e., its population_slope. Further, since an integration of a continuous-time model at the current time must depend on this species’ population just before the integration, we assume that population_change incorporates population changes predicted by the population_slope provided by the previous continuous_adjustment call.
- Parameters
time (
float
) – the simulation time at which the predicted change occurs; this time is used by get_population to interpolate continuous-time predictions between integrations.cont_submodel_id (
str
) – the id of the continuous submodel that is adjusting its predicted population_slopepopulation_slope (
float
orint
) – the predicted rate of change of the species at the provided timetime_step (
float
, optional) – the time step used by the continuous submodel; if provided, will be used to compute the return value
- Returns
- the species’ estimated population in one time step in the future, as predicted
by all population_slopes, including the new slope;
None
is returned if time_step isNone
- Return type
float
- Raises
DynamicSpeciesPopulationError – if an initial population slope was not provided, or if time is not greater than the time of the most recent continuous_adjustment call
DynamicNegativePopulationError – if updating the population based on the previous population_slope makes the population go negative
-
continuous_change
(time)[source]¶ Get the change contributed by continuous submodels to this species’ population since the last adjustment
- Parameters
time (
float
) – the simulation time at which the predicted change occurs; time is used by to interpolate continuous-time predictions in between continuous adjustments- Returns
- the change contributed by continuous submodels to this species’ population
since the last adjustment
- Return type
float
- Raises
DynamicSpeciesPopulationError – if the population_slope has not been set for any continuous submodel modeling this species
-
continuous_time
[source]
-
default_rounding
[source]
-
discrete_adjustment
(time, population_change)[source]¶ Make a discrete adjustment of this species’ population
A submodel running a discrete-time integration algorithm, such as the stochastic simulation algorithm (SSA), must use this method to adjust its species’ populations.
- Parameters
time (
float
) – the simulation time at which the predicted change occurs; this time is used by get_population to interpolate continuous-time predictions between integrationspopulation_change (
float
) – the modeled increase or decrease in the species’ population
- Returns
- if rounding is in effect, an integer approximation of the species’ population;
otherwise the predicted floating population
- Return type
int
orfloat
- Raises
DynamicNegativePopulationError – if the predicted population at time is negative or if decreasing the population by population_change would make the population negative
-
get_history
()[source]¶ Obtain this DynamicSpeciesState’s history
- Returns
a list of `HistoryRecord`s, ordered by time
- Return type
list
- Raises
SpeciesPopulationError – if the history wasn’t recorded
-
get_population
(time, interpolate=None, round=None, temporary_mode=False)[source]¶ Provide the species’ population at time time
If one of the submodel(s) predicting the species’ population is a continuous-time model, then use the species’ last population_slopes to interpolate the current population, as described in the class documentation.
Clearly, species populations in biological systems are non-negative integers. However, continuous-time models approximate populations with continuous representations, and therefore predict real, non-integral, populations. But discrete-time models like SSA do not naturally handle non-integral copy numbers.
We resolve this conflict by storing real valued populations within a species, but providing integral population predictions if round is True. To aovid the bias that would arise by always using floor() or ceiling() to convert a float to an integer, population predictions are stochastically rounded before being returned by get_population. This means that a sequence of calls to `get_population` with `round=True` may **NOT* return a sequence of equal population values.*
- Parameters
time (
float
) – the current simulation timeround (
bool
, optional) – if round then round the population to an integer; if not provided, then use self.default_roundinginterpolate (
bool
, optional) – if not None then control interpolation; otherwise it’s controlled by the ‘interpolate’ config variabletemporary_mode (
bool
, optional) – whether the calling LocalSpeciesPopulation is in temporary mode; if set, do not update last_read_time
- Returns
- if round, an integer approximation of the species’ population, otherwise
the floating population
- Return type
int
- Raises
DynamicSpeciesPopulationError – if time is earlier than the time of a previous continuous or discrete adjustment
DynamicNegativePopulationError – if interpolation predicts a negative population
-
get_temp_population_value
()[source]¶ Get the temporary population
Provide a temporary population that has been stored for temporary, exploratory computations, like the right-hand-side function used to solve ODEs.
- Returns
- if the temporary population is set, the species’ population as a
float
, otherwise
None
- if the temporary population is set, the species’ population as a
- Return type
obj
-
last_adjustment_time
[source]
-
last_population
[source]
-
last_read_time
[source]
-
modeled_continuously
()[source]¶ Indicate whether this :obj: DynamicSpeciesState is modeled by any continuous submodels
- Returns
whether this :obj: DynamicSpeciesState is modeled by any continuous submodels
- Return type
bool
-
population_slopes
[source]
-
random_state
[source]
-
set_temp_population_value
(population)[source]¶ Set a temporary population
Save a temporary population for a temporary, exploratory computation, like the right-hand-side function used to solve ODEs. The time associated with a temporary population value is not provided or needed. These values aren’t saved in the history.
- Parameters
population (
float
) – the temporary population
-
species_name
[source]
-
class
wc_sim.species_populations.
LocalSpeciesPopulation
(name, initial_population, molecular_weights, cont_submodel_ids=None, initial_time=0, random_state=None, retain_history=True, default_rounding=None)[source]¶ Bases:
wc_sim.species_populations.AccessSpeciesPopulationInterface
Maintain the population of a set of species
LocalSpeciesPopulation tracks the population of a set of species. Population values (copy numbers) can be read or modified (adjusted). To enable multi-algorithmic modeling, it supports writes to a species’ population by both discrete time and continuous time submodels.
All access operations that read or modify the population must provide a simulation time. For any given species, all operations must occur in non-decreasing simulation time order. Record history operations must also occur in time order.
Simulation time arguments enable detection of temporal causality errors by shared accesses from different submodels in a sequential simulator. In particular, every read operation must access the previous modification.
A LocalSpeciesPopulation object is accessed via local method calls. It can be wrapped as a DES simulation object – a SimulationObject – to provide distributed access, as is done by SpeciesPopSimObject.
-
_molecular_weights
[source]¶ map: species_id -> molecular_weight; the molecular weight of each species
- Type
dict
offloat
-
_population
[source]¶ map: species_id -> DynamicSpeciesState(); the species whose counts are stored, represented by DynamicSpeciesState objects.
- Type
dict
ofDynamicSpeciesState
-
last_access_time
[source]¶ map: species_name -> last_time; the last time at which the species was accessed.
- Type
dict
offloat
-
temporary_mode
[source]¶ if True, this LocalSpeciesPopulation is being accessed through a TempPopulationsLSP
- Type
bool
-
default_rounding
[source]¶ whether species populations get rounded when rounding isn’t specified
- Type
bool
-
__str__
()[source]¶ Provide readable LocalSpeciesPopulation state
Provide the name of this LocalSpeciesPopulation, the current time, and the id, population of each species stored by this object. Species modeled by continuous time submodels also have the most recent continuous time adjustment and the current population slope.
- Returns
a multi-line string describing this LocalSpeciesPopulation’s state
- Return type
str
-
adjust_continuously
(time, cont_submodel_id, population_slopes, time_step=None)[source]¶ A continuous submodel adjusts the population slopes of a set of species at simulation time time
Species retain the population slopes to interpolate the population until the next call to adjust_continuously.
- Parameters
time (
float
) – the time at which the population is being adjustedcont_submodel_id (
str
) – the id of the continuous submodel that’s adjusting the population slopespopulation_slopes (
dict
offloat
) – map: species_id -> population_slope; updated population slopes for some, or all, species populationstime_step (
float
, optional) – the time step used by the continuous submodel; if provided, will be used by continuous_adjustment to estimate the predicted populations one time step in the future
- Warns
:obj:`MultialgorithmWarning` – generates a warning if any species populations are predicted to have negative populations at the end of the time step
- Raises
DynamicSpeciesPopulationError – if any adjustment attempts to change the population slope of an unknown species, or if any population estimate would become negative
-
adjust_discretely
(time, adjustments)[source]¶ A submodel adjusts the population of a set of species at simulation time time
- Parameters
time (
float
) – the simulation time of the population adjustedmentadjustments (
dict
offloat
) – map: species_ids -> population_adjustment; adjustments to be made to the population of some species
- Raises
DynamicSpeciesPopulationError – if any adjustment attempts to change the population of an unknown species
DynamicSpeciesPopulationError – if any population estimate would become negative
-
clear_temp_populations
(time, species_ids)[source]¶ Clear temporary population values for multiple species
Used to solve ODE submodels
- Parameters
time (
float
) – simulation timespecies_ids (
iterator
) – an iterator over some species ids
-
compartmental_mass
(compartment_id, species_ids=None, time=None)[source]¶ Compute the current mass of some, or all, species in a compartment
- Parameters
compartment_id (
str
) – the ID of the compartmentspecies_ids (
list
of str, optional) – identifiers of the species whose mass will be obtained; if not provided, then compute the mass of all species in the compartmenttime (number, optional) – the current simulation time
- Returns
the current total mass of the specified species in compartment compartment_id, in grams
- Return type
float
- Raises
DynamicSpeciesPopulationError – if a species’ molecular weight was not provided to __init__() in molecular_weights
-
concentrations_api
()[source]¶ Get the status of the concentrations API; if True, species amounts must be in molar
- Returns
the status of the concentrations API; if set, species amounts must be in molar
- Return type
bool
-
concentrations_api_off
()[source]¶ Turn the concentrations API on; species amounts must be in populations (molecule)
-
concentrations_api_on
()[source]¶ Turn the concentrations API on; species amounts must be in concentrations (molar)
-
concentrations_to_populations
(time, species, concentrations, dynamic_model, populations, volumes=None)[source]¶ Convert species concentrations, in molar, to populations, in molecules
- Parameters
time (
float
) – current simulation timespecies (
np.ndarray
ofstr
) – species idsconcentrations (
np.ndarray
offloat
) – corresponding concentrations of the species in speciesdynamic_model (
DynamicModel
) – the simulation’s dynamic modelpopulations (
np.ndarray
offloat
) – array to hold the populations of the corresponding species in speciesvolumes (
dict
offloat
, optional) – map: compartment id -> volume; volumes of compartments containing species in species; optionally provided as an optimization, to avoid computing volumes
- Returns
None`: the populations are returned in populations
-
fractional_masses
(compartment_id)[source]¶ Report on the fractional mass contribution of each species in a compartment
- Parameters
compartment_id (
str
) – the ID of the compartment- Returns
a tab-separated table containing the fractional mass contribution of each species in compartment
- Return type
str
-
get_continuous_species
()[source]¶ Get the species that are modeled continuously
This is used to compute dependencies in the Next Reaction Method submodel.
- Returns
IDs of the species that are modeled continuously
- Return type
set
ofstr
-
history_debug
()[source]¶ Provide some of the history in a string
Provide a string containing the start and end time of the history and a table with the first and last population value for each species.
- Returns
- the start and end time of he history and a
tab-separated matrix of rows with species id, first, last population values
- Return type
str
- Raises
SpeciesPopulationError – if the history was not recorded.
-
init_cell_state_species
(species_id, population, molecular_weight, cont_submodel_ids=None)[source]¶ Initialize a species with the given population and, optionally, the ids of continuous submodels that model it
Add a species to the cell state.
- Parameters
species_id (
str
) – the species’ globally unique identifierpopulation (
float
) – initial population of the speciesmolecular_weight (
float
) – molecular weight of the speciescont_submodel_ids (
list
ofstr
, optional) – ids of continuous submodels that model this species
- Raises
SpeciesPopulationError – if the species is already stored by this LocalSpeciesPopulation
-
invalid_weights
(species_ids=None)[source]¶ Find the species that do not have a positive, numerical molecular weight
- Parameters
species_ids (
list
of str, optional) – identifiers of the species whose molecular weights will be checked; if not provided, then check all species- Returns
the ids of species that do not have a positive, numerical molecular weight
- Return type
set
-
log_event
(message, species)[source]¶ Log an event that modifies a species’ population
Log the event’s simulation time, event type, species population, and current population slope (if specified).
- Parameters
message (
str
) – description of the event’s type.species (
DynamicSpeciesState
) – the object whose adjustment is being logged
-
populations_to_concentrations
(time, species, populations, dynamic_model, concentrations, volumes=None)[source]¶ Convert species populations, in molecules, to concentrations, in molar
- Parameters
time (
float
) – current simulation timespecies (
np.ndarray
ofstr
) – species idspopulations (
np.ndarray
offloat
) – corresponding populations of the species in speciesdynamic_model (
DynamicModel
) – the simulation’s dynamic modelconcentrations (
np.ndarray
offloat
) – array to hold the concentrations of the corresponding species in speciesvolumes (
dict
offloat
, optional) – map: compartment id -> volume; volumes of compartments containing species in species; optionally provided as an optimization, to avoid computing volumes
- Returns
None`: the concentrations are returned in concentrations
-
read
(time, species=None, round=True)[source]¶ Read the predicted population of a multiple species at simulation time time
Ignores temporary species populations
- Parameters
time (
float
) – the time at which the population should be estimatedspecies (
set
, optional) – identifiers of the species to read; if not supplied, read all speciesround (
bool
, optional) – if round then round the populations to integers
- Returns
species counts: species_id -> copy_number; the predicted copy number of each requested species at time
- Return type
dict
-
read_into_array
(time, species, populations, round=True)[source]¶ Obtain the predicted population of an iterator over species at simulation time time
- Parameters
time (
float
) – the time at which the population should be predictedspecies (
iterator
ofstr
) – identifiers of the species to readpopulations (
np.ndarray
offloat
) – array to hold the populations of the corresponding species in speciesround (
bool
, optional) – if round then round the populations to integers
- Returns
None`: the populations are returned in populations
-
read_one
(time, species_id)[source]¶ Obtain the predicted population of species species_id at simulation time time
If a temporary population value is available, return it.
- Parameters
time (
float
) – the time at which the population should be estimatedspecies_id (
str
) – identifier of the species to access.
- Returns
the predicted population of species_id at simulation time time.
- Return type
float
-
report_history
(numpy_format=False, species_type_ids=None, compartment_ids=None)[source]¶ Provide the time and species count history
- Parameters
numpy_format (
bool
, optional) – if set, return history in a 3 dimensional np arrayspecies_type_ids (
list
ofstr
, optional) – the ids of species_types in the Model being simulatedcompartment_ids (
list
ofstr
, optional) – the ids of the compartments in the Model being simulated
- Returns
The time and species count history. By default, return a dict, with rv[‘time’] = list of time samples rv[‘population’][species_id] = list of counts for species_id at the time samples If numpy_format set, return a tuple containing a pair of np arrays that contain the time and population histories, respectively.
- Return type
dict
- Raises
SpeciesPopulationError – if the history was not recorded
SpeciesPopulationError – if numpy_format set but species or compartments are not provided
-
set_temp_populations
(time, populations)[source]¶ Set temporary population values for multiple species
Used to solve ODE submodels
- Parameters
time (
float
) – simulation timepopulations (
dict
offloat
) – map: species_id -> temporary_population_value
- Raises
SpeciesPopulationError – if any of the species_ids in populations are unknown, or if any population value would become negative
-
-
class
wc_sim.species_populations.
MakeTestLSP
(name=None, initial_population=None, molecular_weights=None, cont_submodel_ids=None, record_history=False, **kwargs)[source]¶ Bases:
object
Make a LocalSpeciesPopulation for testing
Because a LocalSpeciesPopulation takes about 10 lines of code to make, and they’re widely needed for testing wc_sim, provide a configurable class that creates a test LSP.
-
class
wc_sim.species_populations.
SpeciesPopSimObject
(name, initial_population, molecular_weights, initial_population_slopes=None, random_state=None, retain_history=True)[source]¶ Bases:
wc_sim.species_populations.LocalSpeciesPopulation
,de_sim.simulation_object.SimulationObject
Maintain the population of a set of species in a simulation object that can be parallelized
A whole-cell PDES must run multiple submodels in parallel. These share cell state, such as species populations, by accessing shared simulation objects. A SpeciesPopSimObject provides that functionality by wrapping a LocalSpeciesPopulation in a SimulationObject.
-
event_handlers
= [(<class 'de_sim.event_message.AdjustPopulationByDiscreteSubmodel'>, <function SpeciesPopSimObject.handle_adjust_discretely_event>), (<class 'de_sim.event_message.AdjustPopulationByContinuousSubmodel'>, <function SpeciesPopSimObject.handle_adjust_continuously_event>), (<class 'de_sim.event_message.GetPopulation'>, <function SpeciesPopSimObject.handle_get_population_event>), (<class 'de_sim.event_message.GetCurrentProperty'>, <function SpeciesPopSimObject.handle_get_current_property_event>)][source]¶
-
handle_adjust_continuously_event
(event)[source]¶ Handle a simulation event
- Parameters
event (
de_sim.event.Event
) – an Event to process- Raises
SpeciesPopulationError – if an AdjustPopulationByContinuousSubmodel event acts on a non-existent species.
-
handle_adjust_discretely_event
(event)[source]¶ Handle a simulation event
- Parameters
event (
de_sim.event.Event
) – an Event to process
-
handle_get_current_property_event
(event)[source]¶ Handle a simulation event
- Parameters
event (
de_sim.event.Event
) – an Event to process- Raises
SpeciesPopulationError – if an GetCurrentProperty message requests an unknown property.
-
handle_get_population_event
(event)[source]¶ Handle a simulation event
- Parameters
event (
de_sim.event.Event
) – an Event to process- Raises
SpeciesPopulationError – if a GetPopulation message requests the population of an unknown species.
-
-
class
wc_sim.species_populations.
SpeciesPopulationCache
(access_species_populations)[source]¶ Bases:
object
Cache the population of species whose primary stores are remote population stores
-
_cache
[source]¶ map: species_id -> (time, population); the species whose counts are cached, containing the last write time in time, and the population.
- Type
dict
oftuple
-
cache_population
(time, populations)[source]¶ Cache some population values
- Parameters
time (
float
) – the time of the cached valuespopulations (
dict
of float) – map: species_ids -> population; the population of the species at time.
- Raises
SpeciesPopulationError – if the species are stored in the ASP’s local store; they should not be cached.
SpeciesPopulationError – if, for any species, time is not greater than its previous cache time.
-
read
(time, species_ids)[source]¶ Read the cached population of a set of species at a particular time
- Parameters
time (
float
) – the time at which the population should be obtainedspecies_ids (set) – identifiers of the species to read.
- Returns
dict: species_id -> copy_number; the cached copy number of each requested species at simulation time time.
- Return type
species counts
- Raises
SpeciesPopulationError – if any of the species are not stored in the cache
SpeciesPopulationError – if any of the species were cached at a time that differs from time.
-
read_one
(time, species_id)[source]¶ Obtain the cached population of a species at a particular time
- Parameters
time (
float
) – the expected time of the cached valuesspecies_id (
str
) – identifier of the species to obtain.
- Returns
the cached population of species_id at simulation time time.
- Return type
float
- Raises
SpeciesPopulationError – if the species are stored in the ASP’s local store, which means that they should not be cached.
SpeciesPopulationError – if time is not greater than a species’ previous cache time
-