| Version: | 0.2.0 |
| Title: | Understanding Nonlinear Mixed Effects Modeling for Population Pharmacokinetics |
| Description: | This shows how NONMEM(R) software works. NONMEM's classical estimation methods like 'First Order(FO) approximation', 'First Order Conditional Estimation(FOCE)', and 'Laplacian approximation' are explained. Additionally, provides functions for post-run processing of NONMEM output files, generating comprehensive PDF diagnostic reports including objective function value analysis, parameter estimates, prediction diagnostics, residual diagnostics, empirical Bayes estimate (EBE) analysis, input data summary, and individual pharmacokinetic parameter distributions. |
| Depends: | R (≥ 3.5.0), numDeriv |
| Imports: | MASS, grDevices, graphics, stats, utils |
| ByteCompile: | yes |
| License: | GPL-3 |
| Copyright: | 2017-, Kyun-Seop Bae |
| Author: | Kyun-Seop Bae [aut, cre] |
| Maintainer: | Kyun-Seop Bae <k@acr.kr> |
| URL: | https://cran.r-project.org/package=nmw |
| Suggests: | testthat (≥ 3.0.0) |
| Config/testthat/edition: | 3 |
| Encoding: | UTF-8 |
| NeedsCompilation: | no |
| RoxygenNote: | 7.3.3 |
| Packaged: | 2026-03-15 02:57:29 UTC; Kyun-SeopBae |
| Repository: | CRAN |
| Date/Publication: | 2026-04-07 05:20:08 UTC |
Understanding Nonlinear Mixed Effects Modeling for Population Pharmacokinetics
Description
This shows how NONMEM(R) <http://www.iconplc.com/innovation/nonmem/> software works. Additionally, provides functions for post-run processing of NONMEM output files, generating comprehensive PDF diagnostic reports.
Details
This package explains 'First Order(FO) approximation' method, 'First Order Conditional Estimation(FOCE)' method, and 'Laplacian(LAPL)' method of NONMEM software. It also provides post-run processing functions including PDF diagnostic reports for OFV analysis, parameter estimates, prediction diagnostics, residual diagnostics, EBE analysis, input data summary, and individual PK parameter distributions.
Author(s)
Kyun-Seop Bae <k@acr.kr>
References
NONMEM Users guide
Wang Y. Derivation of various NONMEM estimation methods. J Pharmacokinet Pharmacodyn. 2007.
Kang D, Bae K, Houk BE, Savic RM, Karlsson MO. Standard Error of Empirical Bayes Estimate in NONMEM(R) VI. K J Physiol Pharmacol. 2012.
Kim M, Yim D, Bae K. R-based reproduction of the estimation process hidden behind NONMEM Part 1: First order approximation method. 2015.
Bae K, Yim D. R-based reproduction of the estimation process hidden behind NONMEM Part 2: First order conditional estimation. 2016.
Examples
DataAll = Theoph
colnames(DataAll) = c("ID", "BWT", "DOSE", "TIME", "DV")
DataAll[,"ID"] = as.numeric(as.character(DataAll[,"ID"]))
nTheta = 3
nEta = 3
nEps = 2
THETAinit = c(2, 50, 0.1)
OMinit = matrix(c(0.2, 0.1, 0.1, 0.1, 0.2, 0.1, 0.1, 0.1, 0.2), nrow=nEta, ncol=nEta)
SGinit = diag(c(0.1, 0.1))
LB = rep(0, nTheta) # Lower bound
UB = rep(1000000, nTheta) # Upper bound
FGD = deriv(~DOSE/(TH2*exp(ETA2))*TH1*exp(ETA1)/(TH1*exp(ETA1) - TH3*exp(ETA3))*
(exp(-TH3*exp(ETA3)*TIME)-exp(-TH1*exp(ETA1)*TIME)),
c("ETA1","ETA2","ETA3"),
function.arg=c("TH1", "TH2", "TH3", "ETA1", "ETA2", "ETA3", "DOSE", "TIME"),
func=TRUE, hessian=TRUE)
H = deriv(~F + F*EPS1 + EPS2, c("EPS1", "EPS2"), function.arg=c("F", "EPS1", "EPS2"), func=TRUE)
PRED = function(THETA, ETA, DATAi)
{
FGDres = FGD(THETA[1], THETA[2], THETA[3], ETA[1], ETA[2], ETA[3], DOSE=320, DATAi[,"TIME"])
Gres = attr(FGDres, "gradient")
Hres = attr(H(FGDres, 0, 0), "gradient")
if (e$METHOD == "LAPL") {
Dres = attr(FGDres, "hessian")
Res = cbind(FGDres, Gres, Hres, Dres[,1,1], Dres[,2,1], Dres[,2,2], Dres[,3,])
colnames(Res) = c("F", "G1", "G2", "G3", "H1", "H2", "D11", "D21", "D22", "D31", "D32", "D33")
} else {
Res = cbind(FGDres, Gres, Hres)
colnames(Res) = c("F", "G1", "G2", "G3", "H1", "H2")
}
return(Res)
}
####### First Order Approximation Method # Commented out for the CRAN CPU time
#InitStep(DataAll, THETAinit=THETAinit, OMinit=OMinit, SGinit=SGinit, LB=LB, UB=UB,
# Pred=PRED, METHOD="ZERO")
#(EstRes = EstStep()) # 4 sec
#(CovRes = CovStep()) # 2 sec
#PostHocEta() # Using e$FinalPara from EstStep()
#TabStep()
######## First Order Conditional Estimation with Interaction Method
#InitStep(DataAll, THETAinit=THETAinit, OMinit=OMinit, SGinit=SGinit, LB=LB, UB=UB,
# Pred=PRED, METHOD="COND")
#(EstRes = EstStep()) # 2 min
#(CovRes = CovStep()) # 1 min
#get("EBE", envir=e)
#TabStep()
######## Laplacian Approximation with Interaction Method
#InitStep(DataAll, THETAinit=THETAinit, OMinit=OMinit, SGinit=SGinit, LB=LB, UB=UB,
# Pred=PRED, METHOD="LAPL")
#(EstRes = EstStep()) # 4 min
#(CovRes = CovStep()) # 1 min
#get("EBE", envir=e)
#TabStep()
EBE Correlation and Covariance Tables
Description
Prints correlation and covariance tables comparing empirical Bayes estimates (EBE) with the estimated omega matrix, including:
Correlation of covariates and EBE
Covariance of EBE vs omega matrix
Ratios of Cov(EBE)/OM and Cor(EBE)/Cor(OM)
Helper function for nmw_report_ebe.
Usage
.ebe_correlation_tables(tabEta, nEta, EtaNames2, OM, VarStat, FDATA)
Arguments
tabEta |
data.frame with ID, ETA, and covariate columns |
nEta |
integer, number of ETAs |
EtaNames2 |
character vector, c("ID", "ETA1", "ETA2", ...) |
OM |
matrix, omega matrix (nEta x nEta) |
VarStat |
matrix from |
FDATA |
data.frame of NONMEM data |
EBE Covariate Analysis
Description
Performs ETA vs covariate analysis including:
Boxplots of ETAs vs categorical covariates with ANOVA p-values
Pair plots via
EBEpairGrid plots of ETAs vs continuous covariates with outlier labeling and lowess smoothing
Helper function for nmw_report_ebe.
Usage
.ebe_covariate_analysis(
tabEta,
FDATA,
VarStat,
nEta,
nID,
IDs,
EtaNames2,
RunNumber,
defpar
)
Arguments
tabEta |
data.frame with ID and ETA columns |
FDATA |
data.frame of NONMEM data |
VarStat |
matrix from |
nEta |
integer, number of ETAs |
nID |
integer, number of subjects |
IDs |
numeric vector of unique subject IDs |
EtaNames2 |
character vector, c("ID", "ETA1", "ETA2", ...) |
RunNumber |
character, model name |
defpar |
list, saved |
Value
data.frame, tabEta with covariate columns appended
EBE Individual Confidence Intervals and Shrinkage
Description
Computes and exports individual ETA confidence intervals, significance flags, relative standard errors, and individual shrinkage values. Writes results to EBEALL.CSV and prints per-ETA summary tables to the PDF.
For each ETA:
LL/UL: Lower/Upper 95% confidence limit (ETA +/- 2*SE)
ZERO: Whether CI includes zero
RSE: Relative standard error (SE/|ETA|)
SHR: Individual shrinkage (SE/sqrt(omega))
Helper function for nmw_report_ebe.
Usage
.ebe_individual_ci(EtaRep, nEta, nID, OM)
Arguments
EtaRep |
data.frame with ID, ETA1..ETAn, and seETA columns |
nEta |
integer, number of ETAs |
nID |
integer, number of subjects |
OM |
matrix, omega matrix (nEta x nEta) |
EBE Distribution Plots
Description
Generates distribution diagnostic plots for each ETA including
summary statistics, histograms with density overlay, Shapiro-Wilk
normality test, population shrinkage, and Q-Q plots.
Helper function for nmw_report_ebe.
Usage
.ebe_plot_distributions(EtaRep, nEta, OM, defpar)
Arguments
EtaRep |
data.frame with ID, ETA1..ETAn, and seETA columns |
nEta |
integer, number of ETAs |
OM |
matrix, omega matrix (nEta x nEta) |
defpar |
list, saved |
EBE Multiple Linear Regression and Influence Diagnostics
Description
Performs multiple linear regression of each ETA on covariates and generates influence diagnostic plots including:
Cook's Distance
Studentized deleted residuals vs predicted values
e^2/SSE vs hat values
COVRATIO vs DFFITS
Helper function for nmw_report_ebe.
Usage
.ebe_regression_diagnostics(
tabEta,
nEta,
EtaNames,
EtaRep,
VarStat,
FDATA,
defpar
)
Arguments
tabEta |
data.frame with ID, ETA, and covariate columns |
nEta |
integer, number of ETAs |
EtaNames |
character vector, c("Eta 1", "Eta 2", ...) |
EtaRep |
data.frame with ETA values and standard errors |
VarStat |
matrix from |
FDATA |
data.frame of NONMEM data |
defpar |
list, saved |
Add a Covariate Column to an Existing NONMEM dataset
Description
A new covariate column can be added to an existing NONMEM dataset.
Usage
AddCox(nmData, coxData, coxCol, dateCol = "DATE", idCol = "ID")
Arguments
nmData |
an existing NONMEM dataset |
coxData |
a data table containing a covariate column |
coxCol |
the covariate column name in the coxData table |
dateCol |
date column name in the NONMEM dataset and the covariate data table |
idCol |
ID column name in the NONMEM dataset and the covariate data table |
Details
It first carry forward for the missing data. If NA is remained, it carry backward.
Value
A new NONMEM dataset containing the covariate column
Author(s)
Kyun-Seop Bae <k@acr.kr>
Add Dose Number, Time of Latest Dose, and Time after Latest Dose
Description
Adds DoNo (Dosing Occasion Number), ToLD (Time of Latest Dose), and TaLD (Time after Latest Dose) columns to a NONMEM dataset.
Usage
AddDoNoTaLD(
NMData,
ID = "ID",
TIME = "TIME",
AMT = "AMT",
II = "II",
ADDL = "ADDL",
MDV = "MDV"
)
Arguments
NMData |
data.frame of NONMEM dataset |
ID |
character, column name for subject ID |
TIME |
character, column name for time |
AMT |
character, column name for dose amount |
II |
character, column name for interdose interval |
ADDL |
character, column name for additional doses |
MDV |
character, column name for missing dependent variable flag |
Value
data.frame with DoNo, ToLD, TaLD columns added
Add a New Page to PDF
Description
Creates a new page in the PDF output with optional headers and footers.
Usage
AddPage(
Cex = 0.8,
Header1 = "",
Header2 = "",
Header3 = "",
Footer1 = "",
Footer2 = "",
Footer3 = "",
PrintRowNum = FALSE,
StartRowNum = 1
)
Arguments
Cex |
numeric, character expansion factor (0.8 or 0.6) |
Header1 |
character, left header |
Header2 |
character, center header |
Header3 |
character, right header |
Footer1 |
character, left footer |
Footer2 |
character, center footer |
Footer3 |
character, right footer |
PrintRowNum |
logical, whether to print row numbers |
StartRowNum |
integer, starting row number |
Check if All Values are NA
Description
Check if All Values are NA
Usage
AllNA(Column)
Arguments
Column |
vector |
Value
logical
Check if All Values are the Same
Description
Check if All Values are the Same
Usage
AllSame(Column)
Arguments
Column |
vector |
Value
logical
Extract Lines Between XML Tags
Description
Extract Lines Between XML Tags
Usage
BtwTagLines(Tag1, Tag2, RawRead)
Arguments
Tag1 |
opening tag |
Tag2 |
closing tag |
RawRead |
character vector of lines |
Value
character vector of lines between tags
Extract Matrix from NONMEM XML Output
Description
Parses NONMEM XML output to extract omega or sigma matrices.
Usage
BtwTagMat(Tag, RawRead, nRow)
Arguments
Tag |
character, the tag name (e.g., "omega", "sigma") |
RawRead |
character vector of XML lines |
nRow |
integer, dimension of the matrix |
Value
numeric matrix
Extract Value Between XML Tags
Description
Extract Value Between XML Tags
Usage
BtwTagVal(Tag1, Tag2, RawRead)
Arguments
Tag1 |
opening tag |
Tag2 |
closing tag |
RawRead |
character vector of lines |
Value
character, the value between tags
Extract Vector of Values Between XML Tags
Description
Parses NONMEM XML output to extract theta, omega, or sigma vectors.
Usage
BtwTagVals(Tag, RawRead)
Arguments
Tag |
character, the tag name (e.g., "nm:theta") |
RawRead |
character vector of XML lines |
Value
numeric vector of values
Calculate TaLD (Time after Latest Dose) for Report Generation
Description
Calculates dosing occasion information for each record in NONMEM data.
Handles ADDL/II dose expansion when those columns are present.
This is a shared helper used by report_pred.R and report_resid.R
to avoid code duplication.
Usage
CalcTaLDForReport(FDATA, nRec)
Arguments
FDATA |
data.frame of NONMEM data. Must contain ID, TIME, AMT, MDV columns. Optionally ADDL and II columns for expanded dosing. |
nRec |
integer, number of records in FDATA |
Value
list with components:
- ToLD
numeric vector, time of latest dose for each record
- TaLD
numeric vector, time after latest dose for each record
- DOCC
numeric vector, dosing occasion count for each record
- NewID
numeric vector, ID with fractional dosing occasion (ID + DOCC/100)
Close PDF Output
Description
Closes the current PDF device.
Usage
ClosePDF()
Combine the demographics(DM), dosing(EX), and DV(PC) tables into a new NONMEM dataset
Description
A new NONMEM dataset can be created from the demographics, dosing, and DV tables.
Usage
CombDmExPc(dm, ex, pc)
Arguments
dm |
A demographics table. It should contain a row per subject. |
ex |
An exposure table. Drug administration (dosing) history table. |
pc |
A DV(dependent variable) or PC(drug concentration) table |
Details
Combining a demographics, a dosing, and a concentration table can produce a new NONMEM dataset.
Value
A new NONMEM dataset
Author(s)
Kyun-Seop Bae <k@acr.kr>
Connect Two Points with Lines
Description
Draws connecting lines between parent and child nodes in flow diagram.
Usage
ConnPoint(pt1, pt2)
Arguments
pt1 |
numeric vector of length 2, first point (x, y) |
pt2 |
numeric vector of length 2, second point (x, y) |
Count THETA, ETA, EPS Parameters from EXT Data Frame
Description
Counts the number of THETA, OMEGA, and SIGMA parameters from
column names of a NONMEM .ext file data frame. Derives the number
of ETAs and EPSILONs from the lower-triangular element count
using the formula n = (sqrt(1 + 8k) - 1) / 2.
Usage
CountEXTParams(EXT)
Arguments
EXT |
data.frame from .ext file (already read and filtered) |
Details
This function replaces duplicated parameter counting loops that
were previously repeated in report_ebe.R, report_ofv.R,
and report_param.R.
Value
list with components:
- nTheta
integer, number of THETA columns
- nEta
integer, number of ETAs (derived from OMEGA elements)
- nEps
integer, number of EPSILONs (derived from SIGMA elements)
Covariance Step
Description
It calculates standard errors and various variance matrices with the e$FinalPara after estimation step.
Usage
CovStep()
Details
Because EstStep uses nonlinear optimization, covariance step is separated from estimation step.
It calculates variance-covariance matrix of estimates in the original scale.
Value
Time |
consumed time |
Standard Error |
standard error of the estimates in the order of theta, omega, and sigma |
Covariance Matrix of Estimates |
covariance matrix of estimates in the order of theta, omega, and sigma. This is inverse(R) x S x inverse(R) by default. |
Correlation Matrix of Estimates |
correlation matrix of estimates in the order of theta, omega, and sigma |
Inverse Covariance Matrix of Estimates |
inverse covariance matrix of estimates in the order of theta, omega, and sigma |
Eigen Values |
eigen values of covariance matrix |
R Matrix |
R matrix of NONMEM, the second derivative of log likelihood function with respect to estimation parameters |
S Matrix |
S matrix of NONMEM, sum of individual cross-product of the first derivative of log likelihood function with respect to estimation parameters |
Author(s)
Kyun-Seop Bae <k@acr.kr>
References
NONMEM Users Guide
See Also
Examples
# Only after InitStep and EstStep
#CovStep()
Diagnostic Plot for Post-Processing
Description
Creates spaghetti-style diagnostic plots with individual ID labels.
Usage
DxPlotPost(x, y, mat, xlbl, ylbl, smooth, xlm = "", ylm = "", Log = "")
Arguments
x |
numeric vector, x-axis values |
y |
numeric vector, y-axis values |
mat |
data.frame with an ID column |
xlbl |
character, x-axis label |
ylbl |
character, y-axis label |
smooth |
character, "T" for lowess smoothing, "F" for identity line |
xlm |
numeric vector of length 2, x-axis limits |
ylm |
numeric vector of length 2, y-axis limits |
Log |
character, log transformation for axes (e.g., "y") |
EBE Pair Plot
Description
Creates pairs plot of ETAs vs covariates with histograms and correlations.
Usage
EBEpair(tabEta, RunNumber, each = FALSE)
Arguments
tabEta |
data.frame with ID, covariates, and ETA columns |
RunNumber |
character, model/run identifier |
each |
logical, if TRUE creates separate plots per covariate |
Estimation Step
Description
This estimates upon the conditions with InitStep.
Usage
EstStep()
Details
It does not have arguments.
All necessary arguments are stored in the e environment.
It assumes "INTERACTION" between eta and epsilon for "COND" and "LAPL" options.
The output is basically same to NONMEM output.
Value
Initial OFV |
initial value of the objective function |
Time |
time consumed for this step |
Optim |
the raw output from |
Final Estimates |
final estimates in the original scale |
Author(s)
Kyun-Seop Bae <k@acr.kr>
References
NONMEM Users Guide
See Also
Examples
# Only After InitStep
#EstStep()
Expand Dose History with ADDL/II Records
Description
Expands compressed dosing records (ADDL/II) into individual dose records.
Usage
ExpandDoseHist(DoseHistTab)
Arguments
DoseHistTab |
data.frame with columns TIME, AMT, II, ADDL |
Value
data.frame with expanded dose records
Check for Tag in File
Description
Check for Tag in File
Usage
FileTag(FileName, Tag)
Arguments
FileName |
character, filename |
Tag |
character, text to search for |
Value
logical or NA
Test Functional Dependency
Description
Tests whether DepNameList columns are functionally dependent on DetNameList columns in a NONMEM table.
Usage
FuncDep(NMTable, DetNameList, DepNameList)
Arguments
NMTable |
data.frame |
DetNameList |
character vector of determinant column names |
DepNameList |
character vector of dependent column names |
Value
logical, TRUE if functionally dependent
Get Corrected AIC (AICc)
Description
Get Corrected AIC (AICc)
Usage
GetAICc()
Value
numeric, the corrected AIC value
Get Count of All Thetas
Description
Get Count of All Thetas
Usage
GetCountAllTheta()
Value
integer, total number of thetas
Get Count of Epsilons
Description
Get Count of Epsilons
Usage
GetCountEps()
Value
integer, number of epsilon parameters
Get Count of Etas
Description
Get Count of Etas
Usage
GetCountEta()
Value
integer, number of eta parameters
Get Count of Fixed Thetas
Description
Get Count of Fixed Thetas
Usage
GetCountFixedTheta()
Value
integer
Get Count of Observations
Description
Get Count of Observations
Usage
GetCountObs()
Value
integer, total number of observation records
Get Count of Unfixed Omega Elements
Description
Get Count of Unfixed Omega Elements
Usage
GetCountOmega()
Value
integer
Get Count of Parameters
Description
Get Count of Parameters
Usage
GetCountPara()
Value
integer, total number of estimated parameters
Get Count of Unfixed Epsilons
Description
Get Count of Unfixed Epsilons
Usage
GetCountUnfixedEps()
Value
integer
Get Count of Unfixed Thetas
Description
Get Count of Unfixed Thetas
Usage
GetCountUnfixedTheta()
Value
integer
Get Current Model Name from Working Directory
Description
Detects model name by finding the .xml file in the current directory. Falls back to extracting from folder name if no .xml file is found.
Usage
GetCurModelName()
Value
character, the model name
Get Estimation Method
Description
Identifies the estimation method from the .ext file header.
Usage
GetEstMethod()
Value
character, abbreviation of the estimation method
Get Model Names from Folder Names
Description
Extracts model names by splitting folder names on period.
Usage
GetModelNames(vName)
Arguments
vName |
character vector of folder names |
Value
character vector of model names
Get Objective Function Value
Description
Retrieves the final OFV from the .ext file in the current directory.
Usage
GetOFV()
Value
numeric, the objective function value
Get Off-Diagonal Omega Count
Description
Get Off-Diagonal Omega Count
Usage
GetOffDiagOmega()
Value
integer
Get PROBLEM Statement Value
Description
Get PROBLEM Statement Value
Usage
GetProbVal(Tag)
Arguments
Tag |
character, the tag to search for in FCON |
Value
character, the extracted value
Get Termination Reason from PRINT.OUT
Description
Get Termination Reason from PRINT.OUT
Usage
GetReason(folderName)
Arguments
folderName |
character, optional folder to set as working directory |
Value
character, termination reason code
Initialization Step
Description
It receives parameters for the estimation and stores them into e environment.
Usage
InitStep(DataAll, THETAinit, OMinit, SGinit, LB, UB, Pred, METHOD)
Arguments
DataAll |
Data for all subjects. It should contain columns which |
THETAinit |
Theta initial values |
OMinit |
Omega matrix initial values |
SGinit |
Sigma matrix initial values |
LB |
Lower bounds for theta vector |
UB |
Upper bounds for theta vector |
Pred |
Prediction function name |
METHOD |
one of the estimation methods |
Details
Prediction function should return not only prediction values(F or IPRED) but also G (first derivative with respect to etas) and H (first derivative of Y with respect to epsilon).
For the "LAPL", prediction function should return second derivative with respect to eta also.
"INTERACTION" is TRUE for "COND" and "LAPL" option, and FALSE for "ZERO".
Omega matrix should be full block one.
Sigma matrix should be diagonal one.
Value
This does not return values, but stores necessary values into the environment e.
Author(s)
Kyun-Seop Bae <k@acr.kr>
References
NONMEM Users Guide
Examples
DataAll = Theoph
colnames(DataAll) = c("ID", "BWT", "DOSE", "TIME", "DV")
DataAll[,"ID"] = as.numeric(as.character(DataAll[,"ID"]))
nTheta = 3
nEta = 3
nEps = 2
THETAinit = c(2, 50, 0.1) # Initial estimate
OMinit = matrix(c(0.2, 0.1, 0.1, 0.1, 0.2, 0.1, 0.1, 0.1, 0.2), nrow=nEta, ncol=nEta)
OMinit
SGinit = diag(c(0.1, 0.1))
SGinit
LB = rep(0, nTheta) # Lower bound
UB = rep(1000000, nTheta) # Upper bound
FGD = deriv(~DOSE/(TH2*exp(ETA2))*TH1*exp(ETA1)/(TH1*exp(ETA1) - TH3*exp(ETA3))*
(exp(-TH3*exp(ETA3)*TIME)-exp(-TH1*exp(ETA1)*TIME)),
c("ETA1","ETA2","ETA3"),
function.arg=c("TH1", "TH2", "TH3", "ETA1", "ETA2", "ETA3", "DOSE", "TIME"),
func=TRUE, hessian=TRUE)
H = deriv(~F + F*EPS1 + EPS2, c("EPS1", "EPS2"), function.arg=c("F", "EPS1", "EPS2"), func=TRUE)
PRED = function(THETA, ETA, DATAi)
{
FGDres = FGD(THETA[1], THETA[2], THETA[3], ETA[1], ETA[2], ETA[3], DOSE=320, DATAi[,"TIME"])
Gres = attr(FGDres, "gradient")
Hres = attr(H(FGDres, 0, 0), "gradient")
if (e$METHOD == "LAPL") {
Dres = attr(FGDres, "hessian")
Res = cbind(FGDres, Gres, Hres, Dres[,1,1], Dres[,2,1], Dres[,2,2], Dres[,3,])
colnames(Res) = c("F", "G1", "G2", "G3", "H1", "H2", "D11", "D21", "D22", "D31", "D32", "D33")
} else {
Res = cbind(FGDres, Gres, Hres)
colnames(Res) = c("F", "G1", "G2", "G3", "H1", "H2")
}
return(Res)
}
######### First Order Approximation Method
InitStep(DataAll, THETAinit=THETAinit, OMinit=OMinit, SGinit=SGinit, LB=LB, UB=UB,
Pred=PRED, METHOD="ZERO")
######### First Order Conditional Estimation with Interaction Method
InitStep(DataAll, THETAinit=THETAinit, OMinit=OMinit, SGinit=SGinit, LB=LB, UB=UB,
Pred=PRED, METHOD="COND")
######### Laplacian Approximation with Interaction Method
InitStep(DataAll, THETAinit=THETAinit, OMinit=OMinit, SGinit=SGinit, LB=LB, UB=UB,
Pred=PRED, METHOD="LAPL")
Integer Variable Statistics
Description
Prints unique values for all integer variables.
Usage
IntStat(NMTable, VarStat)
Arguments
NMTable |
data.frame |
VarStat |
matrix from NMVarStat |
Check if Model Uses Log-Transformed DV (from Control File)
Description
Check if Model Uses Log-Transformed DV (from Control File)
Usage
LogDV(CtlFileName)
Arguments
CtlFileName |
character, path to NONMEM control file |
Value
logical, TRUE if LOG(F) is found after $PRED or $ERROR
Check if Model Uses Log-Transformed DV (from FSUBS)
Description
Check if Model Uses Log-Transformed DV (from FSUBS)
Usage
LogDV2()
Value
logical, TRUE if LOG(F) is found after SUBROUTINE PRED or ERROR in FSUBS
Match End of String
Description
Match End of String
Usage
MatchEnd(vName0, End0, IgnoreCase = TRUE)
Arguments
vName0 |
character vector of names |
End0 |
character string to match at end |
IgnoreCase |
logical, whether to ignore case |
Value
logical vector
Merge IDStat with Individual OFV from PHI
Description
Computes variable and individual statistics from NONMEM data,
then merges individual OFV values from the PHI file. This is a
common pattern used in report_ofv.R and report_resid.R.
Usage
MergeIDStatOFV(FDATA, PHI)
Arguments
FDATA |
data.frame of NONMEM data (from |
PHI |
data.frame from the .phi file, must contain ID and OBJ columns |
Value
list with components:
- IDStat3
data.frame, merged individual statistics with OFV
- VarStat
matrix, variable statistics from
NMVarStat()- IDStat
list, individual statistics from
NMIDStat()
Check Minimization Success
Description
Check Minimization Success
Usage
MinSuccess()
Value
logical, TRUE if minimization was successful
Internal Min Util Functions
Description
Internal Min Util functions
Details
These are not to be called by the user.
NONMEM Individual (ID) Statistics
Description
Computes per-subject statistics including record counts, DV counts, dosing information, and sorting checks.
Usage
NMIDStat(NMTable)
Arguments
NMTable |
data.frame of NONMEM data |
Value
list with IDStat data.frame, sortedID logical, sortedDT logical
NONMEM Variable Statistics
Description
Computes statistics for each variable in a NONMEM dataset including counts of NA, zero, positive values, unique values, and functional dependency checks.
Usage
NMVarStat(NMTable)
Arguments
NMTable |
data.frame of NONMEM data |
Value
matrix with variable statistics
Post-Hoc OFV and CWRES Calculation
Description
Calculates individual OFV and CWRES using METHOD=COND or METHOD=ZERO.
Usage
OBJfpost(ctlname, sdtab)
Arguments
ctlname |
character, control file name (without extension) |
sdtab |
data.frame, standard output table |
Value
list with OFV, OFVi, CWRES
OFV Report Split Screen Layout
Description
Layout matrix for the S1-OFV report's split screen display.
Used with split.screen() to create overlapping panels
on the first page of the OFV diagnostic report.
Format
A 4x4 numeric matrix. Each row defines a screen region
as c(left, right, bottom, top) in normalized device coordinates:
- Row 1
Full page (0, 1, 0, 1) for text content
- Row 2
Top-right inset (0.55, 0.97, 0.6, 0.95) for scatter plot
- Row 3
Middle-right inset (0.55, 0.97, 0.45, 0.8) for histogram
- Row 4
Bottom-right inset (0.55, 0.97, 0.1, 0.45) for QQ plot
Internal Obj Functions
Description
Internal Obj functions
Details
These are not to be called by the user.
Draw Model Development Flow Diagram
Description
Creates a graphical model development flow diagram from SumOut results.
Usage
Outline(MDL, MDLName, out.start = "0", out.end = "zzzzzzzz", Target = "PDF")
Arguments
MDL |
data.frame from SumOut |
MDLName |
character, model development name for title |
out.start |
character, filter start |
out.end |
character, filter end |
Target |
character, "PDF" or other |
Character Panel for Pairs Plot
Description
Character Panel for Pairs Plot
Usage
PanelChar(x, y)
Arguments
x |
numeric vector |
y |
numeric vector |
Correlation Panel for Pairs Plot
Description
Correlation Panel for Pairs Plot
Usage
PanelCor(x, y, digits = 2, prefix = "", cex.cor)
Arguments
x |
numeric vector |
y |
numeric vector |
digits |
integer, number of digits for correlation |
prefix |
character, prefix for text |
cex.cor |
numeric, character expansion for correlation |
Histogram Panel for Pairs Plot
Description
Histogram Panel for Pairs Plot
Usage
PanelHist(x, ...)
Arguments
x |
numeric vector |
... |
additional arguments |
Parse Data Item Names from NONMEM Output
Description
Parse Data Item Names from NONMEM Output
Usage
ParseItemName(RawRead)
Arguments
RawRead |
character vector of lines from NONMEM output |
Value
character vector of item names
Parse Fixed-Width Format Item Widths from NONMEM Output
Description
Parse Fixed-Width Format Item Widths from NONMEM Output
Usage
ParseItemWidth(RawRead)
Arguments
RawRead |
character vector of lines from NONMEM output |
Value
list with LineCount and Widths
Parse Value After Tag from NONMEM Output
Description
Extracts the value following a tag string (after the colon) in NONMEM output lines.
Usage
ParseOut(TagString, RawRead)
Arguments
TagString |
character, the tag to search for |
RawRead |
character vector of lines from NONMEM output |
Value
character, the value after the tag
Plot Distribution Panel (Summary + Histogram + QQ)
Description
Generates a 3-panel distribution diagnostic plot consisting of:
Summary statistics text (min, Q1, median, mean, Q3, max, SD)
Histogram with kernel density overlay and Shapiro-Wilk test
Normal Q-Q plot
This is a common pattern shared across report_ebe.R,
report_indipk.R, and report_resid.R.
Usage
PlotDistribution(
var.data,
var.name,
show_shrinkage = FALSE,
omega_var = NULL,
show_ttest = FALSE,
show_cv = FALSE
)
Arguments
var.data |
numeric vector of data to plot |
var.name |
character, variable name used for axis labels and title |
show_shrinkage |
logical, whether to display shrinkage annotation
(requires |
omega_var |
numeric, omega variance value for shrinkage calculation.
Only used when |
show_ttest |
logical, whether to display the t-test p-value in the summary panel |
show_cv |
logical, whether to display the coefficient of variation (CV percent) in the summary panel |
Details
The function expects that the graphics device is already open and
par() has been set for a multi-panel layout (e.g., mfrow).
Each call to this function fills 3 panels (one row of a typical layout).
The Shapiro-Wilk test is only performed when the data has positive standard deviation and fewer than 5000 observations.
Prepare PDF Output
Description
Opens a PDF device for NONMEM report generation.
Usage
PrepPDF(FileName, Paper = "letter", FontFamily = "Courier")
Arguments
FileName |
character, output PDF filename |
Paper |
character, paper size (default "letter") |
FontFamily |
character, font family (default "Courier") |
Print Multiple Lines of Text
Description
Prints a character vector of text lines across multiple pages as needed.
Usage
PrinMTxt(
MTxt,
Cex = 0.8,
Header1 = "",
Header2 = "",
Header3 = "",
Footer1 = "",
Footer2 = "",
Footer3 = "",
PrintRowNum = FALSE
)
Arguments
MTxt |
character vector of text lines |
Cex |
numeric, character expansion factor |
Header1 |
character, left header |
Header2 |
character, center header |
Header3 |
character, right header |
Footer1 |
character, left footer |
Footer2 |
character, center footer |
Footer3 |
character, right footer |
PrintRowNum |
logical, whether to print row numbers |
Print Text at Position
Description
Prints text at a specific row and column position on the PDF page.
Usage
PrinTxt(Row, Col, Text, Cex = 0.8)
Arguments
Row |
numeric, row position |
Col |
numeric, column position |
Text |
character, text to print |
Cex |
numeric, character expansion factor |
Read EXT File from Current Directory
Description
Reads the NONMEM .ext file corresponding to the current model
(detected by GetCurModelName()). This is a shared helper
used by GetCountAllTheta(), GetCountEps(),
GetCountOmega(), and GetCountUnfixedEps() to avoid
repeated file-reading logic.
Usage
ReadEXTFile()
Value
data.frame of the .ext file contents, or NULL if the file
is not found in the current directory.
Read FDATA.CSV with Auto-Detection of Header Format
Description
Reads FDATA.CSV, auto-detecting whether it has a NONMEM-style 2-row header (skip=2) or a standard 1-row header (skip=0).
Usage
ReadFDATA(file = "FDATA.CSV")
Arguments
file |
character, path to the CSV file (default: "FDATA.CSV") |
Value
data.frame
Remove Rows with NA Values
Description
Remove Rows with NA Values
Usage
RemoveNA(RawData)
Arguments
RawData |
data.frame |
Value
data.frame with rows containing NA removed
Rename Columns
Description
Rename Columns
Usage
RenCol(ColList, OldCol, NewCol)
Arguments
ColList |
character vector of column names |
OldCol |
old column name |
NewCol |
new column name |
Value
character vector with renamed columns
Residual Count Test Using Binomial Distribution
Description
Tests whether residual counts at various Z-value thresholds follow expected binomial distributions.
Usage
ResTest(
ResTab,
TestCols = c("WRES", "CWRE", "IWRE"),
ZVals = c(0, 1, 2, 3),
PctVals = c(0.005, 0.01, 0.025, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5)
)
Arguments
ResTab |
data.frame with residual columns |
TestCols |
character vector of column names to test |
ZVals |
numeric vector of Z-value thresholds |
PctVals |
numeric vector of percentile values |
Value
matrix of test results
Remove Columns from Table
Description
Remove Columns from Table
Usage
RmvCol(Tab, OldCols)
Arguments
Tab |
data.frame |
OldCols |
character vector of column names to remove |
Value
data.frame with specified columns removed
Remove Fixed (Non-Varying) Columns
Description
Removes columns where all values are the same across rows.
Usage
RmvFixed(Table)
Arguments
Table |
data.frame or matrix |
Value
data.frame with fixed columns removed
Remove Zero Rows/Cols from Symmetric Matrix
Description
Remove Zero Rows/Cols from Symmetric Matrix
Usage
RmvZero(SymmMat)
Arguments
SymmMat |
symmetric matrix |
Value
matrix with zero rows/columns removed
Check Standard Error Success
Description
Check Standard Error Success
Usage
SESuccess()
Value
logical, TRUE if standard errors were computed successfully
Summarize Multiple NONMEM Runs
Description
Scans subdirectories matching RunExt and collects summary metrics for model development flow analysis.
Usage
SumOut(FileExt = ".CTL", RunExt = ".R75", OutExt = ".OUT")
Arguments
FileExt |
character, control file extension |
RunExt |
character, run folder extension |
OutExt |
character, output file extension |
Value
data.frame with summary of all runs
Summarize Single NONMEM Run
Description
Collects key metrics from a single NONMEM run folder.
Usage
SumOut1(ModelName)
Arguments
ModelName |
character, model name |
Value
data.frame with one row of summary metrics
Table Step
Description
This produces standard table.
Usage
TabStep()
Details
It does not have arguments.
All necessary arguments are stored in the e environment.
This is similar to other standard results table.
Value
A table with ID, TIME, DV, PRED, RES, WRES, derivatives of G and H. If the estimation method is other than 'ZERO'(First-order approximation), it includes CWRES, CIPREDI(formerly IPRED), CIRESI(formerly IRES).
Author(s)
Kyun-Seop Bae <k@acr.kr>
References
NONMEM Users Guide
See Also
Examples
# Only After EstStep
#TabStep()
Trimming and beautifying NONMEM original OUTPUT file
Description
TrimOut removes unnecessary parts from NONMEM original OUTPUT file.
Usage
TrimOut(inFile, outFile="PRINT.OUT")
Arguments
inFile |
NONMEM original untidy OUTPUT file name |
outFile |
Output file name to be written |
Details
NONMEM original OUTPUT file contains unnecessary parts such as CONTROL file content, Start/End Time, License Info, Print control characters such as "+", "0", "1". This function trims those.
Value
outFile will be written in the current working folder or designated folder. This returns TRUE if the process was smooth.
Author(s)
Kyun-Seop Bae <k@acr.kr>
environment for internal data
Description
This is for the storage of intermediate data.
Multiple Linear Regression with Influence Diagnostics
Description
Performs multiple linear regression and computes influence diagnostics including DFFITS, DFBETAS, Cook's Distance, COVRATIO, and R-Student.
Usage
mlr2(y, x.raw, standardize = 0)
Arguments
y |
numeric vector of response |
x.raw |
data.frame of predictors |
standardize |
integer, standardization method (0=none, 1=center, 2=scale by mean, 3=z-score) |
Value
list with model estimates and influence diagnostics
Generate EBE Diagnostics Report (S5-EBE.PDF)
Description
Generates a PDF report with empirical Bayes estimate (EBE) analysis including ETA distributions, shrinkage, covariate relationships, correlations, and multiple linear regression with influence diagnostics.
Usage
nmw_report_ebe(run_dir = getwd())
Arguments
run_dir |
character, path to the NONMEM run directory (default: current directory) |
Generate Individual PK Parameter Report (SC-IndiPK.PDF)
Description
Generates a PDF report with individual PK parameter distributions including summary statistics, histograms, and QQ plots.
Usage
nmw_report_indipk(run_dir = getwd())
Arguments
run_dir |
character, path to the NONMEM run directory (default: current directory) |
Generate Input Data Summary Report (SA-Input.PDF)
Description
Generates a PDF report with input data validation including individuals with no dosing/DV, duplicate records, and summary statistics.
Usage
nmw_report_input(run_dir = getwd())
Arguments
run_dir |
character, path to the NONMEM run directory (default: current directory) |
Generate OFV Diagnostic Report (S1-OFV.PDF)
Description
Generates a PDF report with objective function value diagnostics including total OFV, AICc, BIC, individual OFV per DV summary, and gradient analysis.
Usage
nmw_report_ofv(run_dir = getwd())
Arguments
run_dir |
character, path to the NONMEM run directory (default: current directory) |
Generate NONMEM Output Report (SB-Output.PDF)
Description
Includes the NONMEM PRINT.OUT file content in a PDF report.
Usage
nmw_report_output(run_dir = getwd())
Arguments
run_dir |
character, path to the NONMEM run directory (default: current directory) |
Generate Parameter Estimates Report (S2-Parameters.PDF)
Description
Generates a PDF report with theta, omega, and sigma parameter estimates, standard errors, confidence intervals, and significance flags.
Usage
nmw_report_param(run_dir = getwd())
Arguments
run_dir |
character, path to the NONMEM run directory (default: current directory) |
Generate Prediction Diagnostics Report (S3-Predictions.PDF)
Description
Generates a PDF report with spaghetti plots, DV vs PRED/IPRE, and individual fitting curves.
Usage
nmw_report_pred(run_dir = getwd())
Arguments
run_dir |
character, path to the NONMEM run directory (default: current directory) |
Generate Residual Diagnostics Report (S4-Residuals.PDF)
Description
Generates a PDF report with WRES, CWRES, IWRES diagnostics including scatter plots, histograms, normality tests, binomial count tests, and individual residual curves with run tests.
Usage
nmw_report_resid(run_dir = getwd())
Arguments
run_dir |
character, path to the NONMEM run directory (default: current directory) |
Run All NONMEM Post-Processing Reports
Description
Generates all diagnostic PDF reports for a NONMEM run in sequence: S1-OFV, S2-Parameters, S3-Predictions, S4-Residuals, S5-EBE, SA-Input, SB-Output, SC-IndiPK.
Usage
nmw_run(
run_dir = getwd(),
reports = c("ofv", "param", "pred", "resid", "ebe", "input", "output", "indipk")
)
Arguments
run_dir |
character, path to the NONMEM run directory (default: current directory) |
reports |
character vector, which reports to generate. Options: "ofv", "param", "pred", "resid", "ebe", "input", "output", "indipk". Default is all reports. |
Examples
## Not run:
# Generate all reports
nmw_run("/path/to/nonmem/run/directory")
# Generate only OFV and parameter reports
nmw_run("/path/to/run", reports = c("ofv", "param"))
## End(Not run)
Run Test Probability
Description
Calculates P(Run count <= r | m, n) for the runs test.
Usage
run.p(m, n, r)
Arguments
m |
count of fewer species (minimum value = 0) |
n |
count of more frequent species (minimum value = 1) |
r |
count of runs (minimum value = 1) |
Value
numeric, probability
Runs Test for NONMEM Residuals
Description
Performs a runs test on residuals. Zeros are omitted.
Usage
run.test.nm(RES)
Arguments
RES |
numeric vector of residuals |
Value
numeric, two-sided p-value