gillespy2.core package¶
Submodules¶
gillespy2.core.assignmentrule module¶
- class gillespy2.core.assignmentrule.AssignmentRule(variable=None, formula=None, name=None)[source]¶
Bases:
SortableObject
,Jsonify
An AssignmentRule is used to express equations that set the values of variables. This would correspond to a function in the form of x = f(V)
- Parameters:
name (str) – Name of the Rule
variable (str) – Target Species/Parameter to be modified by rule
formula (str) – String representation of formula to be evaluated
- sanitized_formula(species_mappings, parameter_mappings)[source]¶
Sanitize the assignment rule formula.
- Parameters:
species_mappings (dict) – Mapping of species names to sanitized species names.
parameter_mappings (dict) – Mapping of parameter names to sanitized parameter names.
- Returns:
The sanitized formula.
- Return type:
str
gillespy2.core.cleanup module¶
gillespy2.core.events module¶
- class gillespy2.core.events.Event(name='', delay=None, assignments=[], priority='0', trigger=None, use_values_from_trigger_time=False)[source]¶
Bases:
Jsonify
An Event can be given as an assignment_expression (function) or directly as a value (scalar). If given an assignment_expression, it should be understood as evaluable in the namespace of a parent Model.
- Parameters:
name (str) – The name by which this Event is called or referenced in reactions.
assignments (str) – List of EventAssignments to be executed at trigger or delay
trigger (EventTrigger) – contains math expression which can be evaluated to a boolean result. Upon the transition from ‘False’ to ‘True’, event assignments may be executed immediately, or after a designated delay.
delay (str) – contains math expression evaluable within model namespace. This expression designates a delay between the trigger of an event and the execution of its assignments.
priority (str) – Contains math expression evaluable within model namespace.
- add_assignment(assignment)[source]¶
Adds an EventAssignment or a list of EventAssignment.
- Parameters:
assignment (EventAssignment or list[EventAssignment]) – The event or list of events to be added to this event.
- class gillespy2.core.events.EventAssignment(name=None, variable=None, expression=None)[source]¶
Bases:
Jsonify
An EventAssignment describes a change to be performed to the current model simulation. This is assignment can either be fired at the time its associated trigger changes from false to true, or after a specified delay, depending on how the Event to which it is assigned is configured.
- Parameters:
variable (gillespy2.Species, gillespy2.Parameter) – Target model component to be modified by the EventAssignment expression. Valid target variables include gillespy2 Species, Parameters, and Compartments.
expression (str) – String to be evaluated when the event is fired. This expression must be evaluable within the model namespace, and the results of it’s evaluation will be assigned to the EventAssignment variable.
- class gillespy2.core.events.EventTrigger(expression=None, initial_value=False, persistent=False)[source]¶
Bases:
Jsonify
Trigger detects changes in model/environment conditions in order to fire an event. A Trigger contains an expression, a mathematical function which can be evaluated to a boolean value within a model’s namespace. Upon transitioning from ‘false’ to ‘true’, this trigger will cause the immediate execution of an event’s list of assignments if no delay is present, otherwise, the delay evaluation will be initialized.
- Parameters:
expression (str) – String for a function calculating EventTrigger values. Should be evaluable in namespace of Model.
value (bool) – Value of EventTrigger at simulation start, with time t=0
persistent (bool) – Determines if trigger condition is persistent or not
- sanitized_expression(species_mappings, parameter_mappings)[source]¶
Sanitize the event trigger expression.
- Parameters:
species_mappings (dict) – Mapping of species names to sanitized species names.
parameter_mappings (dict) – Mapping of parameter names to sanitized parameter names.
- Returns:
The sanitized expression.
- Return type:
str
gillespy2.core.functiondefinition module¶
- class gillespy2.core.functiondefinition.FunctionDefinition(name='', function=None, args=[])[source]¶
Bases:
SortableObject
,Jsonify
Object representation defining an evaluable function to be used during simulation of a GillesPy2 model
- Parameters:
name (str) – Name of the function to be made and called
function (str) – Defined function body of operation to be performed.
variables (list[str]) – String names of Variables to be used as arguments to function.
- get_arg_string() str [source]¶
Convert function’s argument list into a comma-separated formatted string.
- Returns:
Argument list as a comma-separated formatted string.
- sanitized_function(species_mappings, parameter_mappings)[source]¶
Sanitize the function definition function.
- Parameters:
species_mappings (dict) – Mapping of species names to sanitized species names.
parameter_mappings (dict) – Mapping of parameter names to sanitized parameter names.
- Returns:
The sanitized function.
- Return type:
str
gillespy2.core.gillespyError module¶
- exception gillespy2.core.gillespyError.AssignmentRuleError[source]¶
Bases:
ModelError
- exception gillespy2.core.gillespyError.BuildError[source]¶
Bases:
SolverError
- exception gillespy2.core.gillespyError.DirectoryError[source]¶
Bases:
SolverError
- exception gillespy2.core.gillespyError.EventError[source]¶
Bases:
ModelError
- exception gillespy2.core.gillespyError.ExecutionError[source]¶
Bases:
SolverError
- exception gillespy2.core.gillespyError.FunctionDefinitionError[source]¶
Bases:
ModelError
- exception gillespy2.core.gillespyError.InvalidModelError[source]¶
Bases:
SimulationError
- exception gillespy2.core.gillespyError.InvalidStochMLError[source]¶
Bases:
SimulationError
- exception gillespy2.core.gillespyError.ParameterError[source]¶
Bases:
ModelError
- exception gillespy2.core.gillespyError.RateRuleError[source]¶
Bases:
ModelError
- exception gillespy2.core.gillespyError.ReactionError[source]¶
Bases:
ModelError
- exception gillespy2.core.gillespyError.SimulationTimeoutError[source]¶
Bases:
SimulationError
- exception gillespy2.core.gillespyError.SpeciesError[source]¶
Bases:
ModelError
- exception gillespy2.core.gillespyError.StochMLImportError[source]¶
Bases:
SimulationError
- exception gillespy2.core.gillespyError.TimespanError[source]¶
Bases:
ModelError
- exception gillespy2.core.gillespyError.ValidationError[source]¶
Bases:
ResultsError
gillespy2.core.gillespySolver module¶
- class gillespy2.core.gillespySolver.GillesPySolver[source]¶
Bases:
object
Abstract class for a solver.
- classmethod get_supported_integrator_options() Set[str] [source]¶
Get the supported integrator options
- name = 'GillesPySolver'¶
- run(model, t=20, number_of_trajectories=1, increment=0.05, seed=None, debug=False, profile=False, **kwargs)[source]¶
Call out and run the solver. Collect the results.
- Parameters:
model (gillespy.Model) – The model on which the solver will operate.
t (int) – The end time of the solver
number_of_trajectories (int) – The number of times to sample the chemical master equation. Each trajectory will be returned at the end of the simulation.
increment (float) – The time step of the solution
seed (int) – The random seed for the simulation. Defaults to None.
debug (bool) – Set to True to provide additional debug information about the simulation.
- Returns:
Simulation trajectories.
- classmethod validate_integrator_options(options: dict[str, float]) dict[str, float] [source]¶
Validate the integrator options.
- Parameters:
options (dict) – Integrator options to validate.
- Returns:
Dict of supported integrator options.
- Return type:
dict
- classmethod validate_model(sol_model, model)[source]¶
Validate that the solvers model is the same as the model passed to solver.run.
- Parameters:
sol_model (gillespy2.Model) – Solver model object.
model (gillespy2.Model) – Model object passed to solver.run.
- Raises:
SimulationError – If the models are not equal.
- classmethod validate_sbml_features(model)[source]¶
Validate the models SBML features.
- Parameters:
model (gillespy2.Model) – The model object to be checked.
- Raises:
ModelError – If the model contains unsupported SBML features.
- validate_tspan(increment, t)[source]¶
Validate the models time span and set it if not provided.
- Parameters:
increment (int) – The current value of increment.
t (int) – The end time of the simulation.
- Raises:
SimulationError – if timespan and increment are both set by the user or neither are set by the user.
gillespy2.core.jsonify module¶
- class gillespy2.core.jsonify.ComplexJsonCoder(translation_table=None, encode_private=True, **kwargs)[source]¶
Bases:
JSONEncoder
This class delegates the encoding and decoding of objects to one or more implementees.
- Parameters:
translation_table (TranslationTable) – A TranslationTable instance that will be used to translate objects.
encode_private (bool) – If set to True then all private and public variables will be converted to JSON. If False, only public.
- class gillespy2.core.jsonify.Int64Coder[source]¶
Bases:
Jsonify
This JSON coder enables support for the numpy.int64 type.
- static from_json(obj)[source]¶
Convert some json_str into a decoded Python type. This function should return a new instance of the type.
- Parameters:
json_str (str) – A json str to be converted into a new type instance.
- Returns:
A decoded object.
- static to_dict(obj)[source]¶
Convert the object into a dictionary ready for json encoding. Note: Complex types that inherit from Jsonify do not need to be manually encoded.
By default, this function will return a dictionary of the object’s public types.
- Returns:
The backing var dictionary of the object.
- class gillespy2.core.jsonify.Jsonify[source]¶
Bases:
object
Interface to allow for instances of arbitrary types to be encoded into json strings and decoded into new objects.
- classmethod from_dict(src_dict: dict) object [source]¶
Convert some dict into a new instance of a python type. This function will return a __new__ instance of the type.
- Parameters:
src_dict (dict) – The dictionary to apply onto the new instance.
- Returns:
A new object with its backing __dict__ set to a copy of src_dict.
- classmethod from_json(json_str: str) object [source]¶
Convert some json_str into a decoded Python type. This function should return a new instance of the type.
- Parameters:
json_str (str) – A json str to be converted into a new type instance.
- Returns:
A decoded object.
- get_json_hash(ignore_whitespace=True, hash_private_vals=False) str [source]¶
Get the hash of the json representation of self.
- Parameters:
ignore_whitespace (bool) – If set to True all whitespace will be stripped from the JSON prior to being hashed.
hash_private_vals (bool) – If set to True all private and non-private variables will be included in the hash.
- Returns:
An MD5 hash of the object’s sorted JSON representation.
- get_translation_table() TranslationTable [source]¶
Make and/or return the translation table.
- Returns:
A TranslationTable instance.
- make_translation_table() TranslationTable [source]¶
Make a translation table that describes key:value pairs to convert user-define data into generic equivalents.
- Returns:
A newly generated TranslationTable instance.
- public_vars() dict [source]¶
Gets a dictionary of public vars that exist on self. Keys starting with ‘_’ are ignored.
- Returns:
A dictionary containing all public (‘_’-prefixed) variables on the object.
- to_dict() dict [source]¶
Convert the object into a dictionary ready for json encoding. Note: Complex types that inherit from Jsonify do not need to be manually encoded.
By default, this function will return a dictionary of the object’s public types.
- Returns:
The backing var dictionary of the object.
- class gillespy2.core.jsonify.NdArrayCoder[source]¶
Bases:
Jsonify
This JSON coder enables support for the numpy.ndarray type.
- static from_json(obj)[source]¶
Convert some json_str into a decoded Python type. This function should return a new instance of the type.
- Parameters:
json_str (str) – A json str to be converted into a new type instance.
- Returns:
A decoded object.
- static to_dict(obj)[source]¶
Convert the object into a dictionary ready for json encoding. Note: Complex types that inherit from Jsonify do not need to be manually encoded.
By default, this function will return a dictionary of the object’s public types.
- Returns:
The backing var dictionary of the object.
- class gillespy2.core.jsonify.SetCoder[source]¶
Bases:
Jsonify
This JSON coder enables support for the set type.
- static from_json(obj)[source]¶
Convert some json_str into a decoded Python type. This function should return a new instance of the type.
- Parameters:
json_str (str) – A json str to be converted into a new type instance.
- Returns:
A decoded object.
- static to_dict(obj)[source]¶
Convert the object into a dictionary ready for json encoding. Note: Complex types that inherit from Jsonify do not need to be manually encoded.
By default, this function will return a dictionary of the object’s public types.
- Returns:
The backing var dictionary of the object.
- class gillespy2.core.jsonify.TranslationTable(to_anon: dict[str, str])[source]¶
Bases:
Jsonify
This class contains functions to enable arbitrary object trees to be “translated” to anonymous and named objects. This behavior is defined by a map of ‘named’ and ‘anon’ key values.
- Parameters:
to_anon (dict[str, str]) – A mapping of ‘named’ to ‘anonymous’ strings to be used when converting user-defined names to anon.
- obj_to_anon(obj: object)[source]¶
Recursively anonymise all named properties on the object.
- Parameters:
obj (object) – The object to anonymize.
- Returns:
An anonymized instance of self.
- obj_to_named(obj)[source]¶
Recursively identify all anonymous properties on the object.
- Parameters:
obj (object) – The object that will be converted to named.
- Returns:
A named instance of self.
- recursive_translate(obj: object, translation_table: dict[str, str])[source]¶
Recursively search through the object tree searching for property value matches in the translation table. If a match is found, substitute.
- Parameters:
obj (object) – The object that will be translated.
translation_table (TranslationTable) – The mapping to translate by.
- class gillespy2.core.jsonify.TypeCoder[source]¶
Bases:
Jsonify
This JSON coder enables support for the ‘type’ type.
- static from_json(obj)[source]¶
Convert some json_str into a decoded Python type. This function should return a new instance of the type.
- Parameters:
json_str (str) – A json str to be converted into a new type instance.
- Returns:
A decoded object.
- static to_dict(obj)[source]¶
Convert the object into a dictionary ready for json encoding. Note: Complex types that inherit from Jsonify do not need to be manually encoded.
By default, this function will return a dictionary of the object’s public types.
- Returns:
The backing var dictionary of the object.
gillespy2.core.liveGraphing module¶
- class gillespy2.core.liveGraphing.CRepeatTimer(interval, function, args=None, kwargs=None)[source]¶
Bases:
Timer
Threading timer which repeatedly calls the given function instead of simply ending.
Used for C solver live graphing support
- pause = False¶
- run()[source]¶
Method representing the thread’s activity.
You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.
- class gillespy2.core.liveGraphing.LiveDisplayer(model=None, timeline=None, number_of_trajectories=1, live_output_options={}, resume=False)[source]¶
Bases:
object
holds information required for displaying information when live_output = True
- display(curr_state, curr_time, trajectory_base, finished=False)[source]¶
Display the output for the live grapher.
- Parameters:
curr_state (list) – Current state of the simulation. Should be a list of len 1 to get reference.
curr_time (list) – Current time of the simulation. Should be a list of len 1 to get reference.
trajectory_base (list) – Current results of the simulation.
finished (bool) – Indicates whether or not the simulation has finished.
- class gillespy2.core.liveGraphing.RepeatTimer(interval, function, args=None, kwargs=None)[source]¶
Bases:
Timer
Threading timer which repeatedly calls the given function instead of simply ending
- pause = False¶
- run()[source]¶
Method representing the thread’s activity.
You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.
- gillespy2.core.liveGraphing.display_types()[source]¶
Get the list of supported display types.
- Returns:
Supported display types.
- Return type:
list
- gillespy2.core.liveGraphing.valid_graph_params(live_output_options)[source]¶
Validated the live output options.
- Parameters:
live_output_options (dict) – Options to be validated.
- Raises:
SimulationError – If the display type is invalid.
gillespy2.core.model module¶
- class gillespy2.core.model.Model(name='', population=True, volume=1.0, tspan=None, annotation='model')[source]¶
Bases:
SortableObject
,Jsonify
Representation of a well mixed biochemical model. Contains reactions, parameters, species.
- Parameters:
name (str) – The name of the model, or an annotation describing it.
population (bool) – The type of model being described. A discrete stochastic model is a population model (True), a deterministic model is a concentration model (False). Automatic conversion from population to concentration models may be used, by setting the volume parameter.
volume (float) – The volume of the system matters when converting to from population to concentration form. This will also set a parameter “vol” for use in custom (i.e. non-mass-action) propensity functions.
tspan (numpy ndarray) – The timepoints at which the model should be simulated. If None, a default timespan is added. May be set later, see Model.timespan
annotation (str) – Option further description of model
- add(components)[source]¶
Adds a component, or list of components to the model. If a list is provided, Species and Parameters are added before other components. Lists may contain any combination of accepted types other than lists and do not need to be in any particular order.
- Parameters:
components (Species, Parameters, Reactions, Events, Rate Rules, Assignment Rules, FunctionDefinitions, TimeSpan, or list) – The component or list of components to be added the the model.
- Returns:
The components that were added to the model.
- Return type:
Species, Parameters, Reactions, Events, Rate Rules, Assignment Rules, FunctionDefinitions, TimeSpan, or list
- Raises:
ModelError – Component is invalid.
- add_assignment_rule(assignment_rule)[source]¶
Add an assignment rule, or list of assignment rules to the model.
- Parameters:
assignment_rules (gillespy2.AssignmentRule or list of gillespy2.AssignmentRules) – The assignment rule or list of assignment rules to be added to the model object.
- Returns:
The assignment rule or list of assignment rules that were added to the model.
- Return type:
gillespy2.AssignmentRule | list of gillespy2.AssignmentRule
- Raises:
ModelError – If an invalid assignment rule is provided or if assignment rule validation fails.
- add_event(event)[source]¶
Adds an event, or list of events to the model.
- Parameters:
event (gillespy2.Event | list of gillespy2.Events) – The event or list of event to be added to the model object.
- Returns:
The event or list of events that were added to the model.
- Return type:
gillespy2.Event | list of gillespy2.Event
- Raises:
ModelError – If an invalid event is provided or if event validation fails.
- add_function_definition(function_definition)[source]¶
Add function definition, or list of function definitions to the model
- Parameters:
function_definition (gillespy2.FunctionDefinition | list of gillespy2.FunctionDefinitions.) – The function definition, or list of function definitions to be added to the model object.
- Returns:
The function defintion or list of function definitions that were added to the model.
- Return type:
gillespy2.FunctionDefinitions | list of gillespy2.FunctionDefinitions
- Raises:
ModelError – If an invalid function definition is provided.
- add_parameter(parameters)[source]¶
Adds a parameter, or list of parameters to the model.
- Parameters:
parameters (gillespy2.Parameter | list of gillespy2.Parameter) – The parameter or list of parameters to be added to the model object.
- Returns:
A parameter or list of Parameters that were added to the model.
- Return type:
gillespy2.Parameter | list of gillespy2.Parameter
- Raises:
ModelError – If an invalid parameter is provided or if Parameter.validate fails.
- add_rate_rule(rate_rule)[source]¶
Adds a rate rule, or list of rate rules to the model.
- Parameters:
rate_rule (gillespy2.RateRule | list of gillespy2.RateRules) – The rate rule or list of rate rules to be added to the model object.
- Returns:
The rate rule or list of rate rules that were added to the model.
- Return type:
gillespy2.RateRule | list of gillespy2.RateRule
- Raises:
ModelError – If an invalid rate rule is provided or if rate rule validation fails.
- add_reaction(reactions)[source]¶
Adds a reaction, or list of reactions to the model.
- Parameters:
reactions (gillespy2.Reaction | list of gillespy2.Reaction) – The reaction or list of reactions to be added to the model object
- Returns:
The reaction or list of reactions that were added to the model.
- Return type:
gillespy2.Reaction | list of gillespy2.Reaction
- Raises:
ModelError – If an invalid reaction is provided or if Reaction.validate fails.
- add_species(species)[source]¶
Adds a species, or list of species to the model.
- Parameters:
species (gillespy2.Species | list of gillespy2.Species) – The species or list of species to be added to the model object
- Returns:
The species or list of species that were added to the model.
- Return type:
gillespy2.Species | list of gillespy2.Species
- Raises:
ModelError – If an invalid species is provided or if Species.validate fails.
- delete_assignment_rule(name)[source]¶
Removes an assignment rule object by model.
- Parameters:
name (str) – Name of the assignment rule object to be removed.
- Raises:
ModelError – If the assignment rule is not part of the model.
- delete_event(name)[source]¶
Removes an event object by name.
- Parameters:
name (str) – Name of the event object to be removed.
- delete_function_definition(name)[source]¶
Removes a function definition object by name.
- Parameters:
name (str) – Name of the function definition object to be removed.
- delete_parameter(name)[source]¶
Removes a parameter object by name.
- Parameters:
name (str) – Name of the parameter object to be removed.
- Raises:
ModelError – If the parameter is not part of the model.
- delete_rate_rule(name)[source]¶
Removes rate rule object by name.
- Parameters:
name (str) – Name of the rate rule to be removed.
- Raises:
ModelError – If the rate rule is not part of the model.
- delete_reaction(name)[source]¶
Removes a reaction object by name.
- Parameters:
name (str) – Name of the reaction object to be removed.
- Raises:
ModelError – If the reaction is not part of the model.
- delete_species(name)[source]¶
Removes a species object by name.
- Parameters:
name (str) – Name of the species object to be removed.
- Raises:
ModelError – If the species is not part of the model.
- get_all_assignment_rules()[source]¶
Get all of the assignment rules in the model object.
- Returns:
A dict of all assignemt rules in the model, in the form: {name: reaction object}.
- get_all_events()[source]¶
Get all of the events in the model object.
- Returns:
A dict of all evetns in the model, in the form: {name : event object}
- get_all_function_definitions()[source]¶
Get all of the function definitions in the model object.
- Returns:
A dict of all function definitions in the model, in the form {name : function definition object}.
- Return type:
- get_all_parameters()[source]¶
Get all of the parameters in the model object.
- Returns:
A dict of all parameters in the model, in the form: {name : parameter object}
- Return type:
- get_all_rate_rules()[source]¶
Get all of the rate rules in the model object.
- Returns:
A dict of all rate rules in the model, in the form: {name : rate rule object}.
- Return type:
- get_all_reactions()[source]¶
Get all of the reactions in the model object.
- Returns:
A dict of all reactions in the model, in the form: {name : reaction object}.
- Return type:
- get_all_species()[source]¶
Get all of the species in the model object.
- Returns:
A dict of all species in the model, in the form: {name : species object}.
- Return type:
- get_assignment_rule(name)[source]¶
Returns an assignment rule object by name.
- Parameters:
name (str) – Name of the assignment rule object to be returned.
- Returns:
The specified assignment rule object.
- Return type:
gillespy2.AssignmentRule
- Raises:
ModelError – If the assignment rule is not part of the model.
- get_best_solver()[source]¶
Finds best solver for the users simulation. Currently, AssignmentRules, RateRules, FunctionDefinitions, Events, and Species with a dynamic, or continuous population must use the TauHybridSolver.
- Parameters:
precompile (bool) – If True, and the model contains no AssignmentRules, RateRules, FunctionDefinitions, Events, or Species with a dynamic or continuous population, it will choose SSACSolver
- Returns:
gillespy2.gillespySolver
- get_best_solver_algo(algorithm)[source]¶
If user has specified a particular algorithm, we return either the Python or C++ version of that algorithm
- get_element(name)[source]¶
Get a model element specified by name.
- Parameters:
name (str) – Name of the element to be returned.
- Returns:
The specified gillespy2.Model element.
- Return type:
Species, Parameters, Reactions, Events, RateRules, AssignmentRules, FunctionDefinitions, or TimeSpan
- Raises:
ModelError – If the element is not part of the model.
- get_event(name)[source]¶
Returns an event object by name.
- Parameters:
name (str) – Name of the event object to be returned.
- Returns:
The specified event object.
- Return type:
gillespy2.Event
- Raises:
ModelError – If the event is not part of the model.
- get_function_definition(name)[source]¶
Returns a function definition object by name.
- Parameters:
name (str) – Name of the function definition object to be returned.
- Returns:
The specified function definition object.
- Return type:
gillespy2.FunctionDefinition
- get_model_features() Set[Type] [source]¶
Determine what solver-specific model features are present on the model. Used to validate that the model is compatible with the given solver.
- Returns:
Set containing the classes of every solver-specific feature present on the model.
- get_parameter(name)[source]¶
Returns a parameter object by name.
- Parameters:
name (str) – Name of the parameter object to be returned
- Returns:
The specified parameter object.
- Return type:
gillespy2.Parameter
- Raises:
ModelError – If the parameter is not part of the model.
- get_rate_rule(name)[source]¶
Returns a rate rule object by name.
- Parameters:
name (str) – Name of the rate rule object to be returned.
- Returns:
The specified rate rule object.
- Return type:
gillespy2.RateRule
- Raises:
ModelError – If the rate rule is not part of the model.
- get_reaction(name)[source]¶
Returns a reaction object by name.
- Parameters:
name (str) – Name of the reaction object to be returned
- Returns:
The specified reaction object.
- Return type:
gillespy2.Reaction
- Raises:
ModelError – If the reaction is not part of the model.
- get_species(name)[source]¶
Returns a species object by name.
- Parameters:
name (str) – Name of the species object to be returned.
- Returns:
The specified species object.
- Return type:
gillespy2.Species
- Raises:
ModelError – If the species is not part of the model.
- make_translation_table()[source]¶
Make a translation table that describes key:value pairs to convert user-define data into generic equivalents.
- Returns:
A newly generated TranslationTable instance.
- reserved_names = ['vol']¶
- run(solver=None, timeout=0, t=None, increment=None, algorithm=None, **solver_args)[source]¶
Function calling simulation of the model. There are a number of parameters to be set here.
- Parameters:
solver (gillespy.GillesPySolver) – The solver by which to simulate the model. This solver object may be initialized separately to specify an algorithm. Optional, defaults to ssa solver.
timeout (int) – Allows a time_out value in seconds to be sent to a signal handler, restricting simulation run-time
t (int) – End time of simulation
solver_args – Solver-specific arguments to be passed to solver.run()
algorithm (str) – Specify algorithm (‘ODE’, ‘Tau-Leaping’, or ‘SSA’) for GillesPy2 to automatically pick best solver using that algorithm.
- Returns:
Returns a Results object that inherits UserList and contains one or more Trajectory objects that inherit UserDict. Results object supports graphing and csv export.
To pause a simulation and retrieve data before the simulation, keyboard interrupt the simulation by pressing control+c or pressing stop on a jupyter notebook. To resume a simulation, pass your previously ran results into the run method, and set t = to the time you wish the resuming simulation to end (run(resume=results, t=x)).
- **Pause/Resume is only supported for SINGLE TRAJECTORY simulations.
T MUST BE SET OR UNEXPECTED BEHAVIOR MAY OCCUR.**
- sanitized_parameter_names()[source]¶
Generate a dictionary mapping user chosen parameter names to simplified formats which will be used later on by GillesPySolvers evaluating reaction propensity functions.
- Returns:
the dictionary mapping user parameter names to their internal GillesPy notation.
- sanitized_species_names()[source]¶
Generate a dictionary mapping user chosen species names to simplified formats which will be used later on by GillesPySolvers evaluating reaction propensity functions.
- Returns:
the dictionary mapping user species names to their internal GillesPy notation.
- set_parameter(p_name, expression)[source]¶
Set the value of an existing parameter “pname” to “expression” (deprecated).
- Parameters:
p_name (str) – Name of the parameter whose value will be set.
expression (str) – String that may be executed in C, describing the value of the parameter. May reference other parameters by name. (e.g. “k1*4”)
- set_units(units)[source]¶
Sets the units of the model to either “population” or “concentration”
- Parameters:
units (str) – Either “population” or “concentration”
- special_characters = ['[', ']', '+', '-', '*', '/', '.', '^']¶
- timespan(time_span)[source]¶
Set the time span of simulation. GillesPy2 does not support non-uniform timespans.
- Parameters:
time_span (gillespy2.TimeSpan | iterator) – Evenly-spaced list of times at which to sample the species populations during the simulation. Best to use the form gillespy2.TimeSpan(np.linspace( <start time>, <end time>, <number of time-points, inclusive>))
- validate_reactants_and_products(reactions)[source]¶
Internal function (deprecated): Ensure that the rate and all reactants and products are present in the model for the given reaction. This methods must be called before exporting the model.
- Parameters:
reaction (gillespy2.Reaction) – The target reaction to resolve.
- Raises:
ModelError – If the reaction can’t be resolved.
- class gillespy2.core.model.StochMLDocument[source]¶
Bases:
object
Serializiation and deserialization of a Model to/from the native XML format.
- classmethod from_file(filepath)[source]¶
Intializes the document from an exisiting native XML file read from disk.
- classmethod from_model(model)[source]¶
Creates an XML document from an exisiting Model object. This method assumes that all the parameters in the model are already resolved to scalar floats (see Model.resolveParamters).
Note, this method is intended to be used internally by the models ‘serialization’ function, which performs additional operations and tests on the model prior to writing out the XML file.
You should NOT do:
document = StochMLDocument.fromModel(model) print document.toString()
You SHOULD do:
print model.serialize()
- gillespy2.core.model.export_SBML(gillespy_model, filename=None)[source]¶
GillesPy model to SBML converter
- Parameters:
gillespy_model (gillespy.Model) – GillesPy model to be converted to SBML
filename (str) – Path to the SBML file for conversion
- gillespy2.core.model.export_StochSS(gillespy_model, filename=None, return_stochss_model=False)[source]¶
GillesPy model to StochSS converter
- Parameters:
gillespy_model (gillespy.Model) – GillesPy model to be converted to StochSS
filename (str) – Path to the StochSS file for conversion
- gillespy2.core.model.import_SBML(filename, name=None, gillespy_model=None, report_silently_with_sbml_error=False)[source]¶
SBML to GillesPy model converter. NOTE: non-mass-action rates in terms of concentrations may not be converted for population simulation. Use caution when importing SBML.
- Parameters:
filename (str) – Path to the SBML file for conversion.
name (str) – Name of the resulting model
gillespy_model (gillespy.Model) – If desired, the SBML model may be added to an existing GillesPy model
report_silently_with_sbml_error (bool) – SBML import will fail silently and SBML errors will not output to the user.
gillespy2.core.parameter module¶
- class gillespy2.core.parameter.Parameter(name=None, expression=None)[source]¶
Bases:
SortableObject
,Jsonify
A parameter can be given as an expression (function) or directly as a value (scalar). If given an expression, it should be understood as evaluable in the namespace of a parent Model.
- Parameters:
name (str) – The name by which this parameter is called or referenced in reactions, rate rules, assignment rules, and events.
expression (str) – String for a function calculating parameter values. Should be evaluable in namespace of Model.
- Raises:
ParameterError – Arg is of invalid type. Required arg set to None. Arg value is outside of accepted bounds.
- validate(expression=None, coverage='all')[source]¶
Validate the parameter.
- Parameters:
expression (str) – String for a function calculating parameter values. Should be evaluable in namespace of Model.
coverage (str) – The scope of attributes to validate. Set to an attribute name to restrict validation to a specific attribute.
- Raises:
ParameterError – Attribute is of invalid type. Required attribute set to None. Attribute value is outside of accepted bounds.
gillespy2.core.raterule module¶
- class gillespy2.core.raterule.RateRule(variable=None, formula='', name=None)[source]¶
Bases:
SortableObject
,Jsonify
A RateRule is used to express equations that determine the rates of change of variables. This would correspond to a function in the form of dx/dt=f(W)
- Parameters:
name (str) – Name of Rule
variable (str) – Target Species/Parameter to be modified by rule
formula (str) – String representation of formula to be evaluated
gillespy2.core.reaction module¶
- class gillespy2.core.reaction.Reaction(name=None, reactants=None, products=None, propensity_function=None, ode_propensity_function=None, rate=None, annotation=None, massaction=None)[source]¶
Bases:
SortableObject
,Jsonify
Models a single reaction. A reaction has its own dicts of species (reactants and products) and parameters. The reaction’s propensity function needs to be evaluable (and result in a non-negative scalar value) in the namespace defined by the union of those dicts.
- Parameters:
name (str) – The name by which the reaction is called (optional).
reactants (dict) – The reactants that are consumed in the reaction, with stoichiometry. An example would be {R1 : 1, R2 : 2} if the reaction consumes two of R1 and one of R2, where R1 and R2 are Species objects.
products (dict) – The species that are created by the reaction event, with stoichiometry. Same format as reactants.
propensity_function (str) – The custom propensity function for the reaction. Must be evaluable in the namespace of the reaction using C operations.
ode_propensity_function (str) – The custom ode propensity function for the reaction. Must be evaluable in the namespace of the reaction using C operations.
massaction (bool) – (deprecated) The switch to use a mass-action reaction. If set to True, a rate value is required.
rate (float) – The rate of the mass-action reaction, take care to note the units.
annotation (str) – An optional note about the reaction.
Notes
For a species that is NOT consumed in the reaction but is part of a mass action reaction, add it as both a reactant and a product.
Mass-action reactions must also have a rate term added. Note that the input rate represents the mass-action constant rate independent of volume.
if a name is not provided for reactions, the name will be populated by the model based on the order it was added. This could impact seeded simulation results if the order of addition is not preserved.
- Annotate(*args, **kwargs)[source]¶
Add an annotation to this reaction (deprecated).
- Parameters:
annotation (str) – Annotation note to be added to reaction
- addProduct(*args, **kwargs)[source]¶
Add a product to this reaction (deprecated)
- Parameters:
species (spatialpy.core.species.Species) – Species object to be produced by the reaction
stoichiometry (int) – Stoichiometry of this product.
- addReactant(*args, **kwargs)[source]¶
Add a reactant to this reaction (deprecated)
- Parameters:
species (spatialpy.core.species.Species) – reactant Species object
stoichiometry (int) – Stoichiometry of this participant reactant
- add_product(species, stoichiometry)[source]¶
Add a product to this reaction
- Parameters:
species (spatialpy.core.species.Species | str) – Species object to be produced by the reaction
stoichiometry (int) – Stoichiometry of this product.
- add_reactant(species, stoichiometry)[source]¶
Add a reactant to this reaction
- Parameters:
species (spatialpy.core.species.Species) – reactant Species object
stoichiometry (int) – Stoichiometry of this participant reactant
- create_mass_action(*args, **kwargs)[source]¶
Initializes the mass action propensity function given self.reactants and a single parameter value.
- classmethod from_json(json_object)[source]¶
Convert some json_str into a decoded Python type. This function should return a new instance of the type.
- Parameters:
json_str (str) – A json str to be converted into a new type instance.
- Returns:
A decoded object.
- sanitized_propensity_function(species_mappings, parameter_mappings, ode=False)[source]¶
Sanitize the reaction propensity.
- Parameters:
species_mappings (dict) – Mapping of species names to sanitized species names.
parameter_mappings (dict) – Mapping of parameter names to sanitized parameter names.
- Returns:
The sanitized propensity.
- Return type:
str
- setType(rxntype)[source]¶
Sets reaction type to either “mass-action” or “customized” (deprecated)
- Parameters:
rxntype (str) – Either “mass-action” or “customized”
- set_annotation(annotation)[source]¶
Add an annotation to this reaction.
- Parameters:
annotation (str) – Annotation note to be added to reaction
- set_propensities(propensity_function=None, ode_propensity_function=None)[source]¶
Change the reaction to a customized reaction and set the propensities.
- Parameters:
propensity_function (str) – The custom propensity function for the reaction. Must be evaluable in the namespace of the reaction using C operations.
ode_propensity_function (str) – The custom ode propensity function for the reaction. Must be evaluable in the namespace of the reaction using C operations.
- set_rate(rate)[source]¶
Change the reaction to a mass-action reaction and set the rate.
- Parameters:
rate (int | float | str | Parameter) – The rate of the mass-action reaction, take care to note the units.
- to_dict()[source]¶
Convert the object into a dictionary ready for json encoding. Note: Complex types that inherit from Jsonify do not need to be manually encoded.
By default, this function will return a dictionary of the object’s public types.
- Returns:
The backing var dictionary of the object.
gillespy2.core.results module¶
- class gillespy2.core.results.Results(data)[source]¶
-
List of Trajectory objects created by a gillespy2 solver, extends the UserList object.
- Parameters:
data (UserList) – A list of trajectory objects
- average_ensemble()[source]¶
Generate a single Results object with a Trajectory that is made of the means of all trajectories’ outputs
- Returns:
The Results object
- classmethod build_from_solver_results(solver, live_output_options)[source]¶
Build a gillespy2.Results object using the provided solver results.
- Parameters:
solver (gillespy2.GillesPySolver) – The solver used to run the simulation.
live_output_options (dict) – dictionary contains options for live_output. By default {“interval”:1}. “interval” specifies seconds between displaying. “clear_output” specifies if display should be refreshed with each display
- plot(index=None, xaxis_label='Time', xscale='linear', yscale='linear', yaxis_label='Value', style='default', title=None, show_title=False, show_legend=True, multiple_graphs=False, included_species_list=[], save_png=False, figsize=(18, 10))[source]¶
Plots the Results using matplotlib.
- Parameters:
index (int) – If not none, the index of the Trajectory to be plotted.
xaxis_label (str) – The label for the x-axis
yaxis_label (str) – The label for the y-axis
title (str) – The title of the graph
multiple_graphs (bool) – IF each trajectory should have its own graph or if they should overlap.
included_species_list (list) – A list of strings describing which species to include. By default displays all species.
save_png (bool or str) – Should the graph be saved as a png file. If True, File name is title of graph. If a string is given, file is named after that string.
figsize (tuple of ints (x,y)) – The size of the graph. A tuple of the form (width,height). Is (18,10) by default.
- plot_mean_stdev(xscale='linear', yscale='linear', xaxis_label='Time', yaxis_label='Value', title=None, show_title=False, style='default', show_legend=True, included_species_list=[], ddof=0, save_png=False, figsize=(18, 10))[source]¶
Plot a matplotlib graph depicting mean and standard deviation of a results object.
- Parameters:
xaxis_label (str) – The label for the x-axis
yaxis_label (str) – The label for the y-axis
title (str) – The title of the graph
show_title (bool) – Default False, if True, title will be displayed on the graph.
style (str) – Matplotlib style to be displayed on graph.
show_legend (bool) – Default to True, if False, legend will not be shown on graph.
included_species_list (list) – A list of strings describing which species to include. By default displays all species.
ddof (int) – Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of trajectories. Sample standard deviation uses ddof of 1. Defaults to population standard deviation where ddof is 0.
figsize (tuple of ints (x,y)) – The size of the graph. A tuple of the form (width,height). Is (18,10) by default.
- plot_std_dev_range(**kwargs)[source]¶
Plot a matplotlib graph depicting mean and standard deviation of a results object.
- Parameters:
xaxis_label (str) – The label for the x-axis
yaxis_label (str) – The label for the y-axis
title (str) – The title of the graph
show_title (bool) – Default False, if True, title will be displayed on the graph.
style (str) – Matplotlib style to be displayed on graph.
show_legend (bool) – Default to True, if False, legend will not be shown on graph.
included_species_list (list) – A list of strings describing which species to include. By default displays all species.
ddof (int) – Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of trajectories. Sample standard deviation uses ddof of 1. Defaults to population standard deviation where ddof is 0.
figsize (tuple of ints (x,y)) – The size of the graph. A tuple of the form (width,height). Is (18,10) by default.
- plotplotly(index=None, xaxis_label='Time', yaxis_label='Value', title=None, show_title=False, show_legend=True, multiple_graphs=False, included_species_list=[], return_plotly_figure=False, **layout_args)[source]¶
Plots the Results using plotly. Can only be viewed in a Jupyter Notebook.
- Parameters:
index (int) – If not none, the index of the Trajectory to be plotted.
xaxis_label (str) – The label for the x-axis
yaxis_label (str) – The label for the y-axis
title (str) – The title of the graph
show_title (bool) – If True, title will be shown on graph.
show_legend (bool) – Default True, if False, legend will not be shown on graph.
multiple_graphs (bool) – IF each trajectory should have its own graph or if they should overlap.
included_species_list (list) – A list of strings describing which species to include. By default displays all species.
return_plotly_figure (bool) – Whether or not to return a figure dictionary of data(graph object traces) and layout which may be edited by the user
**layout_args –
Optional additional arguments to be passed to plotlys layout constructor.
- plotplotly_mean_stdev(xaxis_label='Time', yaxis_label='Value', title=None, show_title=False, show_legend=True, included_species_list=[], return_plotly_figure=False, ddof=0, **layout_args)[source]¶
Plot a plotly graph depicting the mean and standard deviation of a results object
- Parameters:
xaxis_label (str) – The label for the x-axis
yaxis_label (str) – The label for the y-axis
title (str) – The title of the graph
show_title (bool) – If True, title will be shown on graph.
show_legend (bool) – Default True, if False, legend will not be shown on graph.
included_species_list (list) – A list of strings describing which species to include. By default displays all species.
return_plotly_figure (bool) – Whether or not to return a figure dicctionary of data(graph object traces) and layout which may be edited by the user
ddof (int) – Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of trajectories. Sample standard deviation uses ddof of 1. Defaults to population standard deviation where ddof is 0.
**layout_args –
Optional additional arguments to be passed to plotlys layout constructor.
- plotplotly_std_dev_range(**kwargs)[source]¶
Plot a plotly graph depicting the mean and standard deviation of a results object
- Parameters:
xaxis_label (str) – The label for the x-axis
yaxis_label (str) – The label for the y-axis
title (str) – The title of the graph
show_title (bool) – If True, title will be shown on graph.
show_legend (bool) – Default True, if False, legend will not be shown on graph.
included_species_list (list) – A list of strings describing which species to include. By default displays all species.
return_plotly_figure (bool) – Whether or not to return a figure dicctionary of data(graph object traces) and layout which may be edited by the user
ddof (int) – Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of trajectories. Sample standard deviation uses ddof of 1. Defaults to population standard deviation where ddof is 0.
**layout_args –
Optional additional arguments to be passed to plotlys layout constructor.
- stddev_ensemble(ddof=0)[source]¶
Generate a single Results object with a Trajectory that is made of the sample standard deviations of all trajectories’ outputs.
- Parameters:
ddof (int) – Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of trajectories. Sample standard deviation uses ddof of 1. Defaults to population standard deviation where ddof is 0.
- Returns:
the Results object
- to_array()[source]¶
Convert the results object into a numpy array.
- Returns:
Array containing the result of the simulation.
- Return type:
numpy.ndarray
- to_csv(path='.', nametag=None, stamp=None, suffix='.odf', verbose=False)[source]¶
Outputs the Results to one or more .csv files in a new directory.
- Parameters:
nametag (str) – allows the user to optionally “tag” the directory and included files. Defaults to the model name.
path (str) – the location for the new directory and included files. Defaults to model location.
stamp (str) – Allows the user to optionally “tag” the directory (not included files). Default is timestamp.
verbose (str) – Print useful informataion.
- Returns:
Path to the observed data files.
- Return type:
str
- class gillespy2.core.results.Trajectory(data, model=None, solver_name='Undefined solver name', rc=0)[source]¶
-
Trajectory Dict created by a gillespy2 solver containing single trajectory, extends the UserDict object.
- Parameters:
data (UserDict) – A dictionary of trajectory values created by a solver
model (str) – The name of the model used to create the trajectory
solver_name (str) – The name of the solver used to create the trajectory
rc (int) – The solvers status return code.
status – The solver status (‘Success’,’Timed out’)
gillespy2.core.sortableobject module¶
gillespy2.core.species module¶
- class gillespy2.core.species.Species(name=None, initial_value=0, constant=False, boundary_condition=False, mode=None, allow_negative_populations=False, switch_min=0, switch_tol=0.03)[source]¶
Bases:
SortableObject
,Jsonify
Chemical species. Can be added to Model object to interact with other species or time.
- Parameters:
name (str) – The name by which this species will be called in reactions and within the model.
initial_value (int | float) – Initial population (discrete) or concentration (continuous) of this species.
constant (bool) – If true, the value of the species cannot be changed (currently TauHybridSolver only)
boundary_condition (bool) – If true, species can be changed by events and rate rules, but not by reactions. (TauHybridSolver only)
mode (str) – *FOR USE WITH TauHybridSolver ONLY* Sets the mode of representation of this species for the TauHybridSolver, can be discrete, continuous, or dynamic. mode=’dynamic’ - Allows a species to be represented as either discrete or continuous mode=’continuous’ - Species will only be represented as continuous mode=’discrete’ - Species will only be represented as discrete
allow_negative_populations (bool) – If true, population can be reduced below 0.
switch_tol (float) – *FOR USE WITH TauHybridSolver ONLY* Tolerance level for considering a dynamic species deterministically, value is compared to an estimated sd/mean population of a species after a given time step. This value will be used if a switch_min is not provided. The default value is 0.03
switch_min (float) – *FOR USE WITH TauHybridSolver ONLY* Minimum population value at which species will be represented as continuous. If a value is given, switch_min will be used instead of switch_tol
- Raises:
SpeciesError – Arg is of invalid type. Required arg set to None. Arg value is outside of accepted bounds.
- set_initial_value(initial_value)[source]¶
Setter method for initial_value of a population
- Parameters:
initial_value (int | float) – Initial population (discrete) or concentration (continuous) of this species.
- Raises:
SpeciesError – initial_value is of invalid type. initial_value set to None. initial_value is a float when mode != ‘continuous’. initial_value is negative when allow_negative_populations=False.
- validate(initial_value=None, coverage='all')[source]¶
Validate the species.
- Parameters:
initial_value (int | float) – Initial population (discrete) or concentration (continuous) of this species.
coverage (str) – The scope of attributes to validate. Set to an attribute name to restrict validation to a specific attribute.
- Raises:
SpeciesError – Attribute is of invalid type. Required attribute set to None. Attribute is value outside of accepted bounds.
gillespy2.core.timespan module¶
- class gillespy2.core.timespan.TimeSpan(items)[source]¶
Bases:
Iterator
,Jsonify
Model timespan that describes the duration to run the simulation and at which timepoint to sample the species populations during the simulation.
- Parameters:
items (list, tuple, range, or numpy.ndarray) – Evenly-spaced list of times at which to sample the species populations during the simulation. Best to use the form np.linspace(<start time>, <end time>, <number of time-points, inclusive>)
- Raises:
TimespanError – items is an invalid type.
- classmethod arange(increment, t=20)[source]¶
Creates a timespan using the form np.arange(0, <t, inclusive>, <increment>).
- Parameters:
increment (float | int) – Distance between sample points for the species populations during the simulation.
t (float | int) – End time for the simulation.
- Returns:
Timespan for the model.
- Return type:
gillespy2.TimeSpan
- Raises:
TimespanError – t or increment are None, <= 0, or invalid type.
- classmethod linspace(t=20, num_points=None)[source]¶
Creates a timespan using the form np.linspace(0, <t>, <num_points, inclusive>).
- Parameters:
t (float | int) – End time for the simulation.
num_points (int) – Number of sample points for the species populations during the simulation.
- Returns:
Timespan for the model.
- Return type:
gillespy2.TimeSpan
- Raises:
TimespanError – t or num_points are None, <= 0, or invalid type.
- validate()[source]¶
Validate the models time span
- Raises:
TimespanError – Timespan is an invalid type, empty, not uniform, contains a single repeated value, or contains a negative initial time.
Module contents¶
- class gillespy2.core.AssignmentRule(variable=None, formula=None, name=None)[source]¶
Bases:
SortableObject
,Jsonify
An AssignmentRule is used to express equations that set the values of variables. This would correspond to a function in the form of x = f(V)
- Parameters:
name (str) – Name of the Rule
variable (str) – Target Species/Parameter to be modified by rule
formula (str) – String representation of formula to be evaluated
- sanitized_formula(species_mappings, parameter_mappings)[source]¶
Sanitize the assignment rule formula.
- Parameters:
species_mappings (dict) – Mapping of species names to sanitized species names.
parameter_mappings (dict) – Mapping of parameter names to sanitized parameter names.
- Returns:
The sanitized formula.
- Return type:
str
- exception gillespy2.core.AssignmentRuleError[source]¶
Bases:
ModelError
- exception gillespy2.core.BuildError[source]¶
Bases:
SolverError
- class gillespy2.core.ChainMap(*maps)[source]¶
Bases:
MutableMapping
A ChainMap groups multiple dicts (or other mappings) together to create a single, updateable view.
The underlying mappings are stored in a list. That list is public and can be accessed or updated using the maps attribute. There is no other state.
Lookups search the underlying mappings successively until a key is found. In contrast, writes, updates, and deletions only operate on the first mapping.
- classmethod fromkeys(iterable, *args)[source]¶
Create a ChainMap with a single dict created from the iterable.
- new_child(m=None)[source]¶
New ChainMap with a new map followed by all previous maps. If no map is provided, an empty dict is used.
- property parents¶
].
- Type:
New ChainMap from maps[1
- exception gillespy2.core.DirectoryError[source]¶
Bases:
SolverError
- class gillespy2.core.Event(name='', delay=None, assignments=[], priority='0', trigger=None, use_values_from_trigger_time=False)[source]¶
Bases:
Jsonify
An Event can be given as an assignment_expression (function) or directly as a value (scalar). If given an assignment_expression, it should be understood as evaluable in the namespace of a parent Model.
- Parameters:
name (str) – The name by which this Event is called or referenced in reactions.
assignments (str) – List of EventAssignments to be executed at trigger or delay
trigger (EventTrigger) – contains math expression which can be evaluated to a boolean result. Upon the transition from ‘False’ to ‘True’, event assignments may be executed immediately, or after a designated delay.
delay (str) – contains math expression evaluable within model namespace. This expression designates a delay between the trigger of an event and the execution of its assignments.
priority (str) – Contains math expression evaluable within model namespace.
- add_assignment(assignment)[source]¶
Adds an EventAssignment or a list of EventAssignment.
- Parameters:
assignment (EventAssignment or list[EventAssignment]) – The event or list of events to be added to this event.
- class gillespy2.core.EventAssignment(name=None, variable=None, expression=None)[source]¶
Bases:
Jsonify
An EventAssignment describes a change to be performed to the current model simulation. This is assignment can either be fired at the time its associated trigger changes from false to true, or after a specified delay, depending on how the Event to which it is assigned is configured.
- Parameters:
variable (gillespy2.Species, gillespy2.Parameter) – Target model component to be modified by the EventAssignment expression. Valid target variables include gillespy2 Species, Parameters, and Compartments.
expression (str) – String to be evaluated when the event is fired. This expression must be evaluable within the model namespace, and the results of it’s evaluation will be assigned to the EventAssignment variable.
- exception gillespy2.core.EventError[source]¶
Bases:
ModelError
- class gillespy2.core.EventTrigger(expression=None, initial_value=False, persistent=False)[source]¶
Bases:
Jsonify
Trigger detects changes in model/environment conditions in order to fire an event. A Trigger contains an expression, a mathematical function which can be evaluated to a boolean value within a model’s namespace. Upon transitioning from ‘false’ to ‘true’, this trigger will cause the immediate execution of an event’s list of assignments if no delay is present, otherwise, the delay evaluation will be initialized.
- Parameters:
expression (str) – String for a function calculating EventTrigger values. Should be evaluable in namespace of Model.
value (bool) – Value of EventTrigger at simulation start, with time t=0
persistent (bool) – Determines if trigger condition is persistent or not
- sanitized_expression(species_mappings, parameter_mappings)[source]¶
Sanitize the event trigger expression.
- Parameters:
species_mappings (dict) – Mapping of species names to sanitized species names.
parameter_mappings (dict) – Mapping of parameter names to sanitized parameter names.
- Returns:
The sanitized expression.
- Return type:
str
- exception gillespy2.core.ExecutionError[source]¶
Bases:
SolverError
- class gillespy2.core.FunctionDefinition(name='', function=None, args=[])[source]¶
Bases:
SortableObject
,Jsonify
Object representation defining an evaluable function to be used during simulation of a GillesPy2 model
- Parameters:
name (str) – Name of the function to be made and called
function (str) – Defined function body of operation to be performed.
variables (list[str]) – String names of Variables to be used as arguments to function.
- get_arg_string() str [source]¶
Convert function’s argument list into a comma-separated formatted string.
- Returns:
Argument list as a comma-separated formatted string.
- sanitized_function(species_mappings, parameter_mappings)[source]¶
Sanitize the function definition function.
- Parameters:
species_mappings (dict) – Mapping of species names to sanitized species names.
parameter_mappings (dict) – Mapping of parameter names to sanitized parameter names.
- Returns:
The sanitized function.
- Return type:
str
- exception gillespy2.core.FunctionDefinitionError[source]¶
Bases:
ModelError
- class gillespy2.core.GillesPySolver[source]¶
Bases:
object
Abstract class for a solver.
- classmethod get_supported_integrator_options() Set[str] [source]¶
Get the supported integrator options
- name = 'GillesPySolver'¶
- run(model, t=20, number_of_trajectories=1, increment=0.05, seed=None, debug=False, profile=False, **kwargs)[source]¶
Call out and run the solver. Collect the results.
- Parameters:
model (gillespy.Model) – The model on which the solver will operate.
t (int) – The end time of the solver
number_of_trajectories (int) – The number of times to sample the chemical master equation. Each trajectory will be returned at the end of the simulation.
increment (float) – The time step of the solution
seed (int) – The random seed for the simulation. Defaults to None.
debug (bool) – Set to True to provide additional debug information about the simulation.
- Returns:
Simulation trajectories.
- classmethod validate_integrator_options(options: dict[str, float]) dict[str, float] [source]¶
Validate the integrator options.
- Parameters:
options (dict) – Integrator options to validate.
- Returns:
Dict of supported integrator options.
- Return type:
dict
- classmethod validate_model(sol_model, model)[source]¶
Validate that the solvers model is the same as the model passed to solver.run.
- Parameters:
sol_model (gillespy2.Model) – Solver model object.
model (gillespy2.Model) – Model object passed to solver.run.
- Raises:
SimulationError – If the models are not equal.
- classmethod validate_sbml_features(model)[source]¶
Validate the models SBML features.
- Parameters:
model (gillespy2.Model) – The model object to be checked.
- Raises:
ModelError – If the model contains unsupported SBML features.
- validate_tspan(increment, t)[source]¶
Validate the models time span and set it if not provided.
- Parameters:
increment (int) – The current value of increment.
t (int) – The end time of the simulation.
- Raises:
SimulationError – if timespan and increment are both set by the user or neither are set by the user.
- exception gillespy2.core.InvalidModelError[source]¶
Bases:
SimulationError
- exception gillespy2.core.InvalidStochMLError[source]¶
Bases:
SimulationError
- class gillespy2.core.Jsonify[source]¶
Bases:
object
Interface to allow for instances of arbitrary types to be encoded into json strings and decoded into new objects.
- classmethod from_dict(src_dict: dict) object [source]¶
Convert some dict into a new instance of a python type. This function will return a __new__ instance of the type.
- Parameters:
src_dict (dict) – The dictionary to apply onto the new instance.
- Returns:
A new object with its backing __dict__ set to a copy of src_dict.
- classmethod from_json(json_str: str) object [source]¶
Convert some json_str into a decoded Python type. This function should return a new instance of the type.
- Parameters:
json_str (str) – A json str to be converted into a new type instance.
- Returns:
A decoded object.
- get_json_hash(ignore_whitespace=True, hash_private_vals=False) str [source]¶
Get the hash of the json representation of self.
- Parameters:
ignore_whitespace (bool) – If set to True all whitespace will be stripped from the JSON prior to being hashed.
hash_private_vals (bool) – If set to True all private and non-private variables will be included in the hash.
- Returns:
An MD5 hash of the object’s sorted JSON representation.
- get_translation_table() TranslationTable [source]¶
Make and/or return the translation table.
- Returns:
A TranslationTable instance.
- make_translation_table() TranslationTable [source]¶
Make a translation table that describes key:value pairs to convert user-define data into generic equivalents.
- Returns:
A newly generated TranslationTable instance.
- public_vars() dict [source]¶
Gets a dictionary of public vars that exist on self. Keys starting with ‘_’ are ignored.
- Returns:
A dictionary containing all public (‘_’-prefixed) variables on the object.
- to_dict() dict [source]¶
Convert the object into a dictionary ready for json encoding. Note: Complex types that inherit from Jsonify do not need to be manually encoded.
By default, this function will return a dictionary of the object’s public types.
- Returns:
The backing var dictionary of the object.
- class gillespy2.core.Model(name='', population=True, volume=1.0, tspan=None, annotation='model')[source]¶
Bases:
SortableObject
,Jsonify
Representation of a well mixed biochemical model. Contains reactions, parameters, species.
- Parameters:
name (str) – The name of the model, or an annotation describing it.
population (bool) – The type of model being described. A discrete stochastic model is a population model (True), a deterministic model is a concentration model (False). Automatic conversion from population to concentration models may be used, by setting the volume parameter.
volume (float) – The volume of the system matters when converting to from population to concentration form. This will also set a parameter “vol” for use in custom (i.e. non-mass-action) propensity functions.
tspan (numpy ndarray) – The timepoints at which the model should be simulated. If None, a default timespan is added. May be set later, see Model.timespan
annotation (str) – Option further description of model
- add(components)[source]¶
Adds a component, or list of components to the model. If a list is provided, Species and Parameters are added before other components. Lists may contain any combination of accepted types other than lists and do not need to be in any particular order.
- Parameters:
components (Species, Parameters, Reactions, Events, Rate Rules, Assignment Rules, FunctionDefinitions, TimeSpan, or list) – The component or list of components to be added the the model.
- Returns:
The components that were added to the model.
- Return type:
Species, Parameters, Reactions, Events, Rate Rules, Assignment Rules, FunctionDefinitions, TimeSpan, or list
- Raises:
ModelError – Component is invalid.
- add_assignment_rule(assignment_rule)[source]¶
Add an assignment rule, or list of assignment rules to the model.
- Parameters:
assignment_rules (gillespy2.AssignmentRule or list of gillespy2.AssignmentRules) – The assignment rule or list of assignment rules to be added to the model object.
- Returns:
The assignment rule or list of assignment rules that were added to the model.
- Return type:
gillespy2.AssignmentRule | list of gillespy2.AssignmentRule
- Raises:
ModelError – If an invalid assignment rule is provided or if assignment rule validation fails.
- add_event(event)[source]¶
Adds an event, or list of events to the model.
- Parameters:
event (gillespy2.Event | list of gillespy2.Events) – The event or list of event to be added to the model object.
- Returns:
The event or list of events that were added to the model.
- Return type:
gillespy2.Event | list of gillespy2.Event
- Raises:
ModelError – If an invalid event is provided or if event validation fails.
- add_function_definition(function_definition)[source]¶
Add function definition, or list of function definitions to the model
- Parameters:
function_definition (gillespy2.FunctionDefinition | list of gillespy2.FunctionDefinitions.) – The function definition, or list of function definitions to be added to the model object.
- Returns:
The function defintion or list of function definitions that were added to the model.
- Return type:
gillespy2.FunctionDefinitions | list of gillespy2.FunctionDefinitions
- Raises:
ModelError – If an invalid function definition is provided.
- add_parameter(parameters)[source]¶
Adds a parameter, or list of parameters to the model.
- Parameters:
parameters (gillespy2.Parameter | list of gillespy2.Parameter) – The parameter or list of parameters to be added to the model object.
- Returns:
A parameter or list of Parameters that were added to the model.
- Return type:
gillespy2.Parameter | list of gillespy2.Parameter
- Raises:
ModelError – If an invalid parameter is provided or if Parameter.validate fails.
- add_rate_rule(rate_rule)[source]¶
Adds a rate rule, or list of rate rules to the model.
- Parameters:
rate_rule (gillespy2.RateRule | list of gillespy2.RateRules) – The rate rule or list of rate rules to be added to the model object.
- Returns:
The rate rule or list of rate rules that were added to the model.
- Return type:
gillespy2.RateRule | list of gillespy2.RateRule
- Raises:
ModelError – If an invalid rate rule is provided or if rate rule validation fails.
- add_reaction(reactions)[source]¶
Adds a reaction, or list of reactions to the model.
- Parameters:
reactions (gillespy2.Reaction | list of gillespy2.Reaction) – The reaction or list of reactions to be added to the model object
- Returns:
The reaction or list of reactions that were added to the model.
- Return type:
gillespy2.Reaction | list of gillespy2.Reaction
- Raises:
ModelError – If an invalid reaction is provided or if Reaction.validate fails.
- add_species(species)[source]¶
Adds a species, or list of species to the model.
- Parameters:
species (gillespy2.Species | list of gillespy2.Species) – The species or list of species to be added to the model object
- Returns:
The species or list of species that were added to the model.
- Return type:
gillespy2.Species | list of gillespy2.Species
- Raises:
ModelError – If an invalid species is provided or if Species.validate fails.
- delete_assignment_rule(name)[source]¶
Removes an assignment rule object by model.
- Parameters:
name (str) – Name of the assignment rule object to be removed.
- Raises:
ModelError – If the assignment rule is not part of the model.
- delete_event(name)[source]¶
Removes an event object by name.
- Parameters:
name (str) – Name of the event object to be removed.
- delete_function_definition(name)[source]¶
Removes a function definition object by name.
- Parameters:
name (str) – Name of the function definition object to be removed.
- delete_parameter(name)[source]¶
Removes a parameter object by name.
- Parameters:
name (str) – Name of the parameter object to be removed.
- Raises:
ModelError – If the parameter is not part of the model.
- delete_rate_rule(name)[source]¶
Removes rate rule object by name.
- Parameters:
name (str) – Name of the rate rule to be removed.
- Raises:
ModelError – If the rate rule is not part of the model.
- delete_reaction(name)[source]¶
Removes a reaction object by name.
- Parameters:
name (str) – Name of the reaction object to be removed.
- Raises:
ModelError – If the reaction is not part of the model.
- delete_species(name)[source]¶
Removes a species object by name.
- Parameters:
name (str) – Name of the species object to be removed.
- Raises:
ModelError – If the species is not part of the model.
- get_all_assignment_rules()[source]¶
Get all of the assignment rules in the model object.
- Returns:
A dict of all assignemt rules in the model, in the form: {name: reaction object}.
- get_all_events()[source]¶
Get all of the events in the model object.
- Returns:
A dict of all evetns in the model, in the form: {name : event object}
- get_all_function_definitions()[source]¶
Get all of the function definitions in the model object.
- Returns:
A dict of all function definitions in the model, in the form {name : function definition object}.
- Return type:
- get_all_parameters()[source]¶
Get all of the parameters in the model object.
- Returns:
A dict of all parameters in the model, in the form: {name : parameter object}
- Return type:
- get_all_rate_rules()[source]¶
Get all of the rate rules in the model object.
- Returns:
A dict of all rate rules in the model, in the form: {name : rate rule object}.
- Return type:
- get_all_reactions()[source]¶
Get all of the reactions in the model object.
- Returns:
A dict of all reactions in the model, in the form: {name : reaction object}.
- Return type:
- get_all_species()[source]¶
Get all of the species in the model object.
- Returns:
A dict of all species in the model, in the form: {name : species object}.
- Return type:
- get_assignment_rule(name)[source]¶
Returns an assignment rule object by name.
- Parameters:
name (str) – Name of the assignment rule object to be returned.
- Returns:
The specified assignment rule object.
- Return type:
gillespy2.AssignmentRule
- Raises:
ModelError – If the assignment rule is not part of the model.
- get_best_solver()[source]¶
Finds best solver for the users simulation. Currently, AssignmentRules, RateRules, FunctionDefinitions, Events, and Species with a dynamic, or continuous population must use the TauHybridSolver.
- Parameters:
precompile (bool) – If True, and the model contains no AssignmentRules, RateRules, FunctionDefinitions, Events, or Species with a dynamic or continuous population, it will choose SSACSolver
- Returns:
gillespy2.gillespySolver
- get_best_solver_algo(algorithm)[source]¶
If user has specified a particular algorithm, we return either the Python or C++ version of that algorithm
- get_element(name)[source]¶
Get a model element specified by name.
- Parameters:
name (str) – Name of the element to be returned.
- Returns:
The specified gillespy2.Model element.
- Return type:
Species, Parameters, Reactions, Events, RateRules, AssignmentRules, FunctionDefinitions, or TimeSpan
- Raises:
ModelError – If the element is not part of the model.
- get_event(name)[source]¶
Returns an event object by name.
- Parameters:
name (str) – Name of the event object to be returned.
- Returns:
The specified event object.
- Return type:
gillespy2.Event
- Raises:
ModelError – If the event is not part of the model.
- get_function_definition(name)[source]¶
Returns a function definition object by name.
- Parameters:
name (str) – Name of the function definition object to be returned.
- Returns:
The specified function definition object.
- Return type:
gillespy2.FunctionDefinition
- get_model_features() Set[Type] [source]¶
Determine what solver-specific model features are present on the model. Used to validate that the model is compatible with the given solver.
- Returns:
Set containing the classes of every solver-specific feature present on the model.
- get_parameter(name)[source]¶
Returns a parameter object by name.
- Parameters:
name (str) – Name of the parameter object to be returned
- Returns:
The specified parameter object.
- Return type:
gillespy2.Parameter
- Raises:
ModelError – If the parameter is not part of the model.
- get_rate_rule(name)[source]¶
Returns a rate rule object by name.
- Parameters:
name (str) – Name of the rate rule object to be returned.
- Returns:
The specified rate rule object.
- Return type:
gillespy2.RateRule
- Raises:
ModelError – If the rate rule is not part of the model.
- get_reaction(name)[source]¶
Returns a reaction object by name.
- Parameters:
name (str) – Name of the reaction object to be returned
- Returns:
The specified reaction object.
- Return type:
gillespy2.Reaction
- Raises:
ModelError – If the reaction is not part of the model.
- get_species(name)[source]¶
Returns a species object by name.
- Parameters:
name (str) – Name of the species object to be returned.
- Returns:
The specified species object.
- Return type:
gillespy2.Species
- Raises:
ModelError – If the species is not part of the model.
- make_translation_table()[source]¶
Make a translation table that describes key:value pairs to convert user-define data into generic equivalents.
- Returns:
A newly generated TranslationTable instance.
- reserved_names = ['vol']¶
- run(solver=None, timeout=0, t=None, increment=None, algorithm=None, **solver_args)[source]¶
Function calling simulation of the model. There are a number of parameters to be set here.
- Parameters:
solver (gillespy.GillesPySolver) – The solver by which to simulate the model. This solver object may be initialized separately to specify an algorithm. Optional, defaults to ssa solver.
timeout (int) – Allows a time_out value in seconds to be sent to a signal handler, restricting simulation run-time
t (int) – End time of simulation
solver_args – Solver-specific arguments to be passed to solver.run()
algorithm (str) – Specify algorithm (‘ODE’, ‘Tau-Leaping’, or ‘SSA’) for GillesPy2 to automatically pick best solver using that algorithm.
- Returns:
Returns a Results object that inherits UserList and contains one or more Trajectory objects that inherit UserDict. Results object supports graphing and csv export.
To pause a simulation and retrieve data before the simulation, keyboard interrupt the simulation by pressing control+c or pressing stop on a jupyter notebook. To resume a simulation, pass your previously ran results into the run method, and set t = to the time you wish the resuming simulation to end (run(resume=results, t=x)).
- **Pause/Resume is only supported for SINGLE TRAJECTORY simulations.
T MUST BE SET OR UNEXPECTED BEHAVIOR MAY OCCUR.**
- sanitized_parameter_names()[source]¶
Generate a dictionary mapping user chosen parameter names to simplified formats which will be used later on by GillesPySolvers evaluating reaction propensity functions.
- Returns:
the dictionary mapping user parameter names to their internal GillesPy notation.
- sanitized_species_names()[source]¶
Generate a dictionary mapping user chosen species names to simplified formats which will be used later on by GillesPySolvers evaluating reaction propensity functions.
- Returns:
the dictionary mapping user species names to their internal GillesPy notation.
- set_parameter(p_name, expression)[source]¶
Set the value of an existing parameter “pname” to “expression” (deprecated).
- Parameters:
p_name (str) – Name of the parameter whose value will be set.
expression (str) – String that may be executed in C, describing the value of the parameter. May reference other parameters by name. (e.g. “k1*4”)
- set_units(units)[source]¶
Sets the units of the model to either “population” or “concentration”
- Parameters:
units (str) – Either “population” or “concentration”
- special_characters = ['[', ']', '+', '-', '*', '/', '.', '^']¶
- timespan(time_span)[source]¶
Set the time span of simulation. GillesPy2 does not support non-uniform timespans.
- Parameters:
time_span (gillespy2.TimeSpan | iterator) – Evenly-spaced list of times at which to sample the species populations during the simulation. Best to use the form gillespy2.TimeSpan(np.linspace( <start time>, <end time>, <number of time-points, inclusive>))
- validate_reactants_and_products(reactions)[source]¶
Internal function (deprecated): Ensure that the rate and all reactants and products are present in the model for the given reaction. This methods must be called before exporting the model.
- Parameters:
reaction (gillespy2.Reaction) – The target reaction to resolve.
- Raises:
ModelError – If the reaction can’t be resolved.
- class gillespy2.core.OrderedDict[source]¶
Bases:
dict
Dictionary that remembers insertion order
- clear() None. Remove all items from od. ¶
- copy() a shallow copy of od ¶
- fromkeys(value=None)¶
Create a new ordered dictionary with keys from iterable and values set to value.
- items() a set-like object providing a view on D's items ¶
- keys() a set-like object providing a view on D's keys ¶
- move_to_end(key, last=True)¶
Move an existing element to the end (or beginning if last is false).
Raise KeyError if the element does not exist.
- pop(k[, d]) v, remove specified key and return the corresponding ¶
value. If key is not found, d is returned if given, otherwise KeyError is raised.
- popitem(last=True)¶
Remove and return a (key, value) pair from the dictionary.
Pairs are returned in LIFO order if last is true or FIFO order if false.
- setdefault(key, default=None)¶
Insert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
- update([E, ]**F) None. Update D from dict/iterable E and F. ¶
If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]
- values() an object providing a view on D's values ¶
- class gillespy2.core.Parameter(name=None, expression=None)[source]¶
Bases:
SortableObject
,Jsonify
A parameter can be given as an expression (function) or directly as a value (scalar). If given an expression, it should be understood as evaluable in the namespace of a parent Model.
- Parameters:
name (str) – The name by which this parameter is called or referenced in reactions, rate rules, assignment rules, and events.
expression (str) – String for a function calculating parameter values. Should be evaluable in namespace of Model.
- Raises:
ParameterError – Arg is of invalid type. Required arg set to None. Arg value is outside of accepted bounds.
- validate(expression=None, coverage='all')[source]¶
Validate the parameter.
- Parameters:
expression (str) – String for a function calculating parameter values. Should be evaluable in namespace of Model.
coverage (str) – The scope of attributes to validate. Set to an attribute name to restrict validation to a specific attribute.
- Raises:
ParameterError – Attribute is of invalid type. Required attribute set to None. Attribute value is outside of accepted bounds.
- exception gillespy2.core.ParameterError[source]¶
Bases:
ModelError
- class gillespy2.core.RateRule(variable=None, formula='', name=None)[source]¶
Bases:
SortableObject
,Jsonify
A RateRule is used to express equations that determine the rates of change of variables. This would correspond to a function in the form of dx/dt=f(W)
- Parameters:
name (str) – Name of Rule
variable (str) – Target Species/Parameter to be modified by rule
formula (str) – String representation of formula to be evaluated
- exception gillespy2.core.RateRuleError[source]¶
Bases:
ModelError
- class gillespy2.core.Reaction(name=None, reactants=None, products=None, propensity_function=None, ode_propensity_function=None, rate=None, annotation=None, massaction=None)[source]¶
Bases:
SortableObject
,Jsonify
Models a single reaction. A reaction has its own dicts of species (reactants and products) and parameters. The reaction’s propensity function needs to be evaluable (and result in a non-negative scalar value) in the namespace defined by the union of those dicts.
- Parameters:
name (str) – The name by which the reaction is called (optional).
reactants (dict) – The reactants that are consumed in the reaction, with stoichiometry. An example would be {R1 : 1, R2 : 2} if the reaction consumes two of R1 and one of R2, where R1 and R2 are Species objects.
products (dict) – The species that are created by the reaction event, with stoichiometry. Same format as reactants.
propensity_function (str) – The custom propensity function for the reaction. Must be evaluable in the namespace of the reaction using C operations.
ode_propensity_function (str) – The custom ode propensity function for the reaction. Must be evaluable in the namespace of the reaction using C operations.
massaction (bool) – (deprecated) The switch to use a mass-action reaction. If set to True, a rate value is required.
rate (float) – The rate of the mass-action reaction, take care to note the units.
annotation (str) – An optional note about the reaction.
Notes
For a species that is NOT consumed in the reaction but is part of a mass action reaction, add it as both a reactant and a product.
Mass-action reactions must also have a rate term added. Note that the input rate represents the mass-action constant rate independent of volume.
if a name is not provided for reactions, the name will be populated by the model based on the order it was added. This could impact seeded simulation results if the order of addition is not preserved.
- Annotate(*args, **kwargs)[source]¶
Add an annotation to this reaction (deprecated).
- Parameters:
annotation (str) – Annotation note to be added to reaction
- addProduct(*args, **kwargs)[source]¶
Add a product to this reaction (deprecated)
- Parameters:
species (spatialpy.core.species.Species) – Species object to be produced by the reaction
stoichiometry (int) – Stoichiometry of this product.
- addReactant(*args, **kwargs)[source]¶
Add a reactant to this reaction (deprecated)
- Parameters:
species (spatialpy.core.species.Species) – reactant Species object
stoichiometry (int) – Stoichiometry of this participant reactant
- add_product(species, stoichiometry)[source]¶
Add a product to this reaction
- Parameters:
species (spatialpy.core.species.Species | str) – Species object to be produced by the reaction
stoichiometry (int) – Stoichiometry of this product.
- add_reactant(species, stoichiometry)[source]¶
Add a reactant to this reaction
- Parameters:
species (spatialpy.core.species.Species) – reactant Species object
stoichiometry (int) – Stoichiometry of this participant reactant
- create_mass_action(*args, **kwargs)[source]¶
Initializes the mass action propensity function given self.reactants and a single parameter value.
- classmethod from_json(json_object)[source]¶
Convert some json_str into a decoded Python type. This function should return a new instance of the type.
- Parameters:
json_str (str) – A json str to be converted into a new type instance.
- Returns:
A decoded object.
- sanitized_propensity_function(species_mappings, parameter_mappings, ode=False)[source]¶
Sanitize the reaction propensity.
- Parameters:
species_mappings (dict) – Mapping of species names to sanitized species names.
parameter_mappings (dict) – Mapping of parameter names to sanitized parameter names.
- Returns:
The sanitized propensity.
- Return type:
str
- setType(rxntype)[source]¶
Sets reaction type to either “mass-action” or “customized” (deprecated)
- Parameters:
rxntype (str) – Either “mass-action” or “customized”
- set_annotation(annotation)[source]¶
Add an annotation to this reaction.
- Parameters:
annotation (str) – Annotation note to be added to reaction
- set_propensities(propensity_function=None, ode_propensity_function=None)[source]¶
Change the reaction to a customized reaction and set the propensities.
- Parameters:
propensity_function (str) – The custom propensity function for the reaction. Must be evaluable in the namespace of the reaction using C operations.
ode_propensity_function (str) – The custom ode propensity function for the reaction. Must be evaluable in the namespace of the reaction using C operations.
- set_rate(rate)[source]¶
Change the reaction to a mass-action reaction and set the rate.
- Parameters:
rate (int | float | str | Parameter) – The rate of the mass-action reaction, take care to note the units.
- to_dict()[source]¶
Convert the object into a dictionary ready for json encoding. Note: Complex types that inherit from Jsonify do not need to be manually encoded.
By default, this function will return a dictionary of the object’s public types.
- Returns:
The backing var dictionary of the object.
- exception gillespy2.core.ReactionError[source]¶
Bases:
ModelError
- class gillespy2.core.Results(data)[source]¶
-
List of Trajectory objects created by a gillespy2 solver, extends the UserList object.
- Parameters:
data (UserList) – A list of trajectory objects
- average_ensemble()[source]¶
Generate a single Results object with a Trajectory that is made of the means of all trajectories’ outputs
- Returns:
The Results object
- classmethod build_from_solver_results(solver, live_output_options)[source]¶
Build a gillespy2.Results object using the provided solver results.
- Parameters:
solver (gillespy2.GillesPySolver) – The solver used to run the simulation.
live_output_options (dict) – dictionary contains options for live_output. By default {“interval”:1}. “interval” specifies seconds between displaying. “clear_output” specifies if display should be refreshed with each display
- plot(index=None, xaxis_label='Time', xscale='linear', yscale='linear', yaxis_label='Value', style='default', title=None, show_title=False, show_legend=True, multiple_graphs=False, included_species_list=[], save_png=False, figsize=(18, 10))[source]¶
Plots the Results using matplotlib.
- Parameters:
index (int) – If not none, the index of the Trajectory to be plotted.
xaxis_label (str) – The label for the x-axis
yaxis_label (str) – The label for the y-axis
title (str) – The title of the graph
multiple_graphs (bool) – IF each trajectory should have its own graph or if they should overlap.
included_species_list (list) – A list of strings describing which species to include. By default displays all species.
save_png (bool or str) – Should the graph be saved as a png file. If True, File name is title of graph. If a string is given, file is named after that string.
figsize (tuple of ints (x,y)) – The size of the graph. A tuple of the form (width,height). Is (18,10) by default.
- plot_mean_stdev(xscale='linear', yscale='linear', xaxis_label='Time', yaxis_label='Value', title=None, show_title=False, style='default', show_legend=True, included_species_list=[], ddof=0, save_png=False, figsize=(18, 10))[source]¶
Plot a matplotlib graph depicting mean and standard deviation of a results object.
- Parameters:
xaxis_label (str) – The label for the x-axis
yaxis_label (str) – The label for the y-axis
title (str) – The title of the graph
show_title (bool) – Default False, if True, title will be displayed on the graph.
style (str) – Matplotlib style to be displayed on graph.
show_legend (bool) – Default to True, if False, legend will not be shown on graph.
included_species_list (list) – A list of strings describing which species to include. By default displays all species.
ddof (int) – Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of trajectories. Sample standard deviation uses ddof of 1. Defaults to population standard deviation where ddof is 0.
figsize (tuple of ints (x,y)) – The size of the graph. A tuple of the form (width,height). Is (18,10) by default.
- plot_std_dev_range(**kwargs)[source]¶
Plot a matplotlib graph depicting mean and standard deviation of a results object.
- Parameters:
xaxis_label (str) – The label for the x-axis
yaxis_label (str) – The label for the y-axis
title (str) – The title of the graph
show_title (bool) – Default False, if True, title will be displayed on the graph.
style (str) – Matplotlib style to be displayed on graph.
show_legend (bool) – Default to True, if False, legend will not be shown on graph.
included_species_list (list) – A list of strings describing which species to include. By default displays all species.
ddof (int) – Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of trajectories. Sample standard deviation uses ddof of 1. Defaults to population standard deviation where ddof is 0.
figsize (tuple of ints (x,y)) – The size of the graph. A tuple of the form (width,height). Is (18,10) by default.
- plotplotly(index=None, xaxis_label='Time', yaxis_label='Value', title=None, show_title=False, show_legend=True, multiple_graphs=False, included_species_list=[], return_plotly_figure=False, **layout_args)[source]¶
Plots the Results using plotly. Can only be viewed in a Jupyter Notebook.
- Parameters:
index (int) – If not none, the index of the Trajectory to be plotted.
xaxis_label (str) – The label for the x-axis
yaxis_label (str) – The label for the y-axis
title (str) – The title of the graph
show_title (bool) – If True, title will be shown on graph.
show_legend (bool) – Default True, if False, legend will not be shown on graph.
multiple_graphs (bool) – IF each trajectory should have its own graph or if they should overlap.
included_species_list (list) – A list of strings describing which species to include. By default displays all species.
return_plotly_figure (bool) – Whether or not to return a figure dictionary of data(graph object traces) and layout which may be edited by the user
**layout_args –
Optional additional arguments to be passed to plotlys layout constructor.
- plotplotly_mean_stdev(xaxis_label='Time', yaxis_label='Value', title=None, show_title=False, show_legend=True, included_species_list=[], return_plotly_figure=False, ddof=0, **layout_args)[source]¶
Plot a plotly graph depicting the mean and standard deviation of a results object
- Parameters:
xaxis_label (str) – The label for the x-axis
yaxis_label (str) – The label for the y-axis
title (str) – The title of the graph
show_title (bool) – If True, title will be shown on graph.
show_legend (bool) – Default True, if False, legend will not be shown on graph.
included_species_list (list) – A list of strings describing which species to include. By default displays all species.
return_plotly_figure (bool) – Whether or not to return a figure dicctionary of data(graph object traces) and layout which may be edited by the user
ddof (int) – Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of trajectories. Sample standard deviation uses ddof of 1. Defaults to population standard deviation where ddof is 0.
**layout_args –
Optional additional arguments to be passed to plotlys layout constructor.
- plotplotly_std_dev_range(**kwargs)[source]¶
Plot a plotly graph depicting the mean and standard deviation of a results object
- Parameters:
xaxis_label (str) – The label for the x-axis
yaxis_label (str) – The label for the y-axis
title (str) – The title of the graph
show_title (bool) – If True, title will be shown on graph.
show_legend (bool) – Default True, if False, legend will not be shown on graph.
included_species_list (list) – A list of strings describing which species to include. By default displays all species.
return_plotly_figure (bool) – Whether or not to return a figure dicctionary of data(graph object traces) and layout which may be edited by the user
ddof (int) – Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of trajectories. Sample standard deviation uses ddof of 1. Defaults to population standard deviation where ddof is 0.
**layout_args –
Optional additional arguments to be passed to plotlys layout constructor.
- stddev_ensemble(ddof=0)[source]¶
Generate a single Results object with a Trajectory that is made of the sample standard deviations of all trajectories’ outputs.
- Parameters:
ddof (int) – Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of trajectories. Sample standard deviation uses ddof of 1. Defaults to population standard deviation where ddof is 0.
- Returns:
the Results object
- to_array()[source]¶
Convert the results object into a numpy array.
- Returns:
Array containing the result of the simulation.
- Return type:
numpy.ndarray
- to_csv(path='.', nametag=None, stamp=None, suffix='.odf', verbose=False)[source]¶
Outputs the Results to one or more .csv files in a new directory.
- Parameters:
nametag (str) – allows the user to optionally “tag” the directory and included files. Defaults to the model name.
path (str) – the location for the new directory and included files. Defaults to model location.
stamp (str) – Allows the user to optionally “tag” the directory (not included files). Default is timestamp.
verbose (str) – Print useful informataion.
- Returns:
Path to the observed data files.
- Return type:
str
- exception gillespy2.core.SimulationTimeoutError[source]¶
Bases:
SimulationError
- class gillespy2.core.SortableObject[source]¶
Bases:
object
Base class for GillesPy2 objects that are sortable.
- class gillespy2.core.Species(name=None, initial_value=0, constant=False, boundary_condition=False, mode=None, allow_negative_populations=False, switch_min=0, switch_tol=0.03)[source]¶
Bases:
SortableObject
,Jsonify
Chemical species. Can be added to Model object to interact with other species or time.
- Parameters:
name (str) – The name by which this species will be called in reactions and within the model.
initial_value (int | float) – Initial population (discrete) or concentration (continuous) of this species.
constant (bool) – If true, the value of the species cannot be changed (currently TauHybridSolver only)
boundary_condition (bool) – If true, species can be changed by events and rate rules, but not by reactions. (TauHybridSolver only)
mode (str) – *FOR USE WITH TauHybridSolver ONLY* Sets the mode of representation of this species for the TauHybridSolver, can be discrete, continuous, or dynamic. mode=’dynamic’ - Allows a species to be represented as either discrete or continuous mode=’continuous’ - Species will only be represented as continuous mode=’discrete’ - Species will only be represented as discrete
allow_negative_populations (bool) – If true, population can be reduced below 0.
switch_tol (float) – *FOR USE WITH TauHybridSolver ONLY* Tolerance level for considering a dynamic species deterministically, value is compared to an estimated sd/mean population of a species after a given time step. This value will be used if a switch_min is not provided. The default value is 0.03
switch_min (float) – *FOR USE WITH TauHybridSolver ONLY* Minimum population value at which species will be represented as continuous. If a value is given, switch_min will be used instead of switch_tol
- Raises:
SpeciesError – Arg is of invalid type. Required arg set to None. Arg value is outside of accepted bounds.
- set_initial_value(initial_value)[source]¶
Setter method for initial_value of a population
- Parameters:
initial_value (int | float) – Initial population (discrete) or concentration (continuous) of this species.
- Raises:
SpeciesError – initial_value is of invalid type. initial_value set to None. initial_value is a float when mode != ‘continuous’. initial_value is negative when allow_negative_populations=False.
- validate(initial_value=None, coverage='all')[source]¶
Validate the species.
- Parameters:
initial_value (int | float) – Initial population (discrete) or concentration (continuous) of this species.
coverage (str) – The scope of attributes to validate. Set to an attribute name to restrict validation to a specific attribute.
- Raises:
SpeciesError – Attribute is of invalid type. Required attribute set to None. Attribute is value outside of accepted bounds.
- exception gillespy2.core.SpeciesError[source]¶
Bases:
ModelError
- class gillespy2.core.StochMLDocument[source]¶
Bases:
object
Serializiation and deserialization of a Model to/from the native XML format.
- classmethod from_file(filepath)[source]¶
Intializes the document from an exisiting native XML file read from disk.
- classmethod from_model(model)[source]¶
Creates an XML document from an exisiting Model object. This method assumes that all the parameters in the model are already resolved to scalar floats (see Model.resolveParamters).
Note, this method is intended to be used internally by the models ‘serialization’ function, which performs additional operations and tests on the model prior to writing out the XML file.
You should NOT do:
document = StochMLDocument.fromModel(model) print document.toString()
You SHOULD do:
print model.serialize()
- exception gillespy2.core.StochMLImportError[source]¶
Bases:
SimulationError
- class gillespy2.core.TimeSpan(items)[source]¶
Bases:
Iterator
,Jsonify
Model timespan that describes the duration to run the simulation and at which timepoint to sample the species populations during the simulation.
- Parameters:
items (list, tuple, range, or numpy.ndarray) – Evenly-spaced list of times at which to sample the species populations during the simulation. Best to use the form np.linspace(<start time>, <end time>, <number of time-points, inclusive>)
- Raises:
TimespanError – items is an invalid type.
- classmethod arange(increment, t=20)[source]¶
Creates a timespan using the form np.arange(0, <t, inclusive>, <increment>).
- Parameters:
increment (float | int) – Distance between sample points for the species populations during the simulation.
t (float | int) – End time for the simulation.
- Returns:
Timespan for the model.
- Return type:
gillespy2.TimeSpan
- Raises:
TimespanError – t or increment are None, <= 0, or invalid type.
- classmethod linspace(t=20, num_points=None)[source]¶
Creates a timespan using the form np.linspace(0, <t>, <num_points, inclusive>).
- Parameters:
t (float | int) – End time for the simulation.
num_points (int) – Number of sample points for the species populations during the simulation.
- Returns:
Timespan for the model.
- Return type:
gillespy2.TimeSpan
- Raises:
TimespanError – t or num_points are None, <= 0, or invalid type.
- validate()[source]¶
Validate the models time span
- Raises:
TimespanError – Timespan is an invalid type, empty, not uniform, contains a single repeated value, or contains a negative initial time.
- exception gillespy2.core.TimespanError[source]¶
Bases:
ModelError
- class gillespy2.core.Trajectory(data, model=None, solver_name='Undefined solver name', rc=0)[source]¶
-
Trajectory Dict created by a gillespy2 solver containing single trajectory, extends the UserDict object.
- Parameters:
data (UserDict) – A dictionary of trajectory values created by a solver
model (str) – The name of the model used to create the trajectory
solver_name (str) – The name of the solver used to create the trajectory
rc (int) – The solvers status return code.
status – The solver status (‘Success’,’Timed out’)
- class gillespy2.core.TranslationTable(to_anon: dict[str, str])[source]¶
Bases:
Jsonify
This class contains functions to enable arbitrary object trees to be “translated” to anonymous and named objects. This behavior is defined by a map of ‘named’ and ‘anon’ key values.
- Parameters:
to_anon (dict[str, str]) – A mapping of ‘named’ to ‘anonymous’ strings to be used when converting user-defined names to anon.
- obj_to_anon(obj: object)[source]¶
Recursively anonymise all named properties on the object.
- Parameters:
obj (object) – The object to anonymize.
- Returns:
An anonymized instance of self.
- obj_to_named(obj)[source]¶
Recursively identify all anonymous properties on the object.
- Parameters:
obj (object) – The object that will be converted to named.
- Returns:
A named instance of self.
- recursive_translate(obj: object, translation_table: dict[str, str])[source]¶
Recursively search through the object tree searching for property value matches in the translation table. If a match is found, substitute.
- Parameters:
obj (object) – The object that will be translated.
translation_table (TranslationTable) – The mapping to translate by.
- class gillespy2.core.UserList(initlist=None)[source]¶
Bases:
MutableSequence
A more or less complete user-defined wrapper around list objects.
- index(value[, start[, stop]]) integer -- return first index of value. [source]¶
Raises ValueError if the value is not present.
Supporting start and stop arguments is optional, but recommended.
- pop([index]) item -- remove and return item at index (default last). [source]¶
Raise IndexError if list is empty or index is out of range.
- exception gillespy2.core.ValidationError[source]¶
Bases:
ResultsError
- class gillespy2.core.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])[source]¶
Bases:
date
The year, month and day arguments are required. tzinfo may be None, or an instance of a tzinfo subclass. The remaining arguments may be ints.
- astimezone()¶
tz -> convert to local time in new timezone tz
- combine()¶
date, time -> datetime with same date and time fields
- ctime()¶
Return ctime() style string.
- date()¶
Return date object with same year, month and day.
- dst()¶
Return self.tzinfo.dst(self).
- fold¶
- fromisoformat()¶
string -> datetime from datetime.isoformat() output
- fromtimestamp()¶
timestamp[, tz] -> tz’s local time from POSIX timestamp.
- hour¶
- isoformat()¶
[sep] -> string in ISO 8601 format, YYYY-MM-DDT[HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM]. sep is used to separate the year from the time, and defaults to ‘T’. timespec specifies what components of the time to include (allowed values are ‘auto’, ‘hours’, ‘minutes’, ‘seconds’, ‘milliseconds’, and ‘microseconds’).
- max = datetime.datetime(9999, 12, 31, 23, 59, 59, 999999)¶
- microsecond¶
- min = datetime.datetime(1, 1, 1, 0, 0)¶
- minute¶
- now()¶
Returns new datetime object representing current time local to tz.
- tz
Timezone object.
If no tz is specified, uses local timezone.
- replace()¶
Return datetime with new specified fields.
- resolution = datetime.timedelta(microseconds=1)¶
- second¶
- strptime()¶
string, format -> new datetime parsed from a string (like time.strptime()).
- time()¶
Return time object with same time but with tzinfo=None.
- timestamp()¶
Return POSIX timestamp as float.
- timetuple()¶
Return time tuple, compatible with time.localtime().
- timetz()¶
Return time object with same time and tzinfo.
- tzinfo¶
- tzname()¶
Return self.tzinfo.tzname(self).
- utcfromtimestamp()¶
Construct a naive UTC datetime from a POSIX timestamp.
- utcnow()¶
Return a new datetime representing UTC day and time.
- utcoffset()¶
Return self.tzinfo.utcoffset(self).
- utctimetuple()¶
Return UTC time tuple, compatible with time.localtime().
- gillespy2.core.export_SBML(gillespy_model, filename=None)[source]¶
GillesPy model to SBML converter
- Parameters:
gillespy_model (gillespy.Model) – GillesPy model to be converted to SBML
filename (str) – Path to the SBML file for conversion
- gillespy2.core.export_StochSS(gillespy_model, filename=None, return_stochss_model=False)[source]¶
GillesPy model to StochSS converter
- Parameters:
gillespy_model (gillespy.Model) – GillesPy model to be converted to StochSS
filename (str) – Path to the StochSS file for conversion
- gillespy2.core.import_SBML(filename, name=None, gillespy_model=None, report_silently_with_sbml_error=False)[source]¶
SBML to GillesPy model converter. NOTE: non-mass-action rates in terms of concentrations may not be converted for population simulation. Use caution when importing SBML.
- Parameters:
filename (str) – Path to the SBML file for conversion.
name (str) – Name of the resulting model
gillespy_model (gillespy.Model) – If desired, the SBML model may be added to an existing GillesPy model
report_silently_with_sbml_error (bool) – SBML import will fail silently and SBML errors will not output to the user.