---
title: "Editing a model and saving it as SBML"
output:
  rmarkdown::html_vignette:
    toc: true
    toc_depth: 2
vignette: >
  %\VignetteIndexEntry{Editing a model and saving it as SBML}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---
<!--
DISCLAIMER: This software is provided "as is", without warranty of any
kind, express or implied, including but not limited to the warranties of
merchantability, fitness for a particular purpose and non-infringement. In
no event shall the authors or copyright holders be liable for any claim,
damages or other liability, whether in an action of contract, tort or
otherwise, arising from, out of or in connection with this software or its
use.
-->


```{r setup, include = FALSE}
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
has_desolve <- requireNamespace("deSolve", quietly = TRUE)
```

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.

```{r library}
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.

```{r load}
model <- load(ex("sbmlmutlicompartment.xml"))
getParameterTable(model)[, c("ID", "Value", "Units")]
getReactionMath(model)
```

# 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:

```{r in-place}
original <- copyModel(model)
same <- model

setParameterValue(model, "k1", 1000)

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

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

```{r chain}
model |>
  setParameterValue("k2", 500) |>
  setCompartmentSize("nucleus", 2)
```

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

```{r unknown, error = TRUE}
setParameterValue(model, "k9", 1)
```

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

```{r values}
getCmtSizes(model)
setCompartmentSize(model, "cytoplasm", 4)
getCmtSizes(model)
```

`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:

```{r local, error = TRUE}
simple <- load(ex("sbmlsimple.xml"))
setParameterValue(simple, "kcat", 0.5)
```

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:

```{r species}
setSpeciesIC(model, "X", 0.5, as = "concentration")
getSpeciesTable(model)[, c("ID", "InitialConcentration", "InitialAmount")]
```

## 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`:

```{r overridden}
rules <- load(ex("sbmlassignmentrules.xml"))
getRuleMath(rules)
setSpeciesIC(rules, "S1", 1, as = "concentration")
```

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:

```{r rate-law}
setRateLaw(model, "degradation", "cytoplasm * k3 * Y2 / (1 + Y2)")
getReactionMath(model)
```

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:

```{r rate-law-bad, error = TRUE}
setRateLaw(model, "degradation", "cytoplasm * kdeg * Y2")
setRateLaw(model, "degradation", "cytoplasm * (k3 * Y2")
```

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:

```{r rate-law-local}
getReactionMath(simple)
setRateLaw(simple, "vcat", "comp * 0.5 * ES")
getReactionMath(simple)
```

`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:

```{r remove}
removeReaction(model, "transport")
getReactionMath(model)
getSpeciesNames(model)
```

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`:

```{r remove-refused, error = TRUE}
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")
```

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`:

```{r add-load}
enzyme <- getModel(system.file("examples", "sbmlsimple.xml", package = "r2sbml"))
```

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

```{r add-scalar}
addParameter(enzyme, "kdeg", 0.1)
addSpecies(enzyme, "Pext", "comp", 0, as = "concentration")
getSpeciesNames(enzyme)
```

`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`:

```{r add-reaction}
addReaction(enzyme, "deg", reactants = c(P = 1), rateLaw = "comp * kdeg * P")
getReactionTable(enzyme)[, c("ID", "Reversible", "RateLaw")]
getReactionStoichiometry(enzyme)
```

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:

```{r add-reaction-bad, error = TRUE}
addReaction(enzyme, "bad", reactants = c(Ghost = 1), rateLaw = "comp * kdeg * P")
```

`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:

```{r add-rule}
addParameter(enzyme, "Etot", constant = FALSE)
addAssignmentRule(enzyme, "Etot", "E + ES")
invisible(getRuleMath(enzyme))
```

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

```{r remove-referenced, error = TRUE}
removeSpecies(enzyme, "E")
```

An unreferenced component removes cleanly:

```{r remove-clean}
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.

```{r write}
out <- tempfile(fileext = ".xml")
writeSBML(model, out)
```

Reading the file back gives the edited model:

```{r read-back}
edited <- load(out)
getParameterTable(edited)[, c("ID", "Value")]
getReactionMath(edited)
```

## 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:

- **Errors** stop it. The diagnostics are printed and nothing is written, so
  an invalid file is never produced.
- **Warnings**, typically about units, are printed and reported as one R
  warning, and the file is still written.

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:

```{r write-warning}
diagnostics <- capture.output(type = "message", writeSBML(model, out))
grep("^line", diagnostics, value = TRUE)
```

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:

```{r write-error}
setRateLaw(model, "degradation", "cytoplasm * k3 * Y2 * Y1c")
bad <- tempfile(fileext = ".xml")
diagnostics <- capture.output(type = "message",
  result <- tryCatch(writeSBML(model, bad), error = conditionMessage))
result
grep("^line|^ The species", diagnostics, value = TRUE)
file.exists(bad)
```

Restoring a valid rate law makes the model writable again:

```{r write-fixed}
setRateLaw(model, "degradation", "cytoplasm * k3 * Y2")
writeSBML(model, out)
```

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:

```{r simulate, eval = has_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)
```

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

- Edits change the model in place; `copyModel()` keeps the original.
- Components can be added (`addParameter()`, `addCompartment()`,
  `addSpecies()`, `addReaction()`, `addAssignmentRule()`, `addRateRule()`) and
  removed (`removeParameter()`, `removeSpecies()`, `removeCompartment()`,
  `removeRule()`); an adder validates before it mutates.
- Unknown ids, unparseable rate laws, undefined names in a rate law and
  removals that would leave dangling references are errors, and they leave
  the model unchanged.
- A value that an initial assignment or assignment rule overrides is stored,
  with a warning.
- `writeSBML()` validates before writing: errors stop it, warnings do not.
- `convertReactions()` takes the edited model directly.
