Package {nlmixr2save}


Title: Save 'nlmixr2' Fits in a Format Readable Outside 'nlmixr2'
Version: 0.2.0
Description: Provides tools to save 'nlmixr2' fitted models in a portable format readable outside of 'nlmixr2' and independent of the package version. 'nlmixr2' fits and compares nonlinear mixed-effects models in differential equations with flexible dosing information commonly seen in pharmacokinetics and pharmacodynamics (Almquist, Leander, and Jirstrand 2015 <doi:10.1007/s10928-015-9409-1>). Differential equation solving uses compiled C code from the 'rxode2' package (Wang, Hallow, and James 2015 <doi:10.1002/psp4.12052>).
License: MIT + file LICENSE
URL: https://nlmixr2.github.io/nlmixr2save/, https://github.com/nlmixr2/nlmixr2save/
BugReports: https://github.com/nlmixr2/nlmixr2save/issues/
Encoding: UTF-8
Imports: checkmate, cli, digest, Rcpp, rxode2 (> 5.0.1), zip
Suggests: babelmixr2, dplyr, knitr, nlmixr2data, nlmixr2est (≥ 5.0.2), PopED, rmarkdown, testthat (≥ 3.0.0), tidyvpc, withr
VignetteBuilder: knitr
Config/testthat/edition: 3
LinkingTo: Rcpp
Config/roxygen2/version: 8.0.0
NeedsCompilation: yes
Packaged: 2026-08-04 23:53:13 UTC; matt-fidler
Author: Matthew Fidler ORCID iD [aut, cre]
Maintainer: Matthew Fidler <matthew.fidler@gmail.com>
Repository: CRAN
Date/Publication: 2026-08-05 00:20:02 UTC

This returns or assigns the environment used in the ⁠:=⁠ operator

Description

This returns or assigns the environment used in the ⁠:=⁠ operator

Usage

.assignParent(env = NULL)

Arguments

env

environment to assign to; if NULL (the default), the current parent environment is returned.

Value

the environment used in the ⁠:=⁠ operator

Author(s)

Matthew L. Fidler

Examples

.assignParent()

Return if the last ⁠:=⁠ assignment was actually a restore from a file

Description

Return if the last ⁠:=⁠ assignment was actually a restore from a file

Usage

.assignRestore()

Value

TRUE if the last ⁠:=⁠ assignment was a restore from a file, FALSE otherwise

Author(s)

Matthew L. Fidler

Examples

.assignRestore()

This gets the properties of the nlmixr2 call for saving and loading purposes

Description

This is used to:

Usage

.nlmixr2saveProps(object, data, est = NULL, control = NULL, table = NULL, ...)

Arguments

object

Fitted object or function specifying the model.

data

nlmixr data

est

estimation method (all methods are shown by 'nlmixr2AllEst()'). Methods can be added for other tools

control

The estimation control object. These are expected to be different for each type of estimation method

table

The output table control object (like 'tableControl()')

...

additional arguments for nlmixr2 but ignored for this call.

Details

Value

A list containing

Author(s)

Matthew L. Fidler


This assignment operator is meant to assign or load a nlmixr2 fit (and other objects)

Description

By default it is equivalent to the standard assignment operator ⁠<-⁠, but it is a S3 generic so it can have other behaviors for specific classes.

Usage

x := value

Arguments

x

the name of the object to assign the value to

value

the value to assign to the object, because R can use non-standard evaluation, this expression may not be evaluated when passed to the function. In the case of the nlmixr2 function, the expression will be evaluated only if the fit needs to be refit (i.e. if the zip file does not exist or if the sha1 hash of the arguments does not match).

Details

For example, when used with a nlmixr2 call, say:

fit := nlmixr2(one.cmt, theo_sd, est="focei")

the ⁠:=⁠ operator will assign the result of the nlmixr2 call to fit, but it will also save the fit to a file named "fit.zip" in the current working directory.

If the "fit.zip" file already exists, it will be loaded instead of running the possibly expensive fitting process (as long as the sha1 hash of the arguments are the same).

This allows for easy saving and loading of fitted models without having to explicitly call a save function.

This S3 generic can be extended to other classes as needed, allowing for custom behaviors when assigning values to objects of those classes.

When trying to save expensive evaluations like the output of a nlmixr2() fit, the s3 dispach would be to ⁠:=.assign_nlmixr2(x, value)⁠ or whatever function is used in the call. This allows checking the arguments to see if there can be a cache that will be loaded.

Otherwise, the default s3 method would be ⁠:=.class⁠ where class instead. Unlike the un-evaluated function dispach there is no way to check the arguments for a cache, so loading from cache is not possible.

Value

the value that was assigned to the object, invisibly. It also has the side effect of assigning the value to the parent environment.

Author(s)

Matthew L. Fidler

See Also

saveFit() for saving fitted model objects to files, loadFit() for loading fitted model objects from files, and .assignParent() for getting or setting the environment used in the ⁠:=⁠ operator.

Examples



 if (requireNamespace("nlmixr2est", quietly=TRUE) &&
       requireNamespace("nlmixr2data", quietly=TRUE) &&
       requireNamespace("withr")) {
   library(nlmixr2est)
  library(nlmixr2data)
  withr::with_tempdir({
     one.cmt <- function() {
       ini({
         tka <- 0.45
         tcl <- log(c(0, 2.7, 100))
         tv <- 3.45
         eta.ka ~ 0.6
         eta.cl ~ 0.3
         eta.v ~ 0.1
         add.sd <- 0.7
       })
       model({
        ka <- exp(tka + eta.ka)
        cl <- exp(tcl + eta.cl)
        v  <- exp(tv + eta.v)
        linCmt() ~ add(add.sd)
       })
    }
    # First fit creates fit.zip
    fit := nlmixr2(one.cmt, theo_sd, est="focei")

    # Second fit loads from fit.zip since it had the same options
    fit := nlmixr2(one.cmt, theo_sd, est="focei")

    # Third fit refits since the options are different
    fit := nlmixr2(one.cmt, theo_sd, est="saem")
  })
 }


Load a fitted model object from a file

Description

Load a fitted model object from a file

Usage

loadFit(file, checkVersion = .nlmixr2saveCheckVersion())

Arguments

file

the base name of the files to load the fit from.

checkVersion

when TRUE, warn if the fit was produced with a different nlmixr2est/rxode2 version (or remote sha) than the one currently installed. Defaults to getOption("nlmixr2save.checkVersion", TRUE).

Value

the fitted model object


Delete every ⁠:=⁠ cache entry under the active prefix and directory

Description

Removes the cache files (.zip, .rds), the fit loader scripts (.R) and fit component files (⁠-*.csv⁠, ⁠-*.rds⁠, ⁠-*.R⁠) whose names begin with the current getOption("nlmixr2save.prefix") in the current getOption("nlmixr2save.dir"). Use it to force ⁠:=⁠ to re-run cached fits/simulations on the next render when nlmixr2save.check is FALSE.

Usage

nlmixr2saveInvalidate()

Value

invisibly, the character vector of files removed

Author(s)

Matthew L. Fidler

Examples

## Not run: 
  options(nlmixr2save.dir = "cache", nlmixr2save.prefix = "modelPiping-")
  nlmixr2saveInvalidate() # clears cache/modelPiping-* entries

## End(Not run)

Fix nlmixr2 save output

Description

This function modifies the output of nlmixr2's save function to ensure that the numeric columns of the parFixedDf data frame have the types that nlmixr2 outputs after a CSV round-trip (all-NA columns are read back as logical vectors, so they are coerced back to numeric here).

Usage

nlmixr2saveParFixedDf(obj, named = TRUE)

Arguments

obj

A list object returned by nlmixr2's save function.

named

Logical; when TRUE (default, matching fits from older nlmixr2est) the "Estimate" and "SE" columns are named using the row names; when FALSE they are left as unnamed numeric vectors.

Details

Depending on the version of nlmixr2est that created the fit, the "Estimate" and "SE" columns are either named numeric vectors (names matching the row names; nlmixr2est <= 6.0) or plain unnamed numeric vectors (the ⁠$parFixed⁠ refactor in newer nlmixr2est). The named argument selects which structure is restored; nlmixr2save::saveFit() records the correct value in the generated restore script based on the fit being saved.

Value

A modified data.frame object with numeric columns restored to the structure of the original fit


Save a shareable copy of a fit without the original data

Description

Writes a portable .zip copy of a saved fit that omits the original dataset (the subject-level data), so a fitted model can be shared without its data. The input may be a live fit object or the base name of an existing saved fit .zip; either way the original is left unchanged and new sibling zips are written. Names are resolved through getOption("nlmixr2save.dir") and getOption("nlmixr2save.prefix") (as for the ⁠:=⁠ cache).

Usage

nlmixr2saveShare(x, noFit = FALSE, file = NULL)

Arguments

x

a fitted model object, or the base name (no extension) of a saved fit .zip to read.

noFit

Boolean; when TRUE, also strip the output tables (the returned prediction/residual data.frame), writing ⁠<file>-noData-noFit.zip⁠ instead of ⁠<file>-noData.zip⁠.

file

optional output base name; defaults to the name of x.

Details

Value

the path of the written .zip, invisibly.

Author(s)

Matthew L. Fidler

See Also

saveFit(), loadFit()

Examples


  if (requireNamespace("nlmixr2est", quietly=TRUE) &&
        requireNamespace("nlmixr2data", quietly=TRUE) &&
        requireNamespace("withr")) {
    library(nlmixr2est)
    library(nlmixr2data)
    withr::with_tempdir({
      one.cmt <- function() {
        ini({
          tka <- 0.45; tcl <- log(c(0, 2.7, 100)); tv <- 3.45
          eta.ka ~ 0.6; eta.cl ~ 0.3; eta.v ~ 0.1
          add.sd <- 0.7
        })
        model({
          ka <- exp(tka + eta.ka); cl <- exp(tcl + eta.cl); v <- exp(tv + eta.v)
          linCmt() ~ add(add.sd)
        })
      }
      fit <- nlmixr2(one.cmt, theo_sd, est="focei")
      saveFit(fit)                       # fit.zip (with data)
      nlmixr2saveShare("fit")            # fit-noData.zip
      nlmixr2saveShare("fit", noFit=TRUE) # fit-noData-noFit.zip
    })
  }


Standardize and simplify data for nlmixr2 estimation

Description

This function is typically not needed by end users.

Usage

nlmixrDataSimplify(data, object, table = list(), est = NULL, control = NULL)

Arguments

data

nlmixr data

object

an nlmixr_ui object (e.g. the output of running nlmixr(object = model)

table

The output table control object (like 'tableControl()')

est

estimation method (all methods are shown by 'nlmixr2AllEst()'). Methods can be added for other tools

control

The estimation control object. These are expected to be different for each type of estimation method

Details

The standardization keeps columns that rxode2 and nlmixr2 use along with the covariates. Column order is standardized (rxode2 then nlmixr2 then alphabetically sorted covariates), and rxode2 and nlmixr2 column names are converted to lower case.

Some estimation methods take their covariates from the data instead of from the model; est="vae" searches the data for covariates to select. For those methods the covariate columns the search can pick from are kept as well, since dropping them would change the fit.

Value

The data with the nlmixr2 column lower case and on the left and the covariate columns on the right and alphabetically sorted.

Author(s)

William S. Denney with minor modifications from Matt Fidler


Save a fitted model object to a series of files

Description

Save a fitted model object to a series of files

Usage

saveFit(fit, file, zip = TRUE, data = .nlmixr2saveData())

## S3 method for class 'nlmixr2FitCore'
saveFit(fit, file, zip = TRUE, data = .nlmixr2saveData())

## S3 method for class 'nlmixr2FitData'
saveFit(fit, file, zip = TRUE, data = .nlmixr2saveData())

## Default S3 method:
saveFit(fit, file, zip = TRUE, data = .nlmixr2saveData())

Arguments

fit

the fitted model object

file

the base name of the files to save the fit to.

zip

Boolean indicating if the files should be zipped.

data

Boolean indicating whether the original dataset (origData) is stored in the saved fit. When FALSE it is omitted, producing a fit that can be shared without the subject-level data (see nlmixr2saveShare()). Defaults to getOption("nlmixr2save.data", TRUE).

Value

nothing, called for side effects

Author(s)

Matthew L. Fidler

Examples


  if (requireNamespace("nlmixr2est", quietly=TRUE) &&
        requireNamespace("nlmixr2data", quietly=TRUE) &&
        requireNamespace("withr")) {
    library(nlmixr2est)
    library(nlmixr2data)
    withr::with_tempdir({
      one.cmt <- function() {
        ini({
          tka <- 0.45
          tcl <- log(c(0, 2.7, 100))
          tv <- 3.45
          eta.ka ~ 0.6
          eta.cl ~ 0.3
          eta.v ~ 0.1
          add.sd <- 0.7
        })
        model({
          ka <- exp(tka + eta.ka)
          cl <- exp(tcl + eta.cl)
          v  <- exp(tv + eta.v)
          linCmt() ~ add(add.sd)
        })
      }

      fit <- nlmixr2(one.cmt, theo_sd, est="focei")

      saveFit(fit) # saved to fit.zip
      fit2 <- loadFit(fit) # load fit.zip

      if (file.exists("fit.zip")) {
         unlink("fit.zip")
      }

      print(fit2)
    })
  }


Save a fitted model item to a file

Description

This is a generic function to save a fitted model item to a file.

Usage

saveFitItem(item, name, file)

## S3 method for class 'rxUi'
saveFitItem(item, name, file)

## S3 method for class 'data.frame'
saveFitItem(item, name, file)

## S3 method for class 'nlmixr2estSessionInfo'
saveFitItem(item, name, file)

## Default S3 method:
saveFitItem(item, name, file)

## S3 method for class 'saemFit'
saveFitItem(item, name, file)

## S3 method for class 'foceiModelList'
saveFitItem(item, name, file)

Arguments

item

Item to be saved

name

Name of the item

file

Baseline file name to save the item to.

Value

boolean to determine if the item was saved; if it wasn't it will be saved into the general list of items.

Author(s)

Matthew L. Fidler


Manage functions treated as random by ⁠:=⁠

Description

Functions registered here are saved with random-state metadata so cached restores behave like the original call was run again.

Usage

saveFitRandom(fun = NULL, remove = FALSE)

Arguments

fun

Function name(s) to add or remove. If NULL, the current registry is returned without modification.

remove

Boolean indicating if fun should be removed from the registry instead of added.

Value

Character vector of registered function names.

Author(s)

Matthew L. Fidler

Examples

saveFitRandom()
saveFitRandom("myRandomFun")
saveFitRandom("myRandomFun", remove=TRUE)