library(Pmetrics)6 Fit a model with NPAG
6.1 Set up the tutorial environment
Make sure you have run the tutorial setup code in your R session before copying, pasting and running example code here.
6.2 Load the Pmetrics library
First, remember you must always load the Pmetrics library to access its functions in your R script or Quarto document.
6.3 Create a run
To review, recall that the typical workflow in Pmetrics is as follows:
- Create a
PM_dataobject. - Create a
PM_modelobject. - Fit the model to the data with the
$fit()method of the model object. This returns aPM_resultobject, which is also saved to the hard drive and can be loaded later with thePM_loadfunction. - Examine the results with
PM_resultmethods and functions and revise as needed to improve the model fit.
6.3.1 Data objects
Since Pmetrics always needs data and a model to run, let’s create a new data object.
exData <- PM_data$new(data = "src/ex.csv")6.3.2 Model objects
You can specify a model as a list object in R. We’ll do both.
The following code creates the same model as in /src/model.txt file. We made the same model in the chapter on models. The advantage of creating them in R is that one does not need to copy model files into folders to provide necessary inputs.
mod1 <- PM_model$new(
pri = list(
Ka = ab(0.1, 0.9),
Ke = ab(0.001, 0.1),
V = ab(30, 120),
lag1 = ab(0, 4)
),
cov = list(
wt = interp(),
africa = interp("none"),
age = interp(),
gender = interp("none"),
height = interp()
),
eqn = function(){
two_comp_bolus
},
lag = function(){
lag[1] = lag1
},
out = function(){
Y[1] = X[2]/V
},
err = list(
proportional(5, c(0.02, 0.05, -0.0002, 0))
)
)
#> ℹ Compiling model...
#> Using template path: /Library/Frameworks/R.framework/Versions/4.5-arm64/Resources/library/Pmetrics6.3.3 Fit the model to the data
To keep everything tidy, we are working in a folder specifically to store the runs. We are specifying the path in the call to $fit() rather than globally changing the working directory.
# results will be saved in the Runs folder in your working directory
# we use run = 1 and overwrite to force the results to be saved in /Runs/1
# omitting overwrite = TRUE would trigger a warning if /1 already exists
# without run = 1, the next available run number will be used
run1 <- mod1$fit(data = exData, run = 1, overwrite = TRUE, path = "Runs") The PM_model class has a $fit() method that fits the model to the data.
After the run is complete the results are returned to the assigned object, here ‘run1’. However, if you want to load the results later, you can use the PM_load() function. Runs will be sequentially numbered as /1, /2, /3,… in your working directory.
run1 <- PM_load(1, path = "Runs") # load the results from run 1 if returning to this script later