2.1.1.3. wc_sim.submodels package

2.1.1.3.2. Submodules

2.1.1.3.3. wc_sim.submodels.dfba module

A submodel that uses Dynamic Flux Balance Analysis (dFBA) to model a set of reactions

Author

Yin Hoon Chew <yinhoon.chew@mssm.edu>

Author

Arthur Goldberg <Arthur.Goldberg@mssm.edu>

Date

2020-07-29

Copyright

2016-2020, Karr Lab

License

MIT

class wc_sim.submodels.dfba.DfbaSubmodel(id, dynamic_model, reactions, species, dynamic_compartments, local_species_population, dfba_time_step, options=None)[source]

Bases: wc_sim.submodels.dynamic_submodel.ContinuousTimeSubmodel

Use dynamic Flux Balance Analysis to predict the dynamics of chemical species in a container

DFBA_BOUND_SCALE_FACTOR[source]

scaling factor for the bounds on reactions and constraints that avoid negative species populations; the default value is 1.

Type

float

DFBA_COEF_SCALE_FACTOR[source]

scaling factor for the stoichiometric coefficients in dFBA objective reactions; the default value is 1.

Type

float

SOLVER[source]

name of the selected solver in conv_opt, the default value is ‘cplex’

Type

str

PRESOLVE[source]

presolve mode in conv_opt (‘auto’, ‘on’, ‘off’), the default value is ‘on’

Type

str

SOLVER_OPTIONS[source]

parameters for the solver; default values are provided for ‘cplex’

Type

dict

OPTIMIZATION_TYPE[source]

direction of optimization (‘maximize’, ‘max’, ‘minimize’, ‘min’); the default value is ‘maximize’

Type

str

FLUX_BOUNDS_VOLUMETRIC_COMPARTMENT_ID[source]

id of the compartment to which the measured flux bounds are normalized, the default is the whole-cell

Type

str

VERBOSITY[source]

output verbosity of the solver

Type

str

NEG_POP_CONSTRAINTS[source]

whether the constraints that prevent negative species over the next time-step should be used; defaults to True

Type

boolean

dfba_solver_options (:obj:`dict` of :obj:`str`

any): options for solving dFBA submodel

reaction_fluxes (:obj:`dict` of :obj:`str`

float): reaction fluxes data structure, which is pre-allocated

dfba_obj_expr[source]

an analyzed and validated dFBA objective expression

Type

ParsedExpression

exchange_rxns[source]

set of exchange and demand reactions

Type

set of wc_lang.Reactions

_multi_reaction_constraints (:obj:`dict` of :obj:`str`

conv_opt.Constraint): a map from constraint id to constraints that avoid negative species populations in self._conv_model.constraints

_conv_model[source]

linear programming model in conv_opt format

Type

conv_opt.Model

_conv_variables (:obj:`dict` of :obj:`str`

conv_opt.Variable): a dictionary mapping reaction IDs to their associated conv_opt.Variable objects

_conv_metabolite_matrices (:obj:`dict` of :obj:`str`

list): a dictionary mapping metabolite species IDs to lists of conv_opt.LinearTerm objects; each conv_opt.LinearTerm associates a reaction that the species participates in with the species’ stoichiometry in the reaction

_dfba_obj_reactions (:obj:`dict` of :obj:`str`

wc_lang.DfbaObjReaction): all wc_lang.DfbaObjReactions used by the self.dfba_obj_expr

_dfba_obj_species[source]

all species in DfbaObjReactions used by dfba_obj_expr, keyed by their IDs

Type

list of wc_lang.DfbaObjSpecies:

_reaction_bounds (:obj:`dict` of :obj:`str`

tuple): a dictionary that maps reaction IDs to (minimum bound, maximum bound) tuples

_optimal_obj_func_value[source]

the value of objective function returned by the solver

Type

float

DFBA_BOUND_SCALE_FACTOR = 1.0[source]
DFBA_COEF_SCALE_FACTOR = 1.0[source]
FLUX_BOUNDS_VOLUMETRIC_COMPARTMENT_ID = 'wc'[source]
LB = '__LB__'[source]
NEG_POP_CONSTRAINTS = True[source]
NEG_POP_CONSTRAINT_PREFIX = 'neg_pop_constr'[source]
NEG_POP_CONSTRAINT_SEP = '__'[source]
OPTIMIZATION_TYPE = 'maximize'[source]
PRESOLVE = 'on'[source]
RB = '__RB__'[source]
SOLVER = 'cplex'[source]
SOLVER_OPTIONS = {'cplex': {'parameters': {'emphasis': {'numerical': 1}, 'read': {'scale': 1}}}}[source]
VERBOSITY = 'off'[source]
bound_neg_species_pop_constraints()[source]

Update bounds in the negative species population constraints that span multiple reactions

Update the bounds in each constraint in self._multi_reaction_constraints that prevents a species from having a negative species population in the next time step.

Call this before each run of the FBA solver.

compute_population_change_rates()[source]

Compute the rate of change of the populations of species used by this dFBA

Because FBA obtains a steady-state solution for reaction fluxes, only species that participate in the exchange reactions or dFBA objective pseudo-reactions at the edge of the FBA network can have non-zero rates of change.

Updates the existing dict self.adjustments.

del_infeasible_rxns(conv_opt_model, copy_model=True)[source]

Delete infeasible reactions from a convex optimization model

Delete reactions with lower bound == upper bound == 0.

Parameters
  • conv_opt_model (conv_opt.Model) – a convex optimization model

  • copy_model (boolean, optional) – whether to copy the convex optimization model before modifying it; defaults to True

Returns

the convex optimization model with infeasible reactions removed

Return type

conv_opt.Model

determine_bounds()[source]

Determine the minimum and maximum flux bounds for each reaction

Bounds provided by rate laws or flux bound constants in the model are written to self._reaction_bounds.

event_handlers = [(<class 'de_sim.event_message.RunFba'>, 'handle_RunFba_msg')][source]
static gen_neg_species_pop_constraint_id(species_id)[source]

Generate a negative species population constraint id

Parameters

species_id (str) – id of species being constrained

Returns

a negative species population constraint id

Return type

str

get_conv_model()[source]

Get the conv_opt model

Returns

the linear programming model in conv_opt format

Return type

conv_opt.Model

get_reaction_fluxes()[source]

Get the reaction fluxes

Returns

float: reaction fluxes

Return type

dict of str

handle_RunFba_msg(event)[source]

Handle an event containing a RunFba message

Parameters

event (Event) – a simulation event

initialize_neg_species_pop_constraints()[source]

Make constraints that prevent species populations from going negative

A separate constraint is made for each species. These constraints prevent the species population from declining so quickly that it becomes negative in the next time step. Call this when a dFBA submodel is initialized.

Do nothing if negative species population constraints are not being used.

Returns

conv_opt.Constraint: a map from constraint id to constraints stored in self._conv_model.constraints

Return type

dict of str

messages_sent = [<class 'de_sim.event_message.RunFba'>][source]
metadata = <de_sim.simulation_object.SimulationObjectMetadata object>[source]
static parse_neg_species_pop_constraint_id(neg_species_pop_constraint_id)[source]

Parse a negative species population constraint id

Parameters

neg_species_pop_constraint_id (str) – a negative species population constraint id

Returns

id of species being constrained

Return type

str

run_fba_solver()[source]

Run the FBA solver for one time step

Raises

DynamicMultiAlgorithmError – if no optimal solution is found

save_fba_solution(conv_opt_model, conv_opt_solution)[source]

Assign a FBA solution to local variables

Parameters
  • conv_opt_model (conv_opt.Model) – the convex optimization model that was solved

  • conv_opt_solution (conv_opt.Result) – the model’s solution

scale_conv_opt_model(conv_opt_model, copy_model=True, dfba_bound_scale_factor=None, dfba_coef_scale_factor=None)[source]

Apply scaling factors to a conv_opt model

Scaling factors can be used to scale the size of bounds and objective reaction stoichiometric coefficients to address numerical problems with the linear programming solver. They are elements of dfba_solver_options. The dfba_bound_scale_factor option scales the bounds on reactions and constraints that avoid negative species populations. The dfba_coef_scale_factor scales the stoichiometric coefficients in dFBA objective reactions. Scaling is done by the this method. Symmetrically, the solution results are returned to the scale of the whole-cell model by inverting the consequences of these scaling factors. This is done by the unscale_conv_opt_solution method.

Parameters
  • conv_opt_model (conv_opt.Model) – a convex optimization model

  • copy_model (boolean, optional) – whether to copy the convex optimization model before scaling it; defaults to True

  • dfba_bound_scale_factor (float, optional) – factor used to scale the bounds on reactions and constraints that avoid negative species populations; if not supplied, is taken from self.dfba_solver_options

  • dfba_coef_scale_factor (float, optional) – factor used to scale the stoichiometric coefficients in dFBA objective reactions; if not supplied, is taken from self.dfba_solver_options

Returns

the scaled convex optimization model

Return type

conv_opt.Model

set_up_dfba_submodel()[source]

Set up a dFBA submodel, by converting to a linear programming matrix

Raises

MultiAlgorithmError – if the ids in DfbaObjReactions and Reactionss intersect

set_up_optimizations()[source]

To improve performance, pre-compute and pre-allocate some data structures

static species_id_with_brkts(species_id)[source]

Replace codes in a species id with brackets

Parameters

species_id (str) – WC Lang species id with brackets replaced by codes

Returns

standard WC Lang species id

Return type

str

Raises

MultiAlgorithmError – if species_id doesn’t have bracket codes or has brackets

static species_id_without_brkts(species_id)[source]

Replace brackets in a species id with codes

Parameters

species_id (str) – WC Lang species id

Returns

species id with brackets replaced by codes

Return type

str

Raises

MultiAlgorithmError – if species_id isn’t a properly formatted wc_lang.Species id, or has bracket codes

time_step_message[source]

alias of de_sim.event_message.RunFba

unscale_conv_opt_solution(dfba_bound_scale_factor=None, dfba_coef_scale_factor=None)[source]

Remove scaling factors from a conv_opt model solution

Parameters
  • dfba_bound_scale_factor (float, optional) – factor used to scale reaction and constraint bounds; if not supplied, is taken from self.dfba_solver_options

  • dfba_coef_scale_factor (float, optional) – factor used to scale the stoichiometric coefficients in dFBA objective reactions; if not supplied, is taken from self.dfba_solver_options

update_bounds()[source]

Update the minimum and maximum bounds of conv_opt.Variable based on the values in self._reaction_bounds

class wc_sim.submodels.dfba.ObjToRow(col_widths, headers, attrs)[source]

Bases: object

header_rows()[source]
obj_as_row(obj)[source]
class wc_sim.submodels.dfba.ShowConvOptElements[source]

Bases: object

static show_conv_opt_constraint(header=False, constraint=None)[source]
classmethod show_conv_opt_constraints(constraints)[source]
classmethod show_conv_opt_model(conv_opt_model)[source]

Convert a conv_opt into a readable representation

Parameters

conv_opt_model (conv_opt.Model) – a convex optimization model

Returns

a readable representation of conv_opt_model

Return type

str

static show_conv_opt_variable(header=False, variable=None)[source]
static show_conv_opt_variable_term(header=False, variable_term=None)[source]

2.1.1.3.4. wc_sim.submodels.dynamic_submodel module

A generic dynamic submodel; a multi-algorithmic model is constructed of multiple dynamic submodel subclasses

Author

Arthur Goldberg <Arthur.Goldberg@mssm.edu>

Author

Jonathan Karr <karr@mssm.edu>

Date

2016-03-22

Copyright

2016-2018, Karr Lab

License

MIT

class wc_sim.submodels.dynamic_submodel.ContinuousTimeSubmodel(id, dynamic_model, reactions, species, dynamic_compartments, local_species_population, time_step, options=None)[source]

Bases: wc_sim.submodels.dynamic_submodel.DynamicSubmodel

Provide functionality that is shared by multiple continuous time submodels

Discrete time submodels like SSA represent changes in species populations as step functions. Continuous time submodels model changes in species populations as continuous functions, currently piece-wise linear functions. ODEs and dFBA are continuous time submodels.

time_step[source]

time interval between continuous time submodel analyses

Type

float

num_steps[source]

number of analyses made

Type

int

options[source]

continuous time submodel options

Type

dict

species_ids[source]

ids of the species used by this continuous time submodel

Type

list

species_ids_set[source]

ids of the species used by this continuous time submodel

Type

set

num_species[source]

number of species in species_ids and species_ids_set

Type

int

adjustments[source]

pre-allocated adjustments for passing changes to the LocalSpeciesPopulation

Type

dict

populations[source]

pre-allocated numpy array for storing species populations

Type

numpy.ndarray

current_species_populations()[source]

Obtain the current populations of species modeled by this continuous time submodel

The current populations are written into self.populations.

init_before_run()[source]

Send this continuous time submodel’s initial event

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

Schedule the next analysis by this continuous time submodel

set_up_continuous_time_optimizations()[source]

To improve performance, pre-compute and pre-allocate some data structures

set_up_continuous_time_submodel()[source]

Begin setting up a continuous time submodel

class wc_sim.submodels.dynamic_submodel.DynamicSubmodel(id, dynamic_model, reactions, species, dynamic_compartments, local_species_population)[source]

Bases: de_sim.simulation_object.SimulationObject

Provide generic dynamic submodel functionality

All submodels are implemented as subclasses of DynamicSubmodel. Instances of them are combined to make a multi-algorithmic model.

id[source]

unique id of this dynamic submodel and simulation object

Type

str

dynamic_model[source]

the aggregate state of a simulation

Type

DynamicModel

reactions[source]

the reactions modeled by this dynamic submodel

Type

list of Reaction

rates[source]

array to hold reaction rates

Type

np.array

species[source]

the species that participate in the reactions modeled by this dynamic submodel, with their initial concentrations

Type

list of Species

dynamic_compartments[source]

the dynamic compartments containing species that participate in reactions that this dynamic submodel models, including adjacent compartments used by its transfer reactions

Type

dict of str, DynamicCompartment

local_species_population[source]

the store that maintains this dynamic submodel’s species population

Type

LocalSpeciesPopulation

fast_debug_file_logger[source]

a fast logger for debugging messages

Type

FastLogger

calc_reaction_rate(reaction, use_enabled=True)[source]

Calculate an irreversible reaction’s current rate

The rate is computed by eval’ing the reaction’s rate law, with species populations obtained from the simulations’s LocalSpeciesPopulation.

Parameters
  • reaction (Reaction) – the reaction to evaluate

  • use_enabled (boolean, optional) – if reaction is not enabled, return rate of 0.

Returns

the reaction’s rate

Return type

float

calc_reaction_rates()[source]

Calculate the rates for this dynamic submodel’s reactions

Rates are computed by eval’ing rate laws for reactions used by this dynamic submodel, with species populations obtained from the simulations’s LocalSpeciesPopulation. This assumes that all reversible reactions have been split into two forward reactions, as is done by wc_lang.transform.SplitReversibleReactionsTransform.

Returns

a numpy array of reaction rates, indexed by reaction index

Return type

np.ndarray

enabled_reaction(reaction)[source]

Determine whether the cell state has adequate species counts to run a reaction

Indicate whether the current species counts are large enough to execute reaction, based on its stoichiometry.

Parameters

reaction (Reaction) – the reaction to evaluate

Returns

True if reaction is stoichiometrically enabled

Return type

bool

event_handlers = [(<class 'de_sim.event_message.GetCurrentProperty'>, 'handle_get_current_prop_event')][source]
execute_reaction(reaction)[source]

Update species counts to reflect the execution of a reaction

Called by discrete submodels, like SSA. Counts are updated in the LocalSpeciesPopulation that stores them.

Parameters

reaction (Reaction) – the reaction being executed

:raises DynamicMultialgorithmError: if the species population cannot be updated:

get_compartment_masses()[source]

Get the mass (g) of each compartment

Returns

dictionary that maps the ids of compartments to their masses (g)

Return type

dict

get_num_submodels()[source]

Provide the number of submodels

Returns

the number of submodels

Return type

int

get_species_counts()[source]

Get a dictionary of current species counts for this dynamic submodel

Returns

a map: species_id -> current copy number

Return type

dict

get_species_ids()[source]

Get ids of species used by this dynamic submodel

Returns

ids of species used by this dynamic submodel

Return type

list

handle_get_current_prop_event(event)[source]

Handle a GetCurrentProperty simulation event.

Parameters

event (de_sim.event.Event) – an Event to process

Raises

DynamicMultialgorithmError – if an GetCurrentProperty message requests an unknown property

identify_enabled_reactions()[source]

Determine which reactions have adequate species counts to run

Returns

an array indexed by reaction number; 0 indicates reactions without adequate

species counts

Return type

np.array

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

If necessary, prepare a submodel after the DynamicModel has been fully initialized

2.1.1.3.5. wc_sim.submodels.nrm module

A submodel that uses Gibson and Bruck’s Next Reaction Method (NRM) to model a set of reactions

Author

Arthur Goldberg <Arthur.Goldberg@mssm.edu>

Date

2020-04-11

Copyright

2020, Karr Lab

License

MIT

class wc_sim.submodels.nrm.NrmSubmodel(id, dynamic_model, reactions, species, dynamic_compartments, local_species_population)[source]

Bases: wc_sim.submodels.dynamic_submodel.DynamicSubmodel

Use the Next Reaction Method to predict the dynamics of chemical species in a container

dependencies[source]

dependencies that rate laws have on executed reactions; entry i provides the indices of reactions whose rate laws depend on reaction i

Type

list of tuple

execution_time_priority_queue[source]

NRM indexed priority queue of reactions, with the earliest scheduled reaction at the front of the queue

Type

PQDict

propensities[source]

the most recently calculated propensities of the reactions modeled by this NRM submodel

Type

np.ndarray

random_state[source]

the random state that is shared across the simulation, which enables reproducible checkpoint and restore of a simulation

Type

np.random.RandomState

MESSAGE_TYPES_BY_PRIORITY = [<class 'de_sim.event_message.ExecuteAndScheduleNrmReaction'>][source]
SENT_MESSAGE_TYPES = [<class 'de_sim.event_message.ExecuteAndScheduleNrmReaction'>][source]
determine_dependencies()[source]

Determine the dependencies that rate laws have on executed reactions

In a multi-algorithmic simulation, two types of dependencies arise when NRM considers which rate laws to update after a reaction executes:

1) Dependencies between NRM reactions and rate laws for NRM reactions. Rate laws that depend on species whose populations are updated by a reaction, either directly or indirectly through expressions that use the species, must be evaluated after the reaction executes.

2) Rate laws that depend on, again either directly or indirectly, species whose populations can be updated by reactions or continuous changes in other submodels, must always be evaluated after any NRM reaction executes.

This method combines both types of dependencies into a single map from executed reaction to dependent rate laws. It is executed only once at initialization, so its cost is amortized over an entire simulation.

Returns

entry i provides the indices of reactions whose

rate laws depend on the execution of reaction i, not including reaction i itself

Return type

list of tuple

event_handlers = [(<class 'de_sim.event_message.ExecuteAndScheduleNrmReaction'>, 'handle_ExecuteAndScheduleNrmReaction_msg')][source]
execute_nrm_reaction(reaction_index)[source]

Execute a reaction now

Parameters

reaction_index (int) – index of the reaction to execute

handle_ExecuteAndScheduleNrmReaction_msg(event)[source]

Handle an event containing an ExecuteAndScheduleNrmReaction message

Parameters

event (Event) – a simulation event

init_before_run()[source]

Initialize this NRM submodel and schedule its first reaction

This SimulationObject method is called when a Simulator is initialized.

initialize_execution_time_priorities()[source]

Initialize the NRM indexed priority queue of reactions

initialize_propensities()[source]

Get the initial propensities of all reactions

Propensities of reactions with inadequate species counts are set to 0.

Returns

the propensities of the reactions modeled by this NRM submodel

Return type

np.ndarray

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

Prepare this submodel after the DynamicModel has been fully initialized

register_nrm_reaction(execution_time, reaction_index)[source]

Schedule a NRM reaction event with the simulator

Parameters
  • execution_time (float) – simulation time at which the reaction will execute

  • reaction_index (int) – index of the reaction to execute

schedule_after_rxn_retraction()[source]

Schedule the next reaction after a reaction was retracted

Parameters

reaction_index (int) – index of the reaction that was retracted

schedule_next_reaction(reaction_index)[source]

Schedule the next reaction after a reaction executes

Parameters

reaction_index (int) – index of the reaction that just executed

schedule_reaction()[source]

Schedule the next reaction

2.1.1.3.6. wc_sim.submodels.odes module

A submodel that uses a system of ordinary differential equations (ODEs) to model a set of reactions.

Author

Arthur Goldberg <Arthur.Goldberg@mssm.edu>

Date

2018-10-12

Copyright

2018, Karr Lab

License

MIT

class wc_sim.submodels.odes.OdeSubmodel(id, dynamic_model, reactions, species, dynamic_compartments, local_species_population, ode_time_step, options=None)[source]

Bases: wc_sim.submodels.dynamic_submodel.ContinuousTimeSubmodel

Use a system of ordinary differential equations to predict the dynamics of chemical species in a container

solver[source]

the Odes ode solver

Type

scikits.odes.ode.ode

non_negative_populations[source]

pre-allocated numpy array for non-negative species populations

Type

numpy.ndarray

zero_populations[source]

pre-allocated numpy array

Type

numpy.ndarray

rate_of_change_expressions[source]

for each species, a list of its (coefficient, rate law) pairs

Type

list of list of tuple

ABS_ODE_SOLVER_TOLERANCE = 1e-10[source]
REL_ODE_SOLVER_TOLERANCE = 1e-08[source]
compute_population_change_rates(time, new_species_populations, population_change_rates)[source]

Compute the rate of change of the populations of species used by this ODE

Parameters
  • time (float) – simulation time

  • new_species_populations (numpy.ndarray) – populations of all species at time time, listed in the same order as self.species_ids

  • population_change_rates (numpy.ndarray) – the rate of change of new_species_populations at time time; written by this method

create_ode_solver(**options)[source]

Create a scikits.odes ODE solver that uses CVODE

Parameters

options (dict) – options for the solver; see https://github.com/bmcage/odes/blob/master/scikits/odes/sundials/cvode.pyx

Returns

an ODE solver instance

Return type

scikits.odes.ode

Raises

MultialgorithmError – if the ODE solver cannot be created

event_handlers = [(<class 'de_sim.event_message.RunOde'>, 'handle_RunOde_msg')][source]
get_info()[source]

Get info from CVODE

Returns

the information returned by the solver’s get_info() call

Return type

dict

get_solver_lock()[source]

Acquire the solver lock

Raises

DynamicMultialgorithmError – if the solver lock cannot be acquired

handle_RunOde_msg(event)[source]

Handle an event containing a RunOde message

Parameters

event (Event) – a simulation event

messages_sent = [<class 'de_sim.event_message.RunOde'>][source]
metadata = <de_sim.simulation_object.SimulationObjectMetadata object>[source]
release_solver_lock()[source]
right_hand_side(time, new_species_populations, population_change_rates)[source]

Evaluate population change rates for species modeled by ODE; called by ODE solver

This is called by the CVODE ODE solver.

Parameters
  • time (float) – simulation time

  • new_species_populations (numpy.ndarray) – estimated populations of all species at time time, provided by the ODE solver; listed in the same order as self.species_ids

  • population_change_rates (numpy.ndarray) – the rate of change of new_species_populations at time time; written by this method

Returns

return 0 to indicate success, or 1 to indicate failure;

but the important side effects are the values in population_change_rates

Return type

int

Raises

DynamicMultialgorithmError – if this method raises any exception

run_ode_solver()[source]

Run the ODE solver for one WC simulator time step and save the species populations changes

Raises

DynamicMultialgorithmError – if the CVODE ODE solver indicates an error

set_up_ode_submodel()[source]

Set up an ODE submodel, including its ODE solver

set_up_optimizations()[source]

To improve performance, pre-compute and pre-allocate some data structures

time_step_message[source]

alias of de_sim.event_message.RunOde

using_solver = False[source]
exception wc_sim.submodels.odes.WcSimOdeWarning[source]

Bases: UserWarning

wc_sim Ode warning

2.1.1.3.7. wc_sim.submodels.ssa module

A submodel that employs Gillespie’s Stochastic Simulation Algorithm (SSA) to model a set of reactions.

Author

Arthur Goldberg <Arthur.Goldberg@mssm.edu>

Date

2016-07-14

Copyright

2016-2018, Karr Lab

License

MIT

class wc_sim.submodels.ssa.SsaSubmodel(id, dynamic_model, reactions, species, dynamic_compartments, local_species_population, default_center_of_mass=None, options=None)[source]

Bases: wc_sim.submodels.dynamic_submodel.DynamicSubmodel

Use the Stochastic Simulation Algorithm to predict the dynamics of chemical species in a container

This implementation supports a partition of the species populations into private, locally stored populations and shared, remotely stored populations. These are accessed through the ADT provided by the DynamicSubmodel’s LocalSpeciesPopulation. Appropriate optimizations are made if no populations are stored remotely.

# TODO(Arthur): update the rest of this doc string # TODO(Arthur): ensure that this doc string formats properly Algorithm:

implement the 'direct' method, except under unusual circumstances

determine_reaction_propensities():
    determine reactant concentrations
    determine propensities
    eliminate reactions that are not stoichiometrically enabled
    return propensities, total_propensities

schedule_next_event():
    determine_reaction_propensities()
    if total_propensities == 0: *
        schedule_SsaWait()      *
    else:
        reaction delay = random sample of exp(1/total_propensities)
        select and schedule the next reaction

execute_reaction():
    if scheduled reaction is stoichiometrically enabled:
        execute it
    schedule_next_event()

*  2nd order recovery because other submodels can modify shared species counts
num_SsaWaits[source]

count of SsaWaits executed by this SsaSubmodel

Type

int

ema_of_inter_event_time[source]

an EMA of the time between ExecuteSsaReaction events; when total propensities == 0, ema_of_inter_event_time is used as the time delay between SsaWait events

Type

ExponentialMovingAverage

random_state[source]

the random state that is shared across the simulation, which enables reproducible checkpoint and restore of a simulation

Type

numpy.random.RandomState

MESSAGE_TYPES_BY_PRIORITY = [<class 'de_sim.event_message.SsaWait'>, <class 'de_sim.event_message.GivePopulation'>, <class 'de_sim.event_message.ExecuteSsaReaction'>][source]
SENT_MESSAGE_TYPES = [<class 'de_sim.event_message.AdjustPopulationByDiscreteSubmodel'>, <class 'de_sim.event_message.ExecuteSsaReaction'>, <class 'de_sim.event_message.GetPopulation'>, <class 'de_sim.event_message.SsaWait'>][source]
determine_reaction_propensities()[source]

Determine the current reaction propensities for this submodel.

Method: 1. calculate concentrations # TODO(Arthur): IMPORTANT: optimization: simply use counts to calculate propensities # TODO(Arthur): IMPORTANT: create benchmark & profile data to evaluate possible optimizations 2. calculate propensities for this submodel 3. avoid reactions with inadequate species counts

Returns

reaction (propensities, total_propensities)

Raises

DynamicFrozenSimulationError – if the simulation has 1 submodel and the total propensities are 0

event_handlers = [(<class 'de_sim.event_message.SsaWait'>, 'handle_SsaWait_msg'), (<class 'de_sim.event_message.GivePopulation'>, 'handle_GivePopulation_msg'), (<class 'de_sim.event_message.ExecuteSsaReaction'>, 'handle_ExecuteSsaReaction_msg')][source]
execute_SSA_reaction(reaction_index)[source]

Execute a reaction now.

Parameters

reaction_index (int) – index of the reaction to execute

get_reaction_propensities()[source]

Get reaction propensities and handle boundary conditions

Returns

(propensities, total_propensities)

handle_ExecuteSsaReaction_msg(event)[source]

Handle an event containing a ExecuteSsaReaction message

Parameters

event (Event) – a simulation event

handle_GivePopulation_msg(event)[source]

Handle an event containing a GivePopulation message

handle_SsaWait_msg(event)[source]

Handle an event containing a SsaWait message

Parameters

event (Event) – a simulation event

init_before_run()[source]

Send this SSA submodel’s initial events

log_event(event)[source]

Log a SsaSubmodel simulation event.

Parameters

event (Event) – a simulation event

messages_sent = [<class 'de_sim.event_message.AdjustPopulationByDiscreteSubmodel'>, <class 'de_sim.event_message.ExecuteSsaReaction'>, <class 'de_sim.event_message.GetPopulation'>, <class 'de_sim.event_message.SsaWait'>][source]
metadata = <de_sim.simulation_object.SimulationObjectMetadata object>[source]
schedule_ExecuteSsaReaction(dt, reaction_index)[source]

Schedule an ExecuteSsaReaction event.

Parameters
  • dt (float) – simulation delay until the ExecuteSsaReaction will execute

  • reaction_index (int) – index of the reaction to execute

schedule_SsaWait()[source]

Schedule an SsaWait.

schedule_next_SSA_reaction()[source]

Schedule the next SSA reaction for this SSA submodel.

If the sum of propensities is positive, schedule a reaction, otherwise schedule a wait. The delay until the next reaction is an exponential sample with mean 1/sum(propensities).

Method:

  1. calculate propensities

  2. if total propensity == 0:

    schedule a wait equal to the weighted mean inter reaction time return

  3. select time of next reaction

  4. select next reaction

  5. schedule the next reaction

Returns

the delay until the next SSA reaction, or None if no reaction is scheduled

Return type

float

schedule_next_events()[source]

Schedule the next events for this submodel

2.1.1.3.8. Module contents