
Registering simulation functions
Source:vignettes/register-simulation-functions.Rmd
register-simulation-functions.Rmdnlmixr2save can cache more than nlmixr2
fits. If your package has its own simulation or stochastic estimation
functions, you can register them so the := operator
restores cached results without breaking reproducibility.
Registering a stochastic simulation function
Use saveFitRandom() to tell nlmixr2save
that a function should be treated as random-state-aware.
library(nlmixr2save)
saveFitRandom("mySimulate")After registration, calls of the form below are cached in
sim.rds together with the starting and ending random
state:
sim := mySimulate(model, n = 1000)On restore, nlmixr2save checks:
- the function arguments,
- whether the original run changed the random state, and
- whether the current run starts from the same random state.
If those checks pass, the cached value is loaded and the random seed is advanced to the same state the original run would have produced.
Registering at package load time
If your package always wants a function treated as stochastic,
register it in .onLoad():
.onLoad <- function(libname, pkgname) {
nlmixr2save::saveFitRandom("mySimulate")
}You can also unregister it later:
saveFitRandom("mySimulate", remove = TRUE)Integrating stochastic estimation methods
nlmixr2save handles nlmixr2(...) calls
differently from ordinary function calls:
deterministic estimation methods are cached as saved fits (
.zipbundles),stochastic estimation methods are cached with seed metadata (
.rdsfiles).
To place your estimation method into the seed-aware group, define the
nlmixr2Est.<method> method with a random
attribute set to TRUE or to a function that inspects the
control object.
nlmixr2Est.myMethod <- function(object, data, control, ...) {
# run stochastic estimation here
}
attr(nlmixr2Est.myMethod, "random") <- TRUEIf the stochastic behavior depends on control settings, the attribute can be a function:
With that in place, this call uses the seed-aware cache path automatically:
When to use each integration path
Use saveFitRandom() when:
you are caching a regular function such as a simulation helper,
the result should be stored as a generic
.rds, andreproducibility depends on restoring the random seed state.
Use the random attribute on
nlmixr2Est.<method> when:
the function is an
nlmixr2estimation method,deterministic runs should still use the fit-saving
.zippath, andstochastic runs should move into the seed-aware
.rdspath.
Practical limitations
The same limitations apply here as in the main usage vignette:
:=needs to see the expensive call directly on the right-hand side.Seed-aware restores only replay safely when the starting random state matches.
Generic registered functions are restored from
.rds, not from the text-and-csv fit format used for deterministicnlmixr2fits.