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

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

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

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

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

## ----unknown, error = TRUE----------------------------------------------------
try({
setParameterValue(model, "k9", 1)
})

## ----values-------------------------------------------------------------------
getCmtSizes(model)
setCompartmentSize(model, "cytoplasm", 4)
getCmtSizes(model)

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

## ----species------------------------------------------------------------------
setSpeciesIC(model, "X", 0.5, as = "concentration")
getSpeciesTable(model)[, c("ID", "InitialConcentration", "InitialAmount")]

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

## ----rate-law-----------------------------------------------------------------
setRateLaw(model, "degradation", "cytoplasm * k3 * Y2 / (1 + Y2)")
getReactionMath(model)

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

## ----rate-law-local-----------------------------------------------------------
getReactionMath(simple)
setRateLaw(simple, "vcat", "comp * 0.5 * ES")
getReactionMath(simple)

## ----remove-------------------------------------------------------------------
removeReaction(model, "transport")
getReactionMath(model)
getSpeciesNames(model)

## ----remove-refused, error = TRUE---------------------------------------------
try({
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")
})

## ----add-load-----------------------------------------------------------------
enzyme <- getModel(system.file("examples", "sbmlsimple.xml", package = "r2sbml"))

## ----add-scalar---------------------------------------------------------------
addParameter(enzyme, "kdeg", 0.1)
addSpecies(enzyme, "Pext", "comp", 0, as = "concentration")
getSpeciesNames(enzyme)

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

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

## ----add-rule-----------------------------------------------------------------
addParameter(enzyme, "Etot", constant = FALSE)
addAssignmentRule(enzyme, "Etot", "E + ES")
invisible(getRuleMath(enzyme))

## ----remove-referenced, error = TRUE------------------------------------------
try({
removeSpecies(enzyme, "E")
})

## ----remove-clean-------------------------------------------------------------
addParameter(enzyme, "scratch", 1)
removeParameter(enzyme, "scratch")

## ----write--------------------------------------------------------------------
out <- tempfile(fileext = ".xml")
writeSBML(model, out)

## ----read-back----------------------------------------------------------------
edited <- load(out)
getParameterTable(edited)[, c("ID", "Value")]
getReactionMath(edited)

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

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

## ----write-fixed--------------------------------------------------------------
setRateLaw(model, "degradation", "cytoplasm * k3 * Y2")
writeSBML(model, out)

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

