PySB core (pysb.core)

class pysb.core.ANY[source]

Site must have a bond, but identity of binding partner is irrelevant.

Use ANY in a MonomerPattern site_conditions dict to indicate that a site must have a bond without specifying what the binding partner should be.

Equivalent to the “+” bond modifier in BNG.

class pysb.core.Compartment(name, parent=None, dimension=3, size=None, _export=True)[source]

Model component representing a bounded reaction volume.


parent : Compartment, optional

Compartment which contains this one. If not specified, this will be the outermost compartment and its parent will be set to None.

dimension : integer, optional

The number of spatial dimensions in the compartment, either 2 (i.e. a membrane) or 3 (a volume).

size : Parameter, optional

A parameter object whose value defines the volume or area of the compartment. If not specified, the size will be fixed at 1.0.


The compartments of a model must form a tree via their parent attributes with a three-dimensional (volume) compartment at the root. A volume compartment may have any number of two-dimensional (membrane) compartments as its children, but never another volume compartment. A membrane compartment may have a single volume compartment as its child, but nothing else.


Compartment(‘cytosol’, dimension=3, size=cyto_vol, parent=ec_membrane)


Identical to Parameters (see above).  
class pysb.core.ComplexPattern(monomer_patterns, compartment, match_once=False)[source]

A bound set of MonomerPatterns, i.e. a pattern to match a complex.

In BNG terms, a list of patterns combined with the ‘.’ operator.


monomer_patterns : list of MonomerPatterns

MonomerPatterns that make up the complex.

compartment : Compartment

Location restriction. None means don’t care.

match_once : bool, optional

If True, the pattern will only count once against a species in which the pattern can match the monomer graph in multiple distinct ways. If False (default), the pattern will count as many times as it matches the monomer graph, leading to a faster effective reaction rate.


Identical to Parameters (see above).  

Implement our own brand of shallow copy.

The new object will have references to the original compartment, and copies of the monomer_patterns.


Return a bool indicating whether the pattern is ‘concrete’.

‘Concrete’ means the pattern satisfies ANY of the following: 1. All monomer patterns are concrete 2. The compartment is specified AND all monomer patterns are site-concrete


Checks for equality with another ComplexPattern

class pysb.core.Component(name, _export=True)[source]

The base class for all the named things contained within a model.


name : string

Name of the component. Must be unique within the containing model.


name (string) Name of the component.
model (weakref(Model)) Containing model.

Change component’s name.

This is typically only needed when deriving one model from another and it would be desirable to change a component’s name in the derived model.

exception pysb.core.ComponentDuplicateNameError[source]

A component was added with the same name as an existing one.

class pysb.core.ComponentSet(iterable=None)[source]

An add-and-read-only container for storing model Components.

It behaves mostly like an ordered set, but components can also be retrieved by name or index by using the [] operator (like a combination of a dict and a list). Components cannot be removed or replaced, but they can be renamed. Iteration returns the component objects.


iterable : iterable of Components, optional

Initial contents of the set.

rename(c, new_name)[source]

Change the name of component c to new_name.

exception pysb.core.ConstantExpressionError[source]

Expected a constant Expression but got something else.

class pysb.core.Expression(name, expr, _export=True)[source]

Model component representing a symbolic expression of other variables.


expr : sympy.Expr

Symbolic expression.


expr (sympy.Expr) See Parameters.

Return expr rewritten in terms of terminal symbols only.


Return True if all terminal symbols are Parameters or numbers.

exception pysb.core.ExpressionError[source]

Expected an Expression but got something else.


Declare an initial condition (see Model.initial).

exception pysb.core.InvalidComplexPatternException[source]

Expression can not be cast as a ComplexPattern.

exception pysb.core.InvalidComponentNameError(name)[source]

Inappropriate component name.

exception pysb.core.InvalidInitialConditionError[source]

Invalid initial condition pattern.

exception pysb.core.InvalidReactionPatternException[source]

Expression can not be cast as a ReactionPattern.

exception pysb.core.InvalidReversibleSynthesisDegradationRule[source]

Synthesis or degradation rule defined as reversible.


Make a ComplexPattern match-once.

class pysb.core.Model(name=None, base=None, _export=True)[source]

A rule-based model containing monomers, rules, compartments and parameters.


name : string, optional

Name of the model. If not specified, will be set to the name of the file from which the constructor was called (with the .py extension stripped).

base : Model, optional

If specified, the model will begin as a copy of base. This can be used to achieve a simple sort of model extension and enhancement.


name (string) Name of the model. See Parameter section above.
base (Model or None) See Parameter section above.
monomers, compartments, parameters, rules, observables (ComponentSet) The Component objects which make up the model.
initial_conditions (list of tuple of (ComplexPattern, Parameter)) Specifies which species are present in the model’s starting state (t=0) and how much there is of each one. The ComplexPattern defines the species identity, and it must be concrete (see ComplexPattern.is_concrete). The Parameter defines the amount or concentration of the species.
species (list of ComplexPattern) List of all complexes which can be produced by the model, starting from the initial conditions and successively applying the rules. Each ComplexPattern is concrete.
odes (list of sympy.Expr) Mathematical expressions describing the time derivative of the amount of each species, as generated by the rules.
reactions (list of dict) Structures describing each possible unidirectional reaction that can be produced by the model. Each structure stores the name of the rule that generated the reaction (‘rule’), the mathematical expression for the rate of the reaction (‘rate’), tuples of species indexes for the reactants and products (‘reactants’, ‘products’), and a bool indicating whether the reaction is the reverse component of a bidirectional reaction (‘reverse’).
reactions_bidirectional (list of dict) Similar to reactions but with only one entry for each bidirectional reaction. The fields are identical except ‘reverse’ is replaced by ‘reversible’, a bool indicating whether the reaction is reversible. The ‘rate’ is the forward rate minus the reverse rate.
annotations (list of Annotation) Structured annotations of model components. See the Annotation class for details.

Add an annotation to the model.


Add a component to the model.


Return a list of all ComponentSet objects.


Return a ComponentSet containing all components in the model.


Add components needed to support synthesis and degradation rules.


Return a ComponentSet of constant expressions.


Return a ComponentSet of non-constant expressions.


Return all annotations for the given subject.


Return the index of a species.


complex_pattern : ComplexPattern

A concrete pattern specifying the species to find.


Return true if model uses synthesis or degradation reactions.

initial(pattern, value)[source]

Add an initial condition.

An initial condition is made up of a species and its amount or concentration.


pattern : ComplexPattern

A concrete pattern defining the species to initialize.

value : Parameter

Amount of the species the model will start with.


Return a ComponentSet of compartment size parameters.


Return a ComponentSet of initial condition parameters.


Return a ComponentSet of the parameters used in rules.


Return a ComponentSet of unused parameters.


Reload a model after its source files have been edited.

This method does not yet reload the model contents in-place, rather it returns a new model object. Thus the correct usage is model = model.reload().

If the model script imports any modules, these will not be reloaded. Use python’s reload() function to reload them.


Clear out fields generated by bng.generate_equations or the like.

update_initial_condition_pattern(before_pattern, after_pattern)[source]

Update the pattern associated with an initial condition.

Leaves the Parameter object associated with the initial condition unchanged while modifying the pattern associated with that condition. For example this is useful for changing the state of a site on a monomer or complex associated with an initial condition without having to create an independent initial condition, and parameter, associated with that alternative state.


before_pattern : ComplexPattern

The concrete pattern specifying the (already existing) initial condition. If the model does not contain an initial condition for the pattern, a ValueError is raised.

after_pattern : ComplexPattern

The concrete pattern specifying the new pattern to use to replace before_pattern.

exception pysb.core.ModelExistsWarning[source]

A second model was declared in a module that already contains one.

class pysb.core.Monomer(name, sites=None, site_states=None, _export=True)[source]

Model component representing a protein or other molecule.


sites : list of strings, optional

Names of the sites.

site_states : dict of string => string, optional

Allowable states for sites. Keys are sites and values are lists of states. Sites which only take part in bond formation and never take on a state may be omitted.


A Monomer instance may be “called” like a function to produce a MonomerPattern, as syntactic sugar to approximate rule-based modeling language syntax. It is typically called with keyword arguments where the arg names are sites and values are site conditions such as bond numbers or states (see the Notes section of the MonomerPattern documentation for details). To help in situations where kwargs are unwieldy (for example if a site name is computed dynamically or stored in a variable) a dict following the same layout as the kwargs may be passed as the first and only positional argument instead.


Identical to Parameters (see above).  
class pysb.core.MonomerPattern(monomer, site_conditions, compartment)[source]

A pattern which matches instances of a given monomer.


monomer : Monomer

The monomer to match.

site_conditions : dict

The desired state of the monomer’s sites. Keys are site names and values are described below in Notes.

compartment : Compartment or None

The desired compartment where the monomer should exist. None means “don’t-care”.


The acceptable values in the site_conditions dict are as follows:

  • None : no bond
  • str : state
  • int : a bond (to a site with the same number in a ComplexPattern)
  • list of int : multi-bond (not valid in Kappa)
  • ANY : “any” bond (bound to something, but don’t care what)
  • WILD : “wildcard” bond (bound or not bound)
  • tuple of (str, int) : state with specified bond
  • tuple of (str, WILD) : state with wildcard bond
  • tuple of (str, ANY) : state with any bond

If a site is not listed in site_conditions then the pattern will match any state for that site, i.e. “don’t write, don’t care”.


Identical to Parameters (see above).  

Return a bool indicating whether the pattern is ‘concrete’.

‘Concrete’ means the pattern satisfies ALL of the following:

  1. All sites have specified conditions
  2. If the model uses compartments, the compartment is specified.

Return a bool indicating whether the pattern is ‘site-concrete’.

‘Site-concrete’ means all sites have specified conditions.

class pysb.core.Observable(name, reaction_pattern, match='molecules', _export=True)[source]

Model component representing a linear combination of species.

Observables are useful in correlating model simulation results with experimental measurements. For example, an observable for “A()” will report on the total number of copies of Monomer A, regardless of what it’s bound to or the state of its sites. “A(y=’P’)” would report on all instances of A with site ‘y’ in state ‘P’.


reaction_pattern : ReactionPattern

The list of ComplexPatterns to match.

match : ‘species’ or ‘molecules’

Whether to match entire species (‘species’) or individual fragments (‘molecules’). Default is ‘molecules’.


ReactionPattern is used here as a container for a list of ComplexPatterns, solely so users could utilize the ComplexPattern ‘+’ operator overload as syntactic sugar. There are no actual “reaction” semantics in this context.


reaction_pattern (ReactionPattern) See Parameters.
match (‘species’ or ‘molecules’) See Parameters.
species (list of integers) List of species indexes for species matching the pattern.
coefficients (list of integers) List of coefficients by which each species amount is to be multiplied to correct for multiple pattern matches within a species.
class pysb.core.Parameter(name, value=0.0, _export=True)[source]

Model component representing a named constant floating point number.

Parameters are used as reaction rate constants, compartment volumes and initial (boundary) conditions for species.


value : number, optional

The numerical value of the parameter. Defaults to 0.0 if not specified. The provided value is converted to a float before being stored, so any value that cannot be coerced to a float will trigger an exception.


Identical to Parameters (see above).  
class pysb.core.ReactionPattern(complex_patterns)[source]

A pattern for the entire product or reactant side of a rule.

Essentially a thin wrapper around a list of ComplexPatterns. In BNG terms, a list of complex patterns combined with the ‘+’ operator.


complex_patterns : list of ComplexPatterns

ComplexPatterns that make up the reaction pattern.


Identical to Parameters (see above).  
exception pysb.core.RedundantSiteConditionsError[source]

Both conditions dict and kwargs both passed to create pattern.

class pysb.core.Rule(name, rule_expression, rate_forward, rate_reverse=None, delete_molecules=False, move_connected=False, _export=True)[source]

Model component representing a reaction rule.


rule_expression : RuleExpression

RuleExpression containing the essence of the rule (reactants, products, reversibility).

rate_forward : Parameter

Forward reaction rate constant.

rate_reverse : Parameter, optional

Reverse reaction rate constant (only required for reversible rules).

delete_molecules : bool, optional

If True, deleting a Monomer from a species is allowed to fragment the species into multiple pieces (if the deleted Monomer was the sole link between those pieces). If False (default) then fragmentation is disallowed and the rule will not match a reactant species if applying the rule would fragment a species.

move_connected : bool, optional

If True, a rule that transports a Monomer between compartments will co-transport anything connected to that Monomer by a path in the same compartment. If False (default), connected Monomers will remain where they were.


Identical to Parameters (see above), plus the component elements of  
rule_expression: reactant_pattern, product_pattern and is_reversible.  

Return a bool indicating whether this is a degradation rule.


Return a bool indicating whether this is a synthesis rule.

class pysb.core.RuleExpression(reactant_pattern, product_pattern, is_reversible)[source]

A container for the reactant and product patterns of a rule expression.

Contains one ReactionPattern for each of reactants and products, and a bool indicating reversibility. This is a temporary object used to implement syntactic sugar through operator overloading. The Rule constructor takes an instance of this class as its first argument, but simply extracts its fields and discards the object itself.


reactant_pattern, product_pattern : ReactionPattern

The reactants and products of the rule.

is_reversible : bool

If True, the reaction is reversible. If False, it’s irreversible.


Identical to Parameters (see above).  
class pysb.core.SelfExporter[source]

Make model components appear in the calling module’s namespace.

This class is for pysb internal use only. Do not construct any instances.

static cleanup()[source]

Delete previously exported symbols.

static export(obj)[source]

Export an object by name and add it to the default model.

static rename(obj, new_name)[source]

Rename a previously exported symbol

exception pysb.core.SymbolExistsWarning[source]

A component declaration or rename overwrote an existing symbol.

class pysb.core.WILD[source]

Site may be bound or unbound.

Use WILD as part of a (state, WILD) tuple in a MonomerPattern site_conditions dict to indicate that a site must have the given state, irrespective of the presence or absence of a bond. (Specifying only the state implies there must not be a bond). A bare WILD in a site_conditions dict is also permissible, but as this has the same meaning as the much simpler option of leaving the given site out of the dict entirely, this usage is deprecated.

Equivalent to the ”?” bond modifier in BNG.


Internal helper to ‘upgrade’ a MonomerPattern to a ComplexPattern.


Internal helper to ‘upgrade’ a Complex- or MonomerPattern or None to a complete ReactionPattern.

pysb.core.build_rule_expression(reactant, product, is_reversible)[source]

Internal helper for operators which return a RuleExpression.

pysb.core.extract_site_conditions(conditions=None, **kwargs)[source]

Parse MonomerPattern/ComplexPattern site conditions.

pysb.core.validate_const_expr(obj, description)[source]

Raises an exception if the argument is not a constant expression.

pysb.core.validate_expr(obj, description)[source]

Raises an exception if the argument is not an expression.