Nothing
# OQNCA.R
# Operational Qualification (OQ) report generator for the 'NonCompart' NCA engine.
# Runs a set of NCA test cases on the user's machine and compares every computed
# parameter, for every subject, to a pre-specified reference value within a
# pre-specified relative tolerance, then writes a self-contained PDF that lists
# every value next to its reference. Uses only base R + the package's pdf helpers
# (QualReport.R): no LaTeX.
#
# Reference values come from two independent tiers, both shipped in inst/OQ; the
# PPTESTCD -> reference column name map is in inst/OQ/RptCfg.csv.
# Tier B (concordance) : outputs of another NCA software on Theoph and Indometh
# (Final_Parameters_Pivoted_*.csv).
# Tier A (independent) : closed-form values for a synthetic fixture whose terminal
# phase is exactly mono-exponential, so lambda z, HL and
# Clast_pred are known analytically and the AUCs reduce to a
# hand-summable trapezoid (Reference_Analytic_*.csv). The
# fixture carries a lag-phase zero, an embedded BLQ inside the
# lambda z window and trailing BLQ, which the Theoph and
# Indometh profiles do not, and it exercises the UsePoints path.
#-- internal: canonicalize a column name for robust matching (% vs .) ----------
.oqCanon = function(x) tolower(gsub("[^A-Za-z0-9]", "", x))
#-- internal: symmetric relative difference, with absolute fallback near 0 ------
.oqDiff = function(R, W, tol, absTol=1e-6)
{
R = suppressWarnings(as.numeric(R)); W = suppressWarnings(as.numeric(W))
if (is.na(R) && is.na(W)) return(list(rd=0, pass=TRUE))
if (is.na(R) || is.na(W)) return(list(rd=NA_real_, pass=FALSE))
denom = (abs(R) + abs(W)) / 2
if (denom == 0) return(list(rd=0, pass=(abs(R - W) <= absTol)))
rd = abs(R - W) / denom
list(rd=rd, pass=(rd <= tol))
}
#-- internal: analytic OQ fixture ----------------------------------------------
# A single-subject profile engineered so that every BLQ-related code path is exercised:
# t=0 a lag-phase zero -> TLAG must be 0
# t=2 Cmax
# t=8 an EMBEDDED BLQ that falls INSIDE the lambda z window
# -> the x1 (zero-stripped) to x index remapping of UsedPoints must be exact
# t=4,16,24 an exactly mono-exponential terminal phase, A=16 and k=log(2)/8,
# so lambda z, HL and Clast_pred are known in closed form
# t=36,48 TRAILING BLQ
# -> Clast_pred must be anchored at TLST, not at the last sampling time
# Reference values for this fixture are derived analytically (Tier A), not from other software.
.oqFixtureBLQ = function()
{
A = 16
data.frame(Subject = 1,
Time = c(0, 1, 2, 4, 8, 16, 24, 36, 48),
conc = c(0, 5, 12, A*2^(-4/8), 0, 4, 2, 0, 0))
}
#-- internal: analytic steady-state OQ fixture ----------------------------------
# One dosing interval at steady state, extravascular, dose 100, tau = 12:
# t=0 pre-dose trough 2, equal to the concentration at t=12 as it must be at
# steady state
# t=2 Cmax 10
# t=4,8,12 exactly mono-exponential terminal phase 8, 4, 2 (half-life 4), so
# lambda z = log(2)/4 and Clast_pred = 2 in closed form
# Every concentration is a small integer, so AUCtau by the linear trapezoid is the hand sum
# 4 + 8 + 18 + 24 + 12 = 66, Cavg = 66/12 = 5.5, CL/F = 100/66 and Vz/F = CL/F / lambda z.
# Reference values (Reference_Analytic_SS_*.csv) are derived analytically (Tier A). Until
# 0.8.3 SS=TRUE divided the dose by AUClast, which coincides with AUCtau on this fixture
# only because the last sample falls exactly at tau; the tau-in-days case below exercises
# the unit conversion, and tests/Test-SS.R covers a tau that differs from Tlast.
.oqFixtureSS = function()
{
data.frame(Subject = 1,
Time = c(0, 1, 2, 4, 8, 12),
conc = c(2, 6, 10, 8, 4, 2))
}
#-- internal: analytic steady-state OQ fixture, intravascular bolus ---------------
# A one-compartment bolus at steady state: dose 100 every 12 h, V = 20, half-life 4 h,
# sampled every 2 h over one dosing interval. C(t) = C0*exp(-k*t) with k = log(2)/4 and
# C0 = (100/20)/(1 - exp(-12k)) = 40/7. Run with down="Log", every area is exact for a
# mono-exponential curve, so the whole reference row (Reference_Analytic_SS_Bolus_Log.csv)
# is closed form: CL = k*V, MRT to infinity = 1/k, and Vss = Vz = V = 20. Until 0.8.4 the
# steady-state Vss was built on the MRT to Tlast and came out as 14.06 on this fixture.
.oqFixtureSSBolus = function()
{
k = log(2)/4
Time = seq(0, 12, by=2)
data.frame(Subject = 1, Time = Time,
conc = 100/20/(1 - exp(-k*12))*exp(-k*Time))
}
#-- internal: default OQ case set (8 concordance + 6 analytic scenarios) ----------
.oqDefaultCases = function()
{
list(
list(id="Theoph_Linear", desc="Plasma, Extravascular, Linear-up Linear-down",
dataset="Theoph", key="Subject", colTime="Time", colConc="conc",
args=list(dose=320, concUnit="mg/L"), ref="Final_Parameters_Pivoted_Theoph_Linear.csv"),
list(id="Theoph_Log", desc="Plasma, Extravascular, Linear-up Log-down",
dataset="Theoph", key="Subject", colTime="Time", colConc="conc",
args=list(dose=320, down="Log", concUnit="mg/L"), ref="Final_Parameters_Pivoted_Theoph_Log.csv"),
list(id="Indometh_Bolus_Linear", desc="Plasma, IV Bolus, Linear-up Linear-down",
dataset="Indometh", key="Subject", colTime="time", colConc="conc",
args=list(dose=25, adm="Bolus", concUnit="mg/L", R2ADJ=0.8),
ref="Final_Parameters_Pivoted_Indometh_Linear.csv"),
list(id="Indometh_Bolus_Log", desc="Plasma, IV Bolus, Linear-up Log-down",
dataset="Indometh", key="Subject", colTime="time", colConc="conc",
args=list(dose=25, adm="Bolus", down="Log", concUnit="mg/L", R2ADJ=0.8),
ref="Final_Parameters_Pivoted_Indometh_Log.csv"),
list(id="Indometh_Infusion_Linear", desc="Plasma, IV Infusion (dur=0.25), Linear-up Linear-down",
dataset="Indometh", key="Subject", colTime="time", colConc="conc",
args=list(dose=25, adm="Infusion", dur=0.25, concUnit="mg/L", R2ADJ=0.8),
ref="Final_Parameters_Pivoted_Indometh_Linear_Infusion.csv"),
list(id="Indometh_Infusion_Log", desc="Plasma, IV Infusion (dur=0.25), Linear-up Log-down",
dataset="Indometh", key="Subject", colTime="time", colConc="conc",
args=list(dose=25, adm="Infusion", dur=0.25, down="Log", concUnit="mg/L", R2ADJ=0.8),
ref="Final_Parameters_Pivoted_Indometh_Log_Infusion.csv"),
list(id="Indometh_Extravasc_Linear", desc="Plasma, Extravascular (default adm), Linear-up Linear-down",
dataset="Indometh", key="Subject", colTime="time", colConc="conc",
args=list(dose=25, concUnit="mg/L", R2ADJ=0.8),
ref="Final_Parameters_Pivoted_Indometh_Linear_Wrong_Extravascular.csv"),
list(id="Indometh_Extravasc_Log", desc="Plasma, Extravascular (default adm), Linear-up Log-down",
dataset="Indometh", key="Subject", colTime="time", colConc="conc",
args=list(dose=25, down="Log", concUnit="mg/L", R2ADJ=0.8),
ref="Final_Parameters_Pivoted_Indometh_Log_Wrong_Extravascular.csv"),
# -- Tier A (analytic reference): BLQ handling and the UsePoints path ---------
list(id="BLQ_Analytic_Auto",
desc="Analytic fixture, embedded + trailing BLQ, automatic slope selection",
dataset="(built-in analytic fixture)", data=.oqFixtureBLQ(),
key="Subject", colTime="Time", colConc="conc",
args=list(dose=100, concUnit="mg/L"),
ref="Reference_Analytic_BLQ_Extravascular_Linear.csv"),
list(id="BLQ_Analytic_UsePoints",
desc="Analytic fixture, terminal phase forced with UsePoints (indices into x)",
dataset="(built-in analytic fixture)", data=.oqFixtureBLQ(),
key="Subject", colTime="Time", colConc="conc",
args=list(dose=100, concUnit="mg/L", UsePoints=list(c(4L, 6L, 7L))),
ref="Reference_Analytic_BLQ_Extravascular_Linear.csv"),
list(id="BLQ_Analytic_RoundTrip",
desc="Analytic fixture, UsedPoints fed back as UsePoints must reproduce the automatic fit",
dataset="(built-in analytic fixture)", data=.oqFixtureBLQ(),
key="Subject", colTime="Time", colConc="conc",
args=list(dose=100, concUnit="mg/L"), roundTrip=TRUE,
ref="Reference_Analytic_BLQ_Extravascular_Linear.csv"),
# -- Tier A (analytic reference): steady state, AUCTAU and the parameters built on it --
list(id="SS_Analytic_Tau",
desc="Analytic steady-state fixture, SS=TRUE with tau=12 h: AUCTAU, CAVG, CL/F and Vz/F from AUCTAU",
dataset="(built-in analytic steady-state fixture)", data=.oqFixtureSS(),
key="Subject", colTime="Time", colConc="conc",
args=list(dose=100, concUnit="mg/L", SS=TRUE, tau=12),
ref="Reference_Analytic_SS_Extravascular_Linear.csv"),
list(id="SS_Analytic_TauUnit",
desc="Same fixture with tau given in days (tau=0.5, unitTau=d): the unit conversion must not change any value",
dataset="(built-in analytic steady-state fixture)", data=.oqFixtureSS(),
key="Subject", colTime="Time", colConc="conc",
args=list(dose=100, concUnit="mg/L", SS=TRUE, tau=0.5, unitTau="d"),
ref="Reference_Analytic_SS_Extravascular_Linear.csv"),
list(id="SS_Analytic_Bolus",
desc="Analytic steady-state IV bolus fixture, log-down: MRT to infinity = 1/k and Vss = V in closed form",
dataset="(built-in analytic steady-state bolus fixture)", data=.oqFixtureSSBolus(),
key="Subject", colTime="Time", colConc="conc",
args=list(dose=100, adm="Bolus", down="Log", concUnit="mg/L", SS=TRUE, tau=12),
ref="Reference_Analytic_SS_Bolus_Log.csv")
)
}
#-- internal: run a single case -> full comparison table -----------------------
.oqRunCase = function(case, refDir, tol, wnlMap)
{
out = list(id=case$id, desc=case$desc, status="FAIL", nComp=0, nFail=0,
maxRD=NA_real_, nParam=0, nSubj=0, comp=NULL,
params=character(0), subjects=character(0), settings="", message="")
out$settings = tryCatch(
sprintf("dataset=%s, time=%s, conc=%s, %s", case$dataset, case$colTime, case$colConc,
paste(names(case$args), vapply(case$args, as.character, character(1)),
sep="=", collapse=", ")), error=function(e) "")
# a case supplies either an inline data.frame (case[["data"]]) or the name of a datasets::
# object. Index with [[ ]], not $: with $ the name "data" would partial-match "dataset".
d = tryCatch({
if (!is.null(case[["data"]])) as.data.frame(case[["data"]])
else { e = new.env(); utils::data(list=case$dataset, package="datasets", envir=e)
as.data.frame(e[[case$dataset]]) }
}, error=function(err) NULL)
if (is.null(d)) { out$message = paste("dataset not available:", case$dataset); return(out) }
d[[case$key]] = suppressWarnings(as.numeric(as.character(d[[case$key]])))
R = tryCatch(do.call(tblNCA,
c(list(concData=d, key=case$key, colTime=case$colTime, colConc=case$colConc), case$args)),
error=function(err) err)
if (inherits(R, "error")) { out$message = paste("tblNCA error:", conditionMessage(R)); return(out) }
# round-trip cases re-run the analysis with the UsedPoints the first run reported, which must
# leave every parameter unchanged; this is what detects a wrong x1 -> x index remapping
if (isTRUE(case[["roundTrip"]])) {
R = tryCatch(do.call(tblNCA,
c(list(concData=d, key=case$key, colTime=case$colTime, colConc=case$colConc,
UsePoints=attr(R, "UsedPoints")), case$args)),
error=function(err) err)
if (inherits(R, "error")) {
out$message = paste("round-trip tblNCA error:", conditionMessage(R)); return(out) }
}
R = as.data.frame(R)
# map PPTESTCD -> reference column names via the shipped RptCfg mapping
cn = colnames(R)
colnames(R) = c(cn[1], unname(wnlMap[cn[-1]]))
W = tryCatch(read.csv(file.path(refDir, case$ref), as.is=TRUE, check.names=FALSE),
error=function(err) NULL)
if (is.null(W)) { out$message = paste("reference not found:", case$ref); return(out) }
rCanon = .oqCanon(colnames(R)); wCanon = .oqCanon(colnames(W))
skip = .oqCanon(c("Subject", "b0", case$key))
wcols = character(0); rcols = character(0); lost = character(0)
for (j in seq_along(colnames(W))) {
cc = wCanon[j]; if (cc %in% skip || is.na(cc) || !nzchar(cc)) next
ri = match(cc, rCanon); if (is.na(ri)) { lost = c(lost, colnames(W)[j]); next }
wcols = c(wcols, colnames(W)[j]); rcols = c(rcols, colnames(R)[ri])
}
if (length(wcols) == 0) { out$message = "no comparable parameters"; return(out) }
# A reference parameter or subject that the result does not carry, and a subject that
# occurs twice, used to drop out of the comparison in silence, so the case could pass on
# what was left. Each of them now fails the case.
if (length(lost) > 0) {
out$message = paste("reference parameter(s) not in the result:", paste(lost, collapse=", ")); return(out) }
if (anyDuplicated(W[[1]]) > 0 || anyDuplicated(R[[1]]) > 0) {
out$message = "duplicated subject in the reference or in the result"; return(out) }
if (length(setdiff(W[[1]], R[[1]])) > 0) {
out$message = paste("reference subject(s) not in the result:", paste(setdiff(W[[1]], R[[1]]), collapse=", ")); return(out) }
subj = intersect(W[[1]], R[[1]])
np = length(wcols); ns = length(subj); N = np * ns
P = character(N); SB = character(N); RF = numeric(N); OB = numeric(N); RD = numeric(N); PS = logical(N)
k = 0; maxRD = 0; nFail = 0
for (s in subj) {
wr = W[W[[1]] == s, , drop=FALSE][1, ]; rr = R[R[[1]] == s, , drop=FALSE][1, ]
for (m in seq_len(np)) {
st = .oqDiff(rr[[rcols[m]]], wr[[wcols[m]]], tol)
k = k + 1
P[k] = wcols[m]; SB[k] = as.character(s)
RF[k] = suppressWarnings(as.numeric(wr[[wcols[m]]]))
OB[k] = suppressWarnings(as.numeric(rr[[rcols[m]]]))
RD[k] = st$rd; PS[k] = isTRUE(st$pass)
if (!is.na(st$rd) && st$rd > maxRD) maxRD = st$rd
if (!PS[k]) nFail = nFail + 1
}
}
out$comp = data.frame(param=P, subj=SB, ref=RF, obs=OB, reldiff=RD, pass=PS, stringsAsFactors=FALSE)
out$params = wcols; out$subjects = as.character(subj)
out$nParam = np; out$nSubj = ns; out$nComp = N; out$nFail = nFail; out$maxRD = maxRD
out$status = if (N > 0 && nFail == 0) "PASS" else "FAIL"
out
}
#-- main ------------------------------------------------------------------------
OQNCA = function(fileName="NonCompart-OQ-Report.pdf", cases=NULL, tol=1e-3,
refDir=system.file("OQ", package="NonCompart"), performedBy="",
paper="auto", sigField=FALSE)
{
now = Sys.time(); si = Sys.info()
if (is.null(cases)) cases = .oqDefaultCases()
if (!nzchar(refDir) || !dir.exists(refDir))
stop("OQ reference directory not found. Install 'NonCompart' or pass refDir=.")
rc = tryCatch(read.csv(file.path(refDir, "RptCfg.csv"), as.is=TRUE), error=function(e) NULL)
if (is.null(rc) || !all(c("PPTESTCD", "WNL") %in% colnames(rc)))
stop("RptCfg.csv (with PPTESTCD and WNL columns) not found in refDir.")
wnlMap = setNames(rc$WNL, rc$PPTESTCD)
results = lapply(cases, .oqRunCase, refDir=refDir, tol=tol, wnlMap=wnlMap)
pkgVer = function(p) tryCatch(as.character(packageVersion(p)), error=function(e) "not installed")
hr = paste(rep("=", 72), collapse=""); hr2 = paste(rep("-", 72), collapse="")
nFailCases = sum(vapply(results, function(r) r$status != "PASS", logical(1)))
qualified = (nFailCases == 0) && length(results) > 0
status = if (qualified) "QUALIFIED" else "NOT QUALIFIED"
who = if (nzchar(performedBy)) performedBy else as.character(si["login"])
stamp = format(now, "%Y-%m-%d %H:%M:%S")
sig = character(0); sg = function(...) sig <<- c(sig, ...)
sg(hr); sg(" OPERATIONAL QUALIFICATION (OQ) REPORT"); sg(hr); sg("")
sg("Engine under test:")
sg(sprintf(" %-14s %s", "NonCompart", pkgVer("NonCompart")))
sg("")
sg(sprintf("Report generated : %s %s", stamp, Sys.timezone()))
sg(sprintf("Performed by : %s", who))
sg(sprintf("Acceptance : symmetric relative difference <= %g", tol))
sg("Reference : WinNonlin 6.4 NCA outputs (Tier B, concordance) and")
sg(" closed-form analytic values (Tier A, independent)")
sg("")
sg(sprintf("Overall result : %s", status))
sg(sprintf(" %d of %d cases passed", length(results) - nFailCases, length(results)))
sg("")
if (qualified)
sg(strwrap(paste("All operational test cases reproduced the pre-specified",
"reference values within the acceptance tolerance on this",
"system. Detailed per-case results follow on the next pages."), width=72))
else
sg(strwrap(paste("One or more cases did not meet the acceptance criterion.",
"See the per-case details on the following pages."), width=72))
sg(""); sg(""); sg("Approval"); sg(hr2)
sg("Sign this report in Adobe Acrobat Reader (no print/scan): open it,")
sg("choose \"Use a certificate\" > \"Digitally sign\", sign with your Digital")
sg("ID, then click the signature box under each name below. (Generate with")
sg("sigField=TRUE, or run addSigFieldNCA(), to add the boxes.) Scriptable")
sg("alternative: signPDFNCA()/verifyPDFNCA().")
sg("")
perfRow = length(sig) + 1L
sg(" Performed by : ____________________________ Date: __________")
sg(""); sg(""); sg("")
revRow = length(sig) + 1L
sg(" Reviewed by : ____________________________ Date: __________")
sg(""); sg("")
body = character(0); ad = function(...) body <<- c(body, ...)
ad("Case Summary"); ad(hr2)
ad(sprintf(" %-4s %-28s %5s %5s %11s", "Stat", "Case", "Par", "Subj", "max rel.df")); ad(hr2)
for (r in results) {
mrd = if (is.na(r$maxRD)) " NA" else sprintf("%.2e", r$maxRD)
ad(sprintf(" [%-2s] %-28s %5d %5d %11s", if (r$status == "PASS") "OK" else "X",
substr(r$id, 1, 28), r$nParam, r$nSubj, mrd))
}
ad("")
ad("Case Details - every computed value vs its reference"); ad(hr2)
fmtNum = function(x) if (is.na(x)) "NA" else formatC(x, format="g", digits=8)
fmtE = function(x) if (is.na(x)) "NA" else sprintf("%.2e", x)
hdr = sprintf(" %-15s %12s %12s %9s %9s %2s",
"PARAMETER", "REFERENCE", "OBSERVED", "ABS.DIFF", "REL.DIFF", "ST")
for (r in results) {
ad(hr); ad(sprintf("Case: %s [%s]", r$id, r$status)); ad(sprintf(" %s", substr(r$desc, 1, 66)))
if (nzchar(r$settings)) for (ln in strwrap(paste("Settings:", r$settings), width=72, exdent=3)) ad(ln)
if (nzchar(r$message)) { ad(sprintf(" note: %s", r$message)); ad(""); next }
ad(sprintf(" %d parameters x %d subjects = %d comparisons; %d failed; max rel.diff %s",
r$nParam, r$nSubj, r$nComp, r$nFail, fmtE(r$maxRD)))
cp = r$comp
for (s in r$subjects) {
ad(""); ad(sprintf(" Subject %s", s)); ad(hdr); ad(paste0(" ", paste(rep("-", 66), collapse="")))
for (i in which(cp$subj == s)) {
ab = abs(cp$ref[i] - cp$obs[i])
ad(sprintf(" %-15s %12s %12s %9s %9s %2s",
substr(cp$param[i], 1, 15), fmtNum(cp$ref[i]), fmtNum(cp$obs[i]),
fmtE(ab), fmtE(cp$reldiff[i]), if (cp$pass[i]) "OK" else "X"))
}
}
ad("")
}
ad("\f"); ad(hr); ad(" OVERALL RESULT"); ad(hr)
ad(sprintf(" STATUS: %s (%d of %d cases passed)", status, length(results) - nFailCases, length(results)))
ad("\f"); ad("Appendix A. sessionInfo()"); ad(hr2)
ow = options(width=78)
siLines = tryCatch(capture.output(print(sessionInfo())), error=function(e) "unavailable")
options(ow)
for (ln in siLines) ad(ln)
rinfo = .qRenderPDF(fileName, sigLines=sig, bodyLines=body,
title="Operational Qualification Report", verdict=status,
footer=sprintf("NonCompart::OQNCA %s", stamp), paper=paper)
if (isTRUE(sigField))
try(addSigFieldNCA(fileName, page=1L, fieldNames=c("Performed_by", "Reviewed_by"),
rects=list(.qSigRect(rinfo, perfRow), .qSigRect(rinfo, revRow))),
silent=TRUE)
apath = normalizePath(fileName, winslash="/", mustWork=FALSE)
cat(sprintf("OQ report (STATUS: %s, paper: %s, %d/%d cases passed) saved at:\n %s\n",
status, rinfo$paper, length(results) - nFailCases, length(results), apath))
if (isTRUE(sigField))
cat(" Open this PDF in Adobe Acrobat Reader and click a signature field to sign.\n")
invisible(list(fileName=apath, qualified=qualified, tol=tol, results=results,
paper=rinfo$paper, nCases=length(results), nFailCases=nFailCases))
}
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.