libSBML Python API  5.10.0
 All Classes Namespaces Files Functions Variables Modules Pages
Tutorial: creating a simple model

The following is a short example of creating a complete model using the libSBML Python interface.

This tutorial was kindly provided in 2012 by Martins Mednis (marti.nosp@m.ns@m.nosp@m.ednis.nosp@m..inf.nosp@m.o, web page address http://mednis.info/wp/?p=3).

We begin by importing the libSBML Python library and creating an empty SBML document, using SBML Level 2 Version 4 for this example.

from libsbml import *
document = SBMLDocument()
model = document.createModel(2, 4) # SBML level and version
model.setName('My test model')
model.setId('MyModelID')

Next, we create some compartments and set their volumes.

c1 = model.createCompartment()
c1.setName('Forest')
c1.setId('comp_FOREST')
c1.setVolume(1000)

c2 = model.createCompartment()
c2.setName('Meadow')
c2.setId('comp_Meadow')
c2.setVolume(1000)

We continue apace, now creating species and setting their properties such as their identifiers and initial amounts.

s1 = model.createSpecies()
s1.setName('Foxes')
s1.setId('spec_FOXES')
s1.setCompartment('comp_FOREST')
s1.setInitialAmount(10)

s2 = model.createSpecies()
s2.setName('Rabbits')
s2.setId('spec_RABBITS')
s2.setCompartment('comp_FOREST')
s2.setInitialAmount(50)

s3 = model.createSpecies()
s3.setName('Snakes')
s3.setId('spec_Snakes')
s3.setCompartment('comp_Meadow')
s3.setInitialAmount(100)

Next, reactions. For this example, we will create only one reaction.

r1 = model.createReaction()
r1.setName('Foxes eat rabbits')
r1.setId('R1')

# Create reactants and products.
reac1 = r1.createReactant()
reac1.setSpecies('spec_RABBITS')
prod1 = r1.createProduct()
prod1.setSpecies('spec_FOXES')

# Set stoichiometries.
reac1.setStoichiometry(2) # 2 rabbits
prod1.setStoichiometry(1) # 1 fox

Finally, we add the model to the SBML document object and write the whole thing to a file.

document.setModel(model)

# Save to a file.
writeSBMLToFile(document, 'name_of_your_model.xml')

This tutorial has demonstrated one approach to creating models and their components; the libSBML API actually provides other means of accomplishing these goals, but for the purposes of this tutorial we focused only on one. Readers are invited to explore the rest of this API manual as well as the set of Python example files included with the libSBML distribution.