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.

Parameters:
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.

Notes

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.

Examples

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

Attributes:
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.

Parameters:
monomer_patterns : list of MonomerPatterns

MonomerPatterns that make up the complex.

compartment : Compartment or None

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.

Attributes:
Identical to Parameters (see above).
copy()[source]

Implement our own brand of shallow copy.

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

is_concrete()[source]

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

is_equivalent_to(other)[source]

Test a concrete ComplexPattern for equality with another.

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

matches(other)[source]

Compare another ComplexPattern against this one

Parameters:
other: ComplexPattern

A ComplexPattern to match against self

Returns:
bool

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.

Parameters:
name : string

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

Attributes:
name : string

Name of the component.

model : weakref(Model)

Containing model.

rename(new_name)[source]

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.

Parameters:
iterable : iterable of Components, optional

Initial contents of the set.

filter(filter_predicate)[source]

Filter a ComponentSet using a predicate or set of predicates

Parameters:
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.

Returns:
ComponentSet

A ComponentSet containing Components matching all of the supplied filters

Examples

>>> 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) # doctest:+NORMALIZE_WHITESPACE ComponentSet([

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) # doctest: +NORMALIZE_WHITESPACE ComponentSet([

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())) # doctest: +NORMALIZE_WHITESPACE ComponentSet([

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)) # doctest: +NORMALIZE_WHITESPACE ComponentSet([

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’))) 60

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$’)) ComponentSet([

])

Count the number of rules defined in the ‘catalyze’ function: >>> len(model.rules.filter(Function(‘^catalyze$’))) 24

get(k[, d]) → D[k] if k in D, else d. d defaults to None.[source]
index(value) → integer -- return first index of value.[source]

Raises ValueError if the value is not present.

items() → list of D's (key, value) pairs, as 2-tuples[source]
iteritems() → an iterator over the (key, value) items of D[source]
iterkeys() → an iterator over the keys of D[source]
itervalues() → an iterator over the values of D[source]
keys() → list of D's keys[source]
rename(c, new_name)[source]

Change the name of component c to new_name.

values() → list of 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.Expression(name, expr, _export=True)[source]

Model component representing a symbolic expression of other variables.

Parameters:
expr : sympy.Expr

Symbolic expression.

Attributes:
expr : sympy.Expr

See Parameters.

expand_expr(expand_observables=False)[source]

Return expr rewritten in terms of terminal symbols only.

is_constant_expression()[source]

Return True if all terminal symbols are Parameters or numbers.

exception pysb.core.ExpressionError[source]

Expected an Expression but got something else.

pysb.core.Initial(*args)[source]

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.

pysb.core.MatchOnce(pattern)[source]

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.

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.

Attributes:
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.

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_annotation(annotation)[source]

Add an annotation to the model.

add_component(other)[source]

Add a component to the model.

all_component_sets()[source]

Return a list of all ComponentSet objects.

all_components()[source]

Return a ComponentSet containing all components in the model.

enable_synth_deg()[source]

Add components needed to support synthesis and degradation rules.

expressions_constant()[source]

Return a ComponentSet of constant expressions.

expressions_dynamic()[source]

Return a ComponentSet of non-constant expressions.

get_annotations(subject)[source]

Return all annotations for the given subject.

get_species_index(complex_pattern)[source]

Return the index of a species.

Parameters:
complex_pattern : ComplexPattern

A concrete pattern specifying the species to find.

has_synth_deg()[source]

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.

Parameters:
pattern : ComplexPattern

A concrete pattern defining the species to initialize.

value : Parameter

Amount of the species the model will start with.

modules

Return the set of Python modules where Components are defined

Returns:
list

List of module names where model Components are defined

Examples

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

Return sympy Expressions for the time derivative of each species.

parameters_compartments()[source]

Return a ComponentSet of compartment size parameters.

parameters_initial_conditions()[source]

Return a ComponentSet of initial condition parameters.

parameters_rules()[source]

Return a ComponentSet of the parameters used in rules.

parameters_unused()[source]

Return a ComponentSet of unused parameters.

reload()[source]

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.

reset_equations()[source]

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

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.

Parameters:
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.

Parameters:
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.

Notes

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.

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

A pattern which matches instances of a given monomer.

Parameters:
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”.

Notes

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

Attributes:
Identical to Parameters (see above).
is_concrete()[source]

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.
is_site_concrete()[source]

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

Parameters:
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’.

Notes

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.

Attributes:
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.

expand_obs()[source]

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)[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.

Parameters:
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.

Attributes:
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.

Parameters:
complex_patterns : list of ComplexPatterns

ComplexPatterns that make up the reaction pattern.

Attributes:
Identical to Parameters (see above).
matches(other)[source]

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.

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.

Parameters:
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.

Attributes:
Identical to Parameters (see above), plus the component elements of
`rule_expression`: reactant_pattern, product_pattern and is_reversible.
is_deg()[source]

Return a bool indicating whether this is a degradation rule.

is_synth()[source]

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.

Parameters:
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.

Attributes:
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.

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.

pysb.core.as_complex_pattern(v)[source]

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

pysb.core.as_reaction_pattern(v)[source]

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.