Editing a model and saving it as SBML

A model read with getModel() can be changed from R and then written back to an SBML file, or converted straight to simulation code. This vignette covers what can be changed, how the changes behave, and how to save the result.

Function Changes
setParameterValue() a global parameter’s value
setCompartmentSize() a compartment’s size
setSpeciesIC() a species’ initial amount or concentration
setRateLaw() a reaction’s kinetic law, from an infix formula
removeReaction() removes a reaction
copyModel() nothing: returns an independent copy
writeSBML() nothing: validates the model and writes it to a file

Adding components, and removing anything other than reactions, is not supported.

library(r2sbml)
ex <- function(f) system.file("examples", f, package = "r2sbml")
# getModel() prints a header; keep the model, drop the header
load <- function(f) {
  model <- NULL
  invisible(capture.output(model <- getModel(f)))
  model
}

The examples use sbmlmutlicompartment.xml: four species in two compartments, a nucleus and the cytoplasm, linked by four reactions.

model <- load(ex("sbmlmutlicompartment.xml"))
getParameterTable(model)[, c("ID", "Value", "Units")]
#>   ID Value                     Units
#> 1 k1  2500 litre_per_mole_per_second
#> 2 k2  2500 litre_per_mole_per_second
#> 3 KT 25000                per_second
#> 4 k3  2500                per_second
getReactionMath(model)
#> Reaction 0, formula: nucleus * k1 * X * Y1n
#> Reaction 1, formula: cytoplasm * KT * (Y1n - Y1c)
#> Reaction 2, formula: cytoplasm * k2 * Y1c * Y2
#> Reaction 3, formula: cytoplasm * k3 * Y2
#> [1] 0

Edits happen in place

getModel() returns a pointer to a model held by libSBML, not an ordinary R value. A setter changes that model directly, so an edit shows through every variable that holds the same pointer, and x <- model copies the pointer, not the model. Use copyModel() when you want to keep the original:

original <- copyModel(model)
same <- model

setParameterValue(model, "k1", 1000)

getParameterTable(same)$Value[1]     # the same model: changed
#> [1] 1000
getParameterTable(original)$Value[1] # an independent copy: unchanged
#> [1] 2500

Each setter returns the model invisibly, so edits can be chained:

model |>
  setParameterValue("k2", 500) |>
  setCompartmentSize("nucleus", 2)

An unknown id is an error, and nothing is changed:

setParameterValue(model, "k9", 1)
#> Error:
#> ! No parameter 'k9' in the model.

Changing values

Parameters and compartment sizes

setParameterValue() and setCompartmentSize() take a single number. NA removes the value from the model; NaN and Inf are stored as values.

getCmtSizes(model)
#> [1] 5 2
setCompartmentSize(model, "cytoplasm", 4)
getCmtSizes(model)
#> [1] 4 2

setParameterValue() reaches global parameters only. A parameter declared inside a kinetic law (a local parameter, such as kcat in sbmlsimple.xml) is not a model parameter, so it is reported as unknown:

simple <- load(ex("sbmlsimple.xml"))
setParameterValue(simple, "kcat", 0.5)
#> Error:
#> ! No parameter 'kcat' in the model.

To change one, rewrite the rate law with setRateLaw() (below), writing the new value as a number.

Species initial values

An SBML species has either an initial amount or an initial concentration, never both. setSpeciesIC() therefore needs to be told which one value is, through as. It sets that one and removes the other:

setSpeciesIC(model, "X", 0.5, as = "concentration")
getSpeciesTable(model)[, c("ID", "InitialConcentration", "InitialAmount")]
#>    ID InitialConcentration InitialAmount
#> 1   X                  0.5           NaN
#> 2 Y1n                  NaN             1
#> 3 Y1c                  NaN             0
#> 4  Y2                  NaN             1

Values that something else sets

If an initial assignment or an assignment rule sets a component, a value you give it is stored but has no effect, and the setter warns. In sbmlassignmentrules.xml an assignment rule computes S1:

rules <- load(ex("sbmlassignmentrules.xml"))
getRuleMath(rules)
#> Rule 0, formula: S1 = T / (1 + Keq)
#> Rule 1, formula: S2 = Keq * S1
#> [1] 0
setSpeciesIC(rules, "S1", 1, as = "concentration")
#> Warning in setSpeciesIC(rules, "S1", 1, as = "concentration"): The new value of
#> species 'S1' has no effect: an assignment rule sets it.

A rate rule integrates from the initial value, so setting it does have an effect, and there is no warning.

Changing a rate law

setRateLaw() replaces a reaction’s kinetic law. The formula uses libSBML’s Level 3 infix syntax, the same syntax getReactionMath() prints:

setRateLaw(model, "degradation", "cytoplasm * k3 * Y2 / (1 + Y2)")
getReactionMath(model)
#> Reaction 0, formula: nucleus * k1 * X * Y1n
#> Reaction 1, formula: cytoplasm * KT * (Y1n - Y1c)
#> Reaction 2, formula: cytoplasm * k2 * Y1c * Y2
#> Reaction 3, formula: cytoplasm * k3 * Y2 / (1 + Y2)
#> [1] 0

Every name in the formula must be a compartment, species, parameter, reaction or species reference of the model, one of the reaction’s own local parameters, or a function definition. time and avogadro mean simulation time and Avogadro’s constant. Anything else is an error, and the model is left unchanged:

setRateLaw(model, "degradation", "cytoplasm * kdeg * Y2")
#> Error:
#> ! The rate law of reaction 'degradation' names an undefined id: 'kdeg'. The model was not changed.
setRateLaw(model, "degradation", "cytoplasm * (k3 * Y2")
#> Error:
#> ! Cannot parse the rate law of reaction 'degradation': Error when parsing input 'cytoplasm * (k3 * Y2' at position 20:  syntax error, unexpected end of string

A species named in the formula should be one of the reaction’s reactants, products or modifiers. SBML requires this, and setRateLaw() does not check it, but writeSBML() does: see “The model is checked before it is written” below.

A reaction keeps its local parameters, so the new formula can still use them. This is the way to change a local parameter’s value:

getReactionMath(simple)
#> Reaction 0, formula: comp * (kon * E * S - koff * ES)
#> Reaction 1, formula: comp * kcat * ES
#> [1] 0
setRateLaw(simple, "vcat", "comp * 0.5 * ES")
getReactionMath(simple)
#> Reaction 0, formula: comp * (kon * E * S - koff * ES)
#> Reaction 1, formula: comp * 0.5 * ES
#> [1] 0

kcat is now unused but still declared, which is valid SBML.

Removing a reaction

removeReaction() deletes a reaction, with its reactant and product lists and its kinetic law. The species stay:

removeReaction(model, "transport")
getReactionMath(model)
#> Reaction 0, formula: nucleus * k1 * X * Y1n
#> Reaction 1, formula: cytoplasm * k2 * Y1c * Y2
#> Reaction 2, formula: cytoplasm * k3 * Y2 / (1 + Y2)
#> [1] 0
getSpeciesNames(model)
#> [1] "X"   "Y1n" "Y1c" "Y2"

A species that no remaining reaction or rule changes keeps its initial value from then on.

In Level 3 a reaction’s id can appear in math, where it stands for the reaction’s rate, and so can the id of one of its species references, where it stands for a stoichiometry. removeReaction() will not leave such a name pointing at nothing: while anything that stays behind uses the reaction, it stops, names what uses it, and changes nothing. Here an assignment rule reads the rate of r1:

uses <- tempfile(fileext = ".xml")
writeLines('<?xml version="1.0" encoding="UTF-8" ?>
<sbml xmlns="http://www.sbml.org/sbml/level3/version2/core" level="3" version="2">
<model>
<listOfCompartments>
<compartment id="c" size="1" spatialDimensions="3" constant="true"/>
</listOfCompartments>
<listOfSpecies>
<species id="A" compartment="c" initialAmount="10" hasOnlySubstanceUnits="true"
 boundaryCondition="false" constant="false"/>
</listOfSpecies>
<listOfParameters>
<parameter id="k1" value="1" constant="true"/>
<parameter id="flux" constant="false"/>
</listOfParameters>
<listOfRules>
<assignmentRule variable="flux">
<math xmlns="http://www.w3.org/1998/Math/MathML"><ci>r1</ci></math>
</assignmentRule>
</listOfRules>
<listOfReactions>
<reaction id="r1" reversible="false">
<listOfReactants>
<speciesReference species="A" stoichiometry="1" constant="true"/>
</listOfReactants>
<kineticLaw><math xmlns="http://www.w3.org/1998/Math/MathML">
<apply><times/><ci>k1</ci><ci>A</ci></apply></math></kineticLaw>
</reaction>
</listOfReactions>
</model>
</sbml>', uses)
removeReaction(load(uses), "r1")
#> Error:
#> ! Cannot remove reaction 'r1': the assignment rule for 'flux' uses it. The model was not changed.

To switch a reaction off but keep it in the model, set its rate law to zero instead: setRateLaw(model, id, "0").

Adding components

The edits so far changed components a model already had. You can also add new ones. These examples start fresh from sbmlsimple, an enzyme model with species E, S, ES and P in a compartment comp:

enzyme <- getModel(system.file("examples", "sbmlsimple.xml", package = "r2sbml"))
#> 
#>   filename: /tmp/RtmpwHeoT9/Rinst301ac4a3a60ed/r2sbml/examples/sbmlsimple.xml
#>   error(s): 0
#> 
#> 
#> File: /tmp/RtmpwHeoT9/Rinst301ac4a3a60ed/r2sbml/examples/sbmlsimple.xml (Level 3, version 2)

addParameter(), addCompartment() and addSpecies() add those components. Each needs a valid SBML id that is not already in use:

addParameter(enzyme, "kdeg", 0.1)
addSpecies(enzyme, "Pext", "comp", 0, as = "concentration")
getSpeciesNames(enzyme)
#> [1] "E"    "S"    "P"    "ES"   "Pext"

addReaction() builds a reaction from named reactant and product stoichiometries (a species id mapped to its stoichiometry), an optional vector of modifier species, and a rate law in the infix syntax setRateLaw() uses. Here a first-order reaction degrades P:

addReaction(enzyme, "deg", reactants = c(P = 1), rateLaw = "comp * kdeg * P")
getReactionTable(enzyme)[, c("ID", "Reversible", "RateLaw")]
#>     ID Reversible                          RateLaw
#> 1  veq       TRUE comp * (kon * E * S - koff * ES)
#> 2 vcat      FALSE                 comp * kcat * ES
#> 3  deg      FALSE                  comp * kdeg * P
getReactionStoichiometry(enzyme)
#>   Reaction Species     Role Stoichiometry
#> 1      veq       E reactant             1
#> 2      veq       S reactant             1
#> 3      veq      ES  product             1
#> 4     vcat      ES reactant             1
#> 5     vcat       E  product             1
#> 6     vcat       P  product             1
#> 7      deg       P reactant             1

Every species the reaction names must already exist, and every name in its rate law must resolve, or the reaction is refused and the model left unchanged:

addReaction(enzyme, "bad", reactants = c(Ghost = 1), rateLaw = "comp * kdeg * P")
#> Error:
#> ! Reaction 'bad' names a species not in the model: 'Ghost'. The model was not changed.

addAssignmentRule() and addRateRule() add rules. A rule’s variable must be a non-constant component, so add a parameter with constant = FALSE to hold the result:

addParameter(enzyme, "Etot", constant = FALSE)
addAssignmentRule(enzyme, "Etot", "E + ES")
invisible(getRuleMath(enzyme))
#> Rule 0, formula: Etot = E + ES

removeParameter(), removeSpecies(), removeCompartment() and removeRule() take components away. Like removeReaction() they refuse while anything that stays behind still refers to the component:

removeSpecies(enzyme, "E")
#> Error:
#> ! Cannot remove species 'E': the assignment rule for 'Etot', reaction 'veq' and reaction 'vcat' use it. The model was not changed.

An unreferenced component removes cleanly:

addParameter(enzyme, "scratch", 1)
removeParameter(enzyme, "scratch")

The added reaction and parameters flow into convertReactions() and writeSBML() exactly as edits to existing components do.

Saving the model

writeSBML() writes the model, edits included, to a file. It keeps the document’s SBML Level and Version.

out <- tempfile(fileext = ".xml")
writeSBML(model, out)
#> Warning in writeSBML(model, out): '/tmp/Rtmp8WyLpn/file3282c71027932.xml' was
#> written with 2 SBML warning(s), listed above.

Reading the file back gives the edited model:

edited <- load(out)
getParameterTable(edited)[, c("ID", "Value")]
#>   ID Value
#> 1 k1  1000
#> 2 k2   500
#> 3 KT 25000
#> 4 k3  2500
getReactionMath(edited)
#> Reaction 0, formula: nucleus * k1 * X * Y1n
#> Reaction 1, formula: cytoplasm * k2 * Y1c * Y2
#> Reaction 2, formula: cytoplasm * k3 * Y2 / (1 + Y2)
#> [1] 0

The model is checked before it is written

Before writing, writeSBML() runs libSBML’s full consistency checks, the same categories the online SBML validator checks:

The write above warned. The diagnostics go to the console’s error stream, which this document does not show, so here they are captured; only the first line of each is kept:

diagnostics <- capture.output(type = "message", writeSBML(model, out))
#> Warning in writeSBML(model, out): '/tmp/Rtmp8WyLpn/file3282c71027932.xml' was
#> written with 2 SBML warning(s), listed above.
grep("^line", diagnostics, value = TRUE)
#> [1] "line 107: (99505 [Warning]) In situations where a mathematical expression contains literal numbers or parameters whose units have not been declared, it is not possible to verify accurately the consistency of the units in the expression. "
#> [2] "line 107: (10541 [Warning]) The units of the 'math' formula in a <kineticLaw> definition are expected to be the equivalent of _substance per time_."

Both concern the new degradation law: the literal 1 in Y2 / (1 + Y2) has no units, so libSBML cannot fully check the expression (99505), and what it can work out is not a rate of substance per time (10541). The file was written anyway.

An error is different. Here the rate law names Y1c, which takes no part in the degradation reaction:

setRateLaw(model, "degradation", "cytoplasm * k3 * Y2 * Y1c")
bad <- tempfile(fileext = ".xml")
diagnostics <- capture.output(type = "message",
  result <- tryCatch(writeSBML(model, bad), error = conditionMessage))
result
#> [1] "Cannot write '/tmp/Rtmp8WyLpn/file3282c5d39904d.xml': libSBML reported 1 SBML error(s), listed above.  Nothing was written."
grep("^line|^ The species", diagnostics, value = TRUE)
#> [1] "line 103: (21121 [Error]) All species referenced in the <kineticLaw> formula of a given reaction must first be declared using <speciesReference> or <modifierSpeciesReference>. More formally, if a <species> identifier appears in a <ci> element of a <reaction>'s <kineticLaw> formula, that same identifier must also appear in at least one <speciesReference> or <modifierSpeciesReference> in the <reaction> definition."
#> [2] " The species 'Y1c' is not listed as a product, reactant, or modifier of reaction 'degradation'."
file.exists(bad)
#> [1] FALSE

Restoring a valid rate law makes the model writable again:

setRateLaw(model, "degradation", "cytoplasm * k3 * Y2")
writeSBML(model, out)
#> Warning in writeSBML(model, out): '/tmp/Rtmp8WyLpn/file3282c71027932.xml' was
#> written with 2 SBML warning(s), listed above.

These checks are stricter than reading. getModel() reports only problems libSBML finds while parsing, so writeSBML() can refuse a model that getModel() read without complaint: an unchanged file that was already inconsistent, for instance.

The file is rewritten, not patched

libSBML writes the whole document in its own layout. A diff against the original file shows changes in indentation, attribute order and number formatting as well as your edits. Annotations and notes are kept.

Simulating the edited model

convertReactions() accepts the model pointer as well as a file name, so an edited model can be turned into simulation code without saving it first. It converts a copy, and the model in R is not changed.

Here the original model and one whose degradation reaction is ten times slower are simulated side by side with deSolve:

slow <- copyModel(original)
setParameterValue(slow, "k3", 250)

simulate <- function(m, times) {
  code <- tempfile(fileext = ".R")
  invisible(capture.output(convertReactions(m, code, format = "R")))
  env <- new.env()
  source(code, local = env)
  as.data.frame(deSolve::ode(y = env$InitialAmounts, times = times,
                             func = env$massBalances, parms = env$parameters))
}

times <- c(0, 5e-4, 1e-3, 2e-3, 5e-3)
data.frame(time = times,
           Y2_original = simulate(original, times)$Y2,
           Y2_slow = simulate(slow, times)$Y2)
#>    time  Y2_original   Y2_slow
#> 1 0e+00 0.2000000000 0.2000000
#> 2 5e-04 0.0710374901 0.2173356
#> 3 1e-03 0.0260927279 0.2361651
#> 4 2e-03 0.0041552583 0.2722870
#> 5 5e-03 0.0002926807 0.3013849

The values are concentrations: Y2 starts at an amount of 1 in a cytoplasm of volume 5. With degradation at its original rate Y2 is cleared within a few milliseconds; ten times slower, it builds up instead.

Summary