| 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. |
| Authors: | Kyun-Seop Bae [aut, cre] |
| Maintainer: | Kyun-Seop Bae <[email protected]> |
| License: | GPL-3 |
| Version: | 0.3.0 |
| Built: | 2026-05-08 07:27:58 UTC |
| Source: | https://github.com/cran/nmw |
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.
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.
Kyun-Seop Bae <[email protected]>
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.
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()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()
Add a CRCL column to a NM-style data.frame using Cockcroft-Gault. Column names are configurable.
add_crcl_cg( df, age_col = "AGE", bwt_col = "BWT", sex_col = "SEX", crea_col = "CREA", out_col = "CRCL" )add_crcl_cg( df, age_col = "AGE", bwt_col = "BWT", sex_col = "SEX", crea_col = "CREA", out_col = "CRCL" )
df |
data.frame containing AGE, BWT, SEX, CREA columns. |
age_col |
name of the age column (years). Default "AGE". |
bwt_col |
name of the body-weight column (kg). Default "BWT". |
sex_col |
name of the sex column (0=M, 1=F). Default "SEX". |
crea_col |
name of the creatinine column (mg/dL). Default "CREA". |
out_col |
name of the output column. Default "CRCL". |
data.frame with the CRCL column added.
A new covariate column can be added to an existing NONMEM dataset.
AddCox(nmData, coxData, coxCol, dateCol = "DATE", idCol = "ID")AddCox(nmData, coxData, coxCol, dateCol = "DATE", idCol = "ID")
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 |
It first carry forward for the missing data. If NA is remained, it carry backward.
A new NONMEM dataset containing the covariate column
Kyun-Seop Bae <[email protected]>
Adds DoNo (Dosing Occasion Number), ToLD (Time of Latest Dose), and TaLD (Time after Latest Dose) columns to a NONMEM dataset.
AddDoNoTaLD( NMData, ID = "ID", TIME = "TIME", AMT = "AMT", II = "II", ADDL = "ADDL", MDV = "MDV" )AddDoNoTaLD( NMData, ID = "ID", TIME = "TIME", AMT = "AMT", II = "II", ADDL = "ADDL", MDV = "MDV" )
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 |
data.frame with DoNo, ToLD, TaLD columns added
Creates a new page in the PDF output with optional headers and footers.
AddPage( Cex = 0.8, Header1 = "", Header2 = "", Header3 = "", Footer1 = "", Footer2 = "", Footer3 = "", PrintRowNum = FALSE, StartRowNum = 1 )AddPage( Cex = 0.8, Header1 = "", Header2 = "", Header3 = "", Footer1 = "", Footer2 = "", Footer3 = "", PrintRowNum = FALSE, StartRowNum = 1 )
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 |
Parses NONMEM XML output to extract omega or sigma matrices.
BtwTagMat(Tag, RawRead, nRow)BtwTagMat(Tag, RawRead, nRow)
Tag |
character, the tag name (e.g., "omega", "sigma") |
RawRead |
character vector of XML lines |
nRow |
integer, dimension of the matrix |
numeric matrix
Parses NONMEM XML output to extract theta, omega, or sigma vectors.
BtwTagVals(Tag, RawRead)BtwTagVals(Tag, RawRead)
Tag |
character, the tag name (e.g., "nm:theta") |
RawRead |
character vector of XML lines |
numeric vector of values
Build NONMEM dose records from an EX-like data.frame.
EX must contain: SUBJID, DAT2, TIME, AMT, RATE.
Optional: CMT (defaults to dose_cmt).
Output rows have MDV = 1, DV = 0.
build_dose_records(EX, dose_cmt = 1L)build_dose_records(EX, dose_cmt = 1L)
EX |
data.frame with dose information. |
dose_cmt |
default compartment for dose records lacking a CMT column. |
data.frame of dose records with columns SUBJID, DAT2, TIME, AMT, RATE, CMT, DV, MDV.
Build a NONMEM-format dataset from cleaned DM/EX/PC tables.
Time-varying covariates (VS, LB, ...) are NOT merged here. Use
merge_cov_locf afterwards to add them. CRCL is added
separately via add_crcl_cg. Molar conversion is done with
nm_to_molar.
build_nm_dataset( DM, EX, PC, IDs = NULL, id_prefix = "", id_func = NULL, dose_cmt = 1L, verbose = FALSE )build_nm_dataset( DM, EX, PC, IDs = NULL, id_prefix = "", id_func = NULL, dose_cmt = 1L, verbose = FALSE )
DM |
data.frame with one row per subject. Must contain SUBJID; any other columns are merged in as subject-level constants. |
EX |
dose records (see |
PC |
observation records (see |
IDs |
character vector of SUBJIDs to keep. NULL (default) is the intersect of EX and PC where DV > 0. |
id_prefix |
character. When |
id_func |
function(SUBJID) -> character ID. Overrides |
dose_cmt |
default compartment for dose records lacking a CMT column. |
verbose |
print progress. Default FALSE. |
Records are sorted by SUBJID, DAT2, TIME, CMT, MDV, AMT. At tied (SUBJID, DAT2, TIME, CMT, MDV), AMT = 0 (observation) sorts before AMT > 0 (dose) so a pre-dose observation precedes the dose given at the same minute.
data.frame with columns ID, SUBJID, DAT2, TIME, AMT, RATE, CMT, DV, MDV, <DM-columns ...>.
Build NONMEM observation records from a PC-like data.frame. PC must contain: SUBJID, DAT2, TIME, DV, CMT. Output rows have AMT = 0, RATE = 0; DV that is NA or 0 -> MDV = 1.
build_obs_records(PC)build_obs_records(PC)
PC |
data.frame with observation information. |
data.frame of observation records with columns SUBJID, DAT2, TIME, AMT, RATE, CMT, DV, MDV.
Code RACE as integer: ASIAN -> 1, WHITE -> 2, BLACK -> 3, otherwise -> 4. Numeric input is returned unchanged (cast to integer).
code_race(x)code_race(x)
x |
character or numeric vector of race values. |
integer vector.
Code SEX as integer: M -> 0, F -> 1, otherwise -> 2. Numeric input is returned unchanged (cast to integer).
code_sex(x)code_sex(x)
x |
character or numeric vector of sex values. |
integer vector.
A new NONMEM dataset can be created from the demographics, dosing, and DV tables.
CombDmExPc(dm, ex, pc)CombDmExPc(dm, ex, pc)
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 |
Combining a demographics, a dosing, and a concentration table can produce a new NONMEM dataset.
A new NONMEM dataset
Kyun-Seop Bae <[email protected]>
It calculates standard errors and various variance matrices with the e$FinalPara after estimation step.
CovStep()CovStep()
Because EstStep uses nonlinear optimization, covariance step is separated from estimation step.
It calculates variance-covariance matrix of estimates in the original scale.
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 |
Kyun-Seop Bae <[email protected]>
NONMEM Users Guide
# Only after InitStep and EstStep #CovStep()# Only after InitStep and EstStep #CovStep()
Cockcroft-Gault creatinine clearance (mL/min).
crcl_cg(age, bwt, sex, crea)crcl_cg(age, bwt, sex, crea)
age |
numeric, age in years. |
bwt |
numeric, body weight in kg. |
sex |
integer/numeric, 0 = male, 1 = female. |
crea |
numeric, serum creatinine in mg/dL. |
numeric vector of CRCL in mL/min.
Combine "YYYY-MM-DD" and "HH:MM" character vectors into POSIXct.
dat2_time_to_posix(dat2, time, tz = "UTC")dat2_time_to_posix(dat2, time, tz = "UTC")
dat2 |
character vector of dates in "YYYY-MM-DD" format. |
time |
character vector of times in "HH:MM" format. |
tz |
time zone. Default "UTC". |
POSIXct vector.
Creates spaghetti-style diagnostic plots with individual ID labels.
DxPlotPost(x, y, mat, xlbl, ylbl, smooth, xlm = "", ylm = "", Log = "")DxPlotPost(x, y, mat, xlbl, ylbl, smooth, xlm = "", ylm = "", Log = "")
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") |
Creates pairs plot of ETAs vs covariates with histograms and correlations.
EBEpair(tabEta, RunNumber, each = FALSE)EBEpair(tabEta, RunNumber, each = FALSE)
tabEta |
data.frame with ID, covariates, and ETA columns |
RunNumber |
character, model/run identifier |
each |
logical, if TRUE creates separate plots per covariate |
This estimates upon the conditions with InitStep.
EstStep()EstStep()
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.
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 |
Kyun-Seop Bae <[email protected]>
NONMEM Users Guide
# Only After InitStep #EstStep()# Only After InitStep #EstStep()
Expands compressed dosing records (ADDL/II) into individual dose records.
ExpandDoseHist(DoseHistTab)ExpandDoseHist(DoseHistTab)
DoseHistTab |
data.frame with columns TIME, AMT, II, ADDL |
data.frame with expanded dose records
Get Corrected AIC (AICc)
GetAICc()GetAICc()
numeric, the corrected AIC value
Get Count of Epsilons
GetCountEps()GetCountEps()
integer, number of epsilon parameters, or NA if file not found
Get Count of Etas
GetCountEta()GetCountEta()
integer, number of eta parameters, or NA if file not found
Get Count of Observations
GetCountObs()GetCountObs()
integer, total number of observation records
Get Count of Parameters
GetCountPara()GetCountPara()
integer, total number of estimated parameters, or NA if file not found
Identifies the estimation method from the .ext file header.
GetEstMethod()GetEstMethod()
character, abbreviation of the estimation method
Retrieves the final OFV from the .ext file in the current directory.
GetOFV()GetOFV()
numeric, the objective function value
It receives parameters for the estimation and stores them into e environment.
InitStep(DataAll, THETAinit, OMinit, SGinit, LB, UB, Pred, METHOD)InitStep(DataAll, THETAinit, OMinit, SGinit, LB, UB, Pred, METHOD)
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 |
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.
This does not return values, but stores necessary values into the environment e.
Kyun-Seop Bae <[email protected]>
NONMEM Users Guide
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")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")
For each target time, return the most-recent source value at
source_t <= target_t (LOCF). If no preceding source exists, return the
earliest source_v at source_t > target_t (LOCB). Empty source returns
fallback for all targets.
locf_value(target_t, source_t, source_v, fallback = NA_real_)locf_value(target_t, source_t, source_v, fallback = NA_real_)
target_t |
vector of target times (numeric or POSIXct). |
source_t |
vector of source times (same type as target_t). |
source_v |
numeric vector of source values, parallel to source_t. |
fallback |
value used when no source is available. Default NA. |
numeric vector, length(target_t).
Check if Model Uses Log-Transformed DV (from Control File)
LogDV(CtlFileName)LogDV(CtlFileName)
CtlFileName |
character, path to NONMEM control file |
logical, TRUE if LOG(F) is found after $PRED or $ERROR
Check if Model Uses Log-Transformed DV (from FSUBS)
LogDV2()LogDV2()
logical, TRUE if LOG(F) is found after SUBROUTINE PRED or ERROR in FSUBS
Merge time-varying covariate columns into a NM-style data.frame using LOCF
(with LOCB for records before the first source). Subjects/records still NA
after LOCF/LOCB can be filled with the column-wise median of cov_df.
merge_cov_locf( nm, cov_df, value_cols, time_col, median_fb = TRUE, verbose = FALSE, subj_col = "SUBJID", dat_col = "DAT2", tim_col = "TIME" )merge_cov_locf( nm, cov_df, value_cols, time_col, median_fb = TRUE, verbose = FALSE, subj_col = "SUBJID", dat_col = "DAT2", tim_col = "TIME" )
nm |
data.frame with key columns |
cov_df |
data.frame with |
value_cols |
character vector of value columns in |
time_col |
name of the time column in |
median_fb |
logical. If TRUE (default), fill remaining NA values with
the column-wise median of |
verbose |
logical. Print median fill counts. Default FALSE. |
subj_col |
subject ID column name. Default "SUBJID". |
dat_col |
date column name in |
tim_col |
time column name in |
nm with value_cols added.
Check Minimization Success
MinSuccess()MinSuccess()
logical, TRUE if minimization was successful
Performs multiple linear regression and computes influence diagnostics including DFFITS, DFBETAS, Cook's Distance, COVRATIO, and R-Student.
mlr2(y, x.raw, standardize = 0)mlr2(y, x.raw, standardize = 0)
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) |
list with model estimates and influence diagnostics
Convert AMT/RATE/DV columns of a NM data.frame from mass units to molar units.
nm_to_molar( df, mw_dose, mw_dv = mw_dose, amt_cols = c("AMT", "RATE"), dv_col = "DV", cmt_col = "CMT", dose_factor = 1000, dv_factor = 1 )nm_to_molar( df, mw_dose, mw_dv = mw_dose, amt_cols = c("AMT", "RATE"), dv_col = "DV", cmt_col = "CMT", dose_factor = 1000, dv_factor = 1 )
df |
data.frame. |
mw_dose |
numeric scalar. MW for AMT and RATE columns. |
mw_dv |
numeric scalar OR named numeric. Scalar: applied to all DV regardless of CMT. Named: names are CMT values; rows whose CMT is not in names() are left unchanged. Default = mw_dose. |
amt_cols |
columns to convert with mw_dose. Default c("AMT", "RATE"). |
dv_col |
DV column. Default "DV". |
cmt_col |
CMT column. Default "CMT". |
dose_factor |
multiplier applied after AMT/RATE divided by mw_dose. 1000 = mg -> umol (default). |
dv_factor |
multiplier applied after DV divided by mw_dv. 1 = ng/mL -> umol/L (default). |
Typical use:
AMT, RATE in mg, DV in ng/mL, MW in g/mol
mg / MW * 1000 -> umol
ng/mL / MW -> umol/L
For multiple analytes (e.g., parent at CMT=1 and metabolite at CMT=3),
supply mw_dv as a named numeric vector with names equal to the CMT
values (as character): c(`1` = 394.47, `3` = 380.47).
data.frame with converted columns; other columns unchanged.
Computes per-subject statistics including record counts, DV counts, dosing information, and sorting checks.
NMIDStat(NMTable)NMIDStat(NMTable)
NMTable |
data.frame of NONMEM data |
list with IDStat data.frame, sortedID logical, sortedDT logical
Computes statistics for each variable in a NONMEM dataset including counts of NA, zero, positive values, unique values, and functional dependency checks.
NMVarStat(NMTable)NMVarStat(NMTable)
NMTable |
data.frame of NONMEM data |
matrix with variable statistics
Generates a PDF report with empirical Bayes estimate (EBE) analysis including ETA distributions, shrinkage, covariate relationships, correlations, and multiple linear regression with influence diagnostics.
nmw_report_ebe(run_dir = getwd())nmw_report_ebe(run_dir = getwd())
run_dir |
character, path to the NONMEM run directory (default: current directory) |
Generates a PDF report with individual PK parameter distributions including summary statistics, histograms, and QQ plots.
nmw_report_indipk(run_dir = getwd())nmw_report_indipk(run_dir = getwd())
run_dir |
character, path to the NONMEM run directory (default: current directory) |
Generates a PDF report with input data validation including individuals with no dosing/DV, duplicate records, and summary statistics.
nmw_report_input(run_dir = getwd())nmw_report_input(run_dir = getwd())
run_dir |
character, path to the NONMEM run directory (default: current directory) |
Generates a PDF report with objective function value diagnostics including total OFV, AICc, BIC, individual OFV per DV summary, and gradient analysis.
nmw_report_ofv(run_dir = getwd())nmw_report_ofv(run_dir = getwd())
run_dir |
character, path to the NONMEM run directory (default: current directory) |
Includes the NONMEM PRINT.OUT file content in a PDF report.
nmw_report_output(run_dir = getwd())nmw_report_output(run_dir = getwd())
run_dir |
character, path to the NONMEM run directory (default: current directory) |
Generates a PDF report with theta, omega, and sigma parameter estimates, standard errors, confidence intervals, and significance flags.
nmw_report_param(run_dir = getwd())nmw_report_param(run_dir = getwd())
run_dir |
character, path to the NONMEM run directory (default: current directory) |
Generates a PDF report with spaghetti plots, DV vs PRED/IPRE, and individual fitting curves.
nmw_report_pred(run_dir = getwd())nmw_report_pred(run_dir = getwd())
run_dir |
character, path to the NONMEM run directory (default: current directory) |
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.
nmw_report_resid(run_dir = getwd())nmw_report_resid(run_dir = getwd())
run_dir |
character, path to the NONMEM run directory (default: current directory) |
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.
nmw_run( run_dir = getwd(), reports = c("ofv", "param", "pred", "resid", "ebe", "input", "output", "indipk") )nmw_run( run_dir = getwd(), reports = c("ofv", "param", "pred", "resid", "ebe", "input", "output", "indipk") )
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. |
## 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)## 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)
Creates a graphical model development flow diagram from SumOut results.
Outline(MDL, MDLName, out.start = "0", out.end = "zzzzzzzz", Target = "PDF")Outline(MDL, MDLName, out.start = "0", out.end = "zzzzzzzz", Target = "PDF")
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 |
Parse SDTM-style datetime strings into POSIXct. Accepts "YYYY-MM-DDTHH:MM:SS", "YYYY-MM-DDTHH:MM", "YYYY-MM-DD HH:MM:SS", "YYYY-MM-DD HH:MM", or "YYYY-MM-DD". POSIXct / Date inputs are returned coerced to POSIXct.
parse_dtc(x, tz = "UTC")parse_dtc(x, tz = "UTC")
x |
character vector (or POSIXct/Date) of datetime values. |
tz |
time zone. Default "UTC". |
POSIXct vector.
Extracts the value following a tag string (after the colon) in NONMEM output lines.
ParseOut(TagString, RawRead)ParseOut(TagString, RawRead)
TagString |
character, the tag to search for |
RawRead |
character vector of lines from NONMEM output |
character, the value after the tag
Opens a PDF device for NONMEM report generation.
PrepPDF(FileName, Paper = "letter", FontFamily = "Courier")PrepPDF(FileName, Paper = "letter", FontFamily = "Courier")
FileName |
character, output PDF filename |
Paper |
character, paper size (default "letter") |
FontFamily |
character, font family (default "Courier") |
Prints a character vector of text lines across multiple pages as needed.
PrinMTxt( MTxt, Cex = 0.8, Header1 = "", Header2 = "", Header3 = "", Footer1 = "", Footer2 = "", Footer3 = "", PrintRowNum = FALSE )PrinMTxt( MTxt, Cex = 0.8, Header1 = "", Header2 = "", Header3 = "", Footer1 = "", Footer2 = "", Footer3 = "", PrintRowNum = FALSE )
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 |
Prints text at a specific row and column position on the PDF page.
PrinTxt(Row, Col, Text, Cex = 0.8)PrinTxt(Row, Col, Text, Cex = 0.8)
Row |
numeric, row position |
Col |
numeric, column position |
Text |
character, text to print |
Cex |
numeric, character expansion factor |
Remove Rows with NA Values
RemoveNA(RawData)RemoveNA(RawData)
RawData |
data.frame |
data.frame with rows containing NA removed
Tests whether residual counts at various Z-value thresholds follow expected binomial distributions.
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) )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) )
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 |
matrix of test results
Performs a runs test on residuals. Zeros are omitted.
run.test.nm(RES)run.test.nm(RES)
RES |
numeric vector of residuals |
numeric, two-sided p-value
Check Standard Error Success
SESuccess()SESuccess()
logical, TRUE if standard errors were computed successfully
Scans subdirectories matching RunExt and collects summary metrics for model development flow analysis.
SumOut(FileExt = ".CTL", RunExt = ".R75", OutExt = ".OUT")SumOut(FileExt = ".CTL", RunExt = ".R75", OutExt = ".OUT")
FileExt |
character, control file extension |
RunExt |
character, run folder extension |
OutExt |
character, output file extension |
data.frame with summary of all runs
This produces standard table.
TabStep()TabStep()
It does not have arguments.
All necessary arguments are stored in the e environment.
This is similar to other standard results table.
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).
Kyun-Seop Bae <[email protected]>
NONMEM Users Guide
# Only After EstStep #TabStep()# Only After EstStep #TabStep()
TrimOut removes unnecessary parts from NONMEM original OUTPUT file.
TrimOut(inFile, outFile="PRINT.OUT")TrimOut(inFile, outFile="PRINT.OUT")
inFile |
NONMEM original untidy OUTPUT file name |
outFile |
Output file name to be written |
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.
outFile will be written in the current working folder or designated folder. This returns TRUE if the process was smooth.
Kyun-Seop Bae <[email protected]>