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.

parentCompartment, optional

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

dimensioninteger, optional

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

sizeParameter or Expression, optional

A parameter or constant expression 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).
exception pysb.core.CompartmentAlreadySpecifiedError[source]
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_patternslist of MonomerPatterns

MonomerPatterns that make up the complex.

compartmentCompartment or None

Location restriction. None means don’t care.

match_oncebool, 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


Test a concrete ComplexPattern for equality with another.

Use of this method on non-concrete ComplexPatterns was previously allowed, but is now deprecated.


Compare another ComplexPattern against this one

other: ComplexPattern

A ComplexPattern to match against self


True if other matches self; False otherwise.

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

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


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


Name of the component.


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.

iterableiterable of Components, optional

Initial contents of the set.


Filter a ComponentSet using a predicate or set of predicates

filter_predicate: callable or pysb.pattern.FilterPredicate

A predicate (condition) to test each Component in the ComponentSet against. This can either be an anonymous “lambda” function or a subclass of pysb.pattern.FilterPredicate. For lambda functions, the argument is a single Component and return value is a boolean indicating a match or not.


A ComponentSet containing Components matching all of the supplied filters


>>> from pysb.examples.earm_1_0 import model
>>> from pysb.pattern import Name, Pattern, Module, Function
>>> m = model.monomers

Find parameters exactly equal to 10000:

>>> model.parameters.filter(lambda c: c.value == 1e4)              
 Parameter('pC3_0', 10000.0),
 Parameter('pC6_0', 10000.0),

Find rules with a forward rate < 1e-8, using a custom function:

>>> model.rules.filter(lambda c: c.rate_forward.value < 1e-8)             
 Rule('bind_pC3_Apop', Apop(b=None) + pC3(b=None) | Apop(b=1) %
        pC3(b=1), kf25, kr25),

We can also use some built in predicates for more complex matching scenarios, including combining multiple predicates.

Find rules with a name beginning with “inhibit” that contain cSmac:

>>> model.rules.filter(Name('^inhibit') & Pattern(m.cSmac()))             
 Rule('inhibit_cSmac_by_XIAP', cSmac(b=None) + XIAP(b=None) |
        cSmac(b=1) % XIAP(b=1), kf28, kr28),

Find rules with any form of Bax (i.e. Bax, aBax, mBax):

>>> model.rules.filter(Pattern(m.Bax) | Pattern(m.aBax) |                 Pattern(m.MBax)) 
 Rule('bind_Bax_tBid', tBid(b=None) + Bax(b=None) |
      tBid(b=1) % Bax(b=1), kf12, kr12),
 Rule('produce_aBax_via_tBid', tBid(b=1) % Bax(b=1) >>
      tBid(b=None) + aBax(b=None), kc12),
 Rule('transloc_MBax_aBax', aBax(b=None) |
      MBax(b=None), kf13, kr13),
 Rule('inhibit_MBax_by_Bcl2', MBax(b=None) + Bcl2(b=None) |
      MBax(b=1) % Bcl2(b=1), kf14, kr14),
 Rule('dimerize_MBax_to_Bax2', MBax(b=None) + MBax(b=None) |
      Bax2(b=None), kf15, kr15),

Count the number of parameter that don’t start with kf (note the ~ negation operator):

>>> len(model.parameters.filter(~Name('^kf')))

Get components not defined in this module (file). In this case, everything is defined in one file, but for multi-file models this becomes more useful:

>>> model.components.filter(~Module('^pysb.examples.earm_1_0$'))

Count the number of rules defined in the ‘catalyze’ function:

>>> len(model.rules.filter(Function('^catalyze$')))
get(k[, d]) D[k] if k in D, else d.  d defaults to None.[source]
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.

items() a set-like object providing a view on D's items[source]
keys() a set-like object providing a view on D's keys[source]
rename(c, new_name)[source]

Change the name of component c to new_name.

values() an object providing a view on D's values[source]
exception pysb.core.ConstantExpressionError[source]

Expected a constant Expression but got something else.

exception pysb.core.DanglingBondError[source]
exception pysb.core.DuplicateMonomerError[source]
exception pysb.core.DuplicateSiteError[source]
class pysb.core.EnergyPattern(name, pattern, energy, _export=True)[source]

Model component representing an energy pattern.


ComplexPattern describing the species to which the given deltaG in energy should be attributed.


Expression containing model parameters that defines the deltaG to be ascribed to the part of a species matched by pattern.

Identical to Parameters (see above).
class pysb.core.Expression(name, expr, _export=True)[source]

Model component representing a symbolic expression of other variables.


Symbolic expression.


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.

class pysb.core.Initial(pattern, value, fixed=False, _export=True)[source]

An initial condition for a species.

An initial condition is made up of a species, its amount or concentration, and whether it is to be held fixed during a simulation.

Species patterns must satisfy all of the following: * Able to be cast as a ComplexPattern * Concrete (see ComplexPattern.is_concrete) * Distinct from any existing initial condition pattern * match_once is False (nonsensical in this context)


A concrete pattern defining the species to initialize.

valueParameter or Expression Amount of the species the model will start

with. If an Expression is used, it must evaluate to a constant (can’t reference any Observables).


Whether or not the species should be held fixed (never consumed).

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

Compatibility shim for the Model.initial_conditions property.

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.

MatchOnce adjusts reaction rate multiplicity by only counting a pattern match once per species, even if it matches within that species multiple times.

For example, if one were to have molecules of A degrading with a specified rate:

>>> Rule('A_deg', A() >> None, kdeg)                

In the situation where multiple molecules of A() were present in a species (e.g. A(a=1) % A(a=1)), the above A_deg rule would have multiplicity equal to the number of occurences of A() in the degraded species. Thus, A(a=1) % A(a=1) would degrade twice as fast as A(a=None) under the above rule. If this behavior is not desired, the multiplicity can be fixed at one using the MatchOnce keyword:

>>> Rule('A_deg', MatchOnce(A()) >> None, kdeg)     
class pysb.core.Model(name=None, base=None, _export=True)[source]

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

namestring, 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).

baseModel, 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 of the model. See Parameter section above.

baseModel or None

See Parameter section above.

monomers, compartments, parameters, rules, observablesComponentSet

The Component objects which make up the model.

initialslist of Initial

Specifies which species are present in the model’s starting state (t=0) and how much there is of each one.

initial_conditionslist of tuple of (ComplexPattern, Parameter)

The old representation of initial conditions, deprecated in favor of initials.

specieslist 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.

reactionslist 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_bidirectionallist 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.

annotationslist 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.

expressions_dynamic(include_local=True, include_derived=False)[source]

Return a ComponentSet of non-constant expressions.


Return all annotations for the given subject.


Return the index of a species.


A concrete pattern specifying the species to find.


Return true if model uses synthesis or degradation reactions.

initial(pattern, value, fixed=False)[source]

Add an initial condition.

This method is deprecated. Instead, create an Initial object and pass it to add_initial.

property modules

Return the set of Python modules where Components are defined


List of module names where model Components are defined


>>> from pysb.examples.earm_1_0 import model
>>> 'pysb.examples.earm_1_0' in model.modules
property odes

Return sympy Expressions for the time derivative of each species.


Return a ComponentSet of all parameters and derived parameters.


Return a ComponentSet of compartment size parameters.


Return a ComponentSet of the parameters used in expressions.


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.


Return a ComponentSet of energy-based rules.

property stoichiometry_matrix

Return the stoichiometry matrix for the reaction network.

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.


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.


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

property uses_energy

Return True if model uses energy features.

exception pysb.core.ModelExistsWarning[source]

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

exception pysb.core.ModelNotDefinedError[source]

SelfExporter method was called before a model was defined.

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

Model component representing a protein or other molecule.

siteslist of strings, optional

Names of the sites.

site_statesdict 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.

Site names and state values must start with a letter, or one or more underscores followed by a letter. Any remaining characters must be alphanumeric or underscores.

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

A pattern which matches instances of a given monomer.


The monomer to match.


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

compartmentCompartment 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

  • MultiState : duplicate sites

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.MultiState(*args)[source]

MultiState for a Monomer (also known as duplicate sites)

MultiStates are duplicate copies of a site which each have the same name and semantics. In BioNetGen, these are known as duplicate sites. MultiStates are not supported by Kappa.

When declared, a MultiState instance is not connected to any Monomer or site, so full validation is deferred until it is used as part of a MonomerPattern or ComplexPattern.


Define a Monomer “A” with MultiState “a”, which has two copies, and Monomer “B” with MultiState “b”, which also has two copies but can take state values “u” and “p”:

>>> Model()  
<Model '_interactive_' (monomers: 0, ...
>>> Monomer('A', ['a', 'a'])  # BNG: A(a, a)
Monomer('A', ['a', 'a'])
>>> Monomer('B', ['b', 'b'], {'b': ['u', 'p']})  # BNG: B(b~u~p, b~u~p)
Monomer('B', ['b', 'b'], {'b': ['u', 'p']})

To specify MultiStates, use the MultiState class. Here are some valid examples of MultiState patterns, with their BioNetGen equivalents:

>>> A(a=MultiState(1, 2))  # BNG: A(a!1,a!2)
A(a=MultiState(1, 2))
>>> B(b=MultiState('u', 'p'))  # BNG: A(A~u,A~p)
B(b=MultiState('u', 'p'))
>>> A(a=MultiState(1, 2)) % B(b=MultiState(('u', 1), 2))  # BNG: A(a!1, a!2).B(b~u!1, b~2)
A(a=MultiState(1, 2)) % B(b=MultiState(('u', 1), 2))
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’.


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.


See Parameters.

match‘species’ or ‘molecules’

See Parameters.

specieslist of integers

List of species indexes for species matching the pattern.

coefficientslist of integers

List of coefficients by which each species amount is to be multiplied to correct for multiple pattern matches within a species.


Expand observables in terms of species and coefficients

class pysb.core.OdeView(model)[source]

Compatibility shim for the Model.odes property.

class pysb.core.Parameter(name, value=0.0, _export=True, nonnegative=True, integer=False)[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.

valuenumber, 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.

nonnegativebool, optional

Sets the assumption whether this parameter is nonnegative (>=0). Affects simplifications of expressions that involve this parameter. By default, parameters are assumed to be non-negative.

integerbool, optional

Sets the assumption whether this parameter takes integer values, which affects simplifications of expressions that involve this parameter. By default, parameters are not assumed to take integer values.

value (see Parameters 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_patternslist of ComplexPatterns

ComplexPatterns that make up the reaction pattern.

Identical to Parameters (see above).

Match the ‘other’ ReactionPattern against this one

See pysb.pattern.match_reaction_pattern() for details

exception pysb.core.RedundantSiteConditionsError[source]

Both conditions dict and kwargs both passed to create pattern.

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

Model component representing a reaction rule.


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


Forward reaction rate constant.

rate_reverseUnion[Parameter,Expression], optional

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

delete_moleculesbool, 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_connectedbool, 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.

energybool, optional

If True, this rule is an energy rule (as in Energy BNG) and the two parameters are interpreted as the ‘phi’ and deltaG parameters of the Arrhenius equation (see Hogg 2013 for details).

total_rate: bool, optional

If True, the rate is considered to be macroscopic and is not multiplied by the number of reactant molecules during simulation. If False (default), the rate is multiplied by number of reactant molecules. Keyword is used by BioNetGen only for simulations using NFsim. Keyword is ignored by generate_network command of BioNetGen.

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_patternReactionPattern

The reactants and products of the rule.


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 add_initial(initial)[source]

Add an Initial to the default model.

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.Tag(name, _export=True)[source]

Tag for labelling MonomerPatterns and ComplexPatterns

exception pysb.core.TagAlreadySpecifiedError[source]
exception pysb.core.UnknownSiteError[source]
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.


Check the argument is a (state, bond) tuple for a Mononer site

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.