Examples using R functions

This page provides pieces of code to perform some procedures with the R functions for Monolix. The code has to be adapted to use your projects and use the results as you wish in R.


Load and run a project

Simple example to load an existing project, run SAEM and print the number of iterations used in the exploratory and smoothing phases:

# load and initialize the API

demoPath = 'C:/Users/username/lixoft/monolix/monolix2020R1/demos/1.creating_and_using_models/1.1.libraries_of_models/'
project <- paste0(demoPath, "theophylline_project.mlxtran"
loadProject(projectFile = project)

iter <- getSAEMiterations()
print(paste0("Iterations in exploratory phase: ",iter$iterationNumbers[1]))
print(paste0("Iterations in smoothing phase: ",iter$iterationNumbers[2]))


Convergence assessment

Example of the functions to call to build a project from scratch using one of the demo data sets and a model from the libraries, and run a convergence assessment to evaluate the robustness of the convergence:

# load and initialize the API

# create a new project by setting a data set and a structural model
# replace <userFolder> by the path to your home directory
demoPath = 'C:/Users/username/lixoft/monolix/monolix2020R1/demos/1.creating_and_using_models/1.1.libraries_of_models/'
librariesPath = 'C:/ProgramData/Lixoft/MonolixSuite2020R1/factory/library/pk'
newProject(data = list(dataFile = paste0(demoPath,'data/warfarin_data.txt'),
                       headerTypes =c("id", "time", "amount", "observation", "obsid", "contcov", "catcov", "ignore"),
                       observationTypes = list(y1 = "continuous", y2 = "continuous" ),
                       mapping = list("1" = "y1")),
           modelFile = paste0(librariesPath,'/oral1_1cpt_TlagkaVCl.txt'))

# set tasks in scenario
scenario <- getScenario()
scenario$tasks = c(populationParameterEstimation = T, 
                   conditionalModeEstimation = T, 
                   conditionalDistributionSampling = T, 
scenario$linearization = TRUE

# ----------------------------------------------------------------------------
# convergence assessment: run 5 estimations with different initial estimates,
# store the results in tabestimates
# ----------------------------------------------------------------------------
popparams <- getPopulationParameterInformation()
tabestimates <- NULL; tabse <- NULL
for(i in 1:5){
   # sample new initial estimates
   popini <- sapply(1:nrow(popparams), function(j){runif(n=1, min=popparams$initialValue[j]/2, max=popparams$initialValue[j]*2)})

   # set sampled values as new initial estimates
   newpopparams <- popparams
   newpopparams$initialValue <- popini

   # run the estimation

   # store the estimates and s.e. in table
   tabestimates <- cbind(tabestimates, getEstimatedPopulationParameters())
   tabse <- cbind(tabse, getEstimatedStandardErrors()$stochasticApproximation)

The table of estimates can then be further analyzed using typical R functions, and printed or plotted.


Profile likelihood

This code performs a profile likelihood for the parameter f_LDLc_pop. This code which can be modified allows more flexibility than using the function confintmlx predefined in the Rsmlx package.




for(i in tested_values){
  setPopulationParameterInformation(f_LDLc_pop = list(initialValue = i, method = "FIXED"))
  df <- data.frame(param='f_LDLc_pop’, value=i, LL=LL)

Bayesian individual dynamic predictions


This partial example corresponds to bayesian individual dynamic predictions with uncertainty. This is what it does:
  • estimate population parameters for a model,
  • fix the population parameters to the estimates,
  • change the dataset for another, that can be filtered up to some landmark time,
  • run the task Conditional distribution that samples sets of parameters from the individual posterior distributions,
  • simulate the model based on the sampled parameters with Simulx.


initializeLixoftConnectors(software = "monolix")

loadProject(projectFile = "path_to_projet_file.mlxtran")

# set pop params to estimates and fix pop params
popparams <- getPopulationParameterInformation()
popparams$method <- "FIXED"

# here the data can be modified in the project to take into account data until landmark time
filtereddatfile <- "path to data filtered up to landmark time.csv"
BaseData <- getData()
setData(filtereddatfile, BaseData$headerTypes, BaseData$observationTypes)

# set MCMC settings: min number iter=1000, relative interval width=1, number of param per indiv=200
# this is to sample 200 parameters from 1000 iterations. Samples are uniformly spread on the iterations.
CondDistSettings <- getConditionalDistributionSamplingSettings()
setConditionalDistributionSamplingSettings(nbminiterations=500, ratio=1, nbsimulatedparameters=200)

# run SAEM and conditional distribution
runPopulationParameterEstimation() # mandatory before other tasks, but nb of iterations is null as all parameters are fixed
runConditionalDistributionSampling() # this is sampling from the posterior distribution for each individual

simparams <- getSimulatedIndividualParameters()
simparams$id <- row.names(simparams) # replace id by rank of {rep, id}
simparams$rep <- NULL
write.csv(simparams, file="table_simulated_parameters.csv", row.names = F)

# simulate based on simulated parameters using Simulx

initializeLixoftConnectors(software = "simulx", force=TRUE)

importMonolixProject(projectFile = "path_to_projet_file.mlxtran")

defineIndividualElement(name="simulatedParameters", element="table_simulated_parameters.csv")
setGroupElement(group = "simulationGroup1", elements = c("simulatedParameters"))
setGroupSize(group = "simulationGroup1", size = nrow(simparams))

simresults <- getSimulationResults()