| Title: | Pharmacometric Modeling |
| Version: | 3.2.0 |
| Description: | Facilitate Pharmacokinetic (PK) and Pharmacodynamic (PD) modeling and simulation with powerful tools for Nonlinear Mixed-Effects (NLME) modeling. The package provides access to the same advanced Maximum Likelihood algorithms used by the NLME-Engine in the Phoenix platform. These tools support a range of analyses, from parametric methods to individual and pooled data, and support integrated use within the Pirana pharmacometric workbench <doi:10.1002/psp4.70067>. Execution is supported both locally or on remote machines. |
| Depends: | R (≥ 4.0) |
| License: | LGPL-3 |
| URL: | https://certara.github.io/R-RsNLME/ |
| Encoding: | UTF-8 |
| LazyData: | true |
| Suggests: | rlang, knitr, rmarkdown, testthat, magrittr, ellmer (≥ 0.4.0), callr (≥ 3.7.0), ps (≥ 1.7.0), withr, digest, curl, flextable |
| Imports: | xml2, assertthat, Certara.NLME8 (≥ 3.2.0), data.table, jsonlite, methods, utils, ssh |
| Collate: | 'NlmePmlModelInfo.R' 'NlmeRandParamsMapping.R' 'NlmeParamsMapping.R' 'NlmeDoseMapping.R' 'NlmeEmaxParameters.R' 'NlmeIndirectParameters.R' 'NlmeModelAbsorption.R' 'NlmeModelParameterization.R' 'NlmePkParameters.R' 'NlmeModelType.R' 'NlmeDataset.r' 'NlmeColumnMapping.r' 'error_model.r' 'NlmeRandomEffectBlock.r' 'pml_model.r' 'BootstrapParams.R' 'NlmeParallelMethod.R' 'NlmeUserAuthentication.R' 'NlmeParallelHost.R' 'nlme_job_helpers.R' 'SimpleNlmeJob.R' 'BootNlmeJob.R' 'CovariateEffectModel.R' 'engine_params.r' 'FitNlmeJob.R' 'GenerateControlfile.R' 'GenerateParamsfile.R' 'NlmeCovariateParameter.r' 'NlmeRemoteExecutor.R' 'NlmeScenario.R' 'NlmeTableDef.R' 'SortColumns.R' 'ProfileParameters.R' 'ProfileNlmeJob.R' 'ProfileVar.R' 'RandomEffectsMethods.R' 'ShotgunNlmeJob.R' 'SortByNlmeJob.R' 'StepwiseParams.R' 'StepwiseNlmeJob.R' 'acceptAllEffects.R' 'addInfusion.R' 'addLabel.R' 'addTablesToColumnMapping.R' 'add_input_dosingCycles.R' 'scmArchiveHelpers.R' 'readFitSummary.R' 'jobCollectionHelpers.R' 'loadBootstrapResult.R' 'bootstrap.r' 'bootstrapPrint.R' 'built_in_models.r' 'cad_auth.R' 'checkHostParams.R' 'colMapping.R' 'colMapping_validate.R' 'profilePrint.R' 'profile_estimation.r' 'scmPrint.R' 'fitmodelHelperFunctions.R' 'vpc.r' 'collectJob.R' 'copyModel.R' 'cov_validators.R' 'covariateModel.R' 'covariateNames.R' 'createInitialMapping.R' 'create_metamodel_from_model.R' 'create_model_from_metamodel.R' 'create_model_info.R' 'data.r' 'dosing.r' 'editModel.R' 'emaxmodel.R' 'extract_mmdl.R' 'fitmodel.R' 'fitmodelPrint.R' 'fixedEffect.R' 'formatOutputForPirana.R' 'generateCovarSearchArgsFile.R' 'getThetas.R' 'get_omega_omegaSE.R' 'globals.R' 'hostParams.R' 'imputeMissingCovariates.R' 'isPopulation.R' 'job.r' 'jobLaunchHelpers.R' 'linearmodel.R' 'log_Execution.R' 'map_covariates.R' 'map_dosepoints.R' 'mcp_analysis_plan.R' 'mcp_blq.R' 'mcp_bootstrap_summary.R' 'mcp_compare.R' 'mcp_covariate_search.R' 'mcp_data.R' 'mcp_deps.R' 'mcp_execution.R' 'mcp_fit_spec.R' 'mcp_literature.R' 'mcp_mmdl_scaffold.R' 'mcp_model_inspect.R' 'mcp_nonmem.R' 'mcp_ofv_parity.R' 'mcp_perf.R' 'mcp_provider_runtime.R' 'mcp_qc_readiness.R' 'mcp_repro_hooks.R' 'mcp_scm_summary.R' 'mcp_sequential_lrt.R' 'mcp_textual_inspect.R' 'mcp_tools_register.R' 'mcp_update_parameters.R' 'mcp_validate.R' 'mcp_vpc_summary.R' 'mcp_workflow.R' 'mmdl_io.R' 'modelVariableNames.R' 'model_designer.R' 'null_default.R' 'observation.r' 'obtain_NLMELicense.R' 'parameterNames.R' 'parseControlFile.R' 'parsePMLColMap.R' 'parse_mmdl.R' 'pkemaxmodel.R' 'pkindirectmodel.R' 'pklinearmodel.R' 'pkmodel.R' 'randomEffect.R' 'run_metamodel.R' 'saveModel.R' 'saveUpdatedMetamodel.R' 'scmAccess.R' 'scmSearchTable.R' 'scmSummary.R' 'secondary_variable.r' 'shotgunSearch.R' 'simParams.R' 'sortfit.R' 'stepwiseSearch.R' 'structural_param.r' 'tableParams.R' 'update_PMLwithThetas.R' 'update_parameters.R' 'writeColumnMapping.R' 'writeDefaultFiles.R' |
| Config/roxygen2/version: | 8.1.0 |
| NeedsCompilation: | no |
| Packaged: | 2026-09-14 19:59:40 UTC; jcraig |
| Author: | James Craig [aut, cre], Michael Tomashevskiy [aut], Vitalii Nazarov [aut], Shuhua Hu [ctb], Fred Soltanshahi [aut], Certara USA, Inc. [cph, fnd] |
| Maintainer: | James Craig <james.craig@certara.com> |
| Repository: | CRAN |
| Date/Publication: | 2026-09-15 02:20:41 UTC |
Create a self-contained per-run SCM folder from NLME8 archive output.
Description
For local runs, renames the SCM_<runId>/ directory into the final
timestamped folder. For remote runs, materialises the run folder from
the SCM_<runId>.tar.gz bundle and removes both the bundle and any
loose SCM_<runId>/ directory that the remote retrieve downloaded
alongside it. If the bundle is missing but the loose directory is
present (abnormal: NLME8 bundling step failed), warns and falls back to
the local rename path so the user still gets a usable run folder.
Saves the base model and run-context (resolved engine params, package
version, runMode, wall-clock runTime) into a single
rsnlme_run.rds for self-contained archive recovery.
Usage
.archiveScmRunFolder(
cwd,
runId,
searchType,
isRemote,
model,
params = NULL,
runMode = NULL,
runTime = NULL,
selectionCriterion = NULL
)
Arguments
cwd |
Model working directory. |
runId |
The SCM run ID (matches |
searchType |
|
isRemote |
Logical; TRUE for remote runs. |
model |
The base |
params |
Resolved |
runMode |
One of |
runTime |
Wall-clock timing list |
Value
Path to the created run folder, or NULL on failure.
Derive the user-facing fastOptimization mode from internal AD slots.
Description
Derive the user-facing fastOptimization mode from internal AD slots.
Usage
.fastOptimization_mode(x)
Arguments
x |
An |
Value
FALSE or a character string ("InnerAD",
"HessianAD", "OuterAD").
Back-compat alias for is_cov_numeric_value()
Description
Several internal call sites still use the dotted name. Kept as a thin alias.
Usage
.is_numeric(x)
Arguments
x |
Atomic vector of covariate values; |
Value
Logical vector.
Load fitmodel-compatible results from an archived SCM scenario folder.
Description
Reads the archived raw files and assembles a list structure compatible
with the output of fitmodel() / xposeNlmeModel().
Usage
.loadScmFitResults(scenarioDir)
Arguments
scenarioDir |
Path to the scenario subfolder inside the run archive. |
Value
A named list compatible with fitmodel() output.
QRPEM compatibility check for time-varying covariates inside stparm()
Description
Synchronous, engine-free. Returns structured issues when method is QRPEM
(or IMPEM), a mapped covariate has multiple values within at least one
subject, and that covariate is referenced on the RHS of a stparm()
statement. A corrected split model (covariate only in a body assignment)
returns no errors. When method is omitted or cannot be resolved, the check
assumes the engineParams() default, which is never QRPEM (FOCE-ELS or
Laplacian for population models, Naive-Pooled otherwise) - so an omitted
method never blocks here; pass method explicitly to check a QRPEM fit.
Nonlinear covariate forms inside stparm() can also fail under QRPEM even
when subject-constant; that case is not auto-detected here (see the KB
antipattern).
Usage
.mcp_qrpem_time_varying_covariate_check(model, method)
Arguments
model |
An |
method |
Estimation method name, numeric engine code, or
|
Value
A list with ok, checked, errors (character messages), and
issues (structured rows).
Normalize the conditionNumber argument of engineParams() to an
xcondmode integer code.
Description
Normalize the conditionNumber argument of engineParams() to an
xcondmode integer code.
Usage
.normalizeConditionNumber(conditionNumber)
Arguments
conditionNumber |
Character vector; either the full default choices vector (unmodified call, resolves to the first/default choice) or a single canonical name. |
Value
Integer xcondmode code (0-3).
Parse a dmp.txt file into the structured R object used by fitmodel/Xpose.
Description
Parse a dmp.txt file into the structured R object used by fitmodel/Xpose.
Usage
.parseDmpFile(dmpFilePath, stripLargeFields = TRUE, warnMissing = TRUE)
Arguments
dmpFilePath |
Path to the dmp.txt file. |
stripLargeFields |
If |
warnMissing |
If |
Value
The parsed dmp.txt R object, or NULL on failure.
Parse a "ParamName-CovName" string into its components.
Description
Parse a "ParamName-CovName" string into its components.
Usage
.parseEffectPair(effectString)
Value
A list with paramName and covName, or NULL.
Parse enable IDs from a comma-separated string or numeric vector.
Description
Parse enable IDs from a comma-separated string or numeric vector.
Usage
.parseEnableIDs(ids)
Arguments
ids |
A numeric vector or a comma-separated character string of
enable IDs (e.g., |
Value
An integer vector of enable IDs, or integer(0) if
ids is empty or cannot be parsed.
Build a compact fit summary from a working directory.
Description
Reads dmp.txt and nlme7engine.log from workingDir
and returns a seven-column data frame (Parameter, Type,
Estimate, SE, %RSE, Shrinkage,
Diagonal) describing the prior fit's fixed effects, omega
variances and block covariances, and sigma diagonals at raw scale.
Diagonal is TRUE for thetas, sigmas, secondaries, and
omega variances, and FALSE for omega off-diagonal covariances;
downstream consumers use it to keep covariances out of transformed,
variance-scale summaries.
Usage
.readFitSummary(workingDir)
Arguments
workingDir |
Path to the directory holding |
Details
Failure / degradation policy (deliberately gracefully degraded relative to an all-or-nothing rule):
-
dmp.txtmissing or unparseable – returnsNULLwith a single warning. Callers must treatNULLas "no embedded fit summary" rather than as a failure. -
nlme7engine.logmissing or unreadable – returns the full data frame withShrinkage = NAfor every row, plus a single warning naming the missing/unreadable file. TheEstimate/SE/%RSEcolumns come fromdmp.txtalone and stay valid. -
nlme7engine.logpresent and readable but contains zeroeta-shrinkage/Epsilon shrinkage forlines – silent. This is the legitimate state forLL()observation models, naive-pooled fits, and any other topology where the engine doesn't compute eta/eps shrinkage. Eta-shrinkage line count in the log doesn't match
length(colnames(dmp.txt$omega))– returns the data frame with NA-padding/truncation, plus a single warning (mirrorsCertara.Xpose.NLME::get_etaShrinkage's warning).
Value
A data frame with the columns above, or NULL when
dmp.txt is missing/unparseable.
Reconstruct a model for a given SCM scenario by disabling effects that are not in the scenario's active enable IDs.
Description
Reconstruct a model for a given SCM scenario by disabling effects that are not in the scenario's active enable IDs.
Usage
.reconstructScmModel(model, scenarioEnableIDs)
Arguments
model |
The base |
scenarioEnableIDs |
Comma-separated string (or integer vector) of active enable IDs for the target scenario. |
Value
A modified copy of the model with non-active effects disabled.
Require the MCP tool-builder dependency (ellmer) or stop with guidance
Description
Require the MCP tool-builder dependency (ellmer) or stop with guidance
Usage
.require_mcp_deps(packages = names(.mcp_dep_floors()))
Arguments
packages |
Character vector of required package names. |
Value
Invisibly TRUE when satisfied; otherwise stops.
Validate PML syntax for textual models before engine launch.
Description
Runs TDL5 -i (via createModelInfo()) to verify that the
PML in model@statements is syntactically valid. Returns
invisibly on success; stop()s with a descriptive message on
failure.
Usage
.validateTextualPml(model)
Arguments
model |
An |
Details
Built-in models (model@isTextual == FALSE) are always valid
(PML is generated by RsNLME) and skip this check immediately.
Value
NULL, invisibly.
Represents parameters for a bootstrap run
Description
Class initializer for BootstrapParams that represents parameters for a bootstrap run.
Slots
numReplicatesNumber of bootstrap replicates to run
initialEstimatesGet model final estimates to run bootstrap (T|F)
numRetriesNumber of times to retry a failed replicated
randomNumSeedSeed for random number generator
confidenceLevelConfidence level
stratifyColumnsWhat columns to stratify on(comma separated)
Examples
# same object as BootstrapParams()
boot <- BootstrapParams(
numReplicates = 100,
initialEstimates = FALSE,
numRetries = 2,
randomNumSeed = 1234,
confidenceLevel = 95
)
NLME covariate effects model object class
Description
Class represents an NLME covariate effects model
Slots
numCovariatesNumber of covariate effects
covariateListComma separated list of covariate effects names
scenarioNamesComma separated list of scenario names
isDefaultComma separated list of flags
degreesOfFreedomComma separated list of degrees of freedom
enableIDsComma separated list of enable() IDs from the model
Examples
CovariateEffectModel(numCovariates = 2,
covariateList = "V-Age,Cl-BW",
scenarioNames = "S,S",
isDefault = "1,1",
degreesOfFreedom = "1,1",
enableIDs = "0,1")
Creates an extra dose parameter
Description
Creates an extra dose parameter
Arguments
type |
ValueType|ColumnType |
value |
Value of dosing parameter |
column |
Name of column containing dose information |
Defines an extra dose point
Description
Defines an extra dose point
Slots
nameDose point name
typeCharacter; Options are "Bolus" or "Infusion"
amountOptional; Character specifying corresponding column in data or numeric specifying dose amount
rateOptional; Character specifying corresponding column in data or numeric specifying dose rate
deltaTimeOptional; Character specifying corresponding column in data or numeric specifying delta time
isSecondDoseUse second dose point on compartment?
dataOptional data frame. Must specify
dataif supplying column as character value toamount, rate, deltaTimearguments
Class represents map between a model variable and a dataset column
Description
Class represents map between a model variable and a dataset column
Arguments
variableName |
Model variable name |
columnName |
Corresponding column name in the dataset |
variableType |
Model variable type |
Class represents mapping list between model variables and dataset columns
Description
Class represents mapping list between model variables and dataset columns
Class represents an NLME Covariate parameter
Description
Class represents an NLME Covariate parameter
Arguments
name |
Name of covariate |
value |
Covariate value |
NlmeCovariateParameter
Description
Class represents an NLME Covariate parameter
Arguments
name |
Name of covariate parameter |
type |
Type of covariate parameter: Continuous|Category|Occasion |
direction |
Curve fitting method: Forward|Interpolate|Backward |
isDiagonal |
Is the structure diagonal (TRUE)| or box (FALSE) |
centerValue |
Covariate centering value |
isPositive |
Are the covariate values all positive |
continuousType |
Type of value to use for the centering value: CovarNumber|CovarMean|CovarMedian |
covarEffList |
List of covariate effects |
covarItems |
List of covariate items |
ranefFrozen |
Is the occasion random-effect section frozen?
Only meaningful for |
NLME dataset object
Description
Class represents an NLME dataset object
Arguments
dataFile |
Subject datafile |
colDefFile |
Datafile to model mapping file |
modelFile |
PML model file |
estimatesDefFile |
Initial estimates mapping file |
estimatesDataFile |
Initial estimates values |
doseDefFile |
Dose column definition file |
doseDataFile |
Dose datafile |
ranEffectDefFile |
Random effects column definition file |
ranEffectDataFile |
Random effects data file |
predoutFilename |
Name of predcheck output file |
phoenixSourceDir |
Directory containing phoenix generated files |
workingDir |
Directory containing datafiles(default cwd) |
Examples
dataset <- NlmeDataset(workingDir)
Class represents mapping list between model variables and dose columns
Description
Class represents mapping list between model variables and dose columns
Class represents an NLME/PML Emax model parameters
Description
Class represents an NLME/PML Emax model parameters
Arguments
checkBaseline |
Model has a baseline response |
checkFractional |
Model is fractional |
checkInhibitory |
Model is inhibitory |
checkSigmoid |
Model is sigmoidal |
Create a new NlmeEngineExtraParams object
Description
This function creates a new instance of the NlmeEngineExtraParams class
Usage
NlmeEngineExtraParams(...)
Arguments
... |
Named arguments to override the default values. |
Value
An object of class NlmeEngineExtraParams.
NlmeEngineExtraParams : Defines all engine parameters for NLME models
Wrapped up by engineParams function.
Description
NlmeEngineExtraParams : Defines all engine parameters for NLME models
Wrapped up by engineParams function.
Slots
isPopulationlogical; TRUE if the model is a population model, FALSE for an individual model.
sortcharacter; String to pass sorting options to the NLME engine. Typically " -sort " to enable sorting or "" to disable it.
csvcharacter; String to control CSV input options. Typically " -csv " to strict the input data to comma-separated-values. Use "" to disable it (NLME will try to guess the input format).
methodnumeric; Integer code specifying the estimation method.
1: QRPEM
2: IT2S-EM
3: FOCE-LB
4: FO
5: FOCE-ELS/LAPLACIAN (see below for choice between FOCE-ELS and LAPLACIAN)
6: NAIVE-POOLED
The choice between FOCE-ELS and LAPLACIAN (when
methodis 5) depends on thexfocehessslot:xfocehess = 1selects FOCE-ELS, andxfocehess = 0selects LAPLACIAN.numIterationsnumeric; The maximum number of iterations allowed for the estimation algorithm. Values must be non-negative integers.
odeToUsenumeric; Integer code specifying the ODE solver to be used. Possible values are:
1: LSODE with numerical Jacobian
2: LSODE with analytical Jacobian
3: Runge-Kutta
4: LSODA with numerical Jacobian
5: LSODA with analytical Jacobian
6: Matrix Exponent
7: DOPRI5
rtolnumeric; Specifies the relative tolerance for the ODE solver.
atolnumeric; Specifies the absolute tolerance for the ODE solver.
nmxstepnumeric; Specifies the maximum number of steps allowed for the ODE solver.
anagradnumeric; Flag controlling the differentiation method used during the optimization of random effects (etas). 0 uses a finite difference approach, and 1 uses automatic differentiation where possible. Corresponds to the engine flag
-anagrad.popadnumeric; Flag controlling population-level (outer-loop) automatic differentiation. 0 disables (default), 1 enables. When enabled, inner-loop AD (
anagrad) is also required and will be forced on by the NLME engine. Corresponds to the engine flag-popad.xnpnumeric; Controls the use of non-parametric (NP) optimization.
0: No NP optimization.
1: NONMEM-style NP optimization using posthoc estimates as support points.
>1: Evolutionary NP algorithm with
xnpgenerations.
xnorderagqnumeric; Specifies the number of quadrature points per dimension for Adaptive Gaussian Quadrature (AGQ). Only applicable when
methodisFOCE-ELSorLAPLACIAN.1: Standard FOCE-ELS/LAPLACIAN computation (no AGQ).
>1: AGQ is performed. The total number of quadrature points used is
(number of ETAs)^xnorderagq.
xfocehessnumeric; Determines the method for calculating the Hessian matrix when using FOCE methods.
0: Use numerical second derivatives.
1: Use the FOCE approximation.
Applicable only when
methodisFOCE-ELSorLAPLACIAN.xstderrnumeric; Specifies the method for standard error estimation.
0: No standard error estimation.
1: Central difference method.
2: Forward difference method.
xcondmodenumeric; Selects the basis and scope for the reported condition number when standard errors are computed.
0 (default): Covariance matrix of the estimated fixed effects only.
1: Correlation matrix of the estimated fixed effects only.
2: Covariance matrix of all estimated population parameters (fixed effects, standard deviations of residual errors, Omega).
3: Correlation matrix of all estimated population parameters. This is the only mode directly comparable to the condition number calculated from NONMEM's reported eigenvalues.
Independent of
xstderr; controls only how the selected standard-error block is converted for the reported condition number. Corresponds to the engine flag-xcondmode(omitted when 0 to preserve the engine default). The basis actually used is also echoed in the engine'sout.txtas a# conditionNumberBasis = ...comment following thecondition =line.sandcharacter; String to request sandwich standard error calculation. Typically " -sand " or "".
fishercharacter; String to request Fisher score standard error calculation. Typically " -fscore " or "".
autodetectcharacter; String to request auto-detection of standard error method. Typically " -AutoSE " or "".
xlandignumeric; Specifies the optimization accuracy (NDIGIT) for the outer loop (thetas and sigmas) when using
FOCE-ELSorLAPLACIANmethods.xlatolnumeric; Specifies the relative step size used for numerical computation of the Hessian matrix (second derivatives) during standard error calculation.
xblndignumeric; Specifies the optimization accuracy (NDIGIT) for the inner loop (optimization of etas). Also applies to the single optimization loop in the
NAIVE-POOLEDmethod.xbltolnumeric; Specifies the relative step size for numerical differentiation during model linearization.
gradTolOuterNumeric maximum gradient tolerance in the outer (Theta/Omega/Sigma) optimization loop. Applicable to
FOCE-ELSandLAPLACIANmethods.stepTolOuterNumeric maximum step tolerance in the outer (Theta/Omega/Sigma) optimization loop. Applicable to
FOCE-ELSandLAPLACIANmethods.gradTolInnerNumeric maximum gradient tolerance in the inner (Eta) optimization loop. Applicable to
FOCE-ELSandLAPLACIANmethods.stepTolInnerNumeric maximum step tolerance in the inner (Eta) optimization loop. Applicable to
FOCE-ELSandLAPLACIANmethods.refDeltaLaglNumeric LL Delta tolerance value used during Theta/Omega/Sigma optimization. Applicable to
FOCE-ELSandLAPLACIANmethods.isPCWRESnumeric; Flag indicating if Population Conditional Weighted Residuals (PCWRES) should be computed. A value of 1 indicates computation, while 0 indicates no computation. Only applicable to population models.
xpcwresnrepnumeric; Stores the number of simulation replicates used for PCWRES computation. Applicable only when
isPCWRESis 1.xisamplenumeric; Specifies the number of sample points used in the QRPEM algorithm. Only applicable when
methodisQRPEM.xmapassistnumeric; Controls the use of MAP assistance in the QRPEM algorithm.
0: No MAP assistance.
>0: The inner ETAs optimization loop is used in the QRPEM outer optimization loop with a periodicity equal to the value of
xmapassist.
Only applicable when
methodisQRPEM.xmapnpnumeric; Specifies the number of iterations for a preliminary Naive-Pooled optimization run before the main estimation. Applicable when the method is not
NAIVE-POOLED.ximpsampdofnumeric; Controls the importance sampling distribution used in the QRPEM algorithm. Only applicable when
methodisQRPEM.0: Multivariate Normal distribution.
1: Multivariate Double Exponential (Laplace) distribution.
2: Direct sampling from the prior.
3-30: Multivariate T distribution with degrees of freedom equal to the value of
ximpsampdof.-2: Mixture-2 distribution.
-3: Mixture-3 distribution.
xmcpemnumeric; Controls the sampling method used in the QRPEM algorithm.
0: Quasi-Random sampling.
1: Monte-Carlo sampling.
Only applicable when
methodisQRPEM.xpemrunallnumeric; Set to
1to execute all requested iterations specified innumIterations. Only applicable to population models withmethod = "QRPEM".xsirsampnumeric; Specifies the number of samples per eta per subject used in the Sampling Importance Resampling (SIR) algorithm within QRPEM. Only applicable when
methodisQRPEM.xburninnumeric; Specifies the number of burn-in iterations in the QRPEM algorithm. During burn-in, omegas can be frozen (see
xnonomegaburn). Only applicable whenmethodisQRPEM.xnonomegaburnnumeric; Controls whether omegas are frozen during the burn-in phase of the QRPEM algorithm.
0: burn-in with frozen omegas is off.
1: burn-in with frozen omegas is on.
Only applicable when
methodisQRPEM. See alsoxburnin.xaccrationumeric; Specifies the acceptance ratio used in the QRPEM algorithm for scaling the covariance matrix. Only applicable when
methodisQRPEM. Only applicable to population models withmethod = "QRPEM".xscramblenumeric; Specifies the scrambling method for quasi-random number generation in the QRPEM algorithm.
0: No scrambling.
1: Owen-type scrambling.
2: Faure-Tezuka scrambling.
Only applicable when
methodisQRPEM.emTolTypeNumeric specifying QRPEM convergence check type:
- 0
Default (no rollout, LL & Thetas)
- 1
LL & Params with rollout
- 2
LL with rollout
- 3
Params with rollout
Only applicable when
methodisQRPEM.emConvLenNumeric specifying the number of iterations to check for convergence. Only applicable when
methodisQRPEM.emConvCritValNumeric specifying the convergence critical value. Only applicable when
methodisQRPEM.pardernnumeric; Specifies the number of time steps used for outputting partial derivatives of observed variables with respect to parameters. Only applicable to individual models.
parderdnumeric; Specifies the step size for numerical calculation of partial derivatives of observed variables with respect to parameters. Only applicable to individual models.
logtrannumeric; Engine flag controlling log-transformation behavior for single LogAdditive error model.
See Also
Examples
param <- NlmeEngineExtraParams(
method = 3,
numIterations = 1000
)
param <- NlmeEngineExtraParams(
method = 1,
numIterations = 300
)
param <- NlmeEngineExtraParams(
method = 1,
numIterations = 300,
isPopulation = TRUE,
odeToUse = 2
)
Class represents an NLME/PML error model
Description
Class represents an NLME/PML error model
Arguments
effectsList |
List of residual effects to include in the error model |
numberOfEffects |
Number of effects being included in the error model |
Class represents an NLME/PML Indirect PD model parameters
Description
Class represents an NLME/PML Indirect PD model parameters
Arguments
type |
Indirect model type |
hasEffectsCompartment |
Is there data available for an effects compartment? |
isBuildup |
Is the response formation (TRUE) or degradation (FALSE) concentration dependent? |
isExponent |
Is there an exponent in the effect statement? |
frozen |
Freeze standard deviation to prevent estimation of the PK part of the model |
Reads progress file and returns the status of a job
Description
Reads progress file and returns the status of a job
Usage
NlmeJobStatus(job)
Arguments
job |
NLME job object |
Value
Character. Job status messages.
Examples
## Not run:
model <- pkmodel(
parameterization = "Clearance",
numCompartments = 2,
data = pkData,
ID = "Subject",
Time = "Act_Time",
A1 = "Amount",
CObs = "Conc",
workingDir = tempdir()
)
params <- NlmeEngineExtraParams(
method = 3,
numIterations = 1
)
host <- hostParams(
sharedDirectory = tempdir(),
parallelMethod = "LOCAL_MPI",
hostName = "local_mpi",
numCores = 4
)
profile1 <- ProfileVar(
"tvV",
9.548,
"-2,0"
)
profile2 <- ProfileVar(
"tvCl",
0.919,
"-0.5,0"
)
profiles <- ProfileParameters(
"USE_DELTA",
c(profile1, profile2)
)
job <- profilePertubate(
hostPlatform = host,
params = params,
profiles = profiles,
model = model
)
status <- NlmeJobStatus(job)
## End(Not run)
Class initializer for NlmeObservationVar-class
Description
Describes an observation(observe,multi,...)
Arguments
name |
Name of observation variable |
xaxis |
One of: T, TAD, PRED. If nothing is specified, the user-specified name of axis is used. |
binningMethod |
Method of binning: |
binningOption |
Centers or boundary values specified as numeric vector |
stratifyColumns |
Categorical covariates (up to 3) for simulation stratification (overrides stratifyColumns given in NlmeVpcParams) |
ygroup |
Values specifying the category right boundaries (used for categorical observations only; useful for count) |
quantilesValues |
Quantiles to be estimate for each x value (bin value) in each strata for the current observable (internal quantiles) |
quantilesSecondaryValues |
Quantiles to estimate for each internal quantile (quantiles for quantile) |
BQLasLLOQ |
Flag to replace BLQ values with the LLOQ value |
Examples
var <- NlmeObservationVar(
name = "Cobs",
xaxis = "t",
binningMethod = "none",
quantilesValues = c(5, 50, 95)
)
NlmeParallelHost Class
Description
This class defines an NLME parallel host, which can be either local or remote, for running jobs.
Slots
sharedDirectorycharacter. The directory where the run will take place. On Windows, UNC paths are mapped to a drive letter for local execution.installationDirectorycharacter. The directory containing NLME libraries and scripts.hostNamecharacter. A user-friendly name for the host (e.g., "local_mpi").machineNamecharacter. The IP address or hostname of the machine. Defaults to the local system's node name.hostTypecharacter. The operating system of the host, either"windows"or"linux". For remote Linux systems, you can specify a supported distribution (e.g.,"RHEL","UBUNTU") to configure thePML_BIN_DIRenvironment variable.linuxwill be treated as"RHEL".numCoresnumeric. The number of compute cores to be used.isLocallogical.TRUEif the host is local,FALSEif remote.rLocationcharacter. The path to the Rscript executable on a remote host. This is ignored for local runs.scriptPathcharacter. The path to a script to execute on the remote host before Rscript is started. This is ignored for local runs.userAuthenticationNlmeUserAuthentication. An object containing user credentials for remote host authentication. See NlmeUserAuthentication.parallelMethodNlmeParallelMethod. The parallel computing method to use (e.g.,"LOCAL_MPI","SGE","TORQUE"). See NlmeParallelMethod.mpiCoresPerJobinteger. Per-scenario MPI rank for the"Multicore_MPI"method.NA_integer_(default) lets NLME8 size the rank from the current batch; any positive integer fixes the per-job MPI width. Must be<= numCoresand dividenumCoresevenly.gridQueuecharacter. Scheduler queue or partition for grid methods (e.g."bg.q"on SGE,"batch"on SLURM). Empty (default) uses the cluster default queue. Ignored for local methods.gridWalltimeinteger. Wall-clock limit in seconds for grid jobs.NA_integer_(default) imposes no limit. Ignored for local methods.gridMemorycharacter. Memory request for grid jobs (e.g."16G"). Empty (default) requests no explicit memory. Ignored for local methods.gridJobNamePrefixcharacter. Prefix for the scheduler job name shown inqstat/squeue. Empty (default) derives a name from the workflow. Ignored for local methods.gridResourceExtracharacter. Additional site-specific resource request appended verbatim to the scheduler directive (e.g."h_data=4G"). Ignored for local methods.
Examples
host <- hostParams(
parallelMethod = "LOCAL_MPI",
hostName = "local_mpi",
numCores = 4
)
Class initializer for NlmeParallelMethod
Description
Use to define NlmeParallelMethod as for parallelMethod argument in
NlmeParallelHost.
Slots
methodOptions are:
None|Multicore|Multicore_MPI|LOCAL_MPI|SGE|SGE_MPI|TORQUE|TORQUE_MPI|LSF|LSF_MPI|SLURM|SLURM_MPI.Multicore_MPIruns several MPI jobs concurrently on a single local machine; pair it withmpiCoresPerJobinhostParams()to fix the per-job MPI rank, or omitmpiCoresPerJobto let NLME8 size it from the current batch.
Class represents mapping list between model variables and data columns
Description
Class represents mapping list between model variables and data columns
Class represents an NLME/PML PK model parameters
Description
Class represents an NLME/PML PK model parameters
Arguments
parameterization |
Taken from NlmeModelParameterization |
absorption |
Taken from NlmeModelAbsorption |
numCompartments |
Number of compartments |
isTlag |
Does dose have a time lag? |
hasEliminationComp |
Is there data available for an elimination compartment? |
isFractionExcreted |
Does compartment include a fraction excreted parameter? |
isSaturating |
Is the elimination rate equal to the absorption rate? |
infusionAllowed |
Is infusion allowed? |
isDuration |
Is duration of infusion measured (TRUE) or rate (FALSE)? |
isSequential |
Is model part of a PK/PD model that is being fitted sequentially? |
isClosedForm |
Is model closed-form algebraic (TRUE) or differential equation (FALSE)? |
Class initializaer for NlmePmlModel object
Description
The following class represents an NLME/PML model object.
Slots
isPopulationIs this a population model (TRUE) or individual (FALSE)?
modelTypeTaken from NlmeModelType
isTimeBasedIs model time-based?
linearModelTypeType of linear model
isLinearFrozenIs linear model frozen?
pkModelAttrsTaken from NlmePkParameters
indirectModelAttrsTaken from NlmeIndirectParameters
emaxModelAttrsTaken from NlmeEmaxParameters
hasEffectsCompartmentIs there data available for an effects compartment?
errorModelTaken from NlmeErrorModel
structuralParamsList of structural parameters
outputParamsList of output parameters
diffEquationsList of differential equations
statementsList of PML statements
dosePointsList of dosepoints
covariateListList of covariates
columnMappingTaken from NlmeColumnMapping
doseMappingTaken from NlmeDoseMapping
paramsMappingTaken from NlmeParamsMapping
randParamsMappingTaken from NlmeRandParamsMapping
inputDataInput data source
doseDataDose data source
fixedParamDataFixed effect parameter data source
randParamDataRandom effect parameter data source
isTextualIs model textual (TRUE) or graphical (FALSE)?
pmloutputList of PML output to generate
modelInfoTaken from NlmePmlModelInfo
objectsdeprecated
objectsNeedRegeneratingdeprecated
randomEffectsStatementsCustom random effects statements
randomOccasionalEffectsStatementsCustom random occasional effects statements
userDefinedExtraDefsCustom definition for extra column and table generation
Examples
# helper class
setClass("NlmePmlModelInfo",
slots = c(modelName = "character",
workingDir = "character"))
Model <-
new("NlmePmlModel",
modelInfo = new("NlmePmlModelInfo", modelName = "Model", workingDir = "."))
Class initializer for NlmeRemoteExecutor
Description
Creates Remote Executor object class
Slots
sharedDirectoryThe directory in which the run executes
installationDirectoryDirectory containing NLME libraries/scripts
hostNameIP or name of remote host
userAuthenticationCredential for user to log into remote system
Class represents an NLME/PML residual error model
Description
Class represents an NLME/PML residual error model
Arguments
effectName |
Name of the observed variable |
observeName |
Name to use for observation |
epsilonName |
Name to use for Epsilon |
errorType |
Additive|LogAdditive|Multiplicative |AdditiveMultiplicative|MixRatio|Power|Custom |
frozen |
Is the standard deviation frozen? (Default:FALSE) |
SD |
Standard deviation value |
definition |
Definition of a custom type or Power value |
isBQL |
Are there BQL values? (Default:FALSE) |
bqlStatic |
Value LLOQ value |
dobefore |
Code to execute before the observation |
doafter |
Code to execute after the observation |
Class initializer for NlmeScenario
Description
Creates NlmeScenario class object
Arguments
scenarioName |
Name of the scenario |
covariatesList |
Comma separated indices of covariate effects to use for this scenario |
Examples
CovariateEffectNames <- c("dVdBodyWeight", "dCldBodyWeight")
# Do not use any covariate effects
scenario1 <- NlmeScenario("no_covariates", "")
# Use covariate effect index 1
scenario2 <- NlmeScenario("dVdBodyWeight", "1")
# Use second covariate effect in the model
scenario3 <- NlmeScenario("dCldBodyWeight", "2")
# Use 1st and 2nd covariate effect
scenario4 <- NlmeScenario("dVdBodyWeight_dCldBodyWeight", "1,2")
Class initializer for NlmeSimTableDef
Description
Creates NlmeSimTableDef class object used to specify parameters for VPC/Simulation runs
Arguments
name |
Name of the generated simulation file. |
timesList |
Numeric; Time values for simulation.
Applicable for time-based models only. Ignored when |
covrSet |
Character; Vector of covariate names. Simulation point is added
when the covariate value is set. See |
whenDose |
Character; Vector of dosing compartment names. Simulation point is added when the dose value is set. |
whenObs |
Character; String of observed variables names. Simulation point is added when the observation value is set. |
variablesList |
Character; List of variables from the model for simulation. |
keepSource |
Logical; Set to |
timeAfterDose |
Set to |
Class initializer for NlmeSimulationParams
Description
Use to create set of parameters for simulation runs. Parameters numPoints, maxXRange, yVariables, simAtObs
are related to the model in individual mode. They will be outputted to
the file specified in model@dataset@simoutFilename, simout.csv by default
Arguments
numReplicates |
Number of replicates to simulate |
seed |
Random number generator seed |
numPoints |
Number of points in simulation for the models in individual mode |
maxXRange |
Maximum value of independent variable for the models in individual mode |
yVariables |
Comma separated character string of Y variables for the models in individual mode |
simAtObs |
Simulate values at observed values of ivar for the models in individual mode |
simulationTables |
Optional list of simulation tables.
|
See Also
Examples
table1 <- tableParams(
name = "simulate.csv",
timesList = "0,2,4,12,24",
variablesList = "V,Cl",
timeAfterDose = TRUE,
forSimulation = TRUE
)
simParam <- NlmeSimulationParams(
numReplicates = 10,
seed = 29423,
simulationTables = c(table1)
)
simParam <- NlmeSimulationParams(
numPoints = 100,
maxXRange = 50,
yVariables = "C,A1",
simulationTables = table1
)
Class represents style of structural parameter
Description
Class represents style of structural parameter
Slots
styleParameter style: 1=LogNormal, 2=Normal, 3=Combination, 4=Log, 5=Logit
Class initializer for NlmeTableDef
Description
Creates NlmeTableDef class object used to specify parameters for fitting runs
Arguments
name |
Name of the generated simulation file. |
timesList |
Numeric; Time values for simulation.
Applicable for time-based models only. Ignored when |
covrSet |
Character; Vector of covariate names. Simulation point is added
when the covariate value is set. See |
whenDose |
Character; Vector of dosing compartment names. Simulation point is added when the dose value is set. |
whenObs |
Character; String of observed variables names. Simulation point is added when the observation value is set. |
variablesList |
Character; List of variables from the model for simulation. |
keepSource |
Logical; Set to |
timeAfterDose |
Set to |
IRES |
Logical; Set to |
Weight |
Logical; Set to |
IWRES |
Logical; Set to |
mode |
Character; The mode of output. Options are Option |
Class initializer for NlmeUserAuthentication
Description
Use for authentication records
Slots
userNameHow the user is identified to the remote system
privateKeyFilepath to private key file, see
keyfilefor detailsuserPasswordeither a string or a callback function for password prompt, see
passwdfor details
Arguments for VPC runs
Description
Class initializer for arguments of visual predictive check (VPC) runs
Arguments
numReplicates |
Integer; Number of replicates to simulate the model |
seed |
Integer; Random number generator seed |
predCorrection |
Character; Type of correction to use when calculating a prediction-corrected observation.
Options are |
predVarCorr |
Logical; Set to |
outputPRED |
Logical; Set to |
stratifyColumns |
Character or character vector; Names of categorical covariates (up to 3) used to stratify modeling simulation results. |
observationVars |
NlmeObservationVar class instance or list of these instances |
simulationTables |
Optional list of simulation tables.
|
See Also
tableParams, NlmeSimTableDef, NlmeObservationVar
Examples
## Not run:
model <- pkmodel(
parameterization = "Clearance",
numCompartments = 2,
data = pkData,
ID = "Subject",
Time = "Act_Time",
A1 = "Amount",
CObs = "Conc",
workingDir = tempdir()
)
# Define the host
host <- hostParams(parallelMethod = "NONE",
hostName = "local",
numCores = 1,
sharedDirectory = tempdir())
job <- fitmodel(model,
hostPlatform = host)
# View estimation results
print(job)
finalModelVPC <- copyModel(model,
acceptAllEffects = TRUE,
modelName = "model_VPC",
workingDir = tempdir())
# View the model
print(finalModelVPC)
# Set up VPC arguments to have PRED outputted to simulation output dataset "predout.csv"
vpcSetup <- NlmeVpcParams(outputPRED = TRUE)
# Run VPC using the default host, default values for the relevant NLME engine arguments
finalVPCJob <-
vpcmodel(model = finalModelVPC, vpcParams = vpcSetup, )
## End(Not run)
Pharmacokinetic dataset containing 100 subjects with single dose given by infusion
Description
Pharmacokinetic dataset containing 16 subjects with single dose given by infusion.
Usage
OneCpt_IVInfusionData
Format
A data frame with 800 rows and 6 variables:
- Subject
Subject ID
- Time
Time point
- Dose
Amount of dose
- CObs
Observations of drug concentration in blood
- Rate
Rate of infusion
- Duration
Duration of infusion
Source
The data is simulated using a PK model described by a one-compartment model with IV infusion
Class initializer for ProfileParameters
Description
Class represents an NLME profile perturbation variable
Slots
howToPertubateHow to apply profile variables. Options are
USE_DELTAorUSE_PERCENTAGEprofileVarsList of profile variables
Examples
profile1 <- ProfileVar("tvV", 9.548, "-2,-1,0,1,2")
profile2 <- ProfileVar("tvCl", 3.219, "-1,0,1")
profiles <- ProfileParameters("USE_DELTA", c(profile1, profile2))
NLME Profile variable
Description
Class initializer for an NLME profile perturbation variable
Arguments
effectName |
Name of fixed effect |
initialvalue |
Initial value |
pertubateValues |
Values to perturbate by (either delta or percentage),
given as a single comma-separated character string (e.g. |
Examples
ProfileVar("tvV", 9.95, "-2,-1,0,1,2")
Class initializer for ResetColumnInfo
Description
Class initializer for ResetColumnInfo
Arguments
low |
Lower value of reset range |
hi |
Upper value of reset range |
Backgrounded NLME job classes
Description
S4 classes for NLME runs launched with runInBackground = TRUE.
SimpleNlmeJob is the shared base; the run-specific subclasses
(BootNlmeJob, FitNlmeJob, StepwiseNlmeJob,
ShotgunNlmeJob, ProfileNlmeJob, SortByNlmeJob, and
NlmeSimulationJob) carry the launch context for their run mode and are
materialised with collectJob. They are returned to the caller as
handles; you rarely construct them directly.
Slots
jobTypeGENERIC/ESTIMATION_RUN/COVAR_SEARCH/PROFILE_RUN/STEPWISE_SEARCH/BOOTSTRAP/Sort_By_Column
localDirwhere the data/model files are taken and the results are loaded for the local and remote runs
remoteDirwhere the data/model files are taken and the results are loaded on remote host
hostlocal/remote job parallelization type
argsListlist of arguments for run
argsFilefile for arguments for run
scriptFileinitial script generation
workflowworkflow name
runInBackgroundshould the job be executed in background or not
Class initializer for SortColumns
Description
Class represents an NLME sort columns object
Arguments
... |
Names of input data columns (up to 5 for individual models and no limit for population models) used to sort the input data and model outputs. Can be supplied as either a single string or a vector of strings. |
Examples
# The following two setups are equivalent
sortColumnSetUp <- SortColumns("Country,City")
sortColumnSetUp <- SortColumns(c("Country","City"))
# The following two setups are equivalent
sortColumnSetUp <- SortColumns("Sort1 Sort2", "Sort3")
sortColumnSetUp <- SortColumns(c("Sort1, Sort2 "), "Sort3 ")
Class initializer for NLME StepwiseParams
Description
Class represents an NLME Stepwise search parameters
Arguments
addPValue |
Numeric. Threshold for adding a covariate effect |
removePValue |
Numeric. Threshold for removing a covariate effect |
method |
-2LL|AIC|BIC; could be abbreviated. |
Examples
StepwiseParams(0.001, 0.001, "BIC")
Subset SCM search results
Description
Preserves SCM-specific attributes when subsetting still returns a data frame.
Usage
## S3 method for class 'scmSearchResult'
x[...]
Arguments
x |
A |
... |
Arguments passed to |
Value
The subsetted object. If the result is still a data frame, it keeps
the scmSearchResult class.
Accepts all estimates for fixed effects, Sigma, and random effects
Description
Updates PML statements in model object with estimates returned from model
execution. Use copyModel and set argument
acceptAllEffects = TRUE to create new model object with final
estimates from base model run.
Usage
acceptAllEffects(model)
Arguments
model |
Model object |
Value
NlmePmlModel object
See Also
Examples
## Not run:
# Define the model
model <- pkmodel(numComp = 1,
absorption = "Intravenous",
ID = "Subject",
Time = "Act_Time",
CObs = "Conc",
A1 = "Amount",
data = pkData,
modelName = "PkModel",
workingDir = tempdir())
# Fit model
res <- fitmodel(model = model,
hostPlatform = hostParams(sharedDirectory = tempdir()))
model <- acceptAllEffects(model)
## End(Not run)
Adds ADDL extra column definition to model object
Description
Specify ADDL column definition in model object instead of specifying ADDL through addDoseCycle
Usage
addADDL(.Object, ADDL, II)
Arguments
.Object |
Model object |
ADDL |
Column mapping argument specifying corresponding "ADDL" column in input data set |
II |
Column mapping argument specifying corresponding "II" column in input data set |
Value
Modified NlmePmlModel object
Examples
pkData1 <- pkData
pkData1$ii <- 0
pkData1$addl <- 0
model <- pkmodel(numComp = 2,
absorption = "FirstOrder",
ID = "Subject",
Time = "Act_Time",
CObs = "Conc",
Aa = "Amount",
data = pkData1,
modelName = "PkModel",
workingDir = tempdir())
model <- addADDL(model, ADDL = "addl", II = "ii")
Add covariate to model object
Description
Add a continuous, categorical, or occasion covariate to model object and set covariate effect on structural parameters.
Usage
addCovariate(
.Object,
covariate,
effect = NULL,
type = c("Continuous", "Categorical", "Occasion"),
direction = c("Forward", "Interpolate", "Backward"),
option = c("Yes", "PlusOne", "No"),
center = NULL,
centerValue = NULL,
levels = NULL,
labels = NULL,
isDiagonal = TRUE,
values = NULL,
isPositive = TRUE
)
Arguments
.Object |
Model object |
covariate |
Name of covariate. If the involved model has columns
mapped (i.e. model with |
effect |
Name of structural parameter(s) on which the covariate
has an effect. Specify |
type |
Type of covariate. Options are |
direction |
Direction of missing values propagation (if no covariate
value is given). Options are |
option |
Options are
|
center |
Centering method. Options are |
centerValue |
Value used to center covariate. Only applicable if
argument |
levels |
Unique values of categorical or occasion covariate. Only
applicable to covariate |
labels |
Label names (in the same order as levels) for unique levels of
categorical or occasion covariate in data. Only applicable to covariate
|
isDiagonal |
Set to |
values |
Initial values for the diagonal elements of the inter-occasion
covariance matrix (if |
isPositive |
Set to |
Details
The following relationships are applicable for covariates:
-
direction = "Forward"is equivalent to PML code 'fcovariate(CovName)'; -
direction = "Backward"is equivalent to PML code 'covariate(CovName)'; -
direction = "Interpolate"is equivalent to PML code 'interpolate(CovName)'.If the structural parameter has
style = "LogNormal", the options are reflected in PML code as follows: -
option = "Yes"is equivalent tostparm(V = tvV * wt^dVdwt * exp(dVdsex1*(sex==1)) * exp(nV)); -
option = "PlusOneis equivalent tostparm(V = tvV * (1+wt*dVdwt) * (1+dVdsex1*(sex==1)) * exp(nV)).
Value
Modified NlmePmlModel object
Examples
model <- pkmodel(
numCompartments = 2,
data = pkData,
ID = "Subject",
Time = "Act_Time",
A1 = "Amount",
CObs = "Conc",
workingDir = tempdir()
)
# Add Gender covariate of type categorical
model <- addCovariate(model,
covariate = "Gender",
type = "Categorical",
effect = c("V2", "Cl2"),
levels = c(0, 1),
labels = c("Female", "Male")
)
# Add BodyWeight covariate of type continuous
model <- addCovariate(model,
covariate = "BodyWeight",
type = "Continuous",
direction = "Backward",
center = "Mean",
effect = c("V", "Cl")
)
Adds a dosing cycle to model
Description
Add Steady State or ADDL dosing cycle to model object.
Usage
addDoseCycle(
.Object,
type = "SteadyState",
name,
administration = "Bolus",
amount = NULL,
II = NULL,
rate = NULL,
duration = NULL,
isSecondDose = FALSE,
colName = NULL
)
Arguments
.Object |
Model object |
type |
Specification of dose type. Options are |
name |
Dose point name. See |
administration |
Mechanism for administering dose. Options are |
amount |
Optional. Column mapping argument specifying corresponding "ADDL" column in input data, or numeric value specifiying dose amount. |
II |
Optional. Column mapping argument specifying corresponding "II" column in input data, or numeric value specifying delta time. |
rate |
Optional. Column mapping argument specifying corresponding "Rate" column in input data, or numeric specifying dose rate. |
duration |
Optional. Column mapping argument specifying corresponding "Duration" column in data, or numeric specifying duration value. |
isSecondDose |
Use second dose point on compartment |
colName |
Column name in input data corresponding to column mapping for "SteadyState" or "ADDL" as supplied in |
Value
Modified NlmePmlModel object
See Also
Examples
model <- addDoseCycle(pkmodel(columnMap = FALSE,
isPopulation = FALSE,
workingDir = tempdir()),
type = "SteadyState",
name = "A1",
amount = "Amount",
II = "II")
Adds user defined extra column/table definitions to column definition file
Description
Adds user defined extra column/table definitions to column definition file
Usage
addExtraDef(.Object, value)
Arguments
.Object |
PK/PD model |
value |
Character vector of extra column/table definitions |
Value
Modified NlmePmlModel object
Examples
model <- pkmodel(columnMap = FALSE,
workingDir = tempdir())
model <- addExtraDef(model, c("addlcol(ADDL)",
"table(file=\"res.csv\",time(0),Ka,V,Cl,Tlg)"))
Change existing dosing compartment to infusion
Description
Allows user to switch any dosing compartment to infusion
Usage
addInfusion(
.Object,
doseCptName,
isDuration = FALSE,
isSecondDose = FALSE,
colName = NULL
)
Arguments
.Object |
Model object |
doseCptName |
Name of the compartment to which the dose is administered |
isDuration |
Set |
isSecondDose |
Set |
colName |
Name of the input data column that represents the corresponding infusion rate. If not provided, |
Value
Modified NlmePmlModel object
Examples
pkData1 <- pkData
pkData1$A1_1 <- 0
model <- pkmodel(numComp = 2,
absorption = "Intravenous",
ID = "Subject",
Time = "Act_Time",
CObs = "Conc",
A1 = "Amount",
data = pkData1,
modelName = "PkModel",
workingDir = tempdir())
newModel <- addInfusion(model, "A1", FALSE, FALSE, "A1_1")
Add levels and labels to categorical or occasion covariate
Description
Allows users to specify the name and the associated value for each category/occasion of a categorical/occasion covariate in a textual model object. Only applicable to the case where the corresponding input data column of a categorical/occasion covariate is of class character.
Usage
addLabel(.Object, covariate, levels, labels)
Arguments
.Object |
Model object |
covariate |
Existing covariate name |
levels |
Unique values of categorical or occasion covariate column specified as numeric vector |
labels |
Unique values specifying corresponding label names for levels of categorical or occasion covariate column in data specified as character vector. |
Value
Modified NlmePmlModel object
Examples
model <- pkmodel(columnMap = FALSE,
isPopulation = FALSE,
workingDir = tempdir())
model <- suppressWarnings(addCovariate(model,
covariate = "Gender",
type = "Categorical",
effect = c("V"),
levels = c(0, 1)))
model@isTextual <- TRUE
model <- addLabel(model, "Gender", c(1, 2), c("male", "female"))
Adds MDV extra column definition to model object
Description
Use to add MDV statement to model@userDefinedExtraDefs
Usage
addMDV(.Object, MDV)
Arguments
.Object |
Model object |
MDV |
Column mapping argument specifying corresponding "MDV" column in input data set |
Value
Modified NlmePmlModel object
Examples
pkData1 <- pkData
pkData1$MDV <- 0
model <- pkmodel(data = pkData1,
ID = "Subject",
Time = "Act_Time",
A1 = "Amount",
CObs = "Conc",
workingDir = tempdir()
)
model <- addMDV(model, MDV = "MDV")
Adds reset instructions to the model
Description
Adds reset instructions to the model
Usage
addReset(.Object, low, hi, Reset = NULL)
## S4 method for signature 'NlmePmlModel'
addReset(.Object, low, hi, Reset = NULL)
Arguments
.Object |
An 'NlmePmlModel' object to which you want to add reset instructions. |
low |
Lower value of reset range. |
hi |
Upper value of reset range. |
Reset |
Name of reset column in input data set for column mapping. The default is NULL. |
Value
Depends on the specific methods
Returns the 'NlmePmlModel' object with updated reset information and definitions.
Functions
-
addReset(NlmePmlModel): Method for the 'NlmePmlModel' classThis method adds reset instructions to the NlmePmlModel object. It updates the reset information, checks column mappings if input data is not null, and adds a reset definition to user-defined extra definitions.
Adds a secondary parameter to model definition
Description
Adds a secondary parameter to model definition
Usage
addSecondary(.Object, name, definition, unit = "")
## S4 method for signature 'NlmePmlModel'
addSecondary(.Object, name, definition, unit = "")
Arguments
.Object |
An 'NlmePmlModel' object to which you want to add a secondary parameter. |
name |
Name of the secondary parameter. |
definition |
Definition of secondary parameter. |
unit |
Optional units of the secondary parameter. The default is "". |
Value
Depends on the specific methods
Returns the 'NlmePmlModel' object with the added secondary parameter.
Functions
-
addSecondary(NlmePmlModel): Method for the 'NlmePmlModel' classThis method adds a secondary parameter to the NlmePmlModel object. It checks for duplicate parameter names, and if there is no duplicate, it adds the new secondary parameter to the object and updates the PML model.
Examples
model <- pkmodel(columnMap = FALSE,
absorption = "FirstOrder",
workingDir = tempdir())
model <- addSecondary(model, "Ke", "tvCl/tvV")
model <- addSecondary(
model, "Tmax",
"CalcTMax(tvA,tvCl/tvV)"
)
Adds Steady State extra column definition to model object
Description
Use to add Steady State column definition statement to model@userDefinedExtraDefs
Usage
addSteadyState(.Object, SS, II, SSOffset = NULL)
Arguments
.Object |
Model object |
SS |
Column mapping argument specifying corresponding "SS" column in input data set |
II |
Column mapping argument specifying corresponding "II" column in input data set |
SSOffset |
Optional. Column mapping argument specifying corresponding "SSOffset" column in input data set |
Value
Modified NlmePmlModel object
Examples
pkData1 <- pkData
pkData1$SS <- 0
pkData1$II <- 0
model <- pkmodel(data = pkData1,
ID = "Subject",
Time = "Act_Time",
A1 = "Amount",
CObs = "Conc",
workingDir = tempdir()
)
model <- addSteadyState(model, SS = "SS", II = "II")
Add to the NLME Error model
Description
Add to the NLME Error model
Usage
addToErrorModel(model, effectsList)
Arguments
model |
Model object |
effectsList |
List of effects |
Advance a sequential-LRT session by one bounded, idempotent transition
Description
Call this repeatedly to drive a session from start_sequential_lrt()
through to completion. Each call performs at most one bounded pass:
resolve the anchor (refit status + OFV parity) while state == "anchoring", or - once state == "testing" - collect any finished
candidate fits, decide the current phase's winner (forward addition
accepts the most significant approved effect with p < alpha_add;
backward elimination removes the least-supported approved effect with
p >= alpha_remove; ties/order come only from the approved plan), advance
the reference on acceptance, and launch newly-ready operations up to
host_resources$max_concurrent_fits and the remaining fit_budget. Safe
to call again while running (it just re-polls); pauses with
requires_user_attention = TRUE on OFV-parity failure, a failed reference
fit, an altered plan.json, or exhausted budget.
Usage
advance_sequential_lrt(
session_id,
project_dir = ".",
candidate_updates = NULL,
force_continue = FALSE
)
Arguments
session_id |
Session id from |
project_dir |
Project root the session was started under. |
candidate_updates |
Optional named list (or, via MCP, a JSON object
string) mapping operation |
force_continue |
When |
Value
A compact session status: state, phase, reference,
fit_budget/fit_budget_used, status_counts, per-operation
test_results, anchor_ofv_parity (once resolved),
requires_user_attention/explanation when paused, and next_action.
See Also
get_sequential_lrt_status() for a read-only peek without
advancing, collect_sequential_lrt() for the final report.
Analyze a NONMEM control stream
Description
Parses a NONMEM control stream and returns a structured, understanding-led
analysis: which records are present, the ADVAN/TRANS structure, parameter
counts, an $INPUT-derived column-mapping hint, the recommended translation
path (builtin model vs textual PML), an estimation summary, and explicit
open_questions / unsupported lists for constructs without a clean PML
analog. It fails loud on an unparseable stream and extracts partially rather
than silently mis-parsing. It does not write PML; use
draft_pml_from_nonmem() for that.
Usage
analyze_nonmem_control(control_text = NULL, path = NULL)
Arguments
control_text |
Control-stream content as a single string. |
path |
Optional path to a control file (used when |
Value
A list describing the parsed model (see the function's sections,
structure, parameters, column_mapping_hint, estimation,
open_questions, unsupported, and ok/partial fields).
Executes an NLME Bootstrap
Description
Method to execute an NLME Bootstrap
Usage
bootstrap(
model,
hostPlatform = NULL,
params,
bootParams,
runInBackground = FALSE,
saveResult = TRUE,
overwriteFitDir = FALSE,
...
)
Arguments
model |
PK/PD model class object. |
hostPlatform |
Host definition for model execution. See |
params |
Engine parameters. See |
bootParams |
Bootstrap parameters. See |
runInBackground |
Logical. When Background execution is supported only on Linux hosts, whether
local or remote: a local host whose |
saveResult |
Logical; if |
overwriteFitDir |
Logical (default |
... |
Additional class initializer arguments for |
Value
When runInBackground = FALSE, an rsnlme_boot
object: a named list of bootstrap result tables with class
c("rsnlme_boot", "list") and metadata attributes. The list carries
the existing aggregates (BootOverall, BootTheta,
BootOmega, BootOmegaCorrelation, BootOmegaStderr,
BootVarCoVar, BootSecondary) plus the per-replicate stacks
and per-parameter CI tables emitted by recent NLME8 builds
(BootThetaStacked, BootOmegaStacked, BootSigmaStacked,
BootOmegaCI, BootSigmaCI, BootEtaShrinkage,
BootEpsShrinkage). When bootParams@initialEstimates is
TRUE, a compact fitSummary table built from
dmp.txt + nlme7engine.log is also embedded. See
?rsnlme_boot for the full field and attribute contract and
?print.rsnlme_boot for the rendered output.
When saveResult = TRUE (the default), the rsnlme_boot is
also written to disk; see the saveResult parameter for the exact
path.
When runInBackground = TRUE, the bare BootNlmeJob is
returned; pass it to collectJob() to obtain the
rsnlme_boot (the RDS write, if requested, happens at that point).
See Also
hostParams, engineParams, BootstrapParams,
rsnlme_boot, collectJob
Examples
## Not run:
input_data <- pkData
model <-
pkmodel(
numCompartments = 2,
data = input_data,
ID = "Subject",
Time = "Act_Time",
A1 = "Amount",
CObs = "Conc",
workingDir = tempdir()
)
# multicore
multicoreHost <- hostParams(
sharedDirectory = tempdir(),
parallelMethod = "Multicore",
hostName = "local_multicore",
numCores = 4
)
bootstrapdf <- bootstrap(model,
hostPlatform = multicoreHost,
params = engineParams(model),
numReplicates = 5,
randomNumSeed = 1234,
runInBackground = FALSE
)
## End(Not run)
Generic function for cancelling a job
Description
Generic function for cancelling a job
Usage
cancelJob(.Object)
## S4 method for signature 'SimpleNlmeJob'
cancelJob(.Object)
Arguments
.Object |
A 'SimpleNlmeJob' object that you want to cancel |
Value
Depends on the specific methods
Prints the 'SimpleNlmeJob' object after attempting to cancel the job. No return value.
Functions
-
cancelJob(SimpleNlmeJob): Method for cancelling a job of the 'SimpleNlmeJob' classThis method attempts to cancel a job of the 'SimpleNlmeJob' class. If the job is running on a local host or is not running in the background, it throws an error and does nothing. Otherwise, it uploads a 'STOP' command to the host's remote executor.
Certara.RsNLME MCP tool definitions (NLME provider slice)
Description
Returns the NLME-specific authoring, data, execution, comparison, and
interpretation tools as a list of ellmer::tool() objects. This is the
builder named by inst/mcp/tools/manifest.json; the Certara.R MCP host
discovers it and merges these tools with its own knowledge/memory/meta tools.
The generic KB, memory, and capabilities tools live in the host, not here.
Usage
certara_mcp_tools(
groups = c("knowledge", "data", "execution", "comparison", "interpretation",
"qualification")
)
Arguments
groups |
Tool groups to include. Any of |
Value
A list of ellmer ToolDef objects.
Check Host Parameters
Description
Checks NLME Parallel Host object for correct settings for GCC, NLME Installation, MPI and Root directories.
Usage
checkHostParams(obj, verbose = FALSE)
Arguments
obj |
NLME Parallel Host to be checked |
Value
TRUE if all checks are successful, otherwise FALSE
Examples
## Not run:
# multicore
multicoreHost <- hostParams(
parallelMethod = "Multicore",
hostName = "local_multicore",
numCores = 4
)
checkHostParams(multicoreHost)
## End(Not run)
Reconcile a Darwin search candidate's OFV against an RsNLME refit's -2LL
Description
Before trusting a recovered pyDarwin (Certara.RDarwin) candidate as a
structural anchor for sequential LRT, its results.csv$ofv (the raw -2LL;
never fitness, which adds pyDarwin's penalties/postprocess terms) must be
reconciled against this job's RsNLME refit -2LL. A mismatch beyond
tolerance most often means the metamodel's chained ##ESTARGS estimation
stages, BLQ handling, or starting estimates were not fully mirrored in the
refit - and any likelihood comparison built on an unreconciled anchor is not
trustworthy.
Usage
check_ofv_parity(job_id, darwin_ofv, project_dir = ".", tolerance = NULL)
Arguments
job_id |
RsNLME job id for the candidate's refit (from
|
darwin_ofv |
The candidate's |
project_dir |
Project root the job was launched under. |
tolerance |
Optional absolute tolerance in |
Value
A list with job_id, darwin_ofv, refit_neg2ll, tolerance,
abs_delta, and parity_ok (TRUE/FALSE, or NA when the refit is
not yet terminal-successful or darwin_ofv was not numeric). On a
mismatch (or NA), also sets requires_user_attention = TRUE and an
explanation of the likely cause.
Clean up stale or old MCP runs
Description
Clean up stale or old MCP runs
Usage
cleanup_mcp_runs(older_than = 90, project_dir = ".")
Arguments
older_than |
Age threshold; runs whose directory mtime is older are removed. Accepts a difftime or a numeric number of days. Default 90 so a routine sweep cannot drop an active project's run directories. Do not auto-call this from other tools; a sweep is always a deliberate choice. |
project_dir |
Project root. |
Value
A list of removed job ids.
Add column mappings
Description
Piping compatible function for modelColumnMapping used to add column mappings from input data to model object
Usage
colMapping(.Object, mappings = NULL, ...)
Arguments
.Object |
Model ( |
mappings |
Named character vector specifying valid column names in the input data.
Character vector names must be valid model variable names contained
in |
... |
optional pairs ModelTerm = ColumnName or ModelTerm = "ColumnName".
Has higher precedence than |
Value
modified NlmePmlModel object
See Also
dataMapping modelVariableNames
Examples
pkData$id2 <- pkData$Subject
model <- pkmodel(columnMap = FALSE,
data = pkData,
workingDir = tempdir())
modelvar <- unlist(modelVariableNames(model))
colnames <- c("Subject", "Act_Time", "Amount", "Conc")
names(colnames) <- modelvar
# will map subject directly
colnames <- colnames[-c(1)]
model <- colMapping(model, colnames, id = c(Subject, id2))
# also possible:
model <- colMapping(model, colnames, id = c("Subject", "id2"))
# not recommended since only not quoted names are identified
# if both types are provided:
model <- colMapping(model, colnames, id = c("Subject", id2))
Collect the typed result of a finished NLME job
Description
Polls a backgrounded NlmeJob via NlmeJobStatus until
the engine reports "Finished", then materialises the typed result.
Remote-results download (when applicable) and CSV/log parsing are handled
by the class-specific method body. collectJob() is the single
canonical entry point for any runInBackground = TRUE run.
Usage
collectJob(job, timeout = Inf, pollInterval = 5, ...)
## S4 method for signature 'BootNlmeJob'
collectJob(job, timeout = Inf, pollInterval = 5, ...)
## S4 method for signature 'FitNlmeJob'
collectJob(job, timeout = Inf, pollInterval = 5, ...)
## S4 method for signature 'StepwiseNlmeJob'
collectJob(job, timeout = Inf, pollInterval = 5, ...)
## S4 method for signature 'ShotgunNlmeJob'
collectJob(job, timeout = Inf, pollInterval = 5, ...)
## S4 method for signature 'ProfileNlmeJob'
collectJob(job, timeout = Inf, pollInterval = 5, ...)
## S4 method for signature 'SortByNlmeJob'
collectJob(job, timeout = Inf, pollInterval = 5, ...)
## S4 method for signature 'NlmeSimulationJob'
collectJob(job, timeout = Inf, pollInterval = 5, ...)
Arguments
job |
An NLME job object returned by a wrapper invoked with
|
timeout |
Maximum time to wait, in seconds. |
pollInterval |
Seconds between status checks. Defaults to 5. |
... |
Reserved for class-specific arguments; currently unused. |
Details
Background jobs are only started on Linux hosts (local hostType
"linux" or remote "linux" / "RHEL" / "UBUNTU").
Wrappers on Windows do not support runInBackground = TRUE; see
?fitmodel for the platform rule shared by all job executors.
Dispatches on BootNlmeJob, FitNlmeJob,
StepwiseNlmeJob, ShotgunNlmeJob,
ProfileNlmeJob, SortByNlmeJob, and
NlmeSimulationJob (the shared class behind both
vpcmodel and simmodel, discriminated by its
validated runMode slot).
Value
A class-specific result object. For BootNlmeJob, an
rsnlme_boot. For FitNlmeJob and SortByNlmeJob,
the same result list fitmodel / sortfit
produces. For StepwiseNlmeJob and ShotgunNlmeJob, an
scmSearchResult (zero-row when Overall.csv is missing).
For ProfileNlmeJob, a profileResult data frame (zero-row
when Profile.csv is missing). For NlmeSimulationJob, the
same named list of data.tables that vpcmodel /
simmodel produces, with additive
runMode/runTime/RsNLMEVersion list elements.
Functions
-
collectJob(BootNlmeJob): Wait for a backgroundedBootNlmeJobto finish and return itsrsnlme_boot. Downloads remote artefacts idempotently whenfile.path(localDir, "BootOverall.csv")is absent, then reads the bootstrap CSVs fromjob@localDirinto the typedrsnlme_boot(forwardingjob@bootfor replicate counts / confidence level andjob@argsList$enginefor the engine attribute) and – ifjob@saveResultisTRUE– writes the result to<localDir>/bootstrap_<sanitizedModelName>_<YYYYMMDD_HHMMSS>.rds, wheresanitizedModelNameisjob@model@modelInfo@modelNamewith every character outside[A-Za-z0-9._-]replaced by_(falling back tomodelwhen empty) and the timestamp isjob@runStartformatted asYYYYMMDD_HHMMSSin local time. -
collectJob(FitNlmeJob): Wait for a backgroundedFitNlmeJobto finish and return the same result list thatfitmodel's foreground branch produces. Downloads remote artefacts idempotently whenfile.path(localDir, "nlme7engine.log")is absent, then reads engine outputs via.get_resultList()and – ifjob@saveResultisTRUE– writes the result to<localDir>/fitmodel_<sanitizedModelName>_<YYYYMMDD_HHMMSS>.rds, wheresanitizedModelNameisjob@model@modelInfo@modelNamewith every character outside[A-Za-z0-9._-]replaced by_(falling back tomodelwhen empty) and the timestamp isjob@runStartformatted asYYYYMMDD_HHMMSSin local time. -
collectJob(StepwiseNlmeJob): Wait for a backgroundedStepwiseNlmeJobto finish and return the samescmSearchResultthatstepwiseSearch's foreground branch produces. Downloads remote artefacts idempotently whenfile.path(localDir, "Overall.csv")is absent, then reads the search results via.read_covsearch_results()(which archives the run folder whenjob@archiveResultsisTRUE) and applies the stepwise-onlyBestScenarioflag fromStepwise.txt. Returns an emptyscmSearchResult(zero-row,searchTypeattribute set) whenOverall.csvis missing. -
collectJob(ShotgunNlmeJob): Wait for a backgroundedShotgunNlmeJobto finish and return the samescmSearchResultthatshotgunSearch's foreground branch produces. Downloads remote artefacts idempotently whenfile.path(localDir, "Overall.csv")is absent, then reads the search results via.read_covsearch_results()(which archives the run folder whenjob@archiveResultsisTRUE). Returns an emptyscmSearchResult(zero-row,searchTypeattribute set) whenOverall.csvis missing. -
collectJob(ProfileNlmeJob): Wait for a backgroundedProfileNlmeJobto finish and return the sameprofileResultthatprofilePertubate's foreground branch produces. Downloads remote artefacts idempotently whenfile.path(localDir, "Profile.csv")is absent, then reads the profile table via.read_profile_results()and – ifjob@saveResultisTRUE– writes a self-describingprofile_<sanitizedModelName>_<YYYYMMDD_HHMMSS>.rdsalongside the result, wheresanitizedModelNameisjob@model@modelInfo@modelNamewith every character outside[A-Za-z0-9._-]replaced by_(falling back tomodelwhen empty) and the timestamp isjob@runStartformatted asYYYYMMDD_HHMMSSin local time. Returns an emptyprofileResult(zero-row,runMode = "profile"attribute set) whenProfile.csvis missing. -
collectJob(SortByNlmeJob): Wait for a backgroundedSortByNlmeJobto finish and return the same result list thatsortfit's foreground branch produces. Downloads remote artefacts idempotently whenfile.path(localDir, "nlme7engine.log")is absent, then reads engine outputs via.get_resultList()(the shared fitmodel/sortfit reader) withrunMode = "sortfit"and – ifjob@saveResultisTRUE– writes the result to<localDir>/sortfit_<sanitizedModelName>_<YYYYMMDD_HHMMSS>.rds, wheresanitizedModelNameisjob@model@modelInfo@modelNamewith every character outside[A-Za-z0-9._-]replaced by_(falling back tomodelwhen empty) and the timestamp isjob@runStartformatted asYYYYMMDD_HHMMSSin local time. -
collectJob(NlmeSimulationJob): Wait for a backgroundedNlmeSimulationJob(constructed by eithervpcmodelorsimmodel) to finish and return the same named list ofdata.tables the foreground branch produces. Sentinel is mode-specific:predout.csvwhenjob@params@isPopulationisTRUE(population runs), otherwisesimout.csv(individual runs). Reads the engine output via.read_vpcsim_results()and attaches the canonicalrunMode/runTime/RsNLMEVersionlist elements.
See Also
bootstrap,
fitmodel, stepwiseSearch,
shotgunSearch, profilePertubate,
sortfit, vpcmodel, simmodel,
NlmeJobStatus
Collect a finished NLME job
Description
Returns a compact summary plus artifact paths. Does not stream large files.
Usage
collect_nlme_job(
job_id,
project_dir = ".",
refresh_fit_health = TRUE,
darwin_ofv = NULL,
ofv_tolerance = NULL
)
Arguments
job_id |
Job id. |
project_dir |
Project root. |
refresh_fit_health |
When |
darwin_ofv |
Optional |
ofv_tolerance |
Optional absolute tolerance (in |
Details
The summary includes a fit_health block (data file size, engine status,
return code, -2LL, and whether stderr mentions a missing dataset) so a
state == "succeeded" is not mistaken for a good fit - the common failure
mode where a metamodel with a missing ## DATA path "succeeds" on an empty
data1.txt.
Value
A list summary with state, run_dir, artifact_dir, artifacts
(paths relative to artifact_dir), fit_health, tail of logs, and a
next_action directive: save_analysis_plan with blocking = TRUE when
no plan is saved and this job was not launched under an approved
allow_unplanned exception; get_project_workflow_status (non-blocking)
on success once a plan exists or the exception is on record; NULL for a
failed/dead job (see $failure instead). For failed/dead jobs
requires_user_attention is TRUE and a failure block carries a
normalized error_class, suggested_fix, and related_kb entry. When
darwin_ofv is supplied, also includes ofv_parity. artifact_integrity
reports whether the artifacts still match the manifest recorded for this
job; a "violation" takes precedence over every other directive and
yields a blocking artifact_integrity_violation next_action.
Collect the sequential-LRT report (decisions, telemetry, downstream gates)
Description
Readable at any point (not only once terminal): while a session is still
"anchoring"/"testing", the report reflects progress so far and
is_final = FALSE. Once state is "completed"/"budget_exhausted"/
"stopped", is_final = TRUE and downstream_proposals lists
user-gated next steps (VPC, opt-in qpc_score, AIC/BIC re-confirmation
against the original Darwin candidates, bootstrap, or a constrained
Darwin rerun) - none of which launch automatically.
Usage
collect_sequential_lrt(session_id, project_dir = ".")
Arguments
session_id |
Session id from |
project_dir |
Project root the session was started under. |
Value
A list with state, phase, is_final, final_reference,
anchor_job_id, anchor_ofv_parity, the full decisions ledger,
accepted_effects/rejected_or_kept_effects, telemetry (fit counts,
elapsed timestamps, budget usage, and session_provenance for later
benchmarking via record_run()), and (once final) downstream_proposals.
Compare NLME fits on information criteria
Description
Synchronous, base-R comparison of two or more fits. Reads each source's
Overall.csv (a registered job_id, a fit .rds path, or an Overall.csv
path), builds a table of -2LL, AIC, BIC, and the parameter count, and ranks
by AIC and BIC with deltas against a reference (the best-AIC model by
default, falling back to BIC then -2LL when AIC is unavailable). Replaces
ad-hoc model-comparison scripts.
Usage
compare_nlme_jobs(
job_ids,
project_dir = ".",
reference_job_id = NULL,
nested = FALSE
)
Arguments
job_ids |
Character vector of registered job ids and/or paths to fit
|
project_dir |
Project root (for registered job ids). |
reference_job_id |
Optional id/path to use as the comparison reference; defaults to the lowest-AIC model. |
nested |
When |
Details
Likelihood-ratio p-values are computed ONLY when nested = TRUE, because an
LRT is valid only for nested models fit to the same data with comparable
likelihoods. The function reports the numbers; the caller is responsible for
the nesting claim.
Value
A structured, JSON-serializable list with models, ranking_by_aic,
ranking_by_bic, reference, optional lrt, and notes.
Detect and advise on below-quantification (BLQ/BQL) handling
Description
Read-only, base-R inspection of a PK/PD dataset that recommends how (and whether) to handle below-quantification data. It is deliberately gated: it recommends censored-likelihood handling only when a real signal is present
a censoring indicator column with censored rows, an LOQ/LLOQ column, or an explicit
user_requested = TRUE- and otherwise recommends plainobserve()with nobql. This prevents BLQ handling from being applied everywhere by default.
Usage
configure_blq_handling(
data_path,
dv_col = NULL,
blq_col = NULL,
loq_col = NULL,
obs_name = "CObs",
user_requested = FALSE,
model_rds = NULL,
apply = FALSE,
project_dir = "."
)
Arguments
data_path |
Path to a CSV dataset. |
dv_col, blq_col, loq_col |
Optional explicit column names; auto-detected when omitted. |
obs_name |
Observation variable name in the model (default |
user_requested |
Set |
model_rds |
Optional |
apply |
When |
project_dir |
Project root for resolving a relative |
Details
The advice is staged, reflecting the engine constraint that
observe(..., bql) (Beal's M3) and LL() disable Gaussian FO/FOCE: for early
structural-model exploration with BLQ present, excluding BLQ under FOCE (M1)
is an acceptable provisional step; the final/inferential model should use M3
with a likelihood method (Laplacian/QRPEM) when BLQ is material. M4 and other
non-M3 schemes are only available via a custom LL() expression; LOQ/2 (M5)
and zero-imputation (M7) are discouraged (sensitivity-only).
Value
A list with warranted, warrant_reason, blq_fraction,
detected, loq_kind, mapping_token, method_guidance, recommended,
a next_action directive (tool/args/reason; advisory text in
reason), warnings, and (when apply) apply results. blq_fraction is
NA_real_ when detected$dv_detected is FALSE (DV column not found);
callers must not use bare if (blq_fraction > 0.05) because NA is falsy
in if() without signalling unknown fraction.
Confirm a PML draft's structure matches the intended counts
Description
Engine-free structural confirmation: counts the fixef/ranef/error/
observe (and related) statements in a PML draft and, when an expected
named list is supplied, reports any mismatches. Optionally attempts a
textualmodel() build with a synthesized one-row dataset from a
column-mapping spec and runs validate_nlme_model() for a deeper check; the
build is best-effort and its failure is reported, not fatal.
Usage
confirm_pml_structure(
code = NULL,
expected = NULL,
column_map = NULL,
try_build = FALSE,
path = NULL
)
Arguments
code |
PML model code as a single string. Counting is whitespace- and
newline-agnostic, so minified PML (all statements on one line) is counted
correctly. Optional when |
expected |
Optional named list of expected counts (e.g. from a
translation analysis): any of |
column_map |
Optional column-mapping spec (as returned in a translation report) used to synthesize dummy data for the optional build. |
try_build |
Attempt the optional |
path |
Optional path to a PML file to read when |
Value
A list: counts, expected, mismatches, and (when try_build)
build.
Copy model object to iterate over base model
Description
Copies previously executed model into a new object and optionally accept all estimates returned from model execution. A new working directory is created and all files from base model are copied into it.
Usage
copyModel(model, acceptAllEffects = FALSE, modelName = "", workingDir = "")
Arguments
model |
Model object to be copied |
acceptAllEffects |
Set to |
modelName |
New model name for subdirectory created for model output. Subdirectory is created in current working directory. |
workingDir |
Working directory to run the model. Current working directory will be used if workingDir not specified. |
Value
Modified NlmePmlModel object
Examples
## Not run:
model <- pkmodel(
parameterization = "Clearance",
numCompartments = 2,
data = pkData,
ID = "Subject",
Time = "Act_Time",
A1 = "Amount",
CObs = "Conc",
workingDir = tempdir()
)
host <- hostParams(sharedDirectory = tempdir(),
parallelMethod = "None",
hostName = "local",
numCores = 1)
job <- fitmodel(model,
numIterations = 3,
hostPlatform = host)
finalModelVPC <- copyModel(model,
acceptAllEffects = TRUE,
modelName = "model_VPC",
workingDir = tempdir())
## End(Not run)
Sets style for a covariate/variable
Description
Sets style for a covariate/variable
Usage
covariateEffect(.Object, covariateName, parameterName) <- value
Arguments
.Object |
A PK/PD model |
covariateName |
Name of the covariate |
parameterName |
Name of the model variable |
value |
A value to set |
Creates set of covariate effects
Description
Use to create set of covariate effects to be checked during Stepwise or Shotgun covariate search
Usage
covariateModel(model)
Arguments
model |
Model object with covariates and covariate effects specified |
Value
CovariateEffectModel class object
Examples
## Not run:
# Define the model
model <- pkmodel(
numCompartments = 2,
data = pkData,
ID = "Subject",
Time = "Act_Time",
A1 = "Amount",
CObs = "Conc",
workingDir = tempdir()
)
# Add Gender covariate of type categorical
model <- addCovariate(model,
covariate = "Gender",
type = "Categorical",
effect = c("V2", "Cl2"),
levels = c(0, 1),
labels = c("Female", "Male")
)
# Add Bodyweight covariate of type continuous
model <- addCovariate(model,
covariate = "BodyWeight",
type = "Continuous",
direction = "Backward",
center = "Mean",
effect = c("V", "Cl")
)
covariateModel(model)
## End(Not run)
Return covariate names
Description
Use to return character vector of covariate names available in model object.
Usage
covariateNames(model)
Arguments
model |
Model object |
Value
Character vector of covariate names defined in model
Examples
model <- pkmodel(columnMap = FALSE,
workingDir = tempdir())
model <- addCovariate(model, covariate = "BW", effect = "V")
model <- addCovariate(model, covariate = "Age", effect = "Cl")
covariateNames(model)
Creates string from each covariate attribute
Description
Creates string from each covariate attribute
Usage
covariatePartsString(obj)
Arguments
obj |
Model covariate |
Parse the model and get the list of terms
Description
Calls TDL5 to parse the model and get the list of terms
Usage
createModelInfo(model, ForceRun = FALSE)
Arguments
model |
Model object |
ForceRun |
Set to |
Value
List of model information
Examples
## Not run:
model <- pkmodel(columnMap = FALSE,
workingDir = tempdir())
createModelInfo(model)
## End(Not run)
Create a metamodel file from an NlmePmlModel
Description
Creates (or overwrites) a textual metamodel file (e.g. .mmdl) from a
supplied NlmePmlModel object. This is the inverse of read_mmdl().
Usage
create_metamodel_from_model(
model,
metamodelFile,
datafile,
author = "",
engineParams = NULL,
tableParams = NULL,
absolutePaths = FALSE
)
Arguments
model |
An NlmePmlModel object. |
metamodelFile |
Output metamodel file path to create/overwrite. |
datafile |
Input data file path to write into the |
author |
Optional author string to write into the metamodel. |
engineParams |
Optional NlmeEngineExtraParams object created by
|
tableParams |
Optional table definition(s) created by |
absolutePaths |
Logical; controls how |
Value
Invisible model.
Examples
## Not run:
tmp_data <- tempfile(fileext = ".csv")
write.csv(Certara.RsNLME::pkData, tmp_data, row.names = FALSE)
m <- Certara.RsNLME::pkmodel(data = Certara.RsNLME::pkData, workingDir = tempdir())
ep <- Certara.RsNLME::engineParams(m, method = "FOCE-ELS", numIterations = 200)
out_mmdl <- file.path(tempdir(), "example.mmdl")
Certara.RsNLME::create_metamodel_from_model(m, out_mmdl, datafile = tmp_data, engineParams = ep)
## End(Not run)
Use to create model object from parsed metamodel
Description
Legacy entry point retained for sister-package compatibility. New code
should call read_mmdl() instead – it is the canonical user-facing
importer and gains future improvements first.
Usage
create_model_from_metamodel(mmdlfile, directoryToRun)
Arguments
mmdlfile |
File with metamodel description |
directoryToRun |
Directory where the results will be stored; if
|
Details
Builds an NlmePmlModel (plus engine / simulation parameters) from a metamodel file. See Metamodel overview.
Value
a list with the resulted model class instance and engine parameters.
If multiple ESTARGS/SIMARGS blocks are used, a list of estimation argument
classes (NlmeEngineExtraParams()) and simulation argument classes
(simParamsBlock) are returned.
See Also
Examples
## Not run:
ModelParamsList <-
create_model_from_metamodel(
mmdlfile = system.file("extdata/mmdlNoTime", "test.mmdl",
package = "Certara.RsNLME"),
directoryToRun = tempdir())
## End(Not run)
Initialize input data for PK/PD model
Description
Used to initialize input data for PK/PD model
Usage
dataMapping(.Object, data)
Arguments
.Object |
Model object |
data |
Input data of class |
Value
Modified NlmePmlModel object
See Also
Examples
model <- pkmodel(columnMap = FALSE,
workingDir = tempdir())
model <- dataMapping(model, pkData)
Deletes a secondary parameter from the model
Description
Deletes a secondary parameter from the model
Usage
deleteSecondary(.Object, name)
## S4 method for signature 'NlmePmlModel'
deleteSecondary(.Object, name)
Arguments
.Object |
An 'NlmePmlModel' object from which you want to delete a secondary parameter. |
name |
Name of the secondary parameter to be deleted. |
Value
Depends on the specific methods
Returns the 'NlmePmlModel' object with the secondary parameter removed.
Functions
-
deleteSecondary(NlmePmlModel): Method for the 'NlmePmlModel' classThis method deletes a secondary parameter from the NlmePmlModel object. It searches for the parameter by name, and if it is found, it removes it from the object and updates the PML model.
Return dose names
Description
Use to return character vector of dose point names in model object.
Usage
doseNames(model)
Arguments
model |
Model object |
Value
Character vector of dose names defined in model
Examples
model <- pkmodel(columnMap = FALSE,
workingDir = tempdir())
doses <- doseNames(model)
Draft PML from a NONMEM control stream
Description
Translates a conservative common-model subset of a NONMEM control stream into
a PML draft and returns a translation report with per-area confidence. Built
on analyze_nonmem_control(): standard ADVAN/TRANS structures, deterministic
$THETA/$OMEGA/$SIGMA conversions (including the $SIGMA variance to
error() standard-deviation square-root), recognized $PK/$ERROR idioms,
and an $INPUT-derived column-mapping spec. Anything outside the subset is
preserved as a needs_review item rather than guessed. v1 does not rewrite
the dataset.
Usage
draft_pml_from_nonmem(control_text = NULL, path = NULL)
Arguments
control_text |
Control-stream content as a single string. |
path |
Optional path to a control file (used when |
Value
A list: ok, pml (draft text), recommended_path,
builtin_constructor, translation_report (summary, per-area
confidence, deterministic, needs_review, data_requirements,
column_mapping_spec, estimation_notes), and the underlying analysis.
Directly edit PML text in model object
Description
Allows user to edit PML text in model object using internal text editor and return a new textual model containing the edited PML statements.
Usage
editModel(.Object)
Arguments
.Object |
Model object |
Value
Modified NlmePmlModel object
Examples
model <- pkmodel(columnMap = FALSE,
workingDir = tempdir())
if (FALSE) {
# will open an additional window with the model text:
newModel <- editModel(model)
}
Create an Emax or Imax model
Description
Use to create an Emax or Imax model
Usage
emaxmodel(
isPopulation = TRUE,
checkBaseline = FALSE,
checkFractional = FALSE,
checkInhibitory = FALSE,
checkSigmoid = FALSE,
data = NULL,
columnMap = TRUE,
modelName = "",
workingDir = "",
...
)
Arguments
isPopulation |
Is this a population model |
checkBaseline |
Set to |
checkFractional |
Set to |
checkInhibitory |
Set to |
checkSigmoid |
Set to |
data |
Input dataset |
columnMap |
If |
modelName |
Model name for subdirectory created for model output in current working directory. |
workingDir |
Working directory to run the model. Current working directory will be used
if |
... |
Arguments passed on to
|
Value
NlmePmlModel object
Column mapping
Note that quoted and unquoted column names are supported. Please see colMapping.
Examples
model <- emaxmodel(data = pkpdData, ID = "ID", C = "CObs", EObs = "EObs")
model <- emaxmodel(
checkBaseline = TRUE,
checkFractional = TRUE,
checkInhibitory = TRUE,
data = pkpdData,
ID = "ID",
C = "CObs",
EObs = "EObs"
)
# View PML Code
print(model)
Emax model mapping parameters
Description
Emax model mapping parameters
Usage
emaxmodel_MappingParameters(ID = NULL, C = NULL, EObs = NULL)
Arguments
ID |
Column mapping argument for input dataset column(s)
that identify individual data profiles. Only applicable to population models
|
C |
Column mapping argument that represents the input dataset column for the independent variable that is treated as a covariate during the estimation/simulation process. |
EObs |
Column mapping argument that represents the input dataset column for the observed drug effect (i.e., the dependent variable). |
Main function to specify engine parameters
Description
Use to define engine parameters for model execution.
Usage
engineParams(
model,
sort = NULL,
ODE = "MatrixExponent",
rtolODE = 1e-06,
atolODE = 1e-06,
maxStepsODE = 50000,
numIterations = 1000,
method = NULL,
stdErr = NULL,
isCentralDiffStdErr = TRUE,
stepSizeStdErr = NULL,
conditionNumber = c("CovarianceFixef", "CorrelationFixef", "CovarianceFull",
"CorrelationFull"),
logTransform = NULL,
numIntegratePtsAGQ = 1,
numIterNonParametric = 0,
allowSyntheticGradient = FALSE,
fastOptimization = FALSE,
numIterMAPNP = 0,
numRepPCWRES = 0,
stepSizeLinearize = 0.002,
numDigitLaplacian = 7,
numDigitBlup = 13,
gradTolOuter = 2e-04,
stepTolOuter = 1e-04,
gradTolInner = 1.71e-05,
stepTolInner = 7.07e-08,
refDeltaLagl = 0.001,
mapAssist = 0,
iSample = 300,
iAcceptRatio = 0.1,
impDist = "Normal",
tDOF = 4,
numSampleSIR = 10,
numBurnIn = 0,
freezeOmega = FALSE,
MCPEM = FALSE,
runAllIterations = FALSE,
scramble = "Owen",
emTolType = 0,
emConvLen = 10,
emConvCritVal = 5,
stepSizePartialDeriv = 1e-05,
numTimeStepPartialDeriv = 20
)
Arguments
model |
Model object. The type of model (population or individual) is determined by the model@isPopulation slot. If model@isPopulation is TRUE, the model is treated as a population model; otherwise, it's treated as an individual model. |
sort |
Logical; Specifies whether to sort the input data by subject and
time. If |
ODE |
Character; Specifies the ODE solver to be used. Options are:
|
rtolODE |
Numeric; Specifying relative tolerance for the numerical ODE solver. |
atolODE |
Numeric; Specifying absolute tolerance for the numerical ODE solver. |
maxStepsODE |
Numeric; Specifies the maximum number of steps allowed for the ODE solver. |
numIterations |
Integer; Specifies the maximum number of iterations for the estimation algorithm. Must be a non-negative integer, with a maximum value of 10000. |
method |
Character; Specifies the estimation method. For population
models, options are:
|
stdErr |
Character; Specifies the method for standard error computations. Options vary depending on the model type and estimation method:
|
isCentralDiffStdErr |
Logical; If |
stepSizeStdErr |
Numeric; Specifies the relative step size used for the
numerical computation of the Hessian matrix during standard error
calculations. If not specified, a default value is used (0.001 for
|
conditionNumber |
Character; Selects the basis and scope used to compute the reported condition number when standard errors are produced. One of:
This argument is independent of |
logTransform |
Logical or NULL; Controls log-transformation behavior, particularly for models with a LogAdditive residual error (e.g., C*exp(epsilon)). The internal engine parameter 'logtran' is set based on this argument and specific model characteristics as detailed below.
For other model configurations, the
|
numIntegratePtsAGQ |
Integer; Specifies the number of quadrature points
per dimension to use for Adaptive Gaussian Quadrature (AGQ). Only
applicable to population models when
|
numIterNonParametric |
Integer; Controls non-parametric (NP) optimization.
Only applicable to population models when |
allowSyntheticGradient |
Deprecated. |
fastOptimization |
Controls the use of Automatic Differentiation (AD)
during optimization. Accepts a logical value for backward compatibility or
a character string specifying the AD mode. Only applicable to population
models when Accepted values:
|
numIterMAPNP |
Integer; Specifies the number of iterations for a
preliminary Naive-Pooled (NP) optimization run before the main estimation.
Applicable when the |
numRepPCWRES |
Integer; Specifies the number of replicates to generate
for Population Conditional Weighted Residuals (PCWRES) calculations.
Setting this value to 0 disables PCWRES computation. Only applicable to
population models when method is not set to |
stepSizeLinearize |
Numeric; Specifies the relative step size for numerical differentiation during model linearization. |
numDigitLaplacian |
Numeric; Specifies the optimization accuracy
(NDIGIT) for the outer loop (thetas and sigmas) when using
|
numDigitBlup |
Numeric; Specifies the optimization accuracy (NDIGIT) for
the inner loop (optimization of etas). Also applies to the single
optimization loop in the |
gradTolOuter |
Numeric; maximum gradient tolerance for the outer loop (Theta/Omega/Sigma optimization) of "FOCE-ELS" or "Laplacian" method. This tolerance controls how close the gradient must be to zero before the outer optimization is considered converged. |
stepTolOuter |
Numeric; maximum step tolerance for the outer loop (Theta/Omega/Sigma optimization) of "FOCE-ELS" or "Laplacian" method. This measures the relative change in the solution vector between iterations. |
gradTolInner |
Numeric; maximum gradient tolerance for the inner loop (Eta optimization) of "FOCE-ELS" or "Laplacian" method. A smaller value forces the algorithm to iterate until a very small gradient is achieved. |
stepTolInner |
Numeric; maximum step tolerance for the inner loop (Eta optimization) of "FOCE-ELS" or "Laplacian" method. This determines when the algorithm will terminate based on minimal changes in the solution vector. |
refDeltaLagl |
Numeric; tolerance for the change in the log-likelihood (LL) value during outer loop optimization of "FOCE-ELS" or "Laplacian" method. This parameter is used to check convergence by comparing the absolute change in LL between major iterations. If the change in LL is less than refDeltaLagl and the optimization driver returns a specific termination code, the algorithm considers the solution sufficiently converged. This tolerance helps to avoid unnecessary iterations when improvements in LL become marginal. |
mapAssist |
Numeric; Controls the use of MAP assistance in the QRPEM algorithm.
Only applicable to population models with |
iSample |
Numeric; Specifies the number of sample points used in the
QRPEM algorithm. Only applicable to population models with |
iAcceptRatio |
Numeric; Specifies the acceptance ratio used in the QRPEM
algorithm for scaling the covariance matrix. Only applicable to population
models with |
impDist |
Character; Specifies the importance sampling distribution used
in the QRPEM algorithm. Options are: |
tDOF |
Numeric; Specifies the degrees of freedom for the multivariate T
distribution used in importance sampling. Only applicable when |
numSampleSIR |
Numeric; Specifies the number of samples per eta per
subject used in the Sampling Importance Resampling (SIR) algorithm within
QRPEM. Only applicable to population models with |
numBurnIn |
Numeric; Specifies the number of burn-in iterations in the
QRPEM algorithm. During burn-in, omegas can be frozen (see
|
freezeOmega |
Logical; Set to |
MCPEM |
Logical; Controls the sampling method used in the QRPEM algorithm.
Only applicable to population models with |
runAllIterations |
Logical; Set to |
scramble |
Character; Specifies the scrambling method for quasi-random
number generation in the QRPEM algorithm. Options are: |
emTolType |
Numeric; QRPEM convergence check type. Options:
Only applicable to population models with method = "QRPEM". |
emConvLen |
Numeric; number of iterations over which convergence is checked in the QRPEM method. Only applicable to population models with method = "QRPEM" and emTolType being nonzero. |
emConvCritVal |
Numeric; critical value used in the QRPEM convergence check. It specifies the threshold improvement required to continue iterating. Only applicable to population models with method = "QRPEM" and emTolType being nonzero. |
stepSizePartialDeriv |
Numeric; Specifying the step size used to numerically calculate the partial derivatives of observed variables with respect to parameters. Only applicable to individual models. |
numTimeStepPartialDeriv |
Numeric; Specifying the number of time steps used to output the partial derivatives of observed variables with respect to parameters. Only applicable to individual models. |
Details
Both "DVERK" and "DOPRI5" are non-stiff solvers.
"AutoDetect" represents LSODA solver implemenation, which solves the
initial value problem for stiff or nonstiff systems of first order ordinary
differential equations. "Stiff" is a LSODE (Livermore solver). It is
best suited for stiff problems. "MatrixExponent" is a matrix
exponential solver.
For the QRPEM method, the impDist parameter controls the importance
sampling distribution. The ximpsampdof slot in the internal
NlmeEngineExtraParams object is set based on impDist as
follows:
-
"Normal":ximpsampdof= 0 -
"DoubleExponential":ximpsampdof= 1 -
"Direct":ximpsampdof= 2 -
"T":ximpsampdofis set to the value oftDOF. -
"Mixture-2":ximpsampdof= -2 -
"Mixture-3":ximpsampdof= -3
The conditionNumber argument controls both the scope (which
parameters) and the basis (covariance vs. correlation) used to derive the
reported eigenvalues and condition in the engine's
out.txt. Let C be the variance-covariance matrix of the
selected parameters, as produced by the standard-error step (Hessian,
sandwich, or Fisher-score, selected by stdErr); its diagonal
entries are the squared standard errors of the estimates and its
off-diagonals are their estimated covariances.
Scope (which parameters make up C):
-
"...Fixef": only the estimated fixed effects. -
"...Full": all estimated population parameters (fixed effects, standard deviations of residual errors, elements of variance/covariance matrix of the random effects).
Basis (how C is used):
-
"Covariance..."(default scope is Fixef): eigenvalues are those ofCdirectly, andcondition = sqrt(lambda_max / lambda_min), wherelambda_minandlambda_maxare the smallest and largest strictly positive eigenvalues, respectively. This value is scale-dependent: parameters spanning many orders of magnitude (e.g. typical PK fixed effects) inflate it even when the fit is well-conditioned in correlation terms. -
"Correlation...":Cis first normalised to the correlation matrixR = D^(-1/2) * C * D^(-1/2), whereD = diag(C)(the parameter variances); reported eigenvalues are those ofRandcondition = lambda_max / lambda_min. The result is scale-invariant and reflects only the correlation structure of the estimates. If any diagonal ofCis non-positive or non-finite the correlation matrix is undefined and both lines are suppressed.
Only "CorrelationFull" matches NONMEM's condition-number scope
(all estimated THETA/OMEGA/SIGMA, correlation basis); use it for direct
comparison with NONMEM output. The other three options are not
NONMEM-comparable.
Value
List of engine parameters to be used during fitting or simulation
Return extra dose lines
Description
Use to return extra dose lines for model object
Usage
extraDoseLines(model)
Arguments
model |
Model object |
Value
List of extra dose information
Examples
data <- pkData
data$II <- 24
data$ADDL <- 1
model <-
pkmodel(
parameterization = "Clearance",
numCompartments = 2,
data = data,
ID = "Subject",
Time = "Act_Time",
A1 = "Amount",
CObs = "Conc",
workingDir = tempdir())
addDoseCycle(
model,
name = "A1",
amount = 30000,
II = 24,
type = "ADDL",
colName = "ADDL")
extraDoseLines(model)
Return extra dose names
Description
Use to return extra dose names for model object
Usage
extraDoseNames(model)
Arguments
model |
Model object |
Value
Character vector of extra dose names
Examples
data <- pkData
data$II <- 24
data$ADDL <- 1
model <-
pkmodel(
parameterization = "Clearance",
numCompartments = 2,
data = data,
ID = "Subject",
Time = "Act_Time",
A1 = "Amount",
CObs = "Conc",
workingDir = tempdir())
addDoseCycle(
model,
name = "A1",
amount = 30000,
II = 24,
type = "ADDL",
colName = "ADDL")
extraDoseNames(model)
extract files used for powershell script
Description
Use for extraction of the NLME files from mmdl file.
Usage
extract_mmdl(
mmdlfile,
directoryToExtract,
dataFileName = "data1.txt",
mdlOutput = "test.mdl",
cols1Output = "cols1.txt",
nlmeargsOutput = "nlmeargs.txt"
)
Arguments
mmdlfile |
The metamodel file path; relative paths are acceptable. |
directoryToExtract |
The directory where the files should be stored
If |
dataFileName |
the name of the data file
If |
mdlOutput |
the name of the file to output PML code
If |
cols1Output |
the name of the file to output columns defintion
If |
nlmeargsOutput |
the name of the file to output engine parameters
If |
Details
mdlOutput, dataFileName, cols1Output, nlmeargsOutput files are
extracted into the folders, the names of the folders are built as
{Number of estimation/simulation block in metamodel}-
{'est' for estimation block/'sim' for simulation block}. All estimation blocks are going first
irrespective of the simulation blocks presence, all simulation blocks
are going next.
Value
The results of read_mmdl() run are returned.
See Also
Examples
## Not run:
# path to metamodel should be specified, all other arguments set to default
extract_mmdl(system.file("extdata/mmdlNoTime", "test.mmdl",
package = "Certara.RsNLME"),
directoryToExtract = tempdir())
## End(Not run)
Executes an NLME simple estimation
Description
Executes an NLME simple estimation
Usage
fitmodel(
model,
hostPlatform = NULL,
params,
simpleTables,
runInBackground = FALSE,
filesToReturn = "*",
...,
saveResult = TRUE
)
Arguments
model |
PK/PD model class object. |
hostPlatform |
Host definition for model execution. See |
params |
Engine parameters. See |
simpleTables |
Optional list of simple tables. See
|
runInBackground |
Logical. When Background execution is supported only on Linux hosts, whether
local or remote: a local host whose |
filesToReturn |
Used to specify which files to be outputted to the model directory
and loaded as returned value. By default, all the applicable files listed
in the |
... |
Additional arguments for |
saveResult |
Logical; if |
Value
if runInBackground is FALSE, a list with main
resulted dataframes is returned:
Overall
ConvergenceData
residuals
Secondary
StrCovariate - if continuous covariates presented
StrCovariateCat - if categorical covariates presented
theta
posthoc table
posthocStacked table
Requested tables
nlme7engine.log textual output is returned and loaded with the main information related to
fitting. dmp.txt structure with the results of fitting (including LL by subject information)
is returned and loaded. These 2 files are returned and loaded irrespective of
filesToReturn argument value.
For individual models, additional dataframe with partial derivatives is returned:
ParDer
For population models and the method specified is NOT Naive-Pooled,
additional dataframes are returned:
omega
Eta
EtaStacked
EtaEta
EtaCov
EtaCovariate - if continuous covariates presented
EtaCovariateCat - if categorical covariates presented
bluptable.dat
If standard error computation was requested and it was successful, additional dataframes are returned:
thetaCorrelation
thetaCovariance
Covariance
omega_stderr
If nonparametric method was requested (numIterNonParametric > 0) and
the method specified in engineParams is NOT Naive-Pooled,
additional dataframes are returned:
nonParSupportResult
nonParStackedResult
nonParEtaResult
nonParOverallResult
if runInBackground is TRUE, a FitNlmeJob object is
returned. Pass it to collectJob() when the engine has
finished to materialise the same list described above.
filesToReturn with Certara.Xpose.NLME
If filesToReturn is used and "ConvergenceData.csv" and "residuals.csv"
are not in the patterns, these files won't be returned and loaded. These files
are essential for Certara.Xpose.NLME::xposeNlmeModel and
Certara.Xpose.NLME::xposeNlme functions. This makes impossible to
use the resulted object in Certara.Xpose.NLME functions.
Non-loaded but returned files
The non-loaded but returned files in the model working directory are:
err1.txt - concatenated for all runs detailed logs for all steps of optimization,
out.txt - general pivoted information about results,
doses.csv - information about doses given for all subjects,
iniest.csv - information about initial estimates
Self-describing run context
The returned list also carries five run-context elements that make the object self-describing:
-
model- the inputNlmePmlModelas it was at the start of the run (with@modelInfo@workingDirpointing at the artifacts). -
params- the resolvedNlmeEngineExtraParamsactually used. -
runMode- the string"fitmodel". -
runTime- a list withstart,end, andelapsedwall-clock times measured around the engine call. This is distinct from the engine-reported CPU time innlme7engine.log. -
RsNLMEVersion- the package version that produced the result.
No host, machine name, user name, password, or private key path is ever placed in the returned value or in the saved file.
See Also
tableParams, hostParams,
engineParams, collectJob
Examples
## Not run:
# Define the host
host <- hostParams(sharedDirectory = tempdir(),
parallelMethod = "None",
hostName = "local",
numCores = 1)
# Define the model
model <- pkmodel(numComp = 2,
absorption = "FirstOrder",
ID = "Subject",
Time = "Act_Time",
CObs = "Conc",
Aa = "Amount",
data = pkData,
modelName = "PkModel",
workingDir = tempdir())
Table01 <- tableParams(name = "SimTableObs.csv",
timesList = "0,1,2,4,4.9,55.1,56,57,59,60",
variablesList = "C, CObs",
timeAfterDose = FALSE,
forSimulation = FALSE)
# Update fixed effects
model <- fixedEffect(model,
effect = c("tvV", "tvCl", "tvV2", "tvCl2"),
value = c(16, 41, 7, 14))
# Define the engine parameters
params <- engineParams(model)
# Fit model
res <- fitmodel(model = model,
hostPlatform = host,
params = params,
simpleTables = Table01)
## End(Not run)
Specifies the initial values, lower bounds, upper bounds, and units for fixed effects in a model
Description
Built-in-model structural setter for fixed-effect (theta) initials, bounds,
freeze status, and units. Use during model construction when units are
needed, or when configuring several thetas together as part of setup.
Cannot be used on textual or edited models; for pipe-friendly value,
bounds, and freeze edits on built-in or textual models, see
update_Thetas() (textual models also support enable; neither API sets
units except this one).
Usage
fixedEffect(
.Object,
effect,
value = NULL,
lowerBound = NULL,
upperBound = NULL,
isFrozen = NULL,
unit = NULL
)
Arguments
.Object |
Model object in which to define fixed effects values |
effect |
Character or character vector specifying names of fixed effects |
value |
Numeric or numeric vector specifying the initial values of fixed effects. If supplying vector, must be in the same order/length as corresponding |
lowerBound |
Numeric or numeric vector specifying the lower limit values of fixed effects. If supplying vector, must be in the same order as |
upperBound |
Numeric or numeric vector specifying the upper limit values of fixed effects. If supplying vector, must be in the same order as |
isFrozen |
Logical or logical vector. Set to |
unit |
Character or character vector specifying units of measurement for the fixed effects. If supplying a vector, must be in the same order as |
Value
Modified NlmePmlModel object
See Also
Examples
model <- pkmodel(
numCompartments = 2,
data = pkData,
ID = "Subject",
Time = "Act_Time",
A1 = "Amount",
CObs = "Conc",
modelName = "TwCpt_IVBolus_FOCE_ELS",
workingDir = tempdir()
)
# View initial/current fixed effect values
initFixedEffects(model)
model <-
fixedEffect(
model,
effect = c("tvV", "tvCl", "tvV2", "tvCl2"),
value = c(15, 5, 40, 15)
)
Generates PML statements based on the current model
Description
Generates PML statements based on the current model
Usage
generatePML(.Object)
Arguments
.Object |
PK/PD Model |
Return random effect names in model
Description
Use to return character vector of random effect names (if available) in model object
Usage
getRandomEffectNames(model)
Arguments
model |
Model object |
Value
Characters vector of random effect names
Examples
model <- pkmodel(columnMap = FALSE,
workingDir = tempdir())
getRandomEffectNames(model)
Retrieve model and fitmodel-style results for a selected covariate search scenario.
Description
Dispatches on the type of x to resolve an archived covariate-search
run folder and scenario, then loads the base model and run context from
rsnlme_run.rds and reconstructs the scenario-specific model. Use
listSCMRuns to enumerate scenarios in one or more such folders.
Usage
getSCMResults(x, scenario = NULL, enableIDs = NULL)
Arguments
x |
One of:
|
scenario |
Optional scenario identifier (label or token). Only
allowed when |
enableIDs |
Optional comma-separated string or integer vector of
enable IDs to select a scenario by its active PML |
Details
When x is a row-subset of a search-result data frame and the
caller does not specify a scenario explicitly, selection is restricted
to the subset: if the archive's flagged best scenario is filtered out,
the row with the lowest value of the search's selection criterion
(-2LL, AIC, or BIC; recorded for stepwise searches
and always -2LL for shotgun) within the subset is
returned. For stepwise this need not match the engine's chosen winner,
because the user has explicitly excluded that row by subsetting.
Value
An scmResult object (list-like, with a custom
print method) containing three elements:
- model
The reconstructed
NlmePmlModelfor the scenario, with accepted parameter estimates.- fitmodelOutput
A list compatible with
fitmodel()output. In addition to the file-derived elements, this list carries the self-describing fields:model(the reconstructed scenario model),params(resolvedNlmeEngineExtraParams),runMode("stepwise"or"shotgun"),runTime(wall-clock list), andRsNLMEVersion.- scenarioInfo
A single-row data frame with scenario metadata.
Archived run folders
Archived folders are created when shotgunSearch() or
stepwiseSearch() is run with archiveResults = TRUE.
During the engine run, NLME8 writes scenario outputs under a temporary
SCM_<runId>/ directory in the model working directory
(runId is a wall-clock timestamp, optionally suffixed with
runLabel). After the engine finishes, collectJob()
materialises the search result and the package renames that tree into a
durable folder named stepwise_<runId> or shotgun_<runId>
(on remote hosts the bundle SCM_<runId>.tar.gz is extracted
first, then the bundle and any loose SCM_<runId>/ copy are
removed). The final folder holds scenario_index.csv,
per-scenario subfolders, Overall.csv, optional stepwise logs,
and rsnlme_run.rds.
See Also
shotgunSearch, stepwiseSearch,
summary(),
print(),
listSCMRuns
Return theta names and values
Description
Returns named character vector of theta values by parsing PML fixed effect statements
Usage
getThetas(model)
Arguments
model |
PK/PD model |
Value
Character vector of theta names defined in model
Examples
## Not run:
model <- emaxmodel(
checkBaseline = TRUE,
checkFractional = TRUE,
checkInhibitory = TRUE,
data = pkpdData,
ID = "ID",
C = "CObs",
EObs = "EObs"
)
getThetas(model)
## End(Not run)
Get the structured fit summary for a job
Description
Lightweight companion to collect_nlme_job() that returns just the parsed
numeric summary (fit_summary) plus fit_health, for any completed fit -
including .mmdl/run_metamodel jobs started by start_nlme_fit() that have
no fit.rds. In that case the estimates, omega diagonal, and shrinkage are
parsed from the engine artifacts (Overall.csv, theta.csv, omega.csv) so
the agent reads numbers rather than hand-parsing CSVs. fit_summary$estimates_source
reports whether the values came from fit.rds or the artifacts.
Usage
get_fit_summary(job_id, project_dir = ".", full_omega = FALSE)
Arguments
job_id |
Job id from a |
project_dir |
Project root that owns the run (must match the one used to launch the job). |
full_omega |
When |
Details
By default only the omega diagonal and shrinkage are surfaced. Set
full_omega = TRUE to also return the full symmetric omega matrix as
fit_summary$random_effects_matrix (with random_effects_eta_names); this is
what block random-effects models such as FREM need for covariate
post-processing (e.g. beta = Omega_pc %*% solve(Omega_cc)).
Value
A list with job_id, state, job_kind, run_dir, fit_health,
fit_summary, and artifact_integrity. fit_summary additionally carries
parameter_table (per-parameter estimate/SE/%RSE/CI/shrinkage plus
se_missing and boundary_status), a single uncertainty_status, and a
diagnosis block that proposes - never launches - a bootstrap when a
converged fit has missing standard errors and boundary evidence. When
artifact_integrity$status is "violation" the directory was overwritten
after this fit was recorded and fit_summary$next_step says so. For an
unknown id, state == "not_found".
See Also
collect_nlme_job(), get_nlme_job_status()
Get the status of an NLME job
Description
The lifecycle field is state (not status): one of running, succeeded,
failed, dead, unknown, or not_found. The artifacts directory is
artifact_dir (not artifacts_dir) and equals file.path(run_dir, "artifacts"). This is a single-shot progress snapshot - it reads the latest
status once and returns immediately:
Usage
get_nlme_job_status(
job_id,
project_dir = ".",
wait_seconds = 0,
poll_interval = 2
)
Arguments
job_id |
Job id from |
project_dir |
Project root. |
wait_seconds |
Optional server-side wait: block (polling every
|
poll_interval |
Seconds between internal polls while waiting (default 2,
minimum 0.5). Ignored when |
Details
st <- get_nlme_job_status(job_id, project_dir) artifact_dir <- st$artifact_dir
To watch a long fit without burning agent turns, prefer wait_for_nlme_job(),
which blocks server-side using the launch-configured watch budget. The
wait_seconds/poll_interval arguments here are retained for backward
compatibility and advanced manual R use; wait_for_nlme_job() is the
agent-facing watcher.
Value
A list with job_id, state, timing (started/finished/
exit_code), pid, run_dir, artifact_dir, live progress, and (for a
terminal job) fit_health. This is the raw snapshot primitive; the
agent-facing next_action directive is added by wait_for_nlme_job().
See Also
wait_for_nlme_job() for the preferred long-job watcher.
Project workflow status: state, blocking issues, and next tools
Description
Read-only aggregation of the artifacts a project already produces - the saved
analysis plan, the job registry (jobs.jsonl), and the covariate-search
directory - into one snapshot so an agent can see where it is and what to do
next without inferring from scattered files. Nothing is written.
Usage
get_project_workflow_status(project_dir = ".")
Arguments
project_dir |
Project root. |
Value
A list with analysis_plan, jobs, covariate_search, vpc,
qualification (sequential-LRT session summary; see
list_sequential_lrt_sessions()), data_inspection,
blocking_issues, and recommended_next_tools.
Read the latest saved PopPK analysis plan
Description
Read-only companion to save_analysis_plan(): returns the latest versioned
plan persisted under <project_dir>/analysis-plan/ so downstream tools and
agents reference the plan by its stable handle instead of re-reading files by
hand. When no plan has been saved, returns saved = FALSE with a
next_action directive (blocking) pointing at save_analysis_plan().
Usage
get_saved_analysis_plan(project_dir = ".")
Arguments
project_dir |
Project root; the artifact directory is
|
Value
A list with saved and, when a plan exists, analysis_plan_id,
analysis_plan_version, intended_use, content_sha256, created,
latest_path, open_critical_issues, and the full plan body.
Read-only sequential-LRT session status (no state transition)
Description
Unlike advance_sequential_lrt(), this never launches a fit, decides a
phase winner, or mutates the persisted session; it only attaches a live
state peek (via a single-shot, non-blocking get_nlme_job_status()) for
the anchor or any running candidate jobs.
Usage
get_sequential_lrt_status(session_id, project_dir = ".")
Arguments
session_id |
Session id from |
project_dir |
Project root the session was started under. |
Value
The same status shape as advance_sequential_lrt(), with a
live_state field added to operations[[i]] while status == "running" (and top-level anchor_live_state while anchoring).
Create an NLME Parallel Host Configuration
Description
This helper function simplifies the creation and configuration of an
NlmeParallelHost object, which defines the environment for running NLME
jobs.
Usage
hostParams(
sharedDirectory,
installationDirectory = NULL,
hostName = Sys.info()[["nodename"]],
machineName = "127.0.0.1",
hostType = Sys.info()[["sysname"]],
numCores = 4,
parallelMethod = "LOCAL_MPI",
mpiCoresPerJob = NA_integer_,
userName = "",
privateKeyFile = NULL,
userPassword = "",
scriptPath = "",
rLocation = "",
isLocal = TRUE,
gridQueue = "",
gridWalltime = NA_integer_,
gridMemory = "",
gridJobNamePrefix = "",
gridResourceExtra = ""
)
Arguments
sharedDirectory |
|
installationDirectory |
|
hostName |
|
machineName |
|
hostType |
|
numCores |
|
parallelMethod |
|
mpiCoresPerJob |
|
userName |
|
privateKeyFile |
|
userPassword |
|
scriptPath |
|
rLocation |
|
isLocal |
|
gridQueue |
|
gridWalltime |
|
gridMemory |
|
gridJobNamePrefix |
|
gridResourceExtra |
|
Details
Remote Windows hosts are not supported. Background execution
(runInBackground = TRUE on fitmodel() and the other job wrappers) is
available only on Linux hosts (local or remote); on Windows hosts use
runInBackground = FALSE.
Value
An NlmeParallelHost object configured with the specified
parameters.
Examples
host <- hostParams(sharedDirectory = tempdir(),
parallelMethod = "LOCAL_MPI",
hostName = "Local",
numCores = 4)
# Local hybrid: run several models concurrently, each with its own MPI ranks.
# numCores = 10 with mpiCoresPerJob = 2 fits up to 5 models at a time,
# 2 MPI ranks each.
hybridHost <- hostParams(sharedDirectory = tempdir(),
parallelMethod = "Multicore_MPI",
hostName = "LocalHybrid",
numCores = 10,
mpiCoresPerJob = 2)
# Omit mpiCoresPerJob to let NLME8 size the per-job rank from the batch.
autoHybridHost <- hostParams(sharedDirectory = tempdir(),
parallelMethod = "Multicore_MPI",
hostName = "LocalHybridAuto",
numCores = 10)
# Grid host routing long batch work to a non-interactive queue, with an
# informative job name shown in qstat/squeue.
gridHost <- hostParams(sharedDirectory = "~",
parallelMethod = "SGE_MPI",
hostName = "sge",
numCores = 32,
gridQueue = "bg.q",
gridMemory = "16G",
gridJobNamePrefix = "BOOT_prod",
isLocal = FALSE)
Impute missing covariate values
Description
Replaces user-defined sentinel values (default -99) in covariate
columns with values that the NLME engine can consume, leaving the
PML model code untouched. Within a reset block, masked rows are
left as NA so the engine performs row-level propagation via
fcovariate() / covariate() / interpolate(); only blocks (and
subjects) where the engine has nothing to propagate receive an
externally-computed fallback value.
Usage
imputeMissingCovariates(
model,
data = NULL,
missingToken = c(-99),
method = c("subject", "population"),
continuousFn = stats::median,
categoricalFn = imputeMode,
centralValueWeighting = c("subject", "row"),
stratifyBy = NULL,
minStratumFraction = 0.1,
keepOriginal = TRUE,
logFile = NULL
)
Arguments
model |
|
data |
Optional |
missingToken |
Vector of sentinel values. Default |
method |
|
continuousFn |
Function applied to a non-empty numeric vector
returning a single value. Default |
categoricalFn |
Function applied to a non-empty vector
(character, factor, or numeric for occasion / numeric-coded
categorical) returning a single value. Default
|
centralValueWeighting |
How the population / stratum central
value is pooled.
Under |
stratifyBy |
Optional character vector of categorical column names. Population fallback is then computed within each stratum. |
minStratumFraction |
Minimum acceptable stratum size as a
fraction of total subjects; a warning is issued if any stratum is
smaller. Default |
keepOriginal |
If |
logFile |
Path to write the imputation log. Default The returned path uses forward slashes on every platform so it can be copied straight out of the console. |
Details
The function returns a modified clone of the input NlmePmlModel
(with @inputData replaced by the imputed data.frame), along with
the imputed data, a traceability summary, and a log file. All other
model slots (@columnMapping, @covariateList, @statements,
@hasResetInfo, @resetInfo, etc.) are preserved verbatim so custom
mappings like WT -> BodyWeight survive the round-trip.
Imputation cascade (method = "subject", default). The NLME engine
propagates covariate values within a reset block but cannot carry
them across blocks, so the cascade classifies each (subject, reset
block):
-
Block has at least one non-missing value – masked rows are left as
NA(source"engine"). The engine fills them viafcovariate()/covariate()/interpolate(). -
Block is fully missing but the subject has non-missing values in other blocks – the masked rows are filled with the subject aggregate computed by
continuousFn/categoricalFnover the subject's non-missing values across all blocks (source"propagated"). -
Subject is fully missing across every block – the masked rows are filled with the population (or stratum) central value (source
"population"or"stratum").
method = "population" skips subject-level lookups and replaces
every masked row with the population (or stratum) central value.
Note the two methods differ in their effect on covariate centering.
method = "subject" leaves masked rows as NA, and the engine
excludes missing rows when it computes mean() / median()
centering values, so centering is unaffected. method = "population" writes a value into every masked row, and those values
do take part in centering.
Value
A list with elements:
-
model– clone of inputNlmePmlModelwith@inputDatareplaced by the imputeddata.frame. -
data– imputeddata.frame(same object asresult$model@inputData). -
summary–data.framewith one row per (covariate, column, imputation_source, stratum) combination. Columns:covariate,column,type,imputation_source,stratum,imputed_value,n_imputed,n_subjects_affected.imputed_valueisNAfor"engine"(no value written; the engine fills at run time), a truncated list of distinct per-subject donors for"propagated", and the pooled central value for"stratum"/"population". -
logFile– absolute path of the written log file.
Examples
## Not run:
model <- pkmodel(...)
model <- addCovariate(model, "WT", type = "Continuous")
model <- colMapping(model, c(WT = "BodyWeight"))
result <- imputeMissingCovariates(model)
model <- result$model
fit <- fitmodel(model)
print(result$summary)
## End(Not run)
Modal value with deterministic tie-break (default categorical aggregator)
Description
Returns the most frequent value in x. Used as the built-in default
for imputeMissingCovariates()'s categoricalFn argument, and
exposed publicly so callers can plug it into their own workflows or
compose it with other rules.
Usage
imputeMode(x, missingToken = NULL)
Arguments
x |
A non-empty atomic vector (character, factor, numeric, integer, or logical). Length-0 input errors. |
missingToken |
Optional atomic vector of sentinel values to
exclude from the candidate set (compared after |
Details
Properties:
-
Deterministic tie-break. When two or more values tie for the highest frequency, the one that appears first in
xwins. This makes the result stable across runs and independent of locale- sensitive ordering insidetable(). -
Factor-preserving. If
xis a factor, the return value is a factor with the samelevels(x). Plain character / numeric vectors return a length-1 value of the same atomic type. -
NA-tolerant.NAentries are ignored when computing the mode. If every entry isNAthe function errors. -
Optional token avoidance. When
missingTokenis supplied, values matching any element of it are excluded from the candidate set.imputeMissingCovariates()masks the input pool up-front so this is normally a no-op there; the parameter is useful when callingimputeMode()standalone on a raw vector that may still contain sentinels.
Value
A length-1 value of the same atomic type as x (factor for
factor input).
Examples
imputeMode(c("M", "F", "M", "F")) # "M" (ties: first wins)
imputeMode(factor(c("M", "F", "M"), levels = c("F","M"))) # factor "M"
imputeMode(c(70, 70, 65, -99), missingToken = -99) # 70
Attach input data to a model and initialize its column mapping
Description
initColMapping<- attaches an input dataset to an NlmePmlModel and
builds its column mapping in one step. Use it when the data arrives
separately from the model - for example after read_mmdl returned
a model with @inputData = NULL because the ## DATA file was
missing. To edit an existing mapping instead (the data is already attached),
use colMapping(model) <- c(...).
Usage
initColMapping(.Object) <- value
## S4 replacement method for signature 'NlmePmlModel'
initColMapping(.Object) <- value
Arguments
.Object |
An |
value |
A |
Value
The updated NlmePmlModel with @inputData and
@columnMapping set.
See Also
Examples
## Not run:
res <- read_mmdl("model.mmdl") # ## DATA missing -> @inputData is NULL
initColMapping(res$model) <- myData
## End(Not run)
Display/Set initial estimates for fixed effects
Description
Display/Set initial estimates for fixed effects
Usage
initFixedEffects(.Object)
## S4 method for signature 'NlmePmlModel'
initFixedEffects(.Object)
initFixedEffects(.Object) <- value
## S4 replacement method for signature 'NlmePmlModel'
initFixedEffects(.Object) <- value
Arguments
.Object |
PK/PD model |
value |
Named numeric vector |
Value
Named numeric vector of fixed effects estimates
See Also
Examples
model <- pkmodel(
numCompartments = 2,
data = pkData,
ID = "Subject",
Time = "Act_Time",
A1 = "Amount",
CObs = "Conc",
modelName = "TwCpt_IVBolus_FOCE_ELS",
workingDir = tempdir()
)
# View initial/current fixed effect values
initFixedEffects(model)
# May also use as a 'replacement function' to set the values
initFixedEffects(model) <- c(tvV = 15, tvCl = 5, tvV2 = 40, tvCl2 = 15)
Inspect a built NlmePmlModel
Description
Read-only introspection of a model saved as .rds: the current column
mapping (with any unmapped model terms called out), dose points, the
additional-dose / steady-state / MDV flags wired via
addADDL()/addSteadyState()/addMDV(), declared covariates, structural
parameters, and random-effect statements. Use it to see what a model still
needs before fitting (e.g. an observation term mapped to "?", or whether an
ADDL column was actually registered) instead of hand-parsing the object.
Usage
inspect_nlme_model(model_rds)
Arguments
model_rds |
Path to an |
Value
A list with is_textual, model_type, is_population,
structural_params, column_mapping (term/column/type rows),
unmapped_terms, dose_points, extra_dose_defs, covariates,
random_effects, and mapping_complete.
Inspect a PK dataset (read-only)
Description
Synchronous, base-R, read-only exploratory summary of a PK/PD dataset so an
agent can assess data adequacy through MCP instead of ad-hoc Python/shell R.
Never writes or modifies the dataset. A tiny last-inspect stamp may be
written under the pinned project's .certara-mcp/ so
get_project_workflow_status() can report that inspection ran. Data
cleaning that writes output is a separate, explicit step (see
prepare_pk_data.R).
Usage
inspect_pk_dataset(
data_path,
id_col = NULL,
time_col = NULL,
dv_col = NULL,
amt_col = NULL,
rate_col = NULL,
mdv_col = NULL,
dvid_col = NULL,
na_strings = c("NA", ".", ""),
max_dup_report = 20
)
Arguments
data_path |
Path to a CSV dataset. |
id_col, time_col, dv_col, amt_col, rate_col, mdv_col, dvid_col |
Optional
explicit column names; auto-detected when |
na_strings |
Strings treated as missing (default |
max_dup_report |
Max duplicate |
Details
Auto-detects the standard columns (ID/time/DV/amt/rate/MDV/DVID) by common
names; override any of them with the corresponding argument. Reports
subject/observation/dose counts, MDV and DVID breakdowns, a dose-regimen
summary, observation ranges, per-covariate distributions, duplicate
(ID, time) records, and a suggested column_map for a pkmodel fit
(oral/first-order when dose rates are all -1/-2, otherwise IV bolus).
When NONMEM-style C/BLQ flag columns are present a
nonmem_filter_hints block points at the safe %in% filter idiom. When
subject-constant continuous covariates are present, it also returns a
read-only frem_suggestion pointing at the FREM KB recipe (it does not
prepare data).
Value
A structured, JSON-serializable list.
Inspect a textual PML model without fitting
Description
Builds an NlmePmlModel from a textual PML .mdl file and a CSV dataset with
textualmodel(), then returns a read-only summary - no engine fit, no
output files. The headline field is covariate_effect_names (from
listCovariateEffectNames()): the effects, in canonical order, that you turn
into NlmeScenario() scenarios for sortfit(). Also returns the structural
projection from inspect_nlme_model() (column mapping with any UNMAPPED terms,
dose points, covariates, structural/random parameters) and the
validate_nlme_model() verdict (ready_for_fit).
Usage
inspect_textual_model(mdl_path, data_path, mappings_json = NULL, n_rows = NULL)
Arguments
mdl_path |
Path to a textual PML |
data_path |
Path to a CSV dataset to attach. |
mappings_json |
Optional JSON object string of |
n_rows |
Optional cap on rows read from the CSV (the structure does not depend on all rows; a small head speeds up large files). |
Details
Building a textual model and listing its covariate effects is pure R, so this
needs no NLME engine license. Use it before authoring a sortfit batch to
discover the covariate effects and confirm the data attaches and maps.
Value
A list with covariate_effect_names, the inspect_nlme_model()
fields, and a validation block, or an error string on failure.
Interpret parameter estimates against literature
Description
Builds a reconciliation scaffold (units, parameterization, allometry,
population) and a citation policy, then instructs the agent (or the MCP
host, when fetch = TRUE) to retrieve literature with its own web tools.
This provider does not perform the retrieval itself.
Usage
interpret_parameters(
estimates = NULL,
job_id = NULL,
compound_class = NULL,
sources = NULL,
project_dir = ".",
fetch = FALSE
)
Arguments
estimates |
Optional named list/vector of parameter -> value. |
job_id |
Optional job id to derive estimates from (when |
compound_class |
Optional class hint (e.g. "mAb", "small molecule"). |
sources |
Optional character vector of article links (URL/DOI). |
project_dir |
Project root (for |
fetch |
If |
Details
Interpretation is heuristic context, never uncited "established" fact: every literature value must carry source (URL/DOI), unit, and parameterization.
Value
A structured list describing how to compare estimates against literature, plus a citation reminder.
Get or set whether a model is a population model
Description
isPopulation() reports the population / individual mode of an
NlmePmlModel. The replacement form
isPopulation(model) <- value flips that mode and keeps the
column mapping consistent: switching to individual removes the
id mapping entry (the individual write path always injects a
dummy id), and switching to population re-adds an unmapped
id entry that is then auto-mapped against any matching data
column name.
Usage
isPopulation(.Object)
## S4 method for signature 'NlmePmlModel'
isPopulation(.Object)
isPopulation(.Object) <- value
## S4 replacement method for signature 'NlmePmlModel'
isPopulation(.Object) <- value
Arguments
.Object |
An |
value |
A single non- |
Details
Random effects and author-written PML are left untouched; the engine decides how to execute a model whose PML disagrees with the mode.
Value
For the getter, a length-1 logical. For the setter, the updated
NlmePmlModel.
See Also
colMapping, textualmodel,
pkmodel
Examples
## Not run:
model <- pkmodel(columnMap = FALSE, data = pkData)
isPopulation(model)
isPopulation(model) <- FALSE
## End(Not run)
Vectorised numeric-token test for covariate values
Description
Returns a logical vector of the same length as x indicating whether each
element is a numeric literal. Provides column-class fast paths so that
already-numeric, integer, logical, or factor columns avoid the regex call.
Usage
is_cov_numeric_value(x)
Arguments
x |
Atomic vector of covariate values; |
Value
Logical vector.
Vectorised test for values the NLME engine reads as missing
Description
Mirrors the engine's own tokenisation so R-side validators agree with what the fit will actually see. A covariate cell becomes the internal missing sentinel when it is
empty or whitespace-only, or
a bare
.– note.5is a number, so the test is an exact match on.rather than a prefix test, or-
NAin any letter case (NA,na,Na,nA).
A real R NA is included as well: it is written to the data file as the
bare token NA, which the engine also reads as missing.
Usage
is_engine_missing_token(x)
Arguments
x |
Atomic vector of covariate values (character, factor, numeric, integer, or logical). |
Details
Undeclared category labels also end up missing, but that needs the
covariate's declared labels to detect and is handled by
validate_cov_data_coverage(), not here.
Value
Logical vector, same length as x.
Create linear model
Description
Use to create a constant, linear, or quadratic PD model
Usage
linearmodel(
isPopulation = TRUE,
type = "Constant",
data = NULL,
columnMap = TRUE,
modelName = "",
workingDir = "",
...
)
Arguments
isPopulation |
Is this a population model |
type |
Model type. Options are |
data |
Input dataset |
columnMap |
If |
modelName |
Model name for subdirectory created for model output in current working directory. |
workingDir |
Working directory to run the model. Current working directory will be used
if |
... |
Arguments passed on to
|
Value
NlmePmlModel object
Column mapping
Note that quoted and unquoted column names are supported. Please see colMapping.
Examples
model <- linearmodel(type = "Linear", data = pkpdData, ID = "ID", C = "CObs", EObs = "EObs")
# View PML Code
print(model)
Linear model mapping parameters
Description
Linear model mapping parameters
Usage
linearmodel_MappingParameters(ID = NULL, C = NULL, EObs = NULL)
Arguments
ID |
Column mapping argument for input dataset column(s)
that identify individual data profiles. Only applicable to population models
|
C |
Column mapping argument that represents the input dataset column for the independent variable that is treated as a covariate during the estimation/simulation process. |
EObs |
Column mapping argument that represents the input dataset column for the observed drug effect (i.e., the dependent variable). |
Lists covariate effect names in the model
Description
This function lists the names of covariate effects in a provided pharmacokinetic/pharmacodynamic (PK/PD) model.
Usage
listCovariateEffectNames(.Object)
## S4 method for signature 'NlmePmlModel'
listCovariateEffectNames(.Object)
Arguments
.Object |
PK/PD model |
Value
A vector of character strings containing the names of the covariate effects in the model.
Examples
model <- pkmodel(
numCompartments = 2,
data = pkData,
ID = "Subject",
Time = "Act_Time",
A1 = "Amount",
CObs = "Conc",
workingDir = tempdir()
)
model <- addCovariate(model,
covariate = "Gender",
type = "Categorical",
effect = c("V2", "Cl2"),
levels = c(0, 1),
labels = c("Female", "Male")
)
listCovariateEffectNames(model)
List archived covariate search scenarios.
Description
Dispatches on the type of x to discover archived covariate-search
run folders and returns one row per scenario, sorted by timestamp descending
(latest first). This function discovers only stepwise_* and
shotgun_* folders, not transient SCM_* directories.
Usage
listSCMRuns(x)
Arguments
x |
One of:
|
Value
A data frame with one row per scenario. Columns: searchType,
SCMFolder (path to the archived run folder; name kept for
compatibility), runFolder, Scenario, enableFlags,
status, timestamp, runId, overallFile,
stepwiseFile. Returns an empty data frame if no runs are found.
Archived run folders
Archived folders are created when shotgunSearch() or
stepwiseSearch() is run with archiveResults = TRUE.
During the engine run, NLME8 writes scenario outputs under a temporary
SCM_<runId>/ directory in the model working directory
(runId is a wall-clock timestamp, optionally suffixed with
runLabel). After the engine finishes, collectJob()
materialises the search result and the package renames that tree into a
durable folder named stepwise_<runId> or shotgun_<runId>
(on remote hosts the bundle SCM_<runId>.tar.gz is extracted
first, then the bundle and any loose SCM_<runId>/ copy are
removed). The final folder holds scenario_index.csv,
per-scenario subfolders, Overall.csv, optional stepwise logs,
and rsnlme_run.rds.
See Also
shotgunSearch, stepwiseSearch,
summary(),
print(),
getSCMResults
List the built-in NlmePmlModel constructors
Description
Discovery tool: returns the catalog of RsNLME model constructors an agent can
choose from before building a model, each with its model type (pk/pd/pkpd/
custom), the KB entry that documents it, the help topic, and the
required/common column-mapping terms. Prefer a built-in template when one
matches the requested model; use textualmodel for custom PML.
Usage
list_builtin_model_constructors()
Details
The three PK/PD constructors (pklinearmodel, pkindirectmodel,
pkemaxmodel) additionally carry mode_flags: structural
constructor_args (not column-mapping terms) such as the PPP&D staging
pair isSequential/isPkFrozen (mutually exclusive - see
mutually_exclusive) and each model's PD functional-form choice
(linearType/indirectType/checkBaseline/...). validate_fit_spec()
rejects a mutually_exclusive conflict or an out-of-choices enum value
before a job launches.
Value
A list of constructor records.
Examples
list_builtin_model_constructors()
List registered MCP runs
Description
List registered MCP runs
Usage
list_mcp_runs(project_dir = ".")
Arguments
project_dir |
Project root. |
Value
A list of job records.
List artifacts produced by a job
Description
List artifacts produced by a job
Usage
list_nlme_artifacts(job_id, project_dir = ".")
Arguments
job_id |
Job id. |
project_dir |
Project root. |
Value
A list with run_dir, artifact_dir, and artifacts (relative paths
under artifact_dir, i.e. <run_dir>/artifacts).
List sequential-LRT sessions for a project
Description
Read-only: scans <project_dir>/qualification/lrt/ for session
directories and returns each session's persisted status snapshot (the same
shape advance_sequential_lrt()/get_sequential_lrt_status() return) -
no live job polling, so this is safe and cheap to call often. Used by
get_project_workflow_status() and the Certara.R host's
get_certara_project_status() project-status merge, so both can surface
in-progress and completed anchored LRT refinements without re-deriving
session state or re-implementing this provider's session format.
Usage
list_sequential_lrt_sessions(project_dir = ".")
Arguments
project_dir |
Project root. |
Value
A list of per-session status snapshots (list() when the
qualification/lrt/ directory does not exist or holds no sessions).
Load model.rda file
Description
Loads a previously saved model from disk.
Usage
loadModel(directory)
Arguments
directory |
Directory where the model was saved |
Details
Note, the names of model, engine, and host objects will
be appended with name of model directory when reloading model.rda file
to global environment.
Value
No value is returned. Model object is loaded in global environment.
Examples
TempDir <- tempdir()
model <- emaxmodel(
checkBaseline = TRUE,
checkFractional = TRUE,
checkInhibitory = TRUE,
data = pkpdData,
ID = "ID",
C = "CObs",
EObs = "EObs",
modelName = "model",
workingDir = TempDir
)
saveModel(model)
loadModel(TempDir)
Return model variable names
Description
Return a vector of model variable names from model object
Usage
modelVariableNames(model)
Arguments
model |
Model object |
Value
Character vector of required model variable names
Examples
model <- pkmodel(columnMap = FALSE,
workingDir = tempdir())
modelVariableNames(model)
Get observation names
Description
Get observation model variables names.
Usage
observationNames(model)
Arguments
model |
Model object |
Value
Character vector of observation model variables names.
Examples
model <- pkemaxmodel(columnMap = FALSE)
obsnames <- observationNames(model)
Obtain NLME License
Description
This function attempts to authenticate and obtain an NLME license using the specified installation directory and licensing tool.
Usage
obtain_NLMELicense(
InstallDir = Sys.getenv("INSTALLDIR"),
ForceAuth = FALSE,
ForceLicenseGet = FALSE,
verbose = getOption("verbose")
)
Arguments
InstallDir |
A character string specifying the directory
where the NLME Engine is installed e.g., |
ForceAuth |
A logical value indicating whether to force
re-authentication even if already authenticated. Default is |
ForceLicenseGet |
A logical value indicating whether to force obtaining
the license even if already licensed. Default is |
verbose |
A logical value indicating whether to print verbose output.
Default is |
Details
This function checks for the presence of the necessary
appsettings.json file as indicated by the CAD_CONFIG_FILE environment variable,
runs the licensing tool to authenticate the user, and attempts to obtain
an NLME license. It prints detailed messages if the verbose
parameter is set to TRUE.
Value
A logical value indicating whether the license was successfully obtained.
Examples
## Not run:
INSTALLDIR <- Sys.getenv("INSTALLDIR")
if (INSTALLDIR == "") INSTALLDIR <- "C:/Program Files/Certara/NLME_Engine"
result <- obtain_NLMELicense(INSTALLDIR, verbose = TRUE)
if (result) {
message("License obtained successfully!")
} else {
message("Failed to obtain license.")
}
## End(Not run)
Open generated PML in Certara Model Designer (web)
Description
Resolves PML text from exactly one of pml, path, or model_rds,
encodes it the way Certara Model Designer's web frontend expects
(base64url(raw-DEFLATE(UTF-8 PML))), and builds a
{md_base}/models/custom?pml=... URL. When md_base is not supplied, the
Model Designer environment(s) registered for the caller's current CAD
organization are looked up via obtain_NLMELicense()'s auth.json; the
organization is never guessed from the issuer host.
Usage
open_model_in_model_designer(
pml = NULL,
path = NULL,
model_rds = NULL,
md_base = NULL,
open_browser = TRUE,
api_version = "v4",
verbose = TRUE
)
Arguments
pml |
Character PML text. |
path |
Path to a |
model_rds |
Path to an |
md_base |
Optional explicit Model Designer base URL; when supplied, the CAD environment lookup is skipped entirely. |
open_browser |
If |
api_version |
CAD API version for the environments endpoint (default
|
verbose |
If |
Details
Requires the curl package (only when md_base is not supplied) and
an existing CAD auth.json (see obtain_NLMELicense()).
Value
A list with status (one of "ok", "not_registered",
"needs_user_choice"), sso_authority, md_base, url (non-NULL
only when status == "ok"), candidates (registered environment URLs),
and pml_chars.
Examples
## Not run:
open_model_in_model_designer(pml = "test(){\n C = A1 / V\n}")
## End(Not run)
Embed column definition info into the model
Description
Add/update column definition information for the model object
Usage
parsePMLColMap(.Object, ForceRun = TRUE)
Arguments
.Object |
Model ( |
ForceRun |
Set to |
Details
Intended to be used by other packages
Value
modified NLMEPmlModel object with column mapping
definitions
Create NlmeParallelHost object from json file with host definition
Description
Create NlmeParallelHost object from json file with host definition
Usage
parse_NLMEHosts(nlme_hostPath)
Arguments
nlme_hostPath |
json file with host definition for model execution.
See |
Value
the NlmeParallelHost class object is returned.
Examples
## Not run:
# path nlme_hostPath should be specified
nlme_hostPath <- tempfile()
host1 <- paste0('{"profile_name":"Multicore",',
'"hostname":"127.0.0.1",',
'"cores_number":4,',
'"parallel_mode":"MULTICORE"}')
host2 <- paste0('{"profile_name":"MPI",',
'"hostname":"127.0.0.1",',
'"cores_number":8,',
'"parallel_mode":"LOCAL_MPI"}')
writeLines(paste0("[", host1, ",", host2, "]"), nlme_hostPath)
hosts <- parse_NLMEHosts(nlme_hostPath)
## End(Not run)
Pharmacokinetic dataset containing 16 subjects with single bolus dose
Description
Pharmacokinetic dataset containing 16 subjects with single bolus dose.
Usage
pkData
Format
A data frame with 112 rows and 8 variables:
- Subject
Subject ID
- Nom_Time
Nominal Time
- Act_Time
Actual Time
- Amount
Amount of dose
- Conc
Observations of drug concentration in blood
- Age
Age
- BodyWeight
Body weight
- Gender
Gender ("male", "female")
Source
Pharmacokinetic pediatric dataset containing 80 subjects with single bolus dose.
Description
Pharmacokinetic pediatric dataset containing 80 subjects with single bolus dose. Dataset includes covariates and observations Below Quantification Limit (BQL).
Usage
pkcovbqlData
Format
A data frame with 880 rows and 8 variables:
- ID
Subject ID
- Time
Nominal Time
- Dose
Amount of dose
- CObs
Observations of drug concentration in blood
- LLOQ
Lower Limit of Quantification
- CObsBQL
Variable that indicates whether the observed drug concentration is below the limit of quantification
- BW
Body weight
- PMA
Postmenstrual age
Source
The data is simulated using a one-compartment model with IV bolus, where the central volume is allometric weight scaled, and the clearance is scaled by a combination of allometric weight scaling and a sigmoidal maturation function driven by PMA. Germovsek E., et al, Pharmacokinetic–Pharmacodynamic Modeling in Pediatric Drug Development, and the Importance of Standardized Scaling of Clearance, Clin Pharmacokinet (2019) 58:39–52.
Create a PK/Emax or PK/Imax model
Description
Use to create a PK/Emax or PK/Imax model
Usage
pkemaxmodel(
isPopulation = TRUE,
parameterization = "Clearance",
absorption = "Intravenous",
numCompartments = 1,
isClosedForm = TRUE,
isTlag = FALSE,
hasEliminationComp = FALSE,
isFractionExcreted = FALSE,
isSaturating = FALSE,
infusionAllowed = FALSE,
isDuration = FALSE,
isSequential = FALSE,
isPkFrozen = FALSE,
hasEffectsCompartment = FALSE,
checkBaseline = FALSE,
checkFractional = FALSE,
checkInhibitory = FALSE,
checkSigmoid = FALSE,
isEmaxFrozen = FALSE,
data = NULL,
columnMap = TRUE,
modelName = "",
workingDir = "",
...
)
Arguments
isPopulation |
Is this a population model |
parameterization |
Type of parameterization. Options are |
absorption |
Type of absorption. Options are |
numCompartments |
Value of either |
isClosedForm |
Set to |
isTlag |
Set to |
hasEliminationComp |
Set to |
isFractionExcreted |
Set to |
isSaturating |
Set to |
infusionAllowed |
Set to |
isDuration |
Set to |
isSequential |
Set to |
isPkFrozen |
Set to |
hasEffectsCompartment |
Set to |
checkBaseline |
Does Emax/Imax model have a baseline response? |
checkFractional |
Set to |
checkInhibitory |
Set to |
checkSigmoid |
Set to |
isEmaxFrozen |
Set to |
data |
Input dataset |
columnMap |
If |
modelName |
Model name for subdirectory created for model output in current working directory. |
workingDir |
Working directory to run the model. Current working directory will be used
if |
... |
Arguments passed on to
|
Value
NlmePmlModel object
Column mapping
Note that quoted and unquoted column names are supported. Please see colMapping.
Examples
model <- pkemaxmodel(
parameterization = "Macro",
data = pkpdData,
Time = "Time",
ID = "ID",
A1 = "Dose",
C1Obs = "CObs",
EObs = "EObs"
)
# View the model as well as its associated column mappings
print(model)
Create a PK/Indirect response model
Description
Use to create a PK/Indirect response model.
Usage
pkindirectmodel(
isPopulation = TRUE,
parameterization = "Clearance",
absorption = "Intravenous",
numCompartments = 1,
isClosedForm = TRUE,
isTlag = FALSE,
hasEliminationComp = FALSE,
isFractionExcreted = FALSE,
isSaturating = FALSE,
infusionAllowed = FALSE,
isDuration = FALSE,
isSequential = FALSE,
isPkFrozen = FALSE,
hasEffectsCompartment = FALSE,
indirectType = "LimitedStimulation",
isBuildup = TRUE,
isExponent = FALSE,
indirectFrozen = FALSE,
data = NULL,
columnMap = TRUE,
modelName = "",
workingDir = "",
...
)
Arguments
isPopulation |
Is this a population model |
parameterization |
Type of parameterization. Options are |
absorption |
Type of absorption. Options are |
numCompartments |
Value of either |
isClosedForm |
Set to |
isTlag |
Set to |
hasEliminationComp |
Set to |
isFractionExcreted |
Set to |
isSaturating |
Set to |
infusionAllowed |
Set to |
isDuration |
Set to |
isSequential |
Set to |
isPkFrozen |
Set to |
hasEffectsCompartment |
Set to |
indirectType |
Type of drug actions for the indirect response model.
Options are |
isBuildup |
Set to |
isExponent |
Set to |
indirectFrozen |
Set to |
data |
Input dataset |
columnMap |
If |
modelName |
Model name for subdirectory created for model output in current working directory. |
workingDir |
Working directory to run the model. Current working directory will be used
if |
... |
Arguments passed on to
|
Value
NlmePmlModel object
Column mapping
Note that quoted and unquoted column names are supported. Please see colMapping.
Examples
model <- pkindirectmodel(
parameterization = "Micro",
data = pkpdData,
ID = "ID",
Time = "Time",
A1 = "Dose",
CObs = "CObs",
EObs = "EObs"
)
# View PML Code
print(model)
PK Indirect model mapping parameters
Description
PK Indirect mapping parameters
Usage
pkindirectmodel_MappingParameters(
ID = NULL,
Time = NULL,
A1 = NULL,
Aa = NULL,
A = NULL,
A1_Rate = NULL,
A1_Duration = NULL,
Aa_Rate = NULL,
Aa_Duration = NULL,
A_Rate = NULL,
A_Duration = NULL,
A1Strip = NULL,
CObs = NULL,
C1Obs = NULL,
A0Obs = NULL,
EObs = NULL,
nV = NULL,
nV2 = NULL,
nV3 = NULL,
nCl = NULL,
nCl2 = NULL,
nCl3 = NULL,
nKa = NULL,
nA = NULL,
nAlpha = NULL,
nB = NULL,
nBeta = NULL,
nC = NULL,
nGamma = NULL,
nKe = NULL,
nK12 = NULL,
nK21 = NULL,
nK13 = NULL,
nK31 = NULL,
nTlag = NULL,
nKm = NULL,
nVmax = NULL,
nFe = NULL,
nMeanDelayTime = NULL,
nShapeParamMinusOne = NULL,
nShapeParam = NULL
)
Arguments
ID |
Column mapping argument for input dataset column(s) that identify
individual data profiles. Only applicable to population models |
Time |
Column mapping argument that represents the input dataset column for the relative time used in a study and only applicable to time-based models. |
A1 |
Column mapping argument that represents the input dataset column for the amount of drug administered. Only applicable to the following types of models:
|
Aa |
Column mapping argument that represents the input dataset column
for the amount of drug administered and only applicable to models with |
A |
Column mapping argument that represents the input dataset column
for the amount of drug administered and only applicable to models with
|
A1_Rate |
Column mapping argument that represents the input dataset column for the rate of drug administered. Only applicable to the following types of models:
|
A1_Duration |
Column mapping argument that represents the input dataset column for the duration of drug administered. Only applicable to the following types of models:
|
Aa_Rate |
Column mapping argument that represents the input dataset column
for the rate of drug administered and only applicable to models with |
Aa_Duration |
Column mapping argument that represents the input dataset column
for the duration of drug administered and only applicable to models with |
A_Rate |
Column mapping argument that represents the input dataset column
for the rate of drug administered and only applicable to models with |
A_Duration |
Column mapping argument that represents the input dataset column
for the duration of drug administered and only applicable to models with |
A1Strip |
Column mapping argument that represents the input dataset column
for the stripping dose and only applicable to models with |
CObs |
Column mapping argument that represents the input dataset column
for the observations of drug concentration in the central compartment and only applicable
to models with |
C1Obs |
Column mapping argument that represents the input dataset column
for the observations of drug concentration in the central compartment and only applicable
to models with |
A0Obs |
Column mapping argument that represents the input dataset column
for the observed amount of drug in the elimination compartment. ( |
EObs |
Column mapping argument that represents the input dataset column for the observed drug effect. |
nV |
If |
nV2 |
If |
nV3 |
If |
nCl |
If |
nCl2 |
If |
nCl3 |
If |
nKa |
If |
nA |
If |
nAlpha |
If |
nB |
If |
nBeta |
If |
nC |
If |
nGamma |
If |
nKe |
If |
nK12 |
If |
nK21 |
If |
nK13 |
If |
nK31 |
If |
nTlag |
If |
nKm |
If |
nVmax |
If |
nFe |
If |
nMeanDelayTime |
If |
nShapeParamMinusOne |
If |
nShapeParam |
If |
Create PK linear model
Description
Use to create a PK/PD model with PD described by either constant, linear, or quadratic model
Usage
pklinearmodel(
isPopulation = TRUE,
parameterization = "Clearance",
absorption = "Intravenous",
numCompartments = 1,
isClosedForm = TRUE,
isTlag = FALSE,
hasEliminationComp = FALSE,
isFractionExcreted = FALSE,
isSaturating = FALSE,
infusionAllowed = FALSE,
isDuration = FALSE,
isSequential = FALSE,
isPkFrozen = FALSE,
hasEffectsCompartment = FALSE,
linearType = "Constant",
isLinearFrozen = FALSE,
data = NULL,
columnMap = TRUE,
modelName = "",
workingDir = "",
...
)
Arguments
isPopulation |
Is this a population model |
parameterization |
Type of parameterization. Options are |
absorption |
Type of absorption. Options are |
numCompartments |
Value of either |
isClosedForm |
Set to |
isTlag |
Set to |
hasEliminationComp |
Set to |
isFractionExcreted |
Set to |
isSaturating |
Set to |
infusionAllowed |
Set to |
isDuration |
Set to |
isSequential |
Set to |
isPkFrozen |
Set to |
hasEffectsCompartment |
Set to |
linearType |
Type of PD model; Options are |
isLinearFrozen |
Set to |
data |
Input dataset |
columnMap |
If |
modelName |
Model name for subdirectory created for model output in current working directory. |
workingDir |
Working directory to run the model. Current working directory will be used
if |
... |
Arguments passed on to
|
Value
NlmePmlModel object
Column mapping
Note that quoted and unquoted column names are supported. Please see colMapping.
Examples
model <- pklinearmodel(
parameterization = "Clearance",
linearType = "Constant",
data = pkpdData,
ID = "ID",
Time = "Time",
A1 = "Dose",
CObs = "CObs",
EObs = "EObs"
)
# View the model as well as its associated column mappings
print(model)
Creates a PK model
Description
Use to create a PK model
Usage
pkmodel(
isPopulation = TRUE,
parameterization = "Clearance",
absorption = "Intravenous",
numCompartments = 1,
isClosedForm = TRUE,
isTlag = FALSE,
hasEliminationComp = FALSE,
isFractionExcreted = FALSE,
isSaturating = FALSE,
infusionAllowed = FALSE,
isDuration = FALSE,
isStdevFrozen = FALSE,
data = NULL,
columnMap = TRUE,
modelName = "",
workingDir = "",
...
)
Arguments
isPopulation |
Is this a population model |
parameterization |
Type of parameterization. Options are |
absorption |
Type of absorption. Options are |
numCompartments |
Value of either |
isClosedForm |
Set to |
isTlag |
Set to |
hasEliminationComp |
Set to |
isFractionExcreted |
Set to |
isSaturating |
Set to |
infusionAllowed |
Set to |
isDuration |
Set to |
isStdevFrozen |
Set to |
data |
Input dataset |
columnMap |
If |
modelName |
Model name for subdirectory created for model output in current working directory. |
workingDir |
Working directory to run the model. Current working directory will be used
if |
... |
Arguments passed on to
|
Value
NlmePmlModel object
Column mapping
Note that quoted and unquoted column names are supported. Please see colMapping.
Examples
model <- pkmodel(
parameterization = "Clearance",
numCompartments = 2,
data = pkData,
ID = "Subject",
Time = "Act_Time",
A1 = "Amount",
CObs = "Conc",
workingDir = tempdir()
)
# View the model as well as its associated column mappings
print(model)
PK model mapping parameters
Description
PK model mapping parameters
Usage
pkmodel_MappingParameters(
ID = NULL,
Time = NULL,
A1 = NULL,
Aa = NULL,
A = NULL,
A1_Rate = NULL,
A1_Duration = NULL,
Aa_Rate = NULL,
Aa_Duration = NULL,
A_Rate = NULL,
A_Duration = NULL,
A1Strip = NULL,
CObs = NULL,
C1Obs = NULL,
A0Obs = NULL
)
Arguments
ID |
Column mapping argument for input dataset column(s) that identify
individual data profiles. Only applicable to population models |
Time |
Column mapping argument that represents the input dataset column for the relative time used in a study and only applicable to time-based models. |
A1 |
Column mapping argument that represents the input dataset column for the amount of drug administered. Only applicable to the following types of models:
|
Aa |
Column mapping argument that represents the input dataset column
for the amount of drug administered and only applicable to models with |
A |
Column mapping argument that represents the input dataset column
for the amount of drug administered and only applicable to models with
|
A1_Rate |
Column mapping argument that represents the input dataset column for the rate of drug administered. Only applicable to the following types of models:
|
A1_Duration |
Column mapping argument that represents the input dataset column for the duration of drug administered. Only applicable to the following types of models:
|
Aa_Rate |
Column mapping argument that represents the input dataset column
for the rate of drug administered and only applicable to models with |
Aa_Duration |
Column mapping argument that represents the input dataset column
for the duration of drug administered and only applicable to models with |
A_Rate |
Column mapping argument that represents the input dataset column
for the rate of drug administered and only applicable to models with |
A_Duration |
Column mapping argument that represents the input dataset column
for the duration of drug administered and only applicable to models with |
A1Strip |
Column mapping argument that represents the input dataset column
for the stripping dose and only applicable to models with |
CObs |
Column mapping argument that represents the input dataset column
for the observations of drug concentration in the central compartment and only applicable
to models with |
C1Obs |
Column mapping argument that represents the input dataset column
for the observations of drug concentration in the central compartment and only applicable
to models with |
A0Obs |
Column mapping argument that represents the input dataset column
for the observed amount of drug in the elimination compartment. ( |
Column mapping
Note that quoted and unquoted column names are supported. Please see colMapping.
Pharmacokinetic/Pharmacodynamic dataset containing 200 subjects with single bolus dose
Description
Pharmacokinetic/Pharmacodynamic dataset containing 200 subjects with single bolus dose.
Usage
pkpdData
Format
A data frame with 2600 rows and 5 variables:
- ID
Subject ID
- Time
Nominal Time
- Dose
Amount of dose
- CObs
Observations of drug concentration in blood
- EObs
Observations of drug effect
Source
The data is simulated using a PKPD model with PK described by a one-compartment model with IV bolus and PD described by an indirect response model with the loss inhibited.
Prints the data type of the extra dose
Description
Prints the data type of the extra dose
Usage
## S3 method for class 'ExtraDoseDataType'
print(x, ...)
Prints extra dose information
Description
Prints extra dose information
Usage
## S3 method for class 'ExtraDoseItem'
print(x, ...)
Prints any additional information for extra dose
Description
Prints any additional information for extra dose
Usage
## S3 method for class 'ExtraDoseOption'
print(x, ...)
Arguments
x |
ExtraDoseOption object |
... |
Arguments passed to methods. |
Prints column mapping
Description
Prints column mapping
Usage
## S3 method for class 'NlmeColumnMap'
print(x, ...)
Arguments
x |
Class created from |
... |
Arguments passed to methods. |
Prints covariate parameter information
Description
Prints covariate parameter information
Usage
## S3 method for class 'NlmeCovariateParameter'
print(x, ...)
Arguments
x |
Model covariate |
... |
Arguments passed to methods. |
Print generic for class NlmeEngineExtraParams
Description
Print generic for class NlmeEngineExtraParams
Usage
## S3 method for class 'NlmeEngineExtraParams'
print(x, ...)
Arguments
x |
NlmeEngineExtraParams class instance |
... |
Arguments passed to methods. |
Value
NULL
Examples
print(NlmeEngineExtraParams())
Print an NlmeParallelHost Object
Description
Prints a summary of the configuration of an NlmeParallelHost object.
Usage
## S3 method for class 'NlmeParallelHost'
print(x, ...)
Arguments
x |
An |
... |
Additional arguments passed to the |
Value
NULL. This function is called for its side effect of printing
to the console.
Examples
host <- NlmeParallelHost(
sharedDirectory = "~/shared/",
installationDirectory = "~/nlme/",
hostName = "my_host",
machineName = "192.168.1.100",
hostType = "RHEL",
numCores = 8,
isLocal = FALSE,
rLocation = "/usr/bin/R",
scriptPath = "/path/to/script.R",
userAuthentication =
NlmeUserAuthentication(userName = "myuser", userPassword = "mypassword"),
parallelMethod = NlmeParallelMethod("SGE_MPI")
)
print(host)
Print generic for class NlmePmlModel
Description
Prints model information, including PML and column mappings.
Usage
## S3 method for class 'NlmePmlModel'
print(x, ...)
Arguments
x |
NlmePmlModel class instance |
... |
Arguments passed to methods. |
Value
NULL
Examples
model <- pkmodel(columnMap = FALSE,
data = pkData,
workingDir = tempdir())
print(model)
Prints structural parameter information
Description
Prints structural parameter information
Usage
## S3 method for class 'NlmeStructuralParameter'
print(x, ...)
Arguments
x |
Structural parameter |
... |
Arguments passed to methods. |
Prints secondary parameter information
Description
Prints secondary parameter information
Usage
## S3 method for class 'SecondaryParameter'
print(x, ...)
Arguments
x |
Secondary parameter |
... |
Arguments passed to methods. |
Print generic for class Simple.NlmeJob
Description
Reads progress file and prints out its contents. Applicable to remote jobs or jobs running in backgroud.
Usage
## S3 method for class 'SimpleNlmeJob'
print(x, ...)
Arguments
x |
Handle to an NLME job |
... |
Arguments passed to methods. |
Value
NULL
Examples
## Not run:
model <- pkmodel(
parameterization = "Clearance",
numCompartments = 2,
data = pkData,
ID = "Subject",
Time = "Act_Time",
A1 = "Amount",
CObs = "Conc",
workingDir = tempdir()
)
host <- hostParams(sharedDirectory = tempdir(),
parallelMethod = "None",
hostName = "local",
numCores = 1)
if (.Platform$OS.type == "unix") {
# background is not supported on Windows
job <- fitmodel(model,
numIterations = 3,
hostPlatform = host,
runrunInBackground = TRUE)
print(job)
}
## End(Not run)
Print profile perturbation results
Description
Displays a compact summary for results returned by
profilePertubate().
Usage
## S3 method for class 'profileResult'
print(x, n = 10, ...)
Arguments
x |
A |
n |
Number of rows to print from the head of the table. |
... |
Unused. |
Value
x, invisibly.
Print a bootstrap result
Description
Renders an rsnlme_boot as a header block + metadata + one
section per available result table (Original fit + four bootstrap sections:
fixed effects, omegas (including off-diagonal entries when present), sigmas,
secondaries). Values are shown raw (no
transforms, no \
exactly; for transformed, report-ready summaries see
Certara.Xpose.NLME::get_bootSummaryNlme().
Usage
## S3 method for class 'rsnlme_boot'
print(x, n = 10, ...)
Arguments
x |
A |
n |
Maximum total rows shown across the four bootstrap sections
(Original fit is always rendered in full when present). Allocated
greedily in section order; each truncated section gets a
|
... |
Unused. |
Value
x, invisibly.
Print a fitmodel result
Description
Renders an rsnlme_fit as a header block (model name,
run folder, engine, run mode, runtime, return code, nSubj/nObs,
-2LL) followed by a single raw-scale parameter table mirroring the
"Original Fit" block of print.rsnlme_boot. Values are
shown raw (no transforms, no \
underlying dmp.txt exactly; for transformed, report-ready
summaries see Certara.Xpose.NLME::get_summaryNlme().
Usage
## S3 method for class 'rsnlme_fit'
print(x, n = Inf, ...)
Arguments
x |
A |
n |
Maximum parameter rows shown. Defaults to |
... |
Unused. |
Value
x, invisibly.
Print SCM scenario results
Description
Displays scenario metadata, then delegates to print() for the
reconstructed model.
Usage
## S3 method for class 'scmResult'
print(x, ...)
Arguments
x |
A |
... |
Unused. |
Value
x, invisibly.
See Also
summary.scmResult, getSCMResults,
shotgunSearch, stepwiseSearch
Print SCM search results
Description
Displays a compact summary for results returned by
shotgunSearch() and stepwiseSearch().
Usage
## S3 method for class 'scmSearchResult'
print(x, n = 10, ...)
Arguments
x |
A |
n |
Number of ranked scenarios to print. |
... |
Unused. |
Value
x, invisibly.
See Also
summary.scmSearchResult,
scmSearchTable,
shotgunSearch, stepwiseSearch,
getSCMResults
Print a structured SCM scenario summary
Description
Renders the digest returned by summary.scmResult as a
compact console block: scenario metadata followed by a header-level
view of the embedded fitmodelOutput (no parameter table, no
reconstructed model PML).
Usage
## S3 method for class 'summary.scmResult'
print(x, ...)
Arguments
x |
An object of class |
... |
Unused. |
Value
x, invisibly.
Print a structured SCM search summary
Description
Renders the digest returned by summary.scmSearchResult
as a compact console block aligned with
print.scmSearchResult. Truncates the ranking table to
the top n scenarios so a single summary(x) return
value can be printed at any granularity without recomputing.
Usage
## S3 method for class 'summary.scmSearchResult'
print(x, n = 10, ...)
Arguments
x |
An object of class |
n |
Maximum number of ranked scenarios to display. Defaults to
|
... |
Unused. |
Value
x, invisibly.
Executes an NLME profile perturbation
Description
Executes an NLME profile perturbation. Foreground runs return a typed
profileResult data frame; background runs return a
ProfileNlmeJob that the user materialises later via
collectJob().
Usage
profilePertubate(
model,
hostPlatform = NULL,
params = NULL,
profiles,
sortColumns = SortColumns(""),
scenarios = list(),
runInBackground = FALSE,
...,
saveResult = TRUE
)
Arguments
model |
PK/PD model. Required; profile cannot run without a model to derive the working directory and dataset from. |
hostPlatform |
How to execute the run ( |
params |
Engine parameters ( |
profiles |
Profiles to perturbate ( |
sortColumns |
Optional list of columns to sort and fit
( |
scenarios |
Optional list of scenarios to fit
( |
runInBackground |
Logical. When Background execution is supported only on Linux hosts, whether
local or remote: a local host whose |
... |
Reserved for future use. |
saveResult |
When |
Value
If runInBackground = FALSE, an annotated
profileResult data frame
(Scenario, Theta, Estimate, LogLik, RetCode, Delta, Percent
columns plus optional sort columns; carries params,
runMode = "profile", runTime, RsNLMEVersion, and
profileRunDir attributes). Otherwise a ProfileNlmeJob
object; materialise later via collectJob(), which
produces the same profileResult (and writes the RDS when
saveResult = TRUE).
See Also
collectJob, fitmodel,
stepwiseSearch, hostParams,
engineParams
Examples
## Not run:
model <- pkmodel(
parameterization = "Clearance",
numCompartments = 2,
data = pkData,
ID = "Subject",
Time = "Act_Time",
A1 = "Amount",
CObs = "Conc",
workingDir = tempdir()
)
host <- hostParams(
sharedDirectory = tempdir(),
parallelMethod = "MULTICORE",
hostName = "local",
numCores = 4
)
profile1 <- ProfileVar("tvV", 9.548, "-2,2")
profile2 <- ProfileVar("tvCl", 0.919, "-0.5,1.5")
profiles <- ProfileParameters("USE_DELTA", c(profile1, profile2))
result <- profilePertubate(
model = model,
hostPlatform = host,
params = engineParams(model, method = 3, numIterations = 1),
profiles = profiles
)
## End(Not run)
Returns random block statement
Description
Returns random block statement
Usage
randomBlockStatement(.Object)
Arguments
.Object |
PK/PD model |
Sets or updates the covariance matrix of random effects
Description
Built-in-model structural setter for the covariance matrix of random effects (omegas). Use when defining or changing diagonal vs. block membership (which etas belong to a section), together with initial values and section freeze status. Cannot be used on textual or edited models.
Usage
randomEffect(
.Object,
effect,
value = NULL,
isDiagonal = TRUE,
isFrozen = FALSE,
...
)
Arguments
.Object |
Model object |
effect |
One or more names of available random effects. |
value |
Initial values for the diagonal elements of the covariance matrix of
random effects (if |
isDiagonal |
Set to |
isFrozen |
Set to |
... |
Additional arguments |
Details
For value or freeze edits that keep an existing built-in section layout,
see update_Omegas(). That updater also supports textual models for
value/matrix edits through TDL5 (no freeze/unfreeze; frozen or
same()-linked sections may reject edits; textual topology may be
normalized – see update_Omegas()).
Value
Modified NlmePmlModel object
See Also
Examples
model <- pkmodel(
numCompartments = 2,
data = pkData,
ID = "Subject",
Time = "Act_Time",
A1 = "Amount",
CObs = "Conc",
modelName = "TwCpt_IVBolus_FOCE_ELS",
workingDir = tempdir()
)
model <-
randomEffect(model,
effect = c("nV", "nCl", "nCl2"), value = rep(0.1, 3))
Read a metamodel file (.mmdl)
Description
Imports a metamodel file into an NlmePmlModel object (textual) ready for
execution. Canonical user-facing reader; supersedes the legacy
create_model_from_metamodel().
Usage
read_mmdl(file, directoryToRun = NULL)
Arguments
file |
Path to a metamodel file (typically |
directoryToRun |
Optional working directory for the created model.
If |
Details
If the dataset referenced by the ## DATA block is missing from disk,
read_mmdl() emits a warning containing the resolved path and returns the
model with @inputData = NULL. Column mappings declared in the ## MAP
block are still applied. Attach the dataset later via
initColMapping(model) <- yourData to re-run data-dependent validation.
The ## PRE script (if any) is skipped in this case because it requires
the data file.
The dataset may be a plain delimited file or one written in the NLME engine's
own layout (a ##name1,name2 header line, an optional #@unit1,unit2 units
row, and # comment lines) such as the data1.txt found in a run directory.
Units are carried on the returned data as its Units attribute so they are
re-emitted when the model is run.
Value
A list with elements:
-
model: an NlmePmlModel -
params: engine parameters (NlmeEngineExtraParamsor a list, depending on the metamodel content) for any arguments provided in## ESTARGSblocks.
Remove covariate from structural parameters in a model object.
Description
Remove one or more covariates from structural parameters in a model object.
Usage
removeCovariate(.Object, covariate = NULL, paramName = NULL)
Arguments
.Object |
Model object |
covariate |
Covariates to remove from model. If |
paramName |
Structural parameters for which to remove covariate
effect(s) from. If |
Value
Modified NlmePmlModel object
Examples
model <- pkmodel(
numCompartments = 2,
data = pkData,
ID = "Subject",
Time = "Act_Time",
A1 = "Amount",
CObs = "Conc",
workingDir = tempdir()
)
# Add Gender covariate of type categorical
model <- addCovariate(model,
covariate = "Gender",
type = "Categorical",
effect = c("V2", "Cl2"),
levels = c(0, 1),
labels = c("Female", "Male")
)
# Add BodyWeight covariate of type continuous
model <- addCovariate(model,
covariate = "BodyWeight",
type = "Continuous",
direction = "Backward",
center = "Mean",
effect = c("V", "Cl")
)
# Remove all covariates from model
model <- removeCovariate(model)
Remove NLME License
Description
This function attempts to remove an NLME license using the specified installation directory and licensing tool.
Usage
remove_NLMELicense(InstallDir = Sys.getenv("INSTALLDIR"))
Arguments
InstallDir |
A character string specifying the directory
where the NLME Engine is installed e.g., |
Details
The function checks for the presence of the necessary
appsettings.json file in the specified directory or the CAD config file
specified by the CAD_CONFIG_FILE environment variable, runs the licensing
tool to log out the user, and attempts to remove the NLME license.
Value
A logical value indicating whether the license information was successfully removed.
Examples
## Not run:
INSTALLDIR <- Sys.getenv("INSTALLDIR")
if (INSTALLDIR == "") INSTALLDIR <- "C:/Program Files/Certara/NLME_Engine"
if (FALSE) { # to prevent unintended logout
result <- remove_NLMELicense(INSTALLDIR)
}
## End(Not run)
Sets residual effect attributes
Description
Sets residual effect attributes
Usage
residualEffect(.Object, effectName) <- value
Arguments
.Object |
PK/PD model object |
effectName |
Effect to lookup/set attributes for |
value |
A value to be set |
Return residual effect terms available in model
Description
Use to return character vector of residual effect names in model object
Usage
residualEffectNames(model)
Arguments
model |
Object of class |
Value
Character vector of residual effect names
Examples
model <- pkemaxmodel(columnMap = FALSE)
residualEffectNames(model)
Assign residual error model to model object
Description
Built-in-model structural setter for the residual error model. Use when configuring or changing error type (Additive/Multiplicative/etc.), BQL/LLOQ, power exponent, and/or SD and freeze together during model construction. Cannot be used on textual or edited models.
Usage
residualError(
.Object,
predName = "C",
errorType = NULL,
SD = NULL,
isFrozen = FALSE,
isBQL = FALSE,
staticLLOQ = NULL,
EObsBQL = NULL,
CObsBQL = NULL,
C1ObsBQL = NULL,
A0ObsBQL = NULL,
exponent = NULL
)
Arguments
.Object |
Model object |
predName |
Name of the predicted variable as returned in |
errorType |
Options are |
SD |
Value for the standard deviation of the residual error variable. |
isFrozen |
Set to |
isBQL |
Set to |
staticLLOQ |
Optional LLOQ value if |
EObsBQL |
Column mapping argument that represents the input dataset column that contains the BQL flag for observation values corresponding to |
CObsBQL |
Column mapping argument that represents the input dataset column that contains the BQL flag for observation values corresponding to |
C1ObsBQL |
Column mapping argument that represents the input dataset column that contains the BQL flag for observation values corresponding to |
A0ObsBQL |
Column mapping argument that represents the input dataset column that contains the BQL flag for observation values corresponding to |
exponent |
Value of exponent. Only applicable to |
Details
For pipe-friendly SD and freeze edits that leave error type and BQL setup
unchanged, see update_Sigmas(). That updater supports built-in and
textual models for SD; freeze/unfreeze is built-in-only (textual freeze
toggles error; frozen textual errors may also reject value edits).
Value
Modified NlmePmlModel object
See Also
Examples
model <- pkindirectmodel(indirectType = "LimitedInhibition", isBuildup = FALSE,
data = pkpdData, ID = "ID", Time = "Time", A1 = "Dose", CObs = "CObs", EObs = "EObs")
residualEffectNames(model)
# Change error type to "Multiplicative" and value of SD to 0.1 for "E"
model <- residualError(model, predName = "E", errorType = "Multiplicative", SD = 0.1)
# Change error type to "Power", value of SD to 0.15, and set exponent = 2 for "C"
model <- residualError(model, predName = "C", errorType = "Power", SD = 0.15, exponent = 2)
An rsnlme_boot object
Description
bootstrap() (and collectJob() on a backgrounded
BootNlmeJob) return an
rsnlme_boot: a named list of bootstrap result tables with an
SCM-style print method and a small set of metadata attributes that
downstream tools (notably Certara.Xpose.NLME::get_bootSummaryNlme())
read instead of inspecting the on-disk artefacts directly.
Fields
BootOverallPer-replicate
Scenario / Replicate / ReturnCode / LL.BootThetaAggregated theta summary (Mean, Stderr, CV\ Median, percentile CIs).
BootOmega,BootOmegaCorrelationAggregated omega entries split out of
BootOmega.csvby theOmega/Correlationsentinel rows.BootOmegaStderr,BootVarCoVarStandard errors and full var-covar matrix from the engine.
BootSecondarySecondary parameters with the same aggregation columns as
BootTheta.BootThetaStacked,BootOmegaStacked,BootSigmaStackedPer-replicate long stacks (
Replicate,<label>,Value). Inputs to transform-aware downstream pipelines.BootOmegaCI,BootSigmaCIPer-parameter percentile CIs for omega and sigma (one row per upper-triangle entry).
Diagonalmarks variance vs covariance entries;print.rsnlme_bootshows omega rows except constrained-zero off-diagonal covariances (matching Original Fit) and diagonal sigma rows only.BootEtaShrinkage,BootEpsShrinkagePer-replicate long shrinkages (
Replicate,Ranef|Observable,Shrinkage (%)). The CSVs on disk hold fractions (engine convention,1 - SD) under aShrinkageheader;loadBootstrapResult()multiplies by 100 and renames the column at ingestion so the in-memory representation is on the percent scale. Fractional values only survive in the on-disk artefacts.fitSummaryCompact prior-fit summary (
Parameter,Type,Estimate,SE,%RSE,Shrinkage,Diagonal).Typeis one of"the"(theta),"ome"(omega variance or block covariance),"sig"(sigma diagonal), or"sec"(secondary parameter).Estimatefollows theprmTableconvention used byCertara.Xpose.NLME: raw value for thetas, variance for omega diagonals, covariance for omega off-diagonals, standard deviation for sigmas, raw secondary value (engine output) forsecrows.DiagonalisTRUEexcept for omega off-diagonal covariance rows (block omega), which downstream variance-scale summaries (Certara.Xpose.NLME::get_summaryNlme()) exclude.Shrinkageis on the percent scale (the.parseEtaShrinkages/.parseEpsShrinkageshelpers multiply by 100 at parse time), matching the post-ingestionBootEtaShrinkage/BootEpsShrinkagecolumns above andCertara.Xpose.NLME::get_summaryNlme()'s output; off-diagonal omega and secondary rows always carryNAsince shrinkage is a per-eta concept. Theprintmethod labels the columnShrinkage (%)but does not rescale. Present only when the run was launched withinitialEstimates = TRUE.
Fields produced by an older NLME8 build that does not yet emit a given aggregate are silently absent (with a single warning at load time).
Attributes
runDirPath to the directory holding the bootstrap CSVs.
engineEngine method string derived from
params@method.numSamplesNumber of bootstrap replicates requested.
numUsedNumber of replicates contributed to the aggregates, i.e.
nrow(BootOverall). Matches NLME8'ssummarizeBootstrap.Rbehaviour, which feeds every parseable replicate into the percentile CIs regardless ofReturnCode.numConvergedNumber of replicates whose
ReturnCodeindicates convergence achieved (c(1L, 2L, 3L)perCertara.Xpose.NLME::get_term). Other codes (e.g.0,4,-4,-1) may still contribute parameter estimates to the bootstrap aggregates; seenumUsed.returnCodeBreakdownCharacter vector with the per-code occurrence counts (e.g.
c("return code 1: 3", "return code -1: 2")), sorted by code. Drives the diagnostic line inprint.rsnlme_boot.confidenceLevelConfidence level used for percentile CIs (numeric, e.g. 95).
hasFitSummaryTRUEwhenfitSummaryis present.
See Also
bootstrap, print.rsnlme_boot,
collectJob
An rsnlme_fit object
Description
fitmodel() returns an rsnlme_fit: the self-describing
result list (dmp.txt, residuals, posthoc,
nlme7engine.log, ConvergenceData, Overall, ...,
plus the run-context fields model, params,
runMode, runTime, RsNLMEVersion) classed as
c("rsnlme_fit", "list"). getSCMResults() stamps the
same class on every per-scenario fitmodelOutput for symmetry.
Details
The class is purely a print/dispatch hook – every existing access
pattern (fit$dmp.txt, fit$residuals,
xposeNlmeModel(fit), list subsetting) continues to work
unchanged.
Embedded fit summary
Building on top of the list, the constructor adds one new field:
fitSummaryCompact prior-fit summary (
Parameter,Type,Estimate,SE,%RSE,Shrinkage,Diagonal). Same shape and contract as thefitSummaryembedded onrsnlme_bootwhenbootstrap(initialEstimates = TRUE)– raw scale, no transforms. Block-omega fits also list off-diagonal covariance rows (Type = "ome",Diagonal = FALSE); for transformed report-ready summaries useCertara.Xpose.NLME::get_summaryNlme().NULLwhendmp.txtcould not be parsed.
Attributes
engineEngine method string derived from
params@method.returnCodeInteger return code from
dmp.txt$returnCode.nSubj,nObsSubject and observation counts from
dmp.txt.logLikLog-likelihood from
dmp.txt$logLik; the print method renders-2\,\mathrm{logLik}.
See Also
fitmodel, print.rsnlme_fit,
rsnlme_boot
Fit the NLME metamodel
Description
Use for simple model execution given information contained in mmdl file.
Usage
run_metamodel(mmdlfile, directoryToRun, nlme_hostPath, host)
Arguments
mmdlfile |
The metamodel file path; relative paths are acceptable. |
directoryToRun |
The directory where the final results should be stored
If |
nlme_hostPath |
json file with host definition for model execution.
Generated by Pirana application. Consider using |
host |
|
Details
If both nlme_hostPath and host specified, the former is used.
If nlme_hostPath is missing, host is used instead.
If both are missing, MPI local host with 4 threads is used for simple estimation
mode, multicore host is used for the others.
Multiple ESTARGS/SIMARGS are supported, they are applied for the model sequentially, the results of previous estimation are applied to the model before the next one. ESTARGS queue is executed first, SIMARGS queue is executed the second.
Value
the results of fitmodel() run are returned if singular ESTARGS block is
provided; otherwise a list of fitmodel() and simmodel() results
are returned.
See Also
NlmeParallelHost, fitmodel
Examples
## Not run:
mmdlfile <- system.file("extdata/mmdlNoTime/test.mmdl",
package = "Certara.RsNLME",
mustWork = TRUE)
directoryToRun <- file.path(tempdir(TRUE), "MmdlNoTimeTest")
# using default host
mmdlResults <- run_metamodel(mmdlfile = mmdlfile,
directoryToRun = directoryToRun)
## End(Not run)
Save model object to .rda file
Description
Saves the model, engine, and host objects to a single model.rda file
in model's working directory. If no working directory exists it will be
created by default.
Usage
saveModel(model, engine = NULL, host = NULL)
Arguments
model |
NlmePmlModel object |
engine |
Optional engine parameters to save with model |
host |
Optional host to save with model |
Value
NULL
Examples
model <- emaxmodel(
checkBaseline = TRUE,
checkFractional = TRUE,
checkInhibitory = TRUE,
data = pkpdData,
ID = "ID",
C = "CObs",
EObs = "EObs",
workingDir = tempdir()
)
saveModel(model)
workhorse for change_ThetasMmdlin RsNLME.ModelBuilder
Description
workhorse for change_ThetasMmdlin RsNLME.ModelBuilder
Usage
saveUpdatedMetamodel(
mmdl_withComments,
mmdl_model,
resmodel,
metamodelFile,
updateModel = TRUE,
updatedBasedOn = "",
updatedEstArgsBlock = NULL,
updatedTablesBlock = NULL
)
Arguments
mmdl_withComments |
the metamodel text to be substituted |
mmdl_model |
the old model from mmdl_withComments |
resmodel |
the model to be pasted |
metamodelFile |
the name of initial file with metamodel to be overwritten |
Value
text of new metamodel
Save a PopPK analysis plan as a versioned artifact
Description
Validates the plan with validate_analysis_plan(), then persists it under
<project_dir>/analysis-plan/ as analysis_plan.v<N>.json (incrementing) and
updates analysis_plan.latest.json. Each artifact wraps the plan with its
version, creation timestamp, a content_sha256, and the
provenance_summary. When the content is unchanged from the latest version,
no new version is written and the existing one is returned (unchanged = TRUE). Writes are confined to the project's analysis-plan/ directory.
Usage
save_analysis_plan(plan, project_dir = ".", label = NULL, data_path = NULL)
Arguments
plan |
A named list (or parsed JSON object); a JSON string is parsed automatically. |
project_dir |
Project root; the artifact directory is
|
label |
Optional short label recorded in the artifact. |
data_path |
Optional dataset path forwarded to |
Value
A list with saved, valid, version, analysis_plan_id (a stable
id reused across versions), analysis_plan_version, intended_use, path,
latest_path, content_sha256, unchanged, provenance_summary, and (on
validation failure) errors.
Save a NONMEM-to-PML translation as a run artifact
Description
Persists a draft_pml_from_nonmem() result as a standardized, auditable
artifact next to a run: the draft PML (model.pml) and the full translation
report including per-area confidence and needs_review items
(translation_report.json). Keeping these with the run folder is the audit
trail for a translated model - record the same needs_review items in the
modeling log so reviewers see what was deterministic and what was judged.
Usage
save_translation_report(draft, dir)
Arguments
draft |
A list returned by |
dir |
Directory to write into (created if needed). |
Value
Invisibly, a named list of the written file paths.
Scaffold a metamodel (.mmdl) from custom PML
Description
Assembles a runnable metamodel from a block of custom PML, a dataset path, and
a flat column mapping, then parses it back with validate_mmdl() so the agent
gets an immediately checkable artifact. This is the recommended route for
custom ADVAN6 / textualmodel PML and multi-dosepoint models, where the
declarative start_nlme_fit_spec() path is awkward: the ## MAP block maps
each model term to its data column (including several dose columns such as
A1 = AMT1, A2 = AMT2, A3 = AMT3 and forward-covariates), and
start_nlme_fit() replays the resulting .mmdl.
Usage
scaffold_mmdl_from_pml(
pml,
data_path,
map,
coldef = NULL,
estargs = NULL,
tables = NULL,
description = NULL,
author = NULL,
output_path = NULL,
validate = TRUE,
absolute_data_path = FALSE
)
Arguments
pml |
Custom PML model text (a single string). Validate it with
|
data_path |
Path to the CSV dataset. Written into the |
map |
Named list or character vector of |
coldef |
Optional character vector of |
estargs |
Optional |
tables |
Optional character vector of |
description, author |
Optional metadata for the header blocks. |
output_path |
Optional path to write the |
validate |
When |
absolute_data_path |
When |
Value
A list with mmdl_text, output_path (or NA), the resolved
data_path, the normalized map, and (when validate) a validation
block from validate_mmdl().
See Also
validate_mmdl(), start_nlme_fit(), read_mmdl()
Presentation table for SCM search results
Description
Returns a plain data.frame for an scmSearchResult (or an
archived run folder), shaped for a table formatter. Default
print() / summary() output stays compact.
Usage
scmSearchTable(x, full = FALSE)
Arguments
x |
An |
full |
Logical. Include the degrees-of-freedom column ( |
Details
Stepwise reads StepwiseDetails.csv. Chosen
becomes "Y" / "N", and the value columns are named from
the Criteria column (Base -2LL, New AIC, ...);
mixed or missing criteria keep the engine names BaseValue /
NewValue / dValue. Model is the effect tested in
that row (see Details).
Shotgun reads the archived scenario index merged with
Overall.csv, exposing CovEffects (the enabled fixed
effects) next to the fit criteria.
Certara.RsNLME does not import a table formatter; pass the
result to one, e.g. flextable::flextable(tab).
For an archived result the table comes from the archive files, so
subsetting x first does not reduce the rows.
CovEffects in StepwiseDetails.csv is the cumulative
enabled set for a candidate, not the single effect under test, so
Model is recovered as a set difference within each Step:
the step's base set is the intersection of its candidates when adding
and their union when deleting. Steps with a single candidate or an
unrecognised direction keep the full CovEffects string.
Value
A data.frame.
See Also
stepwiseSearch, shotgunSearch,
print.scmSearchResult,
summary.scmSearchResult
Examples
## Not run:
tab <- scmSearchTable(stepwiseResult)
flextable::flextable(tab)
scmSearchTable(shotgunResult)
scmSearchTable(attr(stepwiseResult, "searchRunDir"))
## End(Not run)
Get secondary parameter names
Description
Returns character vector of secondary parameter names for model object.
Usage
secondaryParameterNames(model)
Arguments
model |
Object of class |
Value
Character vector of secondary parameter names defined in model
Examples
model <- pkemaxmodel(columnMap = FALSE)
secondaryparms <- secondaryParameterNames(model)
Executes an NLME shotgun covariate search
Description
Executes an NLME shotgun covariate search
Usage
shotgunSearch(
model,
hostPlatform = NULL,
params,
covariateModel,
runInBackground = FALSE,
archiveResults = TRUE,
runLabel = NULL,
...
)
Arguments
model |
PK/PD model class object. |
hostPlatform |
Host definition for model execution. See |
params |
Engine parameters. See |
covariateModel |
Covariate Effects Model providing the relationship
between covariates and structural parameters to test ( |
runInBackground |
Logical. When Background execution is supported only on Linux hosts, whether
local or remote: a local host whose |
archiveResults |
Logical. When |
runLabel |
Optional character string appended to the auto-generated
timestamp in the archive folder name, e.g. |
... |
Additional arguments for |
Value
if runInBackground = FALSE, an scmSearchResult
data frame is returned with shotgun search results, i.e. the
"Overall" comma separated file, plus a custom print method and a
searchType attribute. The data frame also carries the run context
as attributes: params (resolved NlmeEngineExtraParams),
runMode ("shotgun"), runTime (wall-clock
list(start, end, elapsed) measured around the engine call), and
RsNLMEVersion (the package version that produced the result).
If archiving succeeds it also carries a searchRunDir attribute.
Otherwise (when runInBackground = TRUE) the
ShotgunNlmeJob class object is returned. Backgrounded jobs can
be materialised later via collectJob, which produces the
same scmSearchResult (with archive when
archiveResults = TRUE). Use summary()
for a structured digest (best scenario, top ranking, run context).
Use scmSearchTable for a presentation data.frame
(stepwise decision table, or shotgun ranking plus covariate effects).
See Also
hostParams, engineParams,
collectJob,
summary(),
print(),
scmSearchTable,
getSCMResults
Examples
## Not run:
# Define the model
model <- pkmodel(numCompartments = 2,
data = pkData,
ID = "Subject",
Time = "Act_Time",
A1 = "Amount",
CObs = "Conc",
workingDir = tempdir())
# Add Gender covariate of type categorical
model <- addCovariate(model,
covariate = "Gender",
type = "Categorical",
effect = c("V2", "Cl2"),
levels = c(0, 1),
labels = c("Female", "Male"))
# Add Bodyweight covariate of type continuous
model <- addCovariate(model,
covariate = "BodyWeight",
type = "Continuous",
direction = "Backward",
center = "Mean",
effect = c("V", "Cl"))
# Define the host
host <- hostParams(parallelMethod = "MULTICORE",
hostName = "local",
numCores = 8,
sharedDirectory = tempdir())
# Define the engine parameters
params <- engineParams(model, fastOptimization = TRUE, numIterations = 7)
# Define covariate model
cp <- covariateModel(model)
# Perform shotgun search
OverallDF <- shotgunSearch(model = model,
hostPlatform = host,
params = params,
covariateModel = cp,
runInBackground = FALSE)
## End(Not run)
Executes an NLME simulation
Description
Executes an NLME simulation
Usage
simmodel(
model,
simParams,
params,
hostPlatform = NULL,
runInBackground = FALSE,
...
)
Arguments
model |
PK/PD model class object. |
simParams |
Simulation parameters. See |
params |
Engine parameters. See |
hostPlatform |
Host definition for model execution. See |
runInBackground |
Logical. When Background execution is supported only on Linux hosts, whether
local or remote: a local host whose |
... |
Additional class initializer arguments for |
Value
If runInBackground = FALSE, a named list of
data.tables loaded from the engine's simulation outputs (any
non-empty user-defined simulationTables, plus
predout.csv / simout.csv depending on
params@isPopulation). The list also carries
runMode = "simulation", runTime, and
RsNLMEVersion elements alongside the data. Otherwise an
NlmeSimulationJob object that can be materialised later via
collectJob(), which produces the same result list.
See Also
Examples
## Not run:
SimTableObs <- tableParams(
name = "SimTableObs.csv",
timesList = "0,1,2,4,4.9,55.1,56,57,59,60",
variablesList = "C, CObs",
timeAfterDose = FALSE,
forSimulation = TRUE
)
simParams <- NlmeSimulationParams(
numReplicates = 2,
simulationTables = SimTableObs
)
# Define the model
model <- pkmodel(
numComp = 2,
absorption = "Extravascular",
ID = "Subject",
Time = "Act_Time",
CObs = "Conc",
Aa = "Amount",
data = pkData,
modelName = "PkModel",
workingDir = tempdir()
)
host <- hostParams(
sharedDirectory = tempdir(),
parallelMethod = "NONE",
hostName = "local",
numCores = 1
)
results <- simmodel(model, simParams, hostPlatform = host)
# with seed given additionally:
results <- simmodel(model, simParams, hostPlatform = host, seed = 3527)
## End(Not run)
Executes an NLME simple estimation with sort keys and given scenarios
Description
Executes an NLME simple estimation with sort keys and given scenarios
Usage
sortfit(
model,
hostPlatform = NULL,
params,
sortColumns,
scenarios = list(),
simpleTables,
runInBackground = FALSE,
filesToReturn = "*",
...,
saveResult = TRUE
)
Arguments
model |
PK/PD model class object. |
hostPlatform |
Host definition for model execution. See |
params |
Engine parameters. See |
sortColumns |
List of sort columns. See |
scenarios |
List of scenarios with different sets of covariates.
See |
simpleTables |
Optional list of simple tables. See
|
runInBackground |
Logical. When Background execution is supported only on Linux hosts, whether
local or remote: a local host whose |
filesToReturn |
Used to specify which files to be outputted to the model directory
and loaded as returned value. By default, all the applicable files listed
in the |
... |
Additional arguments for |
saveResult |
When |
Details
All the results in tabular format have scenario column and sorts columns appended. The resulted logs (nlme7engine.log, err1.txt, dmp.txt, out.txt) are appended with a row delimiter where the name of the Scenario and sort values are specified.
Value
If runInBackground = FALSE, the same named list of data
frames fitmodel produces, with scenario and sort columns
appended (see Details). The list carries params,
runMode = "sortfit", runTime, and RsNLMEVersion
attributes. Otherwise a SortByNlmeJob object; materialise later
via collectJob(), which produces the same result list
(and writes the RDS when saveResult = TRUE).
Non-loaded but returned files
The non-loaded but returned files in the model working directory are:
err1.txt - concatenated for all runs detailed logs for all steps of optimization,
out.txt - general pivoted information about results,
doses.csv - information about doses given for all subjects,
iniest.csv - information about initial estimates
See Also
hostParams, engineParams, collectJob,
SortColumns, NlmeScenario, tableParams
Examples
## Not run:
input_data <- pkData
model <-
pkmodel(numCompartments = 2,
data = input_data,
ID = "Subject",
Time = "Act_Time",
A1 = "Amount",
CObs = "Conc",
workingDir = tempdir())
model <-
addCovariate(model,
covariate = "BodyWeight",
direction = "Backward",
center = "Mean",
effect = c("V", "Cl"))
# multicore
multicoreHost <-
hostParams(parallelMethod = "Multicore",
hostName = "multicore",
numCores = 4,
sharedDirectory = tempdir())
# specify scenarios
CovariateEffectNames <- listCovariateEffectNames(model)
combinations <-
combn(c("", CovariateEffectNames),
length(CovariateEffectNames),
simplify = FALSE)
scenarioNames <-
lapply(combinations,
function(x) {paste(x, collapse = " ")})
scenarios <-
lapply(scenarioNames,
function(x, CovariateEffectNames) {
CovariateCombinations <- unlist(strsplit(x, " ", fixed = TRUE))
scenarioIndex <-
paste(which(CovariateEffectNames %in% CovariateCombinations,
arr.ind = TRUE),
collapse = ", ")
NlmeScenario(trimws(x), scenarioIndex)
},
CovariateEffectNames)
res <-
sortfit(model,
hostPlatform = multicoreHost,
params = engineParams(model, numIterations = 5, fastOptimization = TRUE),
sortColumns = SortColumns("Gender"),
scenarios = scenarios)
## End(Not run)
Start a non-blocking, first-class bootstrap of a fitted model
Description
Purpose-built bootstrap launcher so agents no longer need the generic
start_nlme_job() escape hatch (and its hand-written script) for
uncertainty/CIs. The child reads fit$model from fit_rds, always
re-roots it into this job's own run sandbox with copyModel() before
calling bootstrap() - the same isolation the bundled
inst/mcp/scripts/bootstrap.R used, now built in - so the run can never
write its aggregate artifacts (dmp.txt, residuals.csv, Boot*.csv)
into the parent fit's directory (see bootstrap()'s overwriteFitDir
for the underlying guard). Saved artifacts: bootstrap.rds, result.rds.
Usage
start_nlme_bootstrap(
fit_rds,
num_replicates = 200,
seed = NULL,
stratify_columns = NULL,
confidence_level = NULL,
params_rds = NULL,
method = NULL,
condition_number = NULL,
label = NULL,
project_dir = ".",
parent_job_id = NULL,
rationale = NULL,
analysis_plan_id = NULL,
unplanned_override = NULL,
unplanned_reason = NULL
)
Arguments
fit_rds |
Path to an |
num_replicates |
Number of bootstrap replicates (default 200; must be at least 2). |
seed |
Optional random number seed (default: |
stratify_columns |
Optional character vector of data columns to stratify resampling on (e.g. treatment arm). |
confidence_level |
Optional confidence level as a percentage (default
95, matching |
params_rds |
Optional |
method |
Optional estimation method override (ignored when
|
condition_number |
Optional condition-number basis override (ignored
when |
label |
Optional short job label. |
project_dir |
Project root for the run sandbox. |
parent_job_id |
Optional id of the fit job this bootstrap qualifies (lineage). |
rationale |
Optional one-line reason for this run (lineage). |
analysis_plan_id |
Optional stable analysis-plan id (lineage). |
unplanned_override |
Optional; records that this run was launched
under an approved plan-first gate exception (lineage only - the gate
itself lives in |
unplanned_reason |
Optional reason accompanying |
Details
Bootstrap is for uncertainty/robustness after a stable final fit, not for
fixing bad initials or selecting structure, and it is long-running relative
to a single fit; a converged fit with missing standard errors plus boundary
evidence is the concrete trigger to reach for this (see
get_fit_summary()'s uncertainty_status), not RetCode == 3 alone.
Refuses to launch when the fit directory's artifact manifest shows the fit
was overwritten since it was selected.
Value
See start_nlme_job(); tagged with job_kind = "bootstrap".
Start an NLME fit from a metamodel (.mmdl)
Description
Convenience wrapper over start_nlme_job() that runs a metamodel via
run_metamodel() in the sandbox.
Usage
start_nlme_fit(
mmdl_path,
label = NULL,
project_dir = ".",
strict = TRUE,
model_stage = NULL,
parent_job_id = NULL,
rationale = NULL,
analysis_plan_id = NULL,
unplanned_override = NULL,
unplanned_reason = NULL
)
Arguments
mmdl_path |
Path to a |
label |
Short label. |
project_dir |
Project root. |
strict |
When |
model_stage |
Optional model-development stage recorded as run lineage. |
parent_job_id |
Optional id of the job this run derives from (lineage). |
rationale |
Optional one-line reason for this run (lineage). |
analysis_plan_id |
Optional stable analysis-plan id this run follows (lineage). |
unplanned_override |
Optional; records that this run was launched under an approved plan-first gate exception (lineage only - the gate itself lives in .mcp_workflow_gate()). |
unplanned_reason |
Optional reason accompanying |
Details
The sandbox confines only the run outputs (under <run_dir>/artifacts).
The .mmdl and its ## DATA file are read from their original locations, and
## DATA is resolved relative to the .mmdl directory - not the sandbox and
not directoryToRun. A missing data file does not stop the engine, so this
function preflights with validate_mmdl(): if the dataset cannot be attached
it warns and tags the job with data_available = FALSE (set strict = TRUE
to refuse the launch instead). Always check
collect_nlme_job()$fit_health rather than the exit state alone.
Value
See start_nlme_job(); additionally carries data_available.
Start a fit from a declarative model spec (build + validate + fit in one job)
Description
Convenience entry point so an agent does not hand-write R for the common case.
The server generates a child that builds an NlmePmlModel from spec
(constructor + column_map + covariates + initials), saves model.rds,
runs validate_nlme_model() as an embedded preflight, and - if the model is
ready_for_fit - fits it with engineParams(method = spec$method). Custom
structures flow through the same path via constructor = "textualmodel" with
constructor_args$pml, which is PML-validated up front with validate_pml().
Usage
start_nlme_fit_spec(spec, label = NULL, project_dir = ".")
Arguments
spec |
A named list (or, via MCP, a JSON object) with fields:
|
label |
Optional short job label. |
project_dir |
Project root for the run sandbox. |
Value
See start_nlme_job(); tagged with job_kind = "fit_spec".
Start a non-blocking fit of an in-R NlmePmlModel
Description
Model-agnostic direct fit: works for any NlmePmlModel regardless of the
constructor that built it (pkmodel, emaxmodel, pkemaxmodel,
pklinearmodel, pkindirectmodel, linearmodel, textualmodel). The model
is read from model_rds in the child process, re-rooted into the run sandbox,
and fit with fitmodel(). This is the iterate on an already-built model
path; for a cold start (no model.rds yet) use start_nlme_fit_spec() or a
build script via start_nlme_job().
Usage
start_nlme_fitmodel(
model_rds,
params_rds = NULL,
method = NULL,
num_iterations = NULL,
ode = NULL,
label = NULL,
project_dir = ".",
model_stage = NULL,
parent_job_id = NULL,
rationale = NULL,
analysis_plan_id = NULL,
unplanned_override = NULL,
unplanned_reason = NULL
)
Arguments
model_rds |
Path to an |
params_rds |
Optional path to an |
method |
Optional estimation method (e.g. |
num_iterations |
Optional max iterations (used only without |
ode |
Optional ODE solver (used only without |
label |
Optional short job label. |
project_dir |
Project root for the run sandbox. |
model_stage |
Optional model-development stage recorded as run lineage
(one of |
parent_job_id |
Optional id of the job this run derives from (lineage). |
rationale |
Optional one-line reason for this run (lineage). |
analysis_plan_id |
Optional stable analysis-plan id this run follows (lineage). |
unplanned_override |
Optional; records that this run was launched under an approved plan-first gate exception (lineage only - the gate itself lives in .mcp_workflow_gate()). |
unplanned_reason |
Optional reason accompanying |
Details
The child process sets the working directory and NLME_ROOT_DIRECTORY to the
run sandbox so engine artifacts (Overall.csv, err1.txt, ...) land where
collect_nlme_job() looks, and always fits with runInBackground = FALSE
(the background process is this job; nested backgrounding is unsupported on
Windows). Saved artifacts: fit.rds, result.rds, run_context.json.
Value
See start_nlme_job(); tagged with job_kind = "fitmodel".
Start an NLME job in a background process
Description
Launches a detached background R process that evaluates expr (or sources
file) inside the run sandbox, registers the job, and returns immediately.
Never blocks on the fit. expr is evaluated with RUN_DIR bound to the run
directory.
Usage
start_nlme_job(
expr = NULL,
file = NULL,
label = "job",
project_dir = ".",
extra_meta = NULL,
env = NULL
)
Arguments
expr |
Optional R code (single string) to evaluate in the child. |
file |
Optional path to an R script to run in the child (used when
|
label |
Short human label used in the job id / slug. |
project_dir |
Project root under which the run sandbox is created. |
extra_meta |
Optional named list of extra fields merged into the
registered job record ( |
env |
Optional named list/character vector of environment variables to
export in the child process (e.g. a launch recipe's input |
Value
A list: job_id, run_dir, state ("running"), a next_action
directive pointing at wait_for_nlme_job(), plus any extra_meta fields.
Start a non-blocking VPC from a fitted model
Description
Model-agnostic: runs vpcmodel(fit$model) for any fit produced by
start_nlme_fitmodel() / start_nlme_fit_spec(). The child reuses the fit's
engine params (fit$params) unless vpc_params_rds is supplied, and applies
the same sandbox/runInBackground = FALSE rules. Saved artifacts: vpc.rds,
result.rds, run_context.json.
Usage
start_nlme_vpcmodel(
fit_rds,
vpc_params_rds = NULL,
label = NULL,
project_dir = ".",
parent_job_id = NULL,
analysis_plan_id = NULL,
unplanned_override = NULL,
unplanned_reason = NULL
)
Arguments
fit_rds |
Path to an |
vpc_params_rds |
Optional |
label |
Optional short job label. |
project_dir |
Project root for the run sandbox. |
parent_job_id |
Optional id of the fit job this VPC qualifies (lineage). |
analysis_plan_id |
Optional stable analysis-plan id (lineage). |
unplanned_override |
Optional; records that this run was launched under an approved plan-first gate exception (lineage only - the gate itself lives in .mcp_workflow_gate()). |
unplanned_reason |
Optional reason accompanying |
Value
See start_nlme_job(); tagged with job_kind = "vpc" and
model_stage = "qualification_vpc".
Start a sequential-LRT session on a single qualified anchor
Description
Creates a file-backed session under
<project_dir>/qualification/lrt/<session_id>/, persists the approved
plan as an immutable plan.json (its content hash is checked on every
advance_sequential_lrt() call), and either adopts an already-fit
anchor$job_id or launches a fresh anchor refit (model_stage = "structural_anchor"). Refuses to launch without
user_confirmed = TRUE (as an argument, or already set inside spec).
Usage
start_sequential_lrt(spec, project_dir = ".", user_confirmed = FALSE)
Arguments
spec |
See |
project_dir |
Project root; the session directory is created under it. |
user_confirmed |
Explicit confirmation gate. |
Value
A list with session_id, state ("anchoring"), session_dir,
anchor_job_id, anchor_source ("existing_job"/"launched"),
plan_summary, a fixed non_nesting_note, and next_action (call
advance_sequential_lrt()).
Executes an NLME stepwise covariate search
Description
Executes an NLME stepwise covariate search
Usage
stepwiseSearch(
model,
hostPlatform = NULL,
params,
covariateModel,
stepwiseParams,
runInBackground = FALSE,
archiveResults = TRUE,
runLabel = NULL,
updateInitialEstimates = FALSE,
...
)
Arguments
model |
PK/PD model class object. |
hostPlatform |
Host definition for model execution. See |
params |
Engine parameters. See |
covariateModel |
Covariate Effects Model providing the relationship
between covariates and structural parameters to test ( |
stepwiseParams |
Stepwise parameters defining decision tree.
See |
runInBackground |
Logical. When Background execution is supported only on Linux hosts, whether
local or remote: a local host whose |
archiveResults |
Logical. When |
runLabel |
Optional character string appended to the auto-generated
timestamp in the archive folder name, e.g. |
updateInitialEstimates |
Logical. When Notes:
|
... |
Additional arguments for |
Value
if runInBackground = FALSE, an scmSearchResult
data frame is returned with stepwise search results, i.e. the
"Overall" comma separated file, plus a custom print method and a
searchType attribute. The data frame also carries the run context
as attributes: params (resolved NlmeEngineExtraParams),
runMode ("stepwise"), runTime (wall-clock
list(start, end, elapsed) measured around the engine call), and
RsNLMEVersion (the package version that produced the result).
If archiving succeeds it also carries a searchRunDir attribute.
Otherwise (when runInBackground = TRUE) the
StepwiseNlmeJob class object is returned. Backgrounded jobs can
be materialised later via collectJob, which produces the
same scmSearchResult (with archive when
archiveResults = TRUE). Use summary()
for a structured digest (best scenario, top ranking, run context).
Use scmSearchTable for a presentation data.frame
(stepwise decision table, or shotgun ranking plus covariate effects).
See Also
hostParams, engineParams,
collectJob,
summary(),
print(),
scmSearchTable,
getSCMResults
Examples
## Not run:
# Define the model
model <- pkmodel(numCompartments = 1,
data = pkData,
ID = "Subject",
Time = "Act_Time",
A1 = "Amount",
CObs = "Conc",
workingDir = tempdir())
# Add Gender covariate of type categorical
model <- addCovariate(model,
covariate = "Gender",
type = "Categorical",
effect = c("V", "Cl"),
levels = c(0, 1),
labels = c("Female", "Male"))
# Add Bodyweight covariate of type continuous
model <- addCovariate(model,
covariate = "BodyWeight",
type = "Continuous",
direction = "Backward",
center = "Mean",
effect = c("V", "Cl"))
# Define the host
defaultHost <- hostParams(parallelMethod = "MULTICORE",
hostName = "local",
numCores = 8,
sharedDirectory = tempdir())
# Define the engine parameters
params <- engineParams(model, numIterations = 6)
# Define covariate model
cp <- covariateModel(model)
# Define the stepwise parameters
sp <- StepwiseParams(0.01, 0.001, "-2LL")
# Perform stepwise search
OverallDF <- stepwiseSearch(model = model,
hostPlatform = defaultHost,
params = params,
covariateModel = cp,
stepwiseParams = sp,
runInBackground = FALSE)
## End(Not run)
Explicitly stop a sequential-LRT session
Description
The only way a session stops short of "completed"/"budget_exhausted" -
there is no automatic abandonment. Any candidate fit jobs still running
in the background are left to finish on their own; this session simply
stops collecting or acting on their results.
Usage
stop_sequential_lrt(session_id, project_dir = ".", reason = NULL)
Arguments
session_id |
Session id from |
project_dir |
Project root the session was started under. |
reason |
Optional free-text reason recorded on the session. |
Value
The session status (see advance_sequential_lrt()) with
state = "stopped".
Set structural parameter in model object
Description
Use to specify the relationship of the structural parameter with corresponding fixed effect, random effect, and covariate.
Usage
structuralParameter(
.Object,
paramName,
fixedEffName = NULL,
randomEffName = NULL,
style = "LogNormal",
hasRandomEffect = NULL
)
Arguments
.Object |
Model object |
paramName |
Name of the structural parameter |
fixedEffName |
Name of the corresponding fixed effect |
randomEffName |
Name of the corresponding random effect; only applicable to population models. |
style |
Use to specify the relationship of the structural parameter with its corresponding fixed effect, random effect, and covariate, if exists.
|
hasRandomEffect |
Set to |
Value
Modified NlmePmlModel object
Examples
model <- pkindirectmodel(
indirectType = "LimitedInhibition",
isBuildup = FALSE,
data = pkpdData,
ID = "ID",
Time = "Time",
A1 = "Dose",
CObs = "CObs",
EObs = "EObs"
)
# Change style of structural parameter "Imax" to "LogitNormal"
# and rename fixed effect to "tvlogitImax"
model <- structuralParameter(model,
paramName = "Imax",
style = "LogitNormal", fixedEffName = "tvlogitImax"
)
# Remove random effect for structural parameter "IC50"
model <- structuralParameter(model,
paramName = "IC50",
hasRandomEffect = FALSE
)
Get structural parameter names
Description
Returns character vector of structural parameter names for model object.
Usage
structuralParameterNames(model, omitEmpties = TRUE)
Arguments
model |
Object of class |
omitEmpties |
Set to |
Value
Character vector of structural parameter names defined in model
Examples
model <- pkemaxmodel(columnMap = FALSE)
stparms <- structuralParameterNames(model)
Summarize a VPC job (base R, no tidyvpc)
Description
Reads a VPC job's observed (predcheck0.csv) and simulated (predout.csv or
simout.csv) artifacts and returns a structured, bin-wise comparison of observed vs
simulated percentiles (5/50/95) with a coverage heuristic - the fraction of
bins where the observed percentile falls inside the simulated prediction
interval. No tidyvpc or plotting dependency; for plots use a job script.
Usage
summarize_vpc(
job_id,
project_dir = ".",
percentiles = c(0.05, 0.5, 0.95),
ci = 0.9,
n_bins = 10
)
Arguments
job_id |
A VPC |
project_dir |
Project root. |
percentiles |
Observed percentiles to summarize (default 5/50/95). |
ci |
Prediction-interval width for the simulated percentiles (default 0.90 -> 5th/95th across replicates). |
n_bins |
Maximum number of x bins (default 10). |
Value
A structured, JSON-serializable list. coverage_fraction is the
fraction (0–1) of bins where the observed median falls inside the
simulated prediction interval; equals coverage$p50$coverage_pct / 100
when simulation data are available.
Structured summary of an SCM scenario result
Description
Returns a programmatic digest of an scmResult object (from
getSCMResults). Combines scenario metadata from
$scenarioInfo with a header-level digest of the embedded
$fitmodelOutput. Unlike print.scmResult, the
digest does not include the reconstructed model – the
returned object is intended to be consumed programmatically.
Usage
## S3 method for class 'scmResult'
summary(object, ...)
Arguments
object |
A |
... |
Unused. |
Value
An object of class c("summary.scmResult", "list")
with elements:
scenarioScenario label.
statusScenario status string (when available).
criteriaNamed numeric vector with available
-2LL/AIC/BICvalues from$scenarioInfo.fitmodelOutputHeader-level digest of the embedded fit (engine, return code,
nSubj,nObs,logLik,-2LL, plus a nestedrunContextwith method/runMode/elapsed/RsNLMEVersion).NULLwhen$fitmodelOutputis not self-describing – older archives or stub fixtures.diagnosticsNamed list with
files(engine error/log lines) andmissing(absentdmp.txt/final.mdl) when status is notSUCCESS;NULLotherwise.
See Also
getSCMResults, print.scmResult,
shotgunSearch, stepwiseSearch
Structured summary of SCM search results
Description
Returns a programmatic digest of an scmSearchResult object
(from shotgunSearch or stepwiseSearch).
Run-context fields recorded as attributes – resolved estimation
method (from params@method), runMode, wall-clock
runTime$elapsed, and RsNLMEVersion – are surfaced
alongside the scenario inventory. Older archives that lack any of
these attributes silently omit the corresponding fields.
Usage
## S3 method for class 'scmSearchResult'
summary(object, ...)
Arguments
object |
A |
... |
Unused. |
Details
topScenarios contains every ranked scenario so the
digest stays lossless for programmatic consumers; display
truncation is the job of
print.summary.scmSearchResult via its own n
argument.
Value
An object of class c("summary.scmSearchResult",
"list") with elements:
searchTypeOne of
"stepwise","shotgun", orNAwhen the type cannot be resolved.searchRunDirArchive folder path, or
NULLfor unarchived results.nScenariosNumber of scenarios evaluated.
nBest0Lor1L– whether a best scenario is recorded.nFailedCount of scenarios whose archive status is not
SUCCESS.nSucceededCount of scenarios whose archive status is
SUCCESS.bestScenarioA named list with the best scenario label, available
-2LL/AIC/BICcriteria, andstatuswhen the archive reports one. For a 1-row object with no recorded best, this is that row so a failed subset still carries its status.NULLwhen no scenario is recorded.topScenariosA data frame with all ranked scenarios (same ordering as
print.scmSearchResult), withbestandfailedlogical columns.scenarioIndexPath to
scenario_index.csvwhensearchRunDiris set; otherwiseNULL.runContextNamed list with
method,runMode,elapsed,RsNLMEVersion; absent slots are silently dropped.
See Also
shotgunSearch, stepwiseSearch,
getSCMResults,
scmSearchTable,
print.scmSearchResult,
print.summary.scmSearchResult
Wrapper around NlmeTableDef/NlmeSimTableDef-classes initializers.
Description
Wrapper around NlmeTableDef/NlmeSimTableDef-classes initializers.
Usage
tableParams(
name = "",
timesList = numeric(0),
covrSet = "",
whenDose = "",
whenObs = "",
variablesList = "",
keepSource = FALSE,
timeAfterDose = FALSE,
IRES = FALSE,
Weight = FALSE,
IWRES = FALSE,
mode = "all",
forSimulation = FALSE
)
Arguments
name |
Name of the generated simulation file. |
timesList |
Numeric; Time values for simulation.
Applicable for time-based models only. Ignored when |
covrSet |
Character; Vector of covariate names. Simulation point is added
when the covariate value is set. See |
whenDose |
Character; Vector of dosing compartment names. Simulation point is added when the dose value is set. |
whenObs |
Character; String of observed variables names. Simulation point is added when the observation value is set. |
variablesList |
Character; List of variables from the model for simulation. |
keepSource |
Logical; Set to |
timeAfterDose |
Set to |
IRES |
Logical; Set to |
Weight |
Logical; Set to |
IWRES |
Logical; Set to |
mode |
Character; The mode of output. Options are Option |
forSimulation |
logical. Defining whether the table is for simulation
purposes or for postprocessing after fit. Default is |
Value
NlmeTableDef object if forSimulation is FALSE,
NlmeSimTableDef object otherwise.
Examples
Table1 <- tableParams(
name = "Table1.csv",
timesList = seq(0, 24, 2),
whenObs = c("CObs"),
variablesList = "C",
IRES = TRUE,
IWRES = TRUE,
Weight = TRUE)
SimTable1 <- tableParams(
name = "SimTable1.csv",
variablesList = "CL, V",
keepSource = TRUE,
forSimulation = TRUE)
Create a textual model object
Description
Use to create an empty model object and optionally supply location of .mdl file or PML code as a character string to initialize model with PML statements.
Usage
textualmodel(modelName = "", workingDir = "", data, mdl = NULL, pml = NULL)
Arguments
modelName |
Model name to create subdirectory for model output in current working directory. |
workingDir |
Working directory to run the model. Current working directory will be used if |
data |
Input dataset |
mdl |
File path specifying location of .mdl file. Cannot be used together with |
pml |
PML code as a character string. Cannot be used together with |
Value
NlmePmlModel object
Examples
model <- textualmodel(data = pkData)
Update omega (random-effect) initial values and freeze status
Description
Tidy/pipe-friendly updater for the covariance matrix of random effects
(omegas). Complements randomEffect(), which remains the built-in
structural setter for creating or changing diagonal vs. block membership.
Usage
update_Omegas(model, ..., freeze = NULL, unfreeze = NULL)
Arguments
model |
Model object (built-in or textual) |
... |
Named diagonal specs and/or dimnamed matrices; see Details |
freeze |
Character vector of eta names whose containing section(s) should be frozen. Applicable to built-in models only. |
unfreeze |
Character vector of eta names whose containing section(s) should be unfrozen. Applicable to built-in models only. |
Details
On built-in models, edit values or supply a full dimnamed matrix for an
existing section, and use freeze=/unfreeze= to toggle section freeze
status without changing topology.
On textual models, value/matrix edits go through TDL5 override. Freeze
and unfreeze are not supported and raise an error. Frozen or same()-linked
sections may reject value edits. The textual override rebuilds from the
complete omega matrix as a single ranef(block(...)) clause, so section
topology (diag vs block, multiple ranef() sections) is not preserved;
use this path for numeric edits, not layout-sensitive textual models.
Each named argument in ... is either:
a diagonal spec keyed by eta name – a scalar, or a named vector with
initial(aliasvalue); ora base R
matrix()with matching row/columndimnamesgiving eta names, supplying the full covariance values for an existing block/diagonal section (the...name itself is decorative).
Unlike update_Thetas(), a spec here cannot carry freeze: PML has no
per-eta freeze inside a diag()/block() section, so freezing is
necessarily a property of the whole section and is requested through
freeze=/unfreeze= instead. A freeze field inside a spec raises an
error naming that alternative.
Occasion random effects are supported for both value and matrix edits,
targeting the covariate's reference level; a matrix edit must name every
random effect of that occasion covariate, because the stored values cover
its whole inter-occasion covariance matrix. Editing a same()-linked eta
directly raises an error naming the reference level on built-in models, or
a post-hoc error on textual models (which cannot detect same() ahead of
time).
Value
Modified NlmePmlModel object
See Also
Examples
model <- pkmodel(numCompartments = 2, columnMap = FALSE, workingDir = tempdir())
model <- update_Omegas(model, nV = 0.15, nCl = 0.1)
# A dimnamed matrix sets a whole section at once; the dimnames identify the
# section, so the argument name is decorative.
model <- randomEffect(model,
effect = c("nV", "nCl"), isDiagonal = FALSE, value = c(0.1, 0.01, 0.1)
)
blockOmega <- matrix(
c(0.2, 0.03, 0.03, 0.15), nrow = 2,
dimnames = list(c("nV", "nCl"), c("nV", "nCl"))
)
model <- update_Omegas(model, omegaBlock = blockOmega)
# freeze= acts on the whole section containing the named eta
model <- update_Omegas(model, freeze = "nV")
Update residual-error (sigma) initial values and freeze status
Description
Tidy/pipe-friendly updater for residual-error standard deviations
(sigmas). Complements residualError(), which remains the built-in
structural setter for changing error type, BQL/LLOQ, or power
configuration.
Usage
update_Sigmas(model, ..., freeze = NULL, unfreeze = NULL)
Arguments
model |
Model object (built-in or textual) |
... |
Named sigma specs keyed by epsilon or observation name; see Details |
freeze |
Character vector of epsilon/observation names to freeze. Applicable to built-in models only. |
unfreeze |
Character vector of epsilon/observation names to unfreeze. Applicable to built-in models only. |
Details
For built-in models, the standard deviation of the residual error (SD)
can be edited, and it can also be frozen or unfrozen through the
freeze=/unfreeze= arguments (or by specifying freeze in a named spec).
These edits do not change the error type. For textual models, SD edits
go through TDL5 override; freeze and unfreeze are not supported and raise an
error. In addition, a residual error whose error() statement declares
freeze cannot be updated and raises an error.
Each named argument in ... identifies a residual error by either its
epsilon name (e.g. CEps) or its observation name (e.g. CObs). The
argument can be given as either a scalar value (the initial SD) or a named
vector spec that defines the initial SD (initial, alias value) and
whether the SD is frozen (freeze, alias frozen). Observation names are
resolved on built-in models only: a built-in model stores an observation
alongside its epsilon, whereas linking the two on a textual model would
require parsing the observe() statement, so textual models must be keyed
by epsilon name.
The fixed effect corresponding to the proportional component of
AdditiveMultiplicative/MixRatio error models (e.g. CMultStdev) is a
regular fixed effect and should be updated with update_Thetas() rather
than this function.
Value
Modified NlmePmlModel object
See Also
Examples
model <- pkmodel(columnMap = FALSE, workingDir = tempdir())
model <- update_Sigmas(model, CEps = c(initial = 0.05, freeze = TRUE))
Update fixed-effect (theta) initial values, bounds, freeze, and enable
Description
Tidy/pipe-friendly updater for one or more fixed effects (thetas) on
built-in and textual (edited) models. Complements fixedEffect(), which
remains the built-in structural setter when units are needed or when
configuring thetas during model construction. This function does not set
units.
Usage
update_Thetas(model, ...)
Arguments
model |
Model object (built-in or textual) |
... |
Named theta specs; see Details |
Details
Each named argument in ... specifies the theta to update and its new
spec, which may be:
a scalar numeric, which sets the initial value only;
an unnamed length-3 numeric vector
c(lower, initial, upper), which sets the lower bound, initial value, and upper bound;a named vector with any of
lower,initial(aliasvalue),upper,freeze(aliasfrozen),enable. Assign a logical value tofreeze:freeze = TRUEfreezes the associated fixed effect so that it is not estimated, whereasfreeze = FALSEunfreezes it so that it can be estimated. Assign a non-negative whole number toenable; this enables the associated covariate effect, using the assigned value as the enable ID, so that it can be tested during covariate search procedures.
Omitted fields are preserved from the current model. A name that is not a
fixed effect of model raises an error, so a typo is caught rather than
reported as an applied edit.
enable applies to textual models only; built-in models have no enable
slot, so a warning is issued and the field is ignored. Assigning a
non-negative whole number enables the associated covariate effect and uses
that number as the enable ID. enable = FALSE (or NA, or NULL) removes
the enable flag, disabling the covariate effect. A negative number, a
fraction such as 1.8, or a bare enable = TRUE, which carries no ID,
raises an error instead of being truncated or ignored.
Supply enable = FALSE, NULL, or TRUE through a list rather than
c(). Because c() coerces logicals to numbers and drops NULL, a vector
would silently turn the request into something else: TRUE becomes the
valid enable ID 1, FALSE becomes the valid enable ID 0 (leaving the
effect enabled), and NULL disappears entirely (leaving the flag in
place). All three are therefore rejected inside c(), with a message
naming the list form to use, for example
list(initial = 10, enable = FALSE). An enable ID and enable = NA are
unaffected by coercion and may be given either way.
A bound the spec omits is preserved, and a bound the model does not have
stays absent rather than being reported as -Inf/Inf. Passing -Inf as
lower, or Inf as upper, explicitly removes that bound on built-in and
textual models alike.
Value
Modified NlmePmlModel object
See Also
Examples
model <- pkmodel(columnMap = FALSE, workingDir = tempdir())
model <- update_Thetas(model,
tvV = 15,
tvCl = c(lower = 0, initial = 5, upper = 20)
)
initFixedEffects(model)
# -Inf / Inf remove a bound that is currently set
model <- update_Thetas(model, tvCl = c(lower = -Inf))
Update omega (random-effect) values/freeze on a saved model (MCP tool)
Description
Loads model_rds, applies update_Omegas() with the edits in
omegas_json, and saves the result to a new .rds (default
<model>.omegas.rds, or output_path). Freeze/unfreeze toggling is
built-in-models only: TDL5 override never rewrites the (freeze) flag,
so a freeze/unfreeze request against a textual model fails loud.
Usage
update_model_omegas(
model_rds,
omegas_json,
project_dir = ".",
output_path = NULL
)
Arguments
model_rds |
Path to an |
omegas_json |
JSON object string with any of:
At least one of these must carry an edit; an empty object or unknown top-level field is rejected rather than treated as a no-op. |
project_dir |
Project root for resolving a relative |
output_path |
Optional explicit output |
Value
On success, a list with updated = TRUE, model_kind,
model_rds (new path), edits_applied (requested eta names), warnings,
and next_action. On failure, list(updated = FALSE, error = ...).
Update residual-error (sigma) values/freeze on a saved model (MCP tool)
Description
Loads model_rds, applies update_Sigmas() with the edits in
sigmas_json, and saves the result to a new .rds (default
<model>.sigmas.rds, or output_path). Freeze/unfreeze toggling is
built-in-models only. The proportional-part theta of
AdditiveMultiplicative/MixRatio error models (e.g. CMultStdev) is
a regular fixed effect – update it with update_model_thetas, not this
tool.
Usage
update_model_sigmas(
model_rds,
sigmas_json,
project_dir = ".",
output_path = NULL
)
Arguments
model_rds |
Path to an |
sigmas_json |
JSON object string with:
At least one of these must carry an edit; an empty object or unknown top-level field is rejected rather than treated as a no-op. |
project_dir |
Project root for resolving a relative |
output_path |
Optional explicit output |
Value
On success, a list with updated = TRUE, model_kind,
model_rds (new path), edits_applied (requested epsilon/observation
names), warnings, and next_action. On failure,
list(updated = FALSE, error = ...).
Update fixed-effect (theta) values/bounds/freeze/enable on a saved model (MCP tool)
Description
Loads model_rds, applies update_Thetas() with the specs in
thetas_json, and saves the result to a new .rds (default
<model>.thetas.rds, or output_path). Works on both built-in and
textual models; textual updates go through TDL5 override and require a
working NLME installation (INSTALLDIR) – there is no local fallback.
Usage
update_model_thetas(
model_rds,
thetas_json,
project_dir = ".",
output_path = NULL
)
Arguments
model_rds |
Path to an |
thetas_json |
JSON object string keyed by theta name; each value is
a number (initial value only), a 3-element array |
project_dir |
Project root for resolving a relative |
output_path |
Optional explicit output |
Value
On success, a list with updated = TRUE, model_kind,
model_rds (new path), edits_applied (requested theta names),
warnings, and next_action. On failure,
list(updated = FALSE, error = ...). A theta name the model does not
have is a failure, never a partially-applied success.
Validate a PopPK analysis plan
Description
Synchronous, no job launch: checks a protocol-derived analysis plan for
required fields and the per-field provenance contract so an agent gets fast,
structured feedback before persisting it. Every substantive field declares an
origin - protocol_stated (carries protocol_ref), prior_knowledge
(carries reference), or agent_inferred (carries rationale/confidence)
keeping what the protocol states separable from what a prior model contributed and what the agent inferred. Schema:
inst/mcp/schema/analysis-plan.schema.json.
Usage
validate_analysis_plan(plan, project_dir = ".", data_path = NULL)
Arguments
plan |
A named list (or, via MCP, a parsed JSON object); a JSON string is parsed automatically. |
project_dir |
Project root used to resolve a relative |
data_path |
Optional dataset path; when supplied, covariate and flag columns named in the plan are opportunistically cross-checked against the dataset header and any missing column is reported as a warning. Omit when the dataset is not yet available during protocol review. |
Value
A list with valid, errors, warnings, normalized_plan, and a
provenance_summary counting protocol_stated / prior_knowledge /
agent_inferred (and total), plus column_check describing whether the
optional dataset check ran.
Validate that a character / factor covariate column carries labels
Description
RsNLME's checkCatCovariateMappingColumn() decides whether to warn
"data column is of class character – use addLabel()" by running a
per-subject coverage scan: the warning fires iff the scan fails and
none of the column values are blank-only. That rule is effectively
value-based – a character column storing the tokens "0","1" is
accepted because every value is numeric-parseable, while the same
column storing "male","female" is rejected because none are.
Usage
validate_cov_character_labels_required(
data_col_class,
labels,
values = NULL,
n_sample = 500L
)
Arguments
data_col_class |
Character vector from |
labels |
Character vector of labels (possibly |
values |
Optional raw vector of column values (passed untouched
from |
n_sample |
Cap on how many leading values to inspect. Defaults to
|
Details
This validator mirrors that behaviour up-front so the builder can flag
a no-labels Categorical / Occasion panel as soon as the user maps a
column with non-numeric content, without waiting for the full coverage
scan to run (which in the UI is gated on the ID column being mapped).
The scan is bounded to n_sample rows to keep panel blur / effect
events O(1) on large datasets; RsNLME's own scan is linear but runs
only on commit, so a cheap eager check is the right trade-off for
per-keystroke feedback.
Behaviour summary:
-
labelssupplied (any non-blank token) -> always OK. Primary class is neither
characternorfactor-> OK (numeric / integer / logical / POSIXct / etc. carry their own codes).-
characterorfactorwithout labels, andvaluesisNULLor empty -> OK (cannot sniff content; defer to the downstream coverage scan, which will catch it with the richer per-subject message). -
characterorfactorwithout labels, and the sampled values are all blank-only ("","NA","na",".") -> OK (no signal; defer). -
characterorfactorwithout labels, and at least one sampled non-blank value is not numeric-parseable -> ERROR, with the offending class named so the UI can say exactly what the user needs to fix.
Value
List with ok, errors.
Validate per-subject data coverage for a categorical/occasion covariate
Description
For each subject (grouped by id_col) the mapped column must contain at
least one value that is either numeric-like or, when labels is supplied,
that matches a label (case-insensitive, whitespace-trimmed). Mirrors the
legacy per-subject scans in addCovariate() and checkLabels() but runs
in a single vectorised pass with column-class fast paths.
Usage
validate_cov_data_coverage(data, id_col, data_col, labels = NULL)
Arguments
data |
data.frame / data.table holding the input data. If |
id_col |
Name of the subject column. Pass |
data_col |
Name of the covariate column. |
labels |
Optional character vector of labels. |
Value
List with:
-
oklogical scalar -
errorscharacter vector (empty when ok) -
problem_subjectsdata.frame of ID rows that failed coverage
Validate covariate labels argument
Description
Applies the same rules as addLabel(): each label must be non-empty after
trimws(), not match the blank-token list ("", "NA", "na", "."),
contain no internal whitespace, conform to the NLME covariate-label
grammar (leading letter or underscore, then letters, digits, _, -,
., or +), and match length(levels) when levels are provided.
Usage
validate_cov_labels(labels, levels = NULL)
Arguments
labels |
Character vector or |
levels |
Numeric vector used only for the length check. Pass |
Value
List with ok, labels (trimmed, on success), errors.
Validate covariate levels argument
Description
Checks that levels can back a categorical or occasion covariate:
coerces to integer, rejects negatives, fractions, duplicates, and counts
below two.
Usage
validate_cov_levels(levels)
Arguments
levels |
User-supplied |
Value
List with fields:
-
oklogical scalar -
levelscoerced integer vector (or the original input on failure) -
errorscharacter vector of messages; empty whenok = TRUE
Validate that labels are not paired with a numeric data column
Description
RsNLME disallows attaching labels to a covariate whose backing data column
has class numeric (double); the values already carry meaning. Integer
columns are not flagged here because they historically slip through the
same mutex.
Usage
validate_cov_numeric_labels_mutex(data_col_class, labels)
Arguments
data_col_class |
Character scalar from |
labels |
Character vector of labels (possibly |
Value
List with ok, errors.
Validate (and optionally assemble) a covariate-search plan
Description
Synchronous gate for a covariate SEARCH on a settled structural base model. A
search (stepwise, shotgun, sortfit, or covariate_grid) is never
launched silently: this checks that the user explicitly approved it
(user_confirmed = TRUE), that candidate parameter-covariate pairs and a
functional form per pair are given, that stepwise carries forward/backward
criteria (and shotgun/sortfit do not), and that host properties are
present. It also estimates the scenario count (linear for stepwise, 2^n for
shotgun with a red-flag past a threshold, the scenario/recipe count
otherwise). Schema: inst/mcp/schema/covariate-search.schema.json.
Usage
validate_covariate_search(
spec,
project_dir = ".",
data_path = NULL,
model_rds = NULL,
apply = FALSE
)
Arguments
spec |
A named list (or, via MCP, a parsed JSON object); a JSON string is parsed automatically. |
project_dir |
Project root used to resolve relative paths and (for
|
data_path |
Optional dataset path; when supplied, candidate covariate columns are cross-checked against the dataset header. |
model_rds |
Optional path to an |
apply |
When |
Details
The opt-in apply step mirrors configure_blq_handling(): when apply = TRUE
with a built-in base model and a valid, confirmed plan, it calls
addCovariate() for each pair, builds covariateModel(), builds
StepwiseParams() (stepwise), and hostParams() from spec$host, saving the
.rds artifacts under <project_dir>/covariate-search/ so the planned search
and host are runnable via start_nlme_job.
Value
A list with valid, errors, warnings, normalized_spec,
estimated_scenarios, required_inputs, user_confirmed, and (when
apply) an apply sub-list.
Validate a declarative NLME fit spec
Description
Synchronous, no job launch and (by default) no engine fit: checks the spec
consumed by start_nlme_fit_spec() for structural and semantic problems so an
agent gets fast, actionable feedback before a child process is spawned. The
covariate contract is strict - only the MVP fields (name, effect, type,
direction, center, levels, labels) are accepted; ambiguous aliases
(parameter, function) and deferred addCovariate() arguments are rejected
with a fix-it hint rather than silently ignored.
Usage
validate_fit_spec(spec, build_preflight = FALSE, project_dir = ".")
Arguments
spec |
A named list (or, via MCP, a parsed JSON object). See
|
build_preflight |
When |
project_dir |
Project root used to resolve a relative |
Value
A list with valid, ready_for_fit, errors, warnings, and a
normalized_spec (safe aliases resolved; engine$conditionNumber filled
with the MCP default when absent). When build_preflight = TRUE, a
build_preflight sub-list carries the validate_nlme_model() verdict.
Validate a metamodel (.mmdl)
Description
Checks a metamodel by parsing it with RsNLME's own reader. Pure R; no engine
license needed. Surfaces parse/mapping errors so the agent fixes .mmdl
content before running.
Usage
validate_mmdl(text = NULL, path = NULL)
Arguments
text |
Optional metamodel content as a single string. |
path |
Optional path to a |
Details
A missing ## DATA file is intentionally not a parse error (valid stays
TRUE), so the result also reports data health: data_available is FALSE
when the dataset could not be attached, with the declared data_path and the
data_warning text. Agents should check data_available before fitting -
fitting with no data can otherwise look "successful" while producing nonsense.
When data is attached, the result also carries qrpem_compatibility: the
same .mcp_qrpem_time_varying_covariate_check() that start_nlme_fit()
runs before launch, using ## ESTARGS's method (or the engineParams()
default when omitted). qrpem_compatibility$checked is FALSE when the
resolved method is not QRPEM - so most metamodels see no issues here.
Value
A list: valid, errors, warnings, and (on a successful parse)
data_available, data_path, and data_warning.
Validate an in-R NlmePmlModel before fitting
Description
Generic preflight for any NlmePmlModel (built by any constructor or
textualmodel()), read from an .rds. MCP clients cannot pass S4 objects, so
the tool takes a path; the in-memory worker is internal. Returns a structured
verdict so an agent can fix mapping/initials before launching a fit instead of
discovering an empty/garbage fit afterward.
Usage
validate_nlme_model(model_rds)
Arguments
model_rds |
Path to an |
Details
Checks: object class, attached input data, column mapping completeness,
covariate mapping, and whether the fixed-effect initials look like untouched
defaults (all 1) - a frequent cause of -LL = NaN engine aborts. The
initials check is advisory (a warning), not a hard blocker. When initials
are suspicious and the model carries a recognizable id/time/dose/
observation layout, a rough order-of-magnitude starting vector for
V/Cl/Ka/Ke-named parameters is derived from simple dose/Cmax/Tmax moments
(not a full NCA) and returned as suggested_initials.
Value
A list: valid, ready_for_fit, checks, errors, warnings,
model_constructor_hint, and suggested_initials (NULL unless
initials are suspicious and a heuristic starting vector could be
derived).
Validate PML code
Description
Validates a PML model. When a working NLME engine (TDL5) is available the code
is checked by the engine and its own errors/warnings are returned
(mode = "engine", engine_validated = TRUE, confidence = "high").
Otherwise it degrades to a KB-based grammar/keyword lint (mode = "lint",
engine_validated = FALSE, confidence = "lint-only") using the audited
symbol inventory and anti-pattern signatures, and says so.
Usage
validate_pml(code)
Arguments
code |
A length-one character string of PML model code. |
Details
Degraded-mode contract: a clean lint result means "no known structural
error or anti-pattern was detected", not "the engine accepts this". Treat
confidence = "lint-only" as a provisional pass and re-validate with the
engine (set INSTALLDIR) before relying on a translated/authored model. The
lint includes signatures for untranslated NONMEM constructs (e.g. leftover
THETA(1)/ETA(1), $PK/$ERROR records, DADT(n), uppercase intrinsics)
so a NONMEM-to-PML draft that was not fully converted fails the lint.
Value
A list: valid, mode, engine_validated, confidence, errors,
warnings, and (lint mode) matched_anti_patterns.
Check QC/reporting readiness against the analysis plan
Description
Warn-only: compares the saved analysis plan's reporting_outputs with the
artifacts the project has produced (completed fits, a VPC, and a portable
.mmdl handoff) and reports the gaps. Requirements are plan-driven, so they
scale with intended_use. Reads only; never launches or writes.
Usage
validate_qc_readiness(project_dir = ".")
Arguments
project_dir |
Project root. |
Value
A list with ready, gaps, discovered, and expected_outputs.
When no plan is saved, ready = FALSE and the first gap points at
save_analysis_plan().
Validate a sequential-LRT plan (single anchor, ordered nested operations)
Description
Structural preflight for start_sequential_lrt(). Checks the anchor
locator (job_id for an already-fit refit, XOR model_rds/mmdl_path to
fit fresh here), that operations lists >= 1 SINGLE nested add/remove
effect each (unique id, action, positive integer df, a
distribution of chisq or boundary_mixture), alpha_add/
alpha_remove in (0, 1), a positive integer fit_budget, and
host_resources$max_concurrent_fits. Does not launch anything.
Usage
validate_sequential_lrt(spec, project_dir = ".")
Arguments
spec |
A named list (or, via MCP, a JSON object string) with fields:
|
project_dir |
Project root (used only to resolve/validate candidate file paths; no session is created here). |
Value
A list with valid, errors, warnings, normalized_spec,
plan_summary (n_operations, n_add, n_remove, alpha_add,
alpha_remove, fit_budget, max_concurrent_fits), and
user_confirmed.
See Also
start_sequential_lrt() to launch a session from a validated,
user-confirmed plan.
Perform visual predictive check for NLME models
Description
Perform visual predictive check for NLME models
Usage
vpcmodel(
model,
vpcParams,
params,
hostPlatform = NULL,
runInBackground = FALSE,
...
)
Arguments
model |
PK/PD model class object. |
vpcParams |
VPC argument setup. See |
params |
Engine argument setup. See |
hostPlatform |
Host definition for model execution. See |
runInBackground |
Logical. When Background execution is supported only on Linux hosts, whether
local or remote: a local host whose |
... |
Additional class initializer arguments for |
Value
If runInBackground = FALSE, a named list of
data.tables loaded from the engine's VPC outputs
(predcheck*.csv files, any user-defined
simulationTables, plus predout.csv / simout.csv
depending on params@isPopulation). The list also carries
runMode = "vpc", runTime, and RsNLMEVersion
elements alongside the data. Otherwise an NlmeSimulationJob
object that can be materialised later via collectJob(),
which produces the same result list.
See Also
Examples
## Not run:
model <- pkmodel(
numComp = 1,
absorption = "Extravascular",
ID = "Subject",
Time = "Act_Time",
CObs = "Conc",
Aa = "Amount",
data = pkData,
modelName = "PkModel",
workingDir = tempdir()
)
host <- hostParams(
sharedDirectory = tempdir(),
parallelMethod = "NONE",
hostName = "local",
numCores = 1
)
job <- fitmodel(model = model,
hostPlatform = host)
finalModelVPC <- copyModel(model,
acceptAllEffects = TRUE,
modelName = "model_VPC",
workingDir = tempdir())
# View the model
print(finalModelVPC)
# Set up VPC arguments to have PRED outputted to simulation output dataset "predout.csv"
vpcSetup <- NlmeVpcParams(outputPRED = TRUE)
# Run VPC using the default host, default values for the relevant NLME engine arguments
finalVPCJob <- vpcmodel(model = finalModelVPC, vpcParams = vpcSetup, hostPlatform = host)
# the same as:
# finalVPCJob <- vpcmodel(model = finalModelVPC, outputPRED = TRUE)
# Observed dataset predcheck0.csv
dt_ObsData <- finalVPCJob$predcheck0
# Simulation output dataset predout.csv
dt_SimData <- finalVPCJob$predout
# Add PRED from REPLICATE = 0 of simulation output dataset to observed input dataset
dt_ObsData$PRED <- dt_SimData[REPLICATE == 0]$PRED
# tidyvpc package VPC example:
# library(tidyvpc)
# library(magrittr)
# Create a regular VPC plot with binning method set to be "jenks"
# binned_VPC <- observed(dt_ObsData, x = IVAR, yobs = DV) %>%
# simulated(dt_SimData, ysim = DV) %>%
# binning(bin = "jenks") %>%
# vpcstats()
# plot_binned_VPC <- plot(binned_VPC)
# Create a pcVPC plot with binning method set to be "jenks"
# binned_pcVPC <- observed(dt_ObsData, x = IVAR, yobs = DV) %>%
# simulated(dt_SimData, ysim = DV) %>%
# binning(bin = "jenks") %>%
# predcorrect(pred = PRED) %>%
# vpcstats()
# plot_binned_pcVPC <- plot(binned_pcVPC)
## End(Not run)
Watch an NLME job until it finishes or the server's watch budget elapses
Description
The preferred way for an agent to wait on a long fit/bootstrap/SCM job: it
blocks server-side, polling the job status internally, and returns once the
job reaches a terminal state (succeeded/failed/dead/not_found) or the
watch budget elapses. This turns many agent poll turns into a single blocking
tool call. If the job is still running when the call returns
(watch$terminal is FALSE), simply call again to resume watching.
Usage
wait_for_nlme_job(
job_id,
project_dir = ".",
max_wait_seconds = NULL,
detail = c("compact", "full")
)
Arguments
job_id |
Job id from |
project_dir |
Project root. |
max_wait_seconds |
Optional direct-R override for the per-call watch
budget (seconds), clamped to |
Details
The watch budget comes from the server's launch configuration
(launch_certara_mcp()'s job_watch_wait_seconds, set per client by
write_mcp_config() in the Certara.R host) and is treated as a HARD UPPER
BOUND: the internal poll interval is fixed at 5 seconds and the MCP schema
does not expose max_wait_seconds to the agent. The direct-R
max_wait_seconds argument is retained for compatibility - it may SHORTEN
the budget (down to 0 for a single-shot check) but any value at or above
the launch cap is silently clamped to the cap.
st <- wait_for_nlme_job(job_id, project_dir)
while (!st$watch$terminal) { # still running after the budget
st <- wait_for_nlme_job(job_id, project_dir)
}
artifact_dir <- st$artifact_dir
Value
The same list as get_nlme_job_status(), plus a watch block with
max_wait_seconds, poll_seconds, source
("argument"/"launch_config"/"default"), and terminal
(TRUE when the job reached a terminal state), and the agent-facing
next_action directive (tool/args/reason; the single next call to
make - NULL when none applies) with requires_user_attention when a job
is stalled or terminal-without-success. While running in the default compact
detail, only job_id, state, pid_alive, watch, progress,
next_action, and (when set) requires_user_attention are returned.
See Also
get_nlme_job_status() for a single-shot snapshot,
collect_nlme_job() to gather results once terminal.
Wait for multiple NLME jobs to reach a terminal state (bounded batch wait)
Description
There is no engine-level "wait for all" primitive; this polls
get_nlme_job_status() for every id in job_ids in a single bounded loop
instead of the caller looping wait_for_nlme_job() once per id (which would
multiply the per-call watch budget by the number of jobs). Returns as soon as
every job is terminal, or once max_wait_seconds elapses - whichever comes
first; never blocks longer than that budget regardless of how many ids are
passed.
Usage
wait_for_nlme_jobs(
job_ids,
project_dir = ".",
max_wait_seconds = NULL,
poll_interval = .mcp_job_watch_poll_seconds
)
Arguments
job_ids |
Character vector of job ids (from any |
project_dir |
Project root the jobs were launched under. |
max_wait_seconds |
Optional direct-R override for the total wall-clock
budget (seconds), clamped |
poll_interval |
Seconds between internal poll sweeps (default 5, minimum 0.5). |
Value
A list with all_terminal (logical), elapsed_s, and jobs: a
named list (by job_id) of each job's latest get_nlme_job_status()
snapshot.
Writes out data/column mapping and engine parameter files for the engine
Description
Writes out data/column mapping and engine parameter files for the engine
Usage
writeDefaultFiles(model, dataset, simParams, Tables, sortColumns = NULL)
Arguments
model |
Model object |
dataset |
Dataset to run simulation/fitting on |
simParams |
Simulation Parameters (simulation tables are written to coldef) |
Tables |
NlmeTableDef class object(s) |
sortColumns |
SortColumns class object used for proper id mapping during individual modeling |
Value
NULL
Write a metamodel file (.mmdl)
Description
Writes an NlmePmlModel object to a text based metamodel file (.mmdl).
Usage
write_mmdl(
model,
file,
datafile,
author = "",
engineParams = NULL,
tableParams = NULL,
absolutePaths = FALSE
)
Arguments
model |
An NlmePmlModel object. |
file |
Output metamodel file path to create/overwrite. |
datafile |
Input data file path to write into the |
author |
Optional author string to write into the metamodel. |
engineParams |
Optional NlmeEngineExtraParams object created by
|
tableParams |
Optional table definition(s) created by |
absolutePaths |
Logical; how to write the |
Value
Invisible file.