| Title: | Enhances 'xpose' Diagnostics for Pharmacometric Models from 'Certara.RsNLME' and Phoenix NLME |
| Version: | 2.1.0 |
| Description: | Facilitates the creation of 'xpose' data objects from Nonlinear Mixed Effects (NLME) model outputs produced by 'Certara.RsNLME' or Phoenix NLME. This integration enables users to utilize all 'ggplot2'-based plotting functions available in 'xpose' for thorough model diagnostics and data visualization. Additionally, the package introduces specialized plotting functions tailored for covariate model evaluation, extending the analytical capabilities beyond those offered by 'xpose' alone. |
| URL: | https://certara.github.io/R-Xpose-NLME/ |
| Depends: | R (≥ 4.0) |
| License: | LGPL-3 |
| Encoding: | UTF-8 |
| LazyData: | true |
| LazyDataCompression: | xz |
| Suggests: | Certara.RsNLME, data.table, ellmer, flextable, gridExtra, jsonlite, officer, readr, testthat (≥ 3.0.0) |
| Imports: | dplyr, egg, GGally, ggplot2, magrittr, purrr, rlang, scales, stringr, tibble, xpose |
| Config/roxygen2/version: | 8.1.0 |
| NeedsCompilation: | no |
| Packaged: | 2026-09-29 14:39:29 UTC; jcraig |
| Author: | James Craig [aut, cre], Michael Tomashevskiy [aut], Soltanshahi Fred [aut], Shuhua Hu [ctb], Certara USA, Inc [cph, fnd] |
| Maintainer: | James Craig <james.craig@certara.com> |
| Repository: | CRAN |
| Date/Publication: | 2026-09-30 18:40:17 UTC |
Render a parameter comparison as a flextable
Description
as_flextable() method for the prmComparisonNlme object
returned by compare_prmNlme(). Draws solid separators between the
diagnostic block, the parameter block, and the optional RSE block, and
reports the number of models in the footer. Requires the flextable and
officer packages (both Suggests).
Usage
## S3 method for class 'prmComparisonNlme'
as_flextable(x, format = NULL, max_show = NULL, ...)
Arguments
x |
A |
format |
One of |
max_show |
Maximum number of models to render. |
... |
Unused; present for S3 generic compatibility. |
Value
A flextable object.
See Also
Compare original and filtered ETA shrinkage
Description
Computes filtered overall ETA shrinkage from the stored
subject-by-ETA data and returns a comparison table without modifying
the xpdb object.
Usage
compare_etaShrinkageNlme(
xpdb,
threshold = 1e-06,
eta_threshold = NULL,
eta_name = NULL,
.problem = 1
)
Arguments
xpdb |
An |
threshold |
Global default threshold applied to all ETAs
(default |
eta_threshold |
Optional named numeric vector overriding
|
eta_name |
Optional character vector selecting a subset of ETAs to recompute. ETAs not listed keep their current summary values. |
.problem |
Problem number (default |
Value
A tibble with one row per processed ETA containing:
- Eta
ETA name
- n_total
Total number of subjects for this ETA
- n_kept
Number of subjects kept after filtering
- n_removed
Number of subjects removed
- threshold_applied
Resolved threshold used for this ETA
- original_shrinkage
Shrinkage computed from all subjects
- filtered_shrinkage
Shrinkage computed after filtering
- omega_sd
Population omega standard deviation for this ETA
Compare NLME parameter estimates across multiple runs
Description
Builds a single wide table comparing parameter estimates
(and optional %RSE) across two or more NLME runs, alongside a block of
run-level diagnostics (-2LL, OFV diff, method, RetCode,
condition, condition basis, nSub, nObs, and total runtime). It is the multi-model
sibling of get_summaryNlme(): where get_summaryNlme() summarises one
xpose_data object, compare_prmNlme() lines several up side by side for
run-record style model comparison.
Usage
compare_prmNlme(
x = NULL,
dir = ".",
runs = NULL,
auto_detect = TRUE,
max_runs = NULL,
transform = c("untransformed", "sqrt_om2", "sqrt_exp_om2_minus_1"),
param_order = c("original", "alphabetical"),
rse_separate = FALSE,
drop_dOFV = FALSE,
output_file = NULL,
format = c("column", "row"),
log_file = "Table_log.txt"
)
Arguments
x |
Optional named |
dir |
Directory scanned for runs when |
runs |
Optional character vector of run names (subfolders of |
auto_detect |
Logical; when |
max_runs |
Optional cap on the number of successfully loaded runs
to include. |
transform |
One of |
param_order |
One of |
rse_separate |
Logical; when |
drop_dOFV |
Logical; when |
output_file |
Optional path; when set, the full table is written as a
CSV in the chosen |
format |
One of |
log_file |
Name of the excluded-run log written into |
Details
Runs can be supplied three ways:
As a pre-built named
listofxpose_dataobjects (or a singlexpose_data) viax. List names become the column labels.By explicit run name via
runs, loaded fromdirwithxposeNlme().By auto-detection (
auto_detect = TRUE, the default whenxandrunsare bothNULL):diris scanned for model files (*.mdlor*.mmdl, case-insensitive) whose same-named run output folder exists, in alphanumeric order. Name each model so its output folder matches the model file (e.g.run001.mmdlbeside arun001/folder). A run is only included when itsnlme7engine.logis present; runs that fail to load are recorded inlog_file(written intodir) and skipped.
The transform setting affects only diagonal OMEGA rows. Diagonal SIGMA
rows are kept on the reported get_prmNlme() scale (for CEps this is the
SD scale), so SIGMA values and %RSE do not change across transformation
settings. %RSE on transformed OMEGA is propagated with the delta method.
The returned object carries n_header / n_rse attributes marking the
leading diagnostic block and the trailing RSE block, which
as_flextable.prmComparisonNlme() uses to draw separators. Rendering with
flextable and CSV export via output_file are both optional; the core
computation depends only on packages already imported by
Certara.Xpose.NLME.
Timing
The diagnostic row total runtime (sec) is engine-reported CPU time:
the sum of the runtime and covtime rows in xpdb$summary, which are
parsed from nlme7engine.log at import. That total can differ
substantially from the wall-clock elapsed time shown by
print.rsnlme_fit / a fit object's runTime (especially on multi-core
runs). See also get_overallNlme() for the same distinction, including
optional runtime_wallclock when an xpdb was built via
xposeNlmeModel().
Value
A tibble of class prmComparisonNlme with a Description column
followed by one column per run, carrying n_header, n_rse, nModels,
run_labels, and format attributes.
See Also
get_summaryNlme(), get_prmNlme(), get_overallNlme(),
xposeNlme()
Examples
## Not run:
# 1) Compare two already-imported runs.
xp1 <- xposeNlme(dir = "run001")
xp2 <- xposeNlme(dir = "run002")
compare_prmNlme(list(run001 = xp1, run002 = xp2))
# 2) Auto-detect every completed run under the working directory,
# put %RSE on its own rows, and write a CSV.
tbl <- compare_prmNlme(
rse_separate = TRUE,
output_file = "TableofParameters.csv"
)
# 3) Render the comparison as a flextable (requires the flextable and
# officer packages).
flextable::as_flextable(tbl)
## End(Not run)
ETAs vs covariate Plot
Description
Plot ETAs against a continuous or categorical covariate.
Usage
eta_vs_cov(
xpdb,
covariate,
mapping = NULL,
drop_fixed = FALSE,
group = "ID",
type = "bpls",
title = "ETAs vs @x | @run",
subtitle = "Based on @nind individuals",
caption = "@dir",
tag = NULL,
log = NULL,
guide = FALSE,
onlyfirst = TRUE,
facets,
.problem,
quiet,
...
)
Arguments
xpdb |
An xpose database object. |
covariate |
Character; String of covariate name |
mapping |
List of aesthetics mappings to be used for the xpose plot
(e.g. |
drop_fixed |
Logical; Logic specifying whether ETAs having same value for the given covariate value should be removed from plotting |
group |
Grouping variable to be used for lines. |
type |
Character; String setting the type of plot to be used. Must be 'b' for categorical covariates, one or a combination of 'p','l','s' for continuous covariates. |
title |
Character; Plot title. Use |
subtitle |
Character; Plot subtitle. Use |
caption |
Character; Page caption. Use |
tag |
Character; Plot identification tag. Use |
log |
Character; String assigning logarithmic scale to axes, can be either ”, 'x', y' or 'xy'. |
guide |
Logical; Should the guide (e.g. reference distribution) be displayed. |
onlyfirst |
Logical; Should the data be filtered to retain first value for each group/facet. |
facets |
Either a character string to use |
.problem |
The $problem number to be used. By default returns the last estimation problem. |
quiet |
Logical, if |
... |
Any additional aesthetics to be passed on |
Value
An object of class xpose_plot, ggplot, and gg. This object represents a customized plot created using ggplot2.
The xpose_plot class provides additional metadata and integration with xpose workflows, allowing for advanced
customization and compatibility with other xpose functions. Users can interact with the plot object as they
would with any ggplot2 object, including modifying aesthetics, adding layers, or saving the plot.
Layers mapping
Plots can be customized by mapping arguments to specific layers. The naming convention is layer_option where layer is one of the names defined in the list below and option is any option supported by this layer e.g. boxplot_fill = 'blue', etc.
box plot: options to
geom_boxplotpoint plot: options to
geom_pointline plot: options to
geom_linesmooth plot: options to
geom_smoothxscale: options to
scale_x_continuousorscale_x_log10yscale: options to
scale_y_continuousorscale_y_log10
See Also
Examples
eta_vs_cov(xpose::xpdb_ex_pk,
covariate = "WT",
type = "ps",
smooth_color = "red",
point_color = "green",
point_shape = "square",
point_alpha = .5,
point_size = 3
)
eta_vs_cov(xpose::xpdb_ex_pk,
covariate = "AGE",
type = "ps",
facets = DOSE ~ variable,
guide = TRUE,
guide_color = "red",
guide_slope = 0,
guide_intercept = 0
)
Build a fused fit + bootstrap parameter summary
Description
Companion to get_summaryNlme() for
Certara.RsNLME::bootstrap() results. Combines original-fit columns
(Estimate, %RSE, Shrinkage (%)) with per-replicate bootstrap
columns (Bootstrap estimate (<metric>), Bootstrap <pct>% CI)
using the same transform / shrinkage machinery.
Usage
get_bootSummaryNlme(
bootResult,
xpdb = NULL,
transform = list(),
units = list(),
metric = c("Median", "Mean"),
ci_level = NULL,
return_code_ok = 1:3,
digits = 3
)
## S3 method for class 'bootSummaryNlme'
print(x, ...)
Arguments
bootResult |
Object returned by |
xpdb |
Optional |
transform |
Named list of per-parameter transforms keyed by
parameter label. Same contract as |
units |
Named character vector (or list of length-1 character)
keyed by parameter label, overriding the real-units |
metric |
|
ci_level |
Numeric in (0, 1); width of the percentile CI. When
|
return_code_ok |
Integer vector of |
digits |
Significant-digits count applied via |
x |
A |
... |
Further arguments passed to the underlying tibble print method. |
Details
Three input modes drive what columns appear in the output:
- m1:
bootResultonly No original-fit source; output is bootstrap-only –
Section,Parameter, optionalUnit,Bootstrap estimate (<metric>), andBootstrap <pct>% CI. Amessage()notes that original-fit columns are unavailable and how to include them (initialEstimates = TRUEorxpdb). The residual-transform advisory (see below) still fires, since the default's fitness can't be ruled out without PML either way.- m2:
bootResultcarries an embeddedfitSummary fitSummaryis the original-fit source (wheninitialEstimates = TRUEwas used on the bootstrap call). Omega off-diagonal covariance rows (Diagonal = FALSE) are dropped so the original-fit side stays variance-scale, matching m3's "off-diagonals excluded" contract; older fitSummary tables without aDiagonalcolumn are treated as diagonal-only.- m3: explicit
xpdbargument Original-fit columns come from
get_summaryNlme(xpdb, ...). IfbootResult$fitSummaryis also non-NULL a one-shot warning fires andxpdbwins.
Per-replicate filtering: replicates whose BootOverall$ReturnCode
falls outside return_code_ok are dropped silently before the metric
and percentile CI are computed. The BootOverall table on the
rsnlme_boot is the single source of truth – no on-disk reads.
The CI bounds are the empirical (1 - ci_level) / 2 and
1 - (1 - ci_level) / 2 quantiles of the kept replicates, computed
with stats::quantile()'s default method (type 7).
Soft-degrade for missing stacks: BootSigmaStacked and
BootSecondaryStacked are net-new in the corresponding
Certara.NLME8 release. When either is NULL (older NLME8 build) the
function emits NA bootstrap cells for that section and a single warning
naming the missing stacks plus the installed Certara.NLME8 version.
BootThetaStacked and BootOmegaStacked predate the new release and
are always available.
Output formatting (shared with get_summaryNlme()): when a
non-identity transform is active the values are shown on the
transformed scale only, and the scale label is appended to the shared
Parameter name in parentheses – nV (CV%), CEps (SD), or a custom
name for list(fn=, dfn=, name=) specs. Identity / raw rows keep
the bare name. The Unit column carries real units only and is
dropped when every row is dimensionless. The
bootstrap CI is a single character column formatted as "lo - hi" (a
dash range, no brackets). Numeric digits is applied via signif() to
both the bootstrap columns and, when present, the original-fit
Estimate, %RSE, and Shrinkage (%).
Residual-shape advisories: a per-sigma warning fires when PML
classifies a sigma as additive or otherwise non-proportional while it
is reported with the multiplicative_cv default. Classification
requires PML, which is only available when xpdb is supplied (m3); on
m1/m2 no per-sigma warning is emitted. The general default-transform
message() is broader: it fires for any defaulted sigma that isn't
proven proportional, which on m1/m2 (no PML to check) means it
always fires – mirroring get_summaryNlme()'s own no-PML behaviour.
Set options(xposeNlme.summary.quiet_default_warning = TRUE) to
silence it.
Value
A tibble (class bootSummaryNlme) with Section, Parameter
(carrying a (CV%) / (SD) / custom scale flag when a non-identity
transform is active), optional original-fit columns (Estimate,
%RSE, Shrinkage (%)), an optional real-units Unit column, and
the two bootstrap columns (the CI formatted as "lo - hi"). Carries
the attributes n_used, n_total, ci_level, return_code_ok,
transform, metric, fitSource ("xpdb" / "embedded" /
"none"). The bootSummaryNlme class carries a print method that
honours the digits argument for displayed precision.
See Also
Examples
## Not run:
fit_boot <- Certara.RsNLME::bootstrap(model, ...)
# m1: bootstrap-only summary, no fit source.
get_bootSummaryNlme(fit_boot)
# m2: fused summary using the bootstrap's embedded fitSummary
# (initialEstimates = TRUE on the bootstrap call).
fit_boot_init <- Certara.RsNLME::bootstrap(model,
initialEstimates = TRUE, ...)
get_bootSummaryNlme(fit_boot_init)
# m3: fused summary against an explicit xpdb -- preferred when the
# xpdb has its own provenance (covariates, residuals, posthoc) that
# fitSummary doesn't capture.
xp <- xposeNlmeModel(fit_model)
get_bootSummaryNlme(fit_boot, xpdb = xp)
# Custom transform on a sigma applied to both original-fit and
# bootstrap columns; `name` sets the scale flag on the parameter name.
get_bootSummaryNlme(
fit_boot_init,
transform = list(
CEps = list(
fn = function(s) 200 * s,
dfn = function(s) 200,
name = "2xCV%"
)
)
)
## End(Not run)
Access subject-level ETA data
Description
Retrieves the stored subject-by-ETA table from the
xpdb$special slot with type == "eta_subject".
Usage
get_etaSubjectNlme(xpdb, .problem = 1)
Arguments
xpdb |
An |
.problem |
The problem number to extract (default |
Value
A tibble with columns ID, Eta, ETA_VAL,
ETA_SE.
Access NLME model overall fit results
Description
Access model fit diagnostics from an xpdb object generated by xposeNlme.
Usage
get_overallNlme(
xpdb,
.problem = 1,
.subprob = 0,
.method = NULL,
conditionNumber = NULL
)
Arguments
xpdb |
An |
.problem |
The problem to be used. |
.subprob |
The subproblem to be used. |
.method |
The estimation method to be used. |
conditionNumber |
Optional character; overrides the basis/scope used
for the returned |
Details
This function returns only the Overall.csv fit-statistics
table (for example objective function value, AIC, BIC, log-likelihood). It
does not contain run metadata such as estimation settings or timing.
Condition and ConditionBasis report the reported-condition-
number diagnostic (see engineParams(conditionNumber = ...) in
Certara.RsNLME). ConditionBasis labels which basis/scope
Condition actually reflects, e.g. "Correlation (full)" vs.
"Covariance (fixed effects)". Actual-over-requested precedence
(this is the value returned when conditionNumber is NULL):
when the engine's own out.txt reports a value (any
conditionNumber mode), it is used as-is; only when that is
unavailable does this function fall back to an independent, theta-only,
covariance-basis recompute (always labeled
"Covariance (fixed effects)") - so Condition may not be
comparable across rows/fits that used different conditionNumber
modes unless ConditionBasis matches.
Passing conditionNumber forces a specific basis/scope instead,
regardless of what the engine actually used, by recomputing from the raw
covariance data. "...Fixef" scopes (fixed effects only) can always
be recomputed from dmp.txt$varFix. "...Full" scopes (all
free population parameters: fixed effects, free residual error, free
Omega) require Covariance.csv specifically - dmp.txt does not
carry the joint covariance needed, because dmp.txt$omegaSE is only
the per-element standard error of each Omega entry, with no
cross-covariance to fixed effects/error or between different Omega
entries.
Run metadata lives in xpdb$summary (view it with
summary(xpdb)). Two timing rows may appear there and are measured
differently: runtime (and covtime) are engine-reported CPU
times parsed from nlme7engine.log that sum across workers and can
overstate the actual wait on multi-core runs, whereas
runtime_wallclock is the elapsed wall-clock time captured from a
self-describing Certara.RsNLME fit (via
xposeNlmeModel()) and is generally smaller on multi-core
runs. runtime_wallclock is never available on the file-based
xposeNlme(dir = ...) path.
Value
A tibble for single problem/subproblem.
See Also
Examples
# Store the parameter table
prmOverall <- get_overallNlme(xpdb_ex_Nlme)
Access NLME model parameter estimates
Description
Access model parameter estimates from an xpdb object generated by xposeNlme.
Usage
get_prmNlme(
xpdb,
.problem = 1,
.subprob = 0,
.method = NULL,
digits = 6,
show_all = FALSE,
level = 0.95
)
Arguments
xpdb |
An |
.problem |
The problem to be used. |
.subprob |
The subproblem to be used. |
.method |
The estimation method to be used. |
digits |
Integer specifying the number of significant digits to be displayed. |
show_all |
Logical specifying whether the 0 off-diagonal omega elements should be removed from the output or not. |
level |
Numeric specifying confidence level to compute confidence intervals,
which are calculated based on Student's t distribution. Set to |
Value
A tibble for single problem/subproblem.
See Also
Examples
# Store the parameter table
prm <- get_prmNlme(xpdb_ex_Nlme)
# Set the desired number of significant digits to display results
# Note: To have results displayed in the number of significant digits
# specified in the digits argument, one needs to make sure that
# the value of pillar.sigfig option (default value is 3) is greater
# than or equal to this specified value.
options(pillar.sigfig = 6)
get_prmNlme(xpdb_ex_Nlme, digits = 4)
Build a parameter summary table for an NLME xpdb
Description
Produces a single tibble combining fixed effects, random
effects, residual errors, and secondary parameters, along with their
estimates and %RSE on the chosen scale. Shrinkage for random effects
and residual errors is also included. The transform applied to each row
controls both the displayed Estimate and the corresponding %RSE,
which is computed on the transformed scale via the delta method.
Built-in presets carry analytic derivatives; for transforms outside the
catalog, supply a custom fn with its derivative dfn.
Usage
get_summaryNlme(
xpdb,
.problem = 1,
.subprob = 0,
.method = NULL,
transform = list(),
units = list(),
shrinkage = c("engine", "sd", "var"),
digits = NULL,
append_flag = TRUE,
emit_advisories = TRUE
)
## S3 method for class 'summaryNlme'
print(x, ...)
Arguments
xpdb |
An |
.problem |
Problem number (default 1). Mirrors |
.subprob |
Subproblem number (default 0). Mirrors |
.method |
Estimation method filter (default |
transform |
Named list of per-parameter transforms keyed by
|
units |
Named character vector keyed by |
shrinkage |
Shrinkage calculation method, one of
The recompute paths ( |
digits |
Optional significant-digits count. When non- |
append_flag |
When |
emit_advisories |
When |
x |
A |
... |
Further arguments passed to the underlying tibble print method. |
Details
Default transforms per section:
Fixed effects:
raw.Random effects (omegas):
lognormal_cv, defined as100 \sqrt{\exp(\omega^2) - 1}, where\omega^2is the variance stored inprmTable$value.Residual error (sigmas):
multiplicative_cv(100\sigma). This default is applied uniformly to every sigma, regardless of the error-model shape declared in PML – and choosing the wrong scale doesn't correct itself, it just mislabels the number. For purely additive or combined error models the %CV label is misleading – override withtransform = list(<sigma> = "raw")(the engine reports the residual error as a standard deviation) or a customfn.When the PML source is available, each sigma's shape is inferred directly from its
observe()expression by differentiating it with respect to the error variable (base R'sstats::D()) and checking whether that derivative is a constant (additive error) or proportional to the noise-free prediction with no curvature (proportional error – the one shapemultiplicative_cvis exact for). This inference is syntax-only and best-effort: it works directly on whatever PML thexpdbhappens to embed, without assuming it came from any particular model-building tool. The advisory message is skipped only when every defaulted sigma is proven proportional; it fires for additive error, for any other non-proportional shape (combined, power, ...), and whenever the shape can't be determined at all (a function outsideD()'s derivative table, unusual syntax, or no PML source) – in that last case the safer default is to warn rather than assume. An extra per-sigma warning fires for any sigma whose inferred role is additive or otherwise non-proportional. Setemit_advisories = FALSEto silence both the message and the per-sigma warnings, oroptions(xposeNlme.summary.quiet_default_warning = TRUE)to silence only the message.get_bootSummaryNlme()'sbootResult-only and embedded-fitSummaryinput modes have no PML to check either, so they inherit this same "no PML source" behaviour: the default message always fires for a defaulted sigma, while the per-sigma warning (which needs a known shape to name) stays silent.Secondary:
raw.
Built-in preset catalog:
Fixed effects:
raw(customfnalways available).Random effects:
raw,lognormal_cv,normal_sd.normal_sdreturns the standard deviation\sqrt{\Omega}(i.e.fn = sqrt(value)), not the variance.Residual error:
raw,log_additive_cv,multiplicative_cv.log_additive_cvis100 \sqrt{\exp(\sigma^2) - 1}andmultiplicative_cvis100\sigma.
Custom transform spec:
transform = list(<label> = list(fn = function(x) ..., dfn = function(x) ..., name = ...)).
dfn is optional; when omitted, %RSE falls back to the raw scale and a
single warning per call lists the affected parameters. name is the
optional scale flag appended to the parameter name; a custom transform
supplied without name triggers a warning and leaves the name unflagged.
Scale flag and units: when a non-identity transform is active the scale
label is appended to Parameter in parentheses – nV (CV%),
CEps (SD), or the custom name. Identity / raw rows keep the bare
name. The Unit column carries physical units only (user units or the
model's structural-parameter units) and is dropped when every row is
dimensionless.
Off-diagonal omega/sigma rows are excluded entirely. transform and
units are keyed by prmTable$label (the PML-source name – tvCl,
nV, CEps); names not present among the labels emit a single warning
per call and are ignored.
Value
A tibble (class summaryNlme) with columns Section,
Parameter (carrying a (CV%) / (SD) / custom scale flag when a
non-identity transform is active), Estimate, %RSE, Shrinkage (%),
and – only when at least one row resolves to a non-empty physical
unit – Unit. The summaryNlme class carries a print method that honours
the digits argument for displayed precision.
See Also
get_prmNlme(), get_overallNlme(), get_etaSubjectNlme()
Examples
## Not run:
# 1) Default output on a log-normal IIV + proportional error model.
xp <- xposeNlmeModel(fit)
get_summaryNlme(xp)
# 2) Per-parameter override on an additive error model. The engine
# reports residual error as a standard deviation, so `raw` shows the
# SD directly (no misleading %CV flag).
get_summaryNlme(
xp,
transform = list(EEps = "raw"),
units = list(EEps = "ng/mL")
)
# 3) Custom transform for combined add-mult error.
get_summaryNlme(
xp,
transform = list(
CEps = list(
fn = function(s) 100 * s,
dfn = function(s) 100
)
)
)
## End(Not run)
Create covariates scatterplot
Description
Use to create covariates scatterplot.
Usage
nlme.cov.splom(
xpdb,
covColNames,
ggupper = list(continuous = "cor", combo = "box_no_facet", discrete = "count", na =
"na"),
gglower = list(continuous = GGally::wrap("smooth", alpha = 0.3, size = 0.1), combo =
"facethist", discrete = "facetbar", na = "na"),
ggdiag = list(continuous = "densityDiag", discrete = "barDiag", na = "naDiag"),
...
)
Arguments
xpdb |
An xpose database object. |
covColNames |
Character vector of covariates to build the matrix |
ggupper |
See |
gglower |
See |
ggdiag |
See |
... |
Parameters to be passed to |
Value
ggmatrix object.
Examples
nlme.cov.splom(xpdb = xpdb_ex_Nlme,
covColNames = c("sex", "wt", "age")
)
Plot parameter estimates against covariates
Description
Use to create a stack of plots of parameter estimates plotted against covariates.
Usage
nlme.par.vs.cov(xpdb, covColNames, nrow = 1, ncol = 1, ...)
Arguments
xpdb |
An xpose database object. |
covColNames |
Character vector of covariates to build the matrix. |
nrow |
Number of rows. |
ncol |
Number of columns; if ncol=1, each gtable object is treated separately. |
... |
Parameters to be passed to |
Value
List of gtable
Examples
nlme.par.vs.cov(
xpdb = xpdb_ex_Nlme,
covColNames = c("sex", "wt", "age")
)
Plot random parameter estimates against covariates
Description
Use to create a stack of plots of random parameter estimates plotted against covariates.
Usage
nlme.ranpar.vs.cov(xpdb, covColNames, nrow = 1, ncol = 1, ...)
Arguments
xpdb |
An xpose database object. |
covColNames |
Character vector of covariates to build the matrix. |
nrow |
Number of rows. |
ncol |
Number of columns; if ncol=1, each gtable object is treated separately. |
... |
Parameters to be passed to |
Value
List of gtable
Examples
nlme.ranpar.vs.cov(xpdb = xpose::xpdb_ex_pk,
covColNames = c("SEX", "CLCR", "AGE")
)
Build multiple plots for selected variable vs covariates
Description
The type of plot depends on the type of covariate: boxplot for categorical, geom_point and geom_smooth for continuous.
Usage
nlme.var.vs.cov(xpdb, covColNames, nrow = 1, ncol = 1, yVar = "WRES", ...)
Arguments
xpdb |
An xpose database object. |
covColNames |
Character vector of covariates to build the matrix. |
nrow |
Number of rows. |
ncol |
Number of columns; if ncol=1, each gtable object is treated separately. |
yVar |
Variable from xpdb data to build a plot. |
... |
Parameters to be passed to |
Value
List of gtable
Examples
nlme.var.vs.cov(
xpdb = xpdb_ex_Nlme,
covColNames = c("sex", "wt", "age"),
yVar = "WRES",
nrow = 2,
ncol = 2
)
Parameter vs covariate Plot
Description
Plot Parameters against a continuous or categorical covariate.
Usage
prm_vs_cov(
xpdb,
covariate,
mapping = NULL,
drop_fixed = FALSE,
group = "ID",
type = "bpls",
title = "Parameters vs @x | @run",
subtitle = "Based on @nind individuals",
caption = "@dir",
tag = NULL,
log = NULL,
guide = FALSE,
onlyfirst = FALSE,
facets,
.problem,
quiet,
...
)
Arguments
xpdb |
An xpose database object. |
covariate |
Character; String of covariate name |
mapping |
List of aesthetics mappings to be used for the xpose plot
(e.g. |
drop_fixed |
Logical; logic specifying whether structural parameters having same value for the given covariate value should be removed from plotting |
group |
Grouping variable to be used for lines. |
type |
Character; String setting the type of plot to be used. Must be 'b' for categorical covariates, one or a combination of 'p','l','s' for continuous covariates. |
title |
Character; Plot title. Use |
subtitle |
Character; Plot subtitle. Use |
caption |
Character; Page caption. Use |
tag |
Character; Plot identification tag. Use |
log |
Character; String assigning logarithmic scale to axes, can be either ”, 'x', y' or 'xy'. |
guide |
Logical; Enable guide display (e.g. unity line). |
onlyfirst |
Logical; Should the data be filtered to retain first value for each group/facet. |
facets |
Either a character string to use |
.problem |
The $problem number to be used. By default returns the last estimation problem. |
quiet |
Logical, if |
... |
Any additional aesthetics to be passed on |
Value
An object of class xpose_plot, ggplot, and gg. This object represents a customized plot created using ggplot2.
The xpose_plot class provides additional metadata and integration with xpose workflows, allowing for advanced
customization and compatibility with other xpose functions. Users can interact with the plot object as they
would with any ggplot2 object, including modifying aesthetics, adding layers, or saving the plot.
Layers mapping
Plots can be customized by mapping arguments to specific layers. The naming convention is layer_option where layer is one of the names defined in the list below and option is any option supported by this layer e.g. boxplot_fill = 'blue', etc.
box plot: options to
geom_boxplotpoint plot: options to
geom_pointline plot: options to
geom_linesmooth plot: options to
geom_smoothxscale: options to
scale_x_continuousorscale_x_log10yscale: options to
scale_y_continuousorscale_y_log10
See Also
Examples
prm_vs_cov(xpose::xpdb_ex_pk,
covariate = "AGE", type = "ps",
log = "y",
yscale_breaks = scales::trans_breaks("log10", function(x) 10^x),
yscale_labels = scales::trans_format("log10", scales::math_format(10^.x)),
caption = NULL
)
prm_vs_cov(xpose::xpdb_ex_pk,
covariate = "SEX",
type = "b",
boxplot_fill = "blue",
boxplot_color = "black",
boxplot_outlier.color = "red"
)
Residuals vs covariate plot
Description
Plot Residuals against a continuous or categorical covariate.
Usage
res_vs_cov(
xpdb,
mapping = NULL,
covariate,
res = "CWRES",
group = "ID",
type = "bpls",
title = "Residuals vs @x | @run",
subtitle = "Based on @nind individuals",
caption = "@dir",
tag = NULL,
log = NULL,
guide = TRUE,
facets,
.problem,
quiet,
...
)
Arguments
xpdb |
An xpose database object. |
mapping |
List of aesthetics mappings to be used for the xpose plot
(e.g. |
covariate |
Character; String of covariate name |
res |
Character; String of residual name; CWRES by default. |
group |
Grouping variable to be used for lines. |
type |
Character; String setting the type of plot to be used. Must be 'b' for categorical covariates, one or a combination of 'p','l','s' for continuous covariates. |
title |
Character; Plot title. Use |
subtitle |
Character; Plot subtitle. Use |
caption |
Character; Page caption. Use |
tag |
Character; Plot identification tag. Use |
log |
Character; String assigning logarithmic scale to axes, can be either ”, 'x', y' or 'xy'. |
guide |
Logical; Should the guide (e.g. reference distribution) be displayed. |
facets |
Either a character string to use |
.problem |
The $problem number to be used. By default returns the last estimation problem. |
quiet |
Logical, if |
... |
Any additional aesthetics to be passed on |
Value
An object of class xpose_plot, ggplot, and gg. This object represents a customized plot created using ggplot2.
The xpose_plot class provides additional metadata and integration with xpose workflows, allowing for advanced
customization and compatibility with other xpose functions. Users can interact with the plot object as they
would with any ggplot2 object, including modifying aesthetics, adding layers, or saving the plot.
Layers mapping
Plots can be customized by mapping arguments to specific layers. The naming convention is
layer_option where layer is one of the names defined in the list below and option is
any option supported by this layer e.g. boxplot_fill = 'blue', etc.
box plot: options to
geom_boxplotpoint plot: options to
geom_pointline plot: options to
geom_linesmooth plot: options to
geom_smoothxscale: options to
scale_x_continuousorscale_x_log10yscale: options to
scale_y_continuousorscale_y_log10
See Also
Examples
res_vs_cov(xpose::xpdb_ex_pk,
covariate = "SEX",
type = "b",
res = "WRES"
)
res_vs_cov(xpose::xpdb_ex_pk,
covariate = "AGE",
type = "ps",
res = c("CWRES", "WRES", "IRES", "IWRES")
)
Update ETA shrinkage with subject-level filtering
Description
Recomputes overall ETA shrinkage from stored subject-by-ETA
data, applying threshold-based filtering to remove subjects whose
individual shrinkage is too close to 1 (variance form). Returns an
updated xpdb with the etashk summary row replaced.
Usage
update_etaShrinkageNlme(
xpdb,
threshold = 1e-06,
eta_threshold = NULL,
eta_name = NULL,
.problem = 1
)
Arguments
xpdb |
An |
threshold |
Global default threshold applied to all ETAs
(default |
eta_threshold |
Optional named numeric vector overriding
|
eta_name |
Optional character vector selecting a subset of ETAs to recompute. ETAs not listed keep their current summary values. |
.problem |
Problem number (default |
Value
A new xpdb with the etashk value in
xpdb$summary updated.
XposeNlme example xpose_data object
Description
An example xpose::xpose_data object for use in examples
and tests. It holds a one-compartment (Clearance-parameterized) PK model with
three covariates, fit with Phoenix NLME (phx/nlme) and imported via
xposeNlmeModel().
Format
An xpose::xpose_data object.
Details
The model was built from the real Certara.RsNLME::pkData
dataset (16 subjects, 112 observations, single bolus dose) using a
clearance-parameterized one-compartment model with a proportional residual
error, diagonal random effects on V and Cl, and the covariates
age and wt (continuous) plus sex (categorical:
male/female). Roughly reproduced with:
library(Certara.RsNLME)
model <- pkmodel(
parameterization = "Clearance",
numCompartments = 1,
data = pkData,
ID = "Subject",
Time = "Act_Time",
A1 = "Amount",
CObs = "Conc",
workingDir = tempdir()
) |>
addCovariate("age") |>
addCovariate("wt") |>
addCovariate("sex", type = "Categorical",
levels = c(0, 1), labels = c("male", "female")) |>
colMapping(age = "Age", wt = "BodyWeight", sex = "Gender")
Examples
print(xpdb_ex_Nlme)
Default xpose box plot function
Description
Manually generate categorical covariate box plots against eta.
Usage
xplot_box(
xpdb,
mapping = NULL,
type = "b",
guide = FALSE,
yscale = "continuous",
title = NULL,
subtitle = NULL,
caption = NULL,
tag = NULL,
plot_name = "box_plot",
gg_theme,
xp_theme,
opt,
quiet,
...
)
Arguments
xpdb |
An xpose database object. |
mapping |
List of aesthetics mappings to be used for the xpose plot
(e.g. |
type |
String setting the type of plot to be used. Only 'b' applicable. |
guide |
Enable guide display (e.g. unity line). |
yscale |
Scale type for y axis (e.g. 'continuous', 'discrete', 'log10'). |
title |
Plot title. Use |
subtitle |
Plot subtitle. Use |
caption |
Page caption. Use |
tag |
Plot identification tag. Use |
plot_name |
Name to be used by |
gg_theme |
A complete ggplot2 theme object (e.g.
|
xp_theme |
A complete xpose theme object (e.g.
|
opt |
A list of options in order to create appropriate data input for
ggplot2. For more information see |
quiet |
Logical, if |
... |
Any additional aesthetics to be passed on |
Value
An object of class xpose_plot, ggplot, and gg. This object represents a customized plot created using ggplot2.
The xpose_plot class provides additional metadata and integration with xpose workflows, allowing for advanced
customization and compatibility with other xpose functions. Users can interact with the plot object as they
would with any ggplot2 object, including modifying aesthetics, adding layers, or saving the plot.
Faceting
Every xpose plot function has built-in faceting functionalities. Faceting arguments
are passed to the functions facet_wrap_paginate when the facets
argument is a character string (e.g. facets = c('SEX', 'MED1')) or
facet_grid_paginate when facets is a formula (e.g. facets = SEX~MED1).
All xpose plot functions accept all the arguments for the facet_wrap_paginate
and facet_grid_paginate functions e.g. dv_vs_ipred(xpdb_ex_pk,
facets = SEX~MED1, ncol = 3, nrow = 3, page = 1, margins = TRUE, labeller = 'label_both').
Faceting options can either be defined in plot functions (e.g. dv_vs_ipred(xpdb_ex_pk,
facets = 'SEX')) or assigned globally to an xpdb object via the xp_theme (e.g. xpdb
<- update_themes(xpdb_ex_pk, xp_theme = list(facets = 'SEX'))). In the latter example all plots
generate from this xpdb will automatically be stratified by SEX.
By default, some plot functions use a custom stratifying variable named variable, e.g.
eta_distrib(). When using the facets argument, variable needs to be added manually
e.g. facets = c('SEX', 'variable') or facets = c('SEX', 'variable'), but is optional,
when using the facets argument in xp_theme variable is automatically added whenever needed.
Layers mapping
Plots can be customized by mapping arguments to specific layers. The naming convention is layer_option where layer is one of the names defined in the list below and option is any option supported by this layer e.g. boxplot_fill = 'blue', etc.
box plot: options to
geom_boxplotyscale: options to
scale_y_continuousorscale_y_log10
See Also
Examples
# Categorical Covariate MED1 vs ETA1
xplot_box(xpose::xpdb_ex_pk, ggplot2::aes(x = MED1, y = ETA1))
# Categorical Covariate SEX vs CL
xplot_box(xpose::xpdb_ex_pk, ggplot2::aes(x = SEX, y = CL))
Creates xpose database from Certara.RsNLME output files
Description
Imports results of an NLME run into xpose database
Use to import NLME model output files into xpdb object that is compatible
with existing model diagnostic function in Xpose package.
Usage
xposeNlme(
dir = "",
modelName = "",
dmpFile = "dmp.txt",
dmp.txt = NULL,
dataFile = "data1.txt",
logFile = "nlme7engine.log",
ConvergenceData = NULL,
progresstxt = NULL
)
Arguments
dir |
Path to NLME Run directory. Current working directory is used if |
modelName |
name of the model to be written in |
dmpFile |
NLME generated output file. |
dmp.txt |
NLME generated output from dmpFile (substitutes dmpFile if presented). |
dataFile |
Input file for NLME Run. |
logFile |
engine log file |
ConvergenceData |
optional convergence info, as either a data frame
(the long-format |
progresstxt |
optional NLME-generated |
Details
Not all functionality from the xpose package is supported.
Bootstrap working directories are not a supported xposeNlme()
source: artifacts may be overwritten or replicate-concatenated
(dmp.txt, progress.txt). When bootstrap markers are
detected (Boot*.csv, bootstrap_nlme7engine.log,
bootstrap_*.rds):
last-replicate
dmp.txttypically has noresidualstable and noresiduals.csv– import stops with a message pointing atget_bootSummaryNlme;if a residuals table is already present (embedded or leftover
residuals.csvfrom a priorfitmodel()), import continues after a warning. Those CSVs may belong to a different fit (including different initial estimates, orbootstrap(..., overwriteFitDir = TRUE)that overwrotedmp.txtwithout replacing the CSVs). GOF is not the bootstrap last replicate.
For bootstrap parameter summaries, use
get_bootSummaryNlme on the bootstrap() return
value (not this directory). For GOF / convergence plots, import the
original fit with xposeNlme() on the fit folder or
xposeNlmeModel on the fit result.
Run metadata is stored in the summary tibble of the returned
xpdb object (xpdb$summary, or rendered with
summary(xpdb)). On this file-based entry point, every metadata row
beyond the long-standing descr/ofv/method/runtime
set is parsed from nlme7engine.log only – ode_solver,
stderr_algorithm, stderr_method, xnorderagq, and
fastOptimization appear when the log records them (missing fields
are silently omitted, never an error), and the method row
discriminates FOCE-ELS from LAPLACIAN using the log's Hessian-variant
flag. stderr_algorithm and stderr_method are both omitted
entirely for IT2S-EM (which cannot estimate standard errors);
xnorderagq and fastOptimization only ever appear for
FOCE-ELS/LAPLACIAN, and xnorderagq is further
omitted when the log shows OuterAD (which forces the adaptive
Gaussian quadrature order to 1 internally). epsshk/etashk
are likewise omitted when not applicable (no residual-error model / the
NAIVE-POOLED method, respectively).
xposeNlme() deliberately never reads rtol, atol, or
nmxstep (not written to the engine log), never reads
runtime_wallclock, RsNLMEVersion, timestart, or
timestop (only known to Certara.RsNLME at fit time, not to the
engine).
Arguments files are intentionally not read, because requested settings can
differ from the engine run.
Value
xpdb object
See Also
xposeNlmeModel, get_bootSummaryNlme
Examples
## Not run:
# files in arguments supposed to be in the current working directory;
# ConvergenceData.csv (if present) is picked up automatically:
xp <- xposeNlme(
dir = getwd(),
modelName = "PMLModel",
dmpFile = "dmp.txt",
dataFile = "data1.txt",
logFile = "nlme7engine.log"
)
# SCM / Phoenix folders that retain progress.txt but not
# ConvergenceData.csv:
xp <- xposeNlme(
dir = "~/scm_archive/cstep000__0",
modelName = "Base",
dataFile = "../data1.txt",
progresstxt = "progress.txt"
)
# using dmp.txt structure and Convergence Data loaded previously:
xp <- xposeNlme(
dir = "~/Model1/",
modelName = "Model1",
dmp.txt = dmp.txt,
dataFile = "Data.csv",
logFile = "nlme7engine.log",
ConvergenceData = ConvergenceData
)
# explore unique covariate plots specific to Certara.Xpose.NLME:
nlme.cov.splom(xp, covColNames = c("AGE", "WT"))
nlme.par.vs.cov(xp, covColNames = c("AGE", "WT"))
res_vs_cov(xp, covariate = "AGE", res = "IWRES")
# or use existing plotting functions from the xpose package
library(xpose)
dv_vs_pred(xp)
res_vs_idv(xp)
## End(Not run)
Creates xpose database from Certara.RsNLME objects
Description
Imports results of an NLME run into xpose database
Use to import NLME model object and NLME object output
into xpdb object that is compatible
with existing model diagnostic function in Xpose package.
Usage
xposeNlmeModel(model, fitmodelOutput)
Arguments
model |
NlmePmlModel model class object generated by |
fitmodelOutput |
the output object of |
Details
Not all functionality from the xpose package is supported.
Run metadata is stored in the summary tibble of the returned
xpdb object. Access it directly with xpdb$summary or render it
to the console with summary(xpdb). This is distinct from
get_overallNlme(), which returns the Overall.csv
fit-statistics table (objective function, AIC, BIC, and similar).
When fitmodelOutput is a self-describing fit that carries
$params, $runTime, and/or $RsNLMEVersion, the
summary tibble gains additional rows: ode_solver,
rtol, atol, nmxstep, stderr_algorithm,
stderr_method, xnorderagq, fastOptimization,
runtime_wallclock, and RsNLMEVersion, plus timestart /
timestop at the global problem. stderr_algorithm is the
standard-error algorithm (Hessian / Sandwich / Fisher Score /
Auto-Detect / None); stderr_method is the finite-difference scheme
used for the standard-error computation (params@xstderr: none /
central-difference / forward-difference) and is shown when the
finite-difference flag is nonzero (IFLAGSTDERR /
params@xstderr), even if the algorithm name could not be resolved
(e.g. Auto-Detect with no resolution prose). Both SE rows are omitted for
IT2S-EM, which cannot estimate standard errors. xnorderagq and fastOptimization only ever appear for
FOCE-ELS/LAPLACIAN; xnorderagq is further omitted
when the engine actually ran with OuterAD (which forces the
adaptive Gaussian quadrature order to 1 internally).
ode_solver, stderr_algorithm, and fastOptimization
always reflect the engine's actual run (preferring
nlme7engine.log over the params request whenever the log
has the relevant flag) – params is only used as a fallback when
the log lacks the flag (e.g. no log file at all).
The file-based xposeNlme(dir = ...) entry point recovers
ode_solver, stderr_algorithm, stderr_method,
xnorderagq, and fastOptimization from nlme7engine.log
when the log records them, but never rtol, atol,
nmxstep, runtime_wallclock, RsNLMEVersion,
timestart, or timestop – those are not written to the
engine log, only resolved by Certara.RsNLME at fit time.
xposeNlme() also never reads args/params files (for example
nlmeargs.txt, jobArgsCombined.txt, jobControlFile.txt):
those record requested settings, which can go stale relative to what the
engine actually ran, so surfacing them in xp$summary would be
misleading. See xposeNlme for the full file-path contract.
The runtime row reports engine-reported CPU time, which sums across
workers and can exceed the actual wait on multi-core runs;
runtime_wallclock reports the elapsed wall-clock time from
fitmodelOutput$runTime$elapsed and is generally smaller on multi-core
runs.
Value
xpdb object
Examples
## Not run:
library(Certara.RsNLME)
library(Certara.Xpose.NLME)
model <- pkmodel(
parameterization = "Clearance",
numCompartments = 2,
data = pkData,
ID = "Subject",
Time = "Act_Time",
A1 = "Amount",
CObs = "Conc"
)
fit <- fitmodel(model)
# Two-argument form (works with all RsNLME versions):
xp <- xposeNlmeModel(model = model, fitmodelOutput = fit)
# One-argument form (RsNLME with self-describing fitmodel output):
xp <- xposeNlmeModel(fit)
## End(Not run)
Build the Certara.Xpose.NLME MCP tool set
Description
Returns a list of ellmer::tool() objects for the Certara.R MCP host. This
is the builder referenced by inst/mcp/tools/manifest.json. The host calls
it with the launch profile's provider groups; tools whose group is not
requested are omitted.
Usage
xpose_mcp_tools(groups = c("data", "interpretation", "comparison"))
Arguments
groups |
Character vector of tool groups to include. One or more of
|
Value
A list of ellmer::tool() objects (empty list when ellmer is not
installed or no group matches).
Examples
## Not run:
tools <- xpose_mcp_tools()
tools <- xpose_mcp_tools(groups = c("data", "interpretation"))
## End(Not run)