Dynamic or programmatic#

To create a model dynamically, we need to create a Builder instance from a Compartment:

from simbio.components import EmptyCompartment
from simbio.reactions import single


builder = EmptyCompartment.to_builder()

A Builder add several add_* methods, to add species, parameters and reactions.

For instance, to add a species:

A = builder.add_species(name="A", value=1)

A
Reference(name='A', type=<class 'simbio.components.types.Species'>, parent=<class 'simbio.components._dsl.EmptyCompartment'>, stoichiometry=1.0)

The variable A is a Reference to the Species, which we can use in reactions:

builder.add_reaction("create_A", single.Creation(A=A, rate=1))
<simbio.reactions.single.Creation at 0x7f669874f0a0>

We can also obtain a Reference to A using attribute access:

builder.A
Reference(name='A', type=<class 'simbio.components.types.Species'>, parent=<class 'simbio.components._dsl.EmptyCompartment'>, stoichiometry=1.0)

When we finished building the model, we need to use the .build() method to obtain the underlying Compartment:

model = builder.build()

Then, it can be used in a Simulator, just as a class-based model:

import numpy as np
from simbio.simulator import Simulator

t = np.linspace(0, 10, 100)
Simulator(model).run(t).plot()
<AxesSubplot: xlabel='time'>
../_images/dynamic_12_1.png

Inheriting and combining models#

We can inherit from a previous model by calling it .to_builder() method:

from simbio.components import Species


class Base(EmptyCompartment):
    A: Species = 1


builder = Base.to_builder()

Or we can use the update method on an existing Builder instance:

builder = EmptyCompartment.to_builder()
builder.update(Base)
<simbio.components.types.CompartmentBuilder at 0x7f66678fece0>

As in the class-based models, adding an existing species raises an error:

try:
    builder.add_species("A", 2)
except ValueError as e:
    print(e)
A already exists.

If we want to replace it, we must explicitly tell SimBio:

builder.add_species("A", 2, replace=True)
Reference(name='A', type=<class 'simbio.components.types.Species'>, parent=<class 'simbio.components._dsl.EmptyCompartment'>, stoichiometry=1.0)

Check out the chained reactions example, to see it in action.