Package {Certara.RsNLME}


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 NLME_SCM_RUNID).

searchType

"shotgun" or "stepwise".

isRemote

Logical; TRUE for remote runs.

model

The base NlmePmlModel to serialize into the archive.

params

Resolved NlmeEngineExtraParams, persisted as part of the run archive. May be NULL.

runMode

One of "stepwise" or "shotgun"; matches searchType in practice. May be NULL.

runTime

Wall-clock timing list list(start, end, elapsed), captured around the engine call. May be NULL.

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 NlmeEngineExtraParams object.

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; NA is treated as non-numeric.

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 NlmePmlModel with attached data and mapping.

method

Estimation method name, numeric engine code, or NlmeEngineExtraParams (or list thereof). NULL/empty resolves via .mcp_resolve_method_for_qrpem_check().

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 TRUE (the default for fitmodel compat), strips residuals and posthoc sections before parsing. Set to FALSE to retain them (used by the SCM loader to extract these fields). The FALSE branch routes through .fastLoadDmpFile(), which bypasses R's parser on the per-observation column literals when the engine markers are present; it falls back to the legacy full source(textConnection(...)) otherwise. Set the env var RSNLME_FAST_DMP=0 to force the legacy path (used by the equivalence tests and as a user escape hatch).

warnMissing

If TRUE (the default), warn when the file is absent. Set to FALSE where absence is an expected state – a failed SCM scenario never writes dmp.txt, and the caller reports that once with actionable context of its own.

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., "0,1,3" or c(0, 1, 3)).

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 dmp.txt and (optionally) nlme7engine.log.

Details

Failure / degradation policy (deliberately gracefully degraded relative to an all-or-nothing rule):

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 NlmePmlModel object with all covariate effects.

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 NlmePmlModel object.

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

numReplicates

Number of bootstrap replicates to run

initialEstimates

Get model final estimates to run bootstrap (T|F)

numRetries

Number of times to retry a failed replicated

randomNumSeed

Seed for random number generator

confidenceLevel

Confidence level

stratifyColumns

What 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

numCovariates

Number of covariate effects

covariateList

Comma separated list of covariate effects names

scenarioNames

Comma separated list of scenario names

isDefault

Comma separated list of flags

degreesOfFreedom

Comma separated list of degrees of freedom

enableIDs

Comma 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

name

Dose point name

type

Character; Options are "Bolus" or "Infusion"

amount

Optional; Character specifying corresponding column in data or numeric specifying dose amount

rate

Optional; Character specifying corresponding column in data or numeric specifying dose rate

deltaTime

Optional; Character specifying corresponding column in data or numeric specifying delta time

isSecondDose

Use second dose point on compartment?

data

Optional data frame. Must specify data if supplying column as character value to amount, rate, deltaTime arguments


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 type = Occasion. (Default: FALSE)


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

isPopulation

logical; TRUE if the model is a population model, FALSE for an individual model.

sort

character; String to pass sorting options to the NLME engine. Typically " -sort " to enable sorting or "" to disable it.

csv

character; 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).

method

numeric; 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 method is 5) depends on the xfocehess slot: xfocehess = 1 selects FOCE-ELS, and xfocehess = 0 selects LAPLACIAN.

numIterations

numeric; The maximum number of iterations allowed for the estimation algorithm. Values must be non-negative integers.

odeToUse

numeric; 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

rtol

numeric; Specifies the relative tolerance for the ODE solver.

atol

numeric; Specifies the absolute tolerance for the ODE solver.

nmxstep

numeric; Specifies the maximum number of steps allowed for the ODE solver.

anagrad

numeric; 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.

popad

numeric; 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.

xnp

numeric; 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 xnp generations.

xnorderagq

numeric; Specifies the number of quadrature points per dimension for Adaptive Gaussian Quadrature (AGQ). Only applicable when method is FOCE-ELS or LAPLACIAN.

  • 1: Standard FOCE-ELS/LAPLACIAN computation (no AGQ).

  • >1: AGQ is performed. The total number of quadrature points used is (number of ETAs)^xnorderagq.

xfocehess

numeric; 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 method is FOCE-ELS or LAPLACIAN.

xstderr

numeric; Specifies the method for standard error estimation.

  • 0: No standard error estimation.

  • 1: Central difference method.

  • 2: Forward difference method.

xcondmode

numeric; 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's out.txt as a # conditionNumberBasis = ... comment following the condition = line.

sand

character; String to request sandwich standard error calculation. Typically " -sand " or "".

fisher

character; String to request Fisher score standard error calculation. Typically " -fscore " or "".

autodetect

character; String to request auto-detection of standard error method. Typically " -AutoSE " or "".

xlandig

numeric; Specifies the optimization accuracy (NDIGIT) for the outer loop (thetas and sigmas) when using FOCE-ELS or LAPLACIAN methods.

xlatol

numeric; Specifies the relative step size used for numerical computation of the Hessian matrix (second derivatives) during standard error calculation.

xblndig

numeric; Specifies the optimization accuracy (NDIGIT) for the inner loop (optimization of etas). Also applies to the single optimization loop in the NAIVE-POOLED method.

xbltol

numeric; Specifies the relative step size for numerical differentiation during model linearization.

gradTolOuter

Numeric maximum gradient tolerance in the outer (Theta/Omega/Sigma) optimization loop. Applicable to FOCE-ELS and LAPLACIAN methods.

stepTolOuter

Numeric maximum step tolerance in the outer (Theta/Omega/Sigma) optimization loop. Applicable to FOCE-ELS and LAPLACIAN methods.

gradTolInner

Numeric maximum gradient tolerance in the inner (Eta) optimization loop. Applicable to FOCE-ELS and LAPLACIAN methods.

stepTolInner

Numeric maximum step tolerance in the inner (Eta) optimization loop. Applicable to FOCE-ELS and LAPLACIAN methods.

refDeltaLagl

Numeric LL Delta tolerance value used during Theta/Omega/Sigma optimization. Applicable to FOCE-ELS and LAPLACIAN methods.

isPCWRES

numeric; 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.

xpcwresnrep

numeric; Stores the number of simulation replicates used for PCWRES computation. Applicable only when isPCWRES is 1.

xisample

numeric; Specifies the number of sample points used in the QRPEM algorithm. Only applicable when method is QRPEM.

xmapassist

numeric; 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 method is QRPEM.

xmapnp

numeric; Specifies the number of iterations for a preliminary Naive-Pooled optimization run before the main estimation. Applicable when the method is not NAIVE-POOLED.

ximpsampdof

numeric; Controls the importance sampling distribution used in the QRPEM algorithm. Only applicable when method is QRPEM.

  • 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.

xmcpem

numeric; Controls the sampling method used in the QRPEM algorithm.

  • 0: Quasi-Random sampling.

  • 1: Monte-Carlo sampling.

Only applicable when method is QRPEM.

xpemrunall

numeric; Set to 1 to execute all requested iterations specified in numIterations. Only applicable to population models with method = "QRPEM".

xsirsamp

numeric; Specifies the number of samples per eta per subject used in the Sampling Importance Resampling (SIR) algorithm within QRPEM. Only applicable when method is QRPEM.

xburnin

numeric; Specifies the number of burn-in iterations in the QRPEM algorithm. During burn-in, omegas can be frozen (see xnonomegaburn). Only applicable when method is QRPEM.

xnonomegaburn

numeric; 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 method is QRPEM. See also xburnin.

xaccratio

numeric; Specifies the acceptance ratio used in the QRPEM algorithm for scaling the covariance matrix. Only applicable when method is QRPEM. Only applicable to population models with method = "QRPEM".

xscramble

numeric; 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 method is QRPEM.

emTolType

Numeric 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 method is QRPEM.

emConvLen

Numeric specifying the number of iterations to check for convergence. Only applicable when method is QRPEM.

emConvCritVal

Numeric specifying the convergence critical value. Only applicable when method is QRPEM.

pardern

numeric; Specifies the number of time steps used for outputting partial derivatives of observed variables with respect to parameters. Only applicable to individual models.

parderd

numeric; Specifies the step size for numerical calculation of partial derivatives of observed variables with respect to parameters. Only applicable to individual models.

logtran

numeric; Engine flag controlling log-transformation behavior for single LogAdditive error model.

See Also

engineParams()

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: "none" (default), "KMEANS", "CENTERS", "BOUNDARIES"

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

sharedDirectory

character. The directory where the run will take place. On Windows, UNC paths are mapped to a drive letter for local execution.

installationDirectory

character. The directory containing NLME libraries and scripts.

hostName

character. A user-friendly name for the host (e.g., "local_mpi").

machineName

character. The IP address or hostname of the machine. Defaults to the local system's node name.

hostType

character. 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 the PML_BIN_DIR environment variable. linux will be treated as "RHEL".

numCores

numeric. The number of compute cores to be used.

isLocal

logical. TRUE if the host is local, FALSE if remote.

rLocation

character. The path to the Rscript executable on a remote host. This is ignored for local runs.

scriptPath

character. The path to a script to execute on the remote host before Rscript is started. This is ignored for local runs.

userAuthentication

NlmeUserAuthentication. An object containing user credentials for remote host authentication. See NlmeUserAuthentication.

parallelMethod

NlmeParallelMethod. The parallel computing method to use (e.g., "LOCAL_MPI", "SGE", "TORQUE"). See NlmeParallelMethod.

mpiCoresPerJob

integer. 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 ⁠<= numCores⁠ and divide numCores evenly.

gridQueue

character. 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.

gridWalltime

integer. Wall-clock limit in seconds for grid jobs. NA_integer_ (default) imposes no limit. Ignored for local methods.

gridMemory

character. Memory request for grid jobs (e.g. "16G"). Empty (default) requests no explicit memory. Ignored for local methods.

gridJobNamePrefix

character. Prefix for the scheduler job name shown in qstat/squeue. Empty (default) derives a name from the workflow. Ignored for local methods.

gridResourceExtra

character. 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

method

Options are: None|Multicore|Multicore_MPI|LOCAL_MPI|SGE|SGE_MPI|TORQUE|TORQUE_MPI|LSF|LSF_MPI|SLURM|SLURM_MPI.

Multicore_MPI runs several MPI jobs concurrently on a single local machine; pair it with mpiCoresPerJob in hostParams() to fix the per-job MPI rank, or omit mpiCoresPerJob to 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

isPopulation

Is this a population model (TRUE) or individual (FALSE)?

modelType

Taken from NlmeModelType

isTimeBased

Is model time-based?

linearModelType

Type of linear model

isLinearFrozen

Is linear model frozen?

pkModelAttrs

Taken from NlmePkParameters

indirectModelAttrs

Taken from NlmeIndirectParameters

emaxModelAttrs

Taken from NlmeEmaxParameters

hasEffectsCompartment

Is there data available for an effects compartment?

errorModel

Taken from NlmeErrorModel

structuralParams

List of structural parameters

outputParams

List of output parameters

diffEquations

List of differential equations

statements

List of PML statements

dosePoints

List of dosepoints

covariateList

List of covariates

columnMapping

Taken from NlmeColumnMapping

doseMapping

Taken from NlmeDoseMapping

paramsMapping

Taken from NlmeParamsMapping

randParamsMapping

Taken from NlmeRandParamsMapping

inputData

Input data source

doseData

Dose data source

fixedParamData

Fixed effect parameter data source

randParamData

Random effect parameter data source

isTextual

Is model textual (TRUE) or graphical (FALSE)?

pmloutput

List of PML output to generate

modelInfo

Taken from NlmePmlModelInfo

objects

deprecated

objectsNeedRegenerating

deprecated

randomEffectsStatements

Custom random effects statements

randomOccasionalEffectsStatements

Custom random occasional effects statements

userDefinedExtraDefs

Custom 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

sharedDirectory

The directory in which the run executes

installationDirectory

Directory containing NLME libraries/scripts

hostName

IP or name of remote host

userAuthentication

Credential 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 "keepSource=TRUE"

covrSet

Character; Vector of covariate names. Simulation point is added when the covariate value is set. See covariateNames

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 TRUE to keep the number of rows appearing in the table the same as the number of rows in the input dataset.

timeAfterDose

Set to TRUE to output time after dose.


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. NlmeSimTableDef class instance or a list of such instances. Could be generated by tableParams wrapper function or by NlmeSimTableDef class instance initializing directly.

See Also

tableParams, NlmeSimTableDef

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

style

Parameter 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 "keepSource=TRUE"

covrSet

Character; Vector of covariate names. Simulation point is added when the covariate value is set. See covariateNames

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 TRUE to keep the number of rows appearing in the table the same as the number of rows in the input dataset.

timeAfterDose

Set to TRUE to output time after dose.

IRES

Logical; Set to TRUE to output individual residuals. Valid only if whenObs is specified.

Weight

Logical; Set to TRUE to output the weight of current observation. Valid only if whenObs is specified.

IWRES

Logical; Set to TRUE to output individual weighted residuals. Valid only if whenObs is specified.

mode

Character; The mode of output. Options are "all" (default), "unique", "first". Only applicable to non time-based models for the case where only covrSet is defined or the case where only covrSet and variablesList are defined.

Option "all" (default): it outputs all the rows invoked by specified covariates. Option "unique": if the values in a row are the same as the ones in the previous row for the current subject, then the row is omitted; otherwise, it is printed out. Option "first": it outputs only the first row for each subject.


Class initializer for NlmeUserAuthentication

Description

Use for authentication records

Slots

userName

How the user is identified to the remote system

privateKeyFile

path to private key file, see keyfile for details

userPassword

either a string or a callback function for password prompt, see passwd for 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 "none", "proportional", "additive". This option is ignored for discontinuous observed variables (categorical, count, and time-to-event).

predVarCorr

Logical; Set to TRUE to use Prediction Variance Correction. Only applicable to the case where predCorrection is set to either "proportional" or "additive".

outputPRED

Logical; Set to TRUE to include population prediction (PRED) results for continuous observed variables in output.

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. NlmeSimTableDef class instance or a list of such instances. Could be generated by tableParams wrapper function or by NlmeSimTableDef class instance initializing directly.

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

howToPertubate

How to apply profile variables. Options are USE_DELTA or USE_PERCENTAGE

profileVars

List 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. "-2,0,2"). The value must be character and list at least one perturbation; an empty or whitespace-only string is rejected at construction.

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

jobType

GENERIC/ESTIMATION_RUN/COVAR_SEARCH/PROFILE_RUN/STEPWISE_SEARCH/BOOTSTRAP/Sort_By_Column

localDir

where the data/model files are taken and the results are loaded for the local and remote runs

remoteDir

where the data/model files are taken and the results are loaded on remote host

host

local/remote job parallelization type

argsList

list of arguments for run

argsFile

file for arguments for run

scriptFile

initial script generation

workflow

workflow name

runInBackground

should 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 scmSearchResult object.

...

Arguments passed to [.data.frame.

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

copyModel

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 columnMap = TRUE) use named character if the name of the covariate is different from the corresponding column in the input dataset, for example, covariate = c(BW = "BodyWeight"), where BW denotes the name of the covariate, and "BodyWeight" is the name of the corresponding column in the input dataset.

effect

Name of structural parameter(s) on which the covariate has an effect. Specify effect as character or character vector if the covariate has an effect on multiple structural parameters. Important for Occasion Covariates: When modifying an existing occasion covariate (e.g., changing option or values), you must list all structural parameters currently affected by this occasion covariate in the effect argument, even those whose effect relationship is not being changed in this specific call.

type

Type of covariate. Options are "Continuous", "Categorical", "Occasion".

direction

Direction of missing values propagation (if no covariate value is given). Options are "Forward", "Interpolate", "Backward", where "Interpolate" is only applicable to type = "Continuous".

option

Options are "Yes", "PlusOne", or "No".

  • "Yes": Apply the covariate effect using the standard method (multiplicative for LogNormal style, additive for Normal style).

  • "PlusOne": Apply the covariate effect using the "1 + effect" formulation. This is only applicable to continuous and categorical covariates where the affected structural parameter has style = "LogNormal".

  • "No": Remove the specified covariate effect from the specified structural parameter(s). The covariate itself (and its definition, e.g., fcovariate(Occ1)) remains part of the model, but the link between this covariate and the specified parameter(s) in the stparm() statement is removed. See the note for the effect argument regarding occasion covariates. Multiple options are not supported within a single call (i.e., all covariate effects listed in the effect argument for a single call must use the same option). If different options are required, use sequential calls to addCovariate.

center

Centering method. Options are "Mean", "Median", "Value" or "None". Only applicable to covariate type = "Continuous". Must include argument centerValue if center = "Value".

centerValue

Value used to center covariate. Only applicable if argument center = "Value" and type = "Continuous".

levels

Unique values of categorical or occasion covariate. Only applicable to covariate type = "Categorical" or type = "Occasion".

labels

Label names (in the same order as levels) for unique levels of categorical or occasion covariate in data. Only applicable to covariate type = "Categorical" or type = "Occasion" where its corresponding column in the input dataset has character type.

isDiagonal

Set to FALSE if inter-occasion covariance matrix is not diagonal matrix. Only applicable to covariate type = "Occasion".

values

Initial values for the diagonal elements of the inter-occasion covariance matrix (if isDiagonal = TRUE) or initial values for the lower triangular elements (including diagonal elements) of inter-occasion covariance matrix (if isDiagonal = FALSE) in a row-wise order. Only applicable for covariate type = "Occasion".

isPositive

Set to FALSE if covariate contains negative values. Only applicable to covariate type = "Continuous".

Details

The following relationships are applicable for covariates:

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 "SteadyState"and "ADDL"

name

Dose point name. See doseNames

administration

Mechanism for administering dose. Options are "Bolus" or "Infusion"

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 type argument.

Value

Modified NlmePmlModel object

See Also

doseNames

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 TRUE if duration is used to specify infusion information

isSecondDose

Set TRUE if doseCptName is specified in the model through dosepoint2 statement

colName

Name of the input data column that represents the corresponding infusion rate. If not provided, colName must be mapped through colMapping().

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


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

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 start_sequential_lrt().

project_dir

Project root the session was started under.

candidate_updates

Optional named list (or, via MCP, a JSON object string) mapping operation id -> {model_rds}/{mmdl_path}, for operations left status = "stale" (no candidate yet, or one built against a reference that has since changed). An id outside the approved plan, or one already decided, is reported and ignored - never accepted.

force_continue

When TRUE, proceed past a state == "blocked" pause (e.g. an OFV-parity mismatch) that the user has reviewed and explicitly accepted. Does not override an altered-plan.json block.

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 control_text is NULL).

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 hostParams. If missing, multicore local host with 4 threads is used.

params

Engine parameters. See engineParams. If missing, default parameters generated by engineParams(model) are used.

bootParams

Bootstrap parameters. See BootstrapParams. If missing, default parameters generated by BootstrapParams() are used.

runInBackground

Logical. When TRUE, the wrapper starts the engine asynchronously and returns a job object immediately; pass that object to collectJob() when the run has finished to obtain the typed result. When FALSE (the default), the wrapper blocks until the engine completes and returns the result directly.

Background execution is supported only on Linux hosts, whether local or remote: a local host whose hostType is "linux" (the default on Linux workstations), or a remote host with hostType "linux", "RHEL", or "UBUNTU". It is not supported on Windows (hostType = "windows", including the default local host when R runs on Windows): leave the argument at FALSE. Passing TRUE on a Windows host stops with an error. Remote Windows hosts are not supported at all.

saveResult

Logical; if TRUE (default), the returned rsnlme_boot is written to <workingDir>/bootstrap_<sanitizedModelName>_<YYYYMMDD_HHMMSS>.rds so the run becomes self-describing on disk. workingDir is the model's working directory (model@modelInfo@workingDir), not necessarily R's process getwd(). sanitizedModelName is derived from model@modelInfo@modelName by replacing every character outside [A-Za-z0-9._-] with _; if the result is empty or contains no alphanumerics, the literal string model is used instead. The timestamp is the wall-clock start of the engine call, formatted as YYYYMMDD_HHMMSS in the local time zone. For runInBackground = TRUE, the save happens at collectJob() time rather than when bootstrap() returns. A failing write produces a warning, never an error.

overwriteFitDir

Logical (default FALSE). bootstrap() writes its aggregate artifacts (dmp.txt, residuals.csv, Boot*.csv) into model@modelInfo@workingDir - NOT into hostPlatform@sharedDirectory, which does not redirect aggregate output. Passing a model whose workingDir already holds a fit's own dmp.txt/residuals.csv (e.g. a fitted model's workingDir taken as-is) would silently overwrite that fit's outputs with a single bootstrap replicate's estimates, corrupting any downstream GOF/VPC that re-reads the directory. By default bootstrap() detects this and reroots the run into an isolated <workingDir>/bootstrap/<run-id>/ subdirectory instead (via copyModel), leaving the original fit untouched. Set overwriteFitDir = TRUE to force running in-place and overwrite those files anyway (not recommended); this always emits a warning.

...

Additional class initializer arguments for BootstrapParams or hostParams, or arguments available inside engineParams functions. If engineParams arguments are supplied through both params argument and additional argument (i.e., ellipsis), then the arguments in params will be ignored and only the additional arguments will be used with warning. If hostParams arguments are supplied through both hostPlatform argument and additional argument, then its values will be overridden by additional arguments. In addition, if BootstrapParams arguments are supplied through both bootParams argument and additional argument, then its slots will be overridden by additional arguments.

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


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 "knowledge" (NLME authoring/validation), "data", "execution", "comparison", "interpretation", "qualification" (sequential-LRT session orchestration for the Darwin hybrid-qualification workflow).

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 start_nlme_fit() / start_nlme_fitmodel() / start_nlme_fit_spec()).

darwin_ofv

The candidate's results.csv$ofv from pyDarwin (a raw ⁠-2LL⁠, not fitness).

project_dir

Project root the job was launched under.

tolerance

Optional absolute tolerance in ⁠-2LL⁠ units. Defaults to max(0.5, 0.001 * abs(darwin_ofv)).

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 (NlmePmlModel) object

mappings

Named character vector specifying valid column names in the input data. Character vector names must be valid model variable names contained in modelVariableNames(model).

...

optional pairs ModelTerm = ColumnName or ModelTerm = "ColumnName". Has higher precedence than mappings if some ModelTerm is mapped twice in mappings and in .... For multiple mapping, i.e. id mapping, a vector should be provided with the names of columns. See example below.

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 runInBackground = TRUE (bootstrap, fitmodel, stepwiseSearch, shotgunSearch, profilePertubate, sortfit, vpcmodel, simmodel).

timeout

Maximum time to wait, in seconds. Inf (the default) waits indefinitely.

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

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 TRUE (the default), recompute fit_health at collection time. Set FALSE to reuse fit_health from a recent get_nlme_job_status() / wait_for_nlme_job() poll when the job already succeeded and artifacts are unlikely to have changed.

darwin_ofv

Optional results.csv$ofv (raw ⁠-2LL⁠, NOT fitness) from a pyDarwin (Certara.RDarwin) search candidate that this job is a refit of. When supplied and the fit succeeded, an ofv_parity block is attached reconciling darwin_ofv against this refit's fit_health$neg2ll. Required before treating this job as a qualified structural anchor for any nested LRT (see validate_sequential_lrt()).

ofv_tolerance

Optional absolute tolerance (in ⁠-2LL⁠ units) for the ofv_parity check. Defaults to max(0.5, 0.001 * abs(darwin_ofv)) to accommodate pyDarwin's chained ⁠##ESTARGS⁠ stages, which can shift the final -2LL by a small amount versus a single-stage RsNLME refit.

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 start_sequential_lrt().

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 .rds or Overall.csv files (at least two).

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 TRUE, also compute guarded LRT p-values of each model against the reference (caller asserts nesting + same data).

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

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 "CObs"); the required BLQ mapping token is paste0(obs_name, "BQL") (e.g. CObsBQL).

user_requested

Set TRUE when the request/protocol/analysis plan calls for BLQ handling even if the dataset shows no obvious signal.

model_rds

Optional .rds holding a built-in NlmePmlModel; only used with apply = TRUE.

apply

When TRUE and model_rds is a built-in model, wire BLQ via residualError() and save a ⁠<model>.blq.rds⁠. Textual models are not rewritten (the exact observe(..., bql) edit is returned instead).

project_dir

Project root for resolving a relative data_path / model_rds.

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 path is given.

expected

Optional named list of expected counts (e.g. from a translation analysis): any of fixef, ranef, error, observe.

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 textualmodel() build (default FALSE).

path

Optional path to a PML file to read when code is not supplied, so an agent can confirm a model on disk without inlining minified text.

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 TRUE to accept all effects, update PML statements, and test.mdl file from original model run

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 TRUE to force run

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 ⁠## DATA⁠ block.

author

Optional author string to write into the metamodel.

engineParams

Optional NlmeEngineExtraParams object created by engineParams() to serialize into the ⁠## ESTARGS⁠ block. Only arguments that differ from engineParams() defaults for this model (and estimation method) are written.

tableParams

Optional table definition(s) created by tableParams() (i.e., NlmeTableDef and/or NlmeSimTableDef, or a list of them) to serialize into the ⁠## TABLES⁠ block.

absolutePaths

Logical; controls how datafile is written into the ⁠## DATA⁠ block. FALSE (default) writes a path relative to the metamodel directory (e.g. ./data.csv), keeping the resulting metamodel portable across machines. TRUE writes a normalized absolute path, useful when the dataset lives outside the metamodel tree (shared drive, central data location). When relative resolution is not possible (e.g. different Windows drive), the function warns and falls back to an absolute path.

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 missing, a subfolder in the current directory with the model name given in parsedMetamodel will be created

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

read_mmdl(), run_metamodel()

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 data.frame.

Value

Modified NlmePmlModel object

See Also

colMapping

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


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 control_text is NULL).

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 TRUE or individual model FALSE?

checkBaseline

Set to TRUE if the model contains a baseline response.

checkFractional

Set to TRUE to modify the default form for the model. Only applicable to models with checkBaseline = TRUE.

checkInhibitory

Set to TRUE to change the model from an Emax to an Imax model.

checkSigmoid

Set to TRUE to change the model to its corresponding signmoid form.

data

Input dataset

columnMap

If TRUE (default) column mapping arguments are required. Set to FALSE to manually map columns after defining model using colMapping.

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 workingDir not specified.

...

Arguments passed on to emaxmodel_MappingParameters

ID

Column mapping argument for input dataset column(s) that identify individual data profiles. Only applicable to population models isPopulation = TRUE.

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).

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 isPopulation = TRUE.

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 TRUE, data are sorted. If FALSE, data are not sorted. Defaults to FALSE if the model contains reset information (model@hasResetInfo = TRUE); otherwise, defaults to TRUE.

ODE

Character; Specifies the ODE solver to be used. Options are: "MatrixExponent", "DVERK", "DOPRI5", "AutoDetect", "Stiff", "LSODE". See Details section for a description of each solver.

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: "QRPEM", "IT2S-EM", "FOCE-LB", "FO", "FOCE-ELS", "Laplacian", and "Naive-Pooled". For individual models, only "Naive-Pooled" is available. The default for population models depends on model characteristics:

  • If the model includes discontinuous observed variables (LL/multi/count/event), Below Quantifiable Limit (BQL) data, all residual SDs frozen, or no error() statement, FOCE-ELS is unavailable. The default is "Laplacian"; "QRPEM", "IT2S-EM", and "Naive-Pooled" are equally available.

  • Otherwise, the default is "FOCE-ELS".

stdErr

Character; Specifies the method for standard error computations. Options vary depending on the model type and estimation method:

  • Individual models: "Hessian" (default) or "None".

  • Population models with method = "QRPEM": "Fisher-Score" (default) or "None".

  • Population models with method = "IT2S-EM": "None" only.

  • Population models with method in c("FOCE-LB", "FO", "FOCE-ELS", "Laplacian", "Naive-Pooled"): "Sandwich" (default), "Hessian", "Fisher-Score", "Auto-Detect", or "None".

"None" means that standard error calculations are not performed.

isCentralDiffStdErr

Logical; If TRUE (default), uses central difference for standard error calculations when applicable. If FALSE, uses forward difference.

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 "Naive-Pooled" method, and 0.01 otherwise).

conditionNumber

Character; Selects the basis and scope used to compute the reported condition number when standard errors are produced. One of:

"CovarianceFixef"

(Default) Covariance matrix of the estimated fixed effects only.

"CorrelationFixef"

Correlation matrix of the estimated fixed effects only.

"CovarianceFull"

Covariance matrix of all estimated population parameters (fixed effects, standard deviations of residual errors, Omega).

"CorrelationFull"

Correlation matrix of all estimated population parameters. This is the only option directly comparable to the condition number calculated from NONMEM's reported eigenvalues, which are computed over all estimated THETA/OMEGA/SIGMA parameters.

This argument is independent of stdErr: it does not change which standard-error covariance block is computed, only how the reported eigenvalues and condition lines (in the engine's out.txt) are derived from that block. The basis actually used is echoed there as a # conditionNumberBasis = ... comment. See Details for the formulas.

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.

  • NULL (default) or TRUE: When the model has exactly one residual error model and it is LogAdditive, this setting enables Log-Transform Both Sides (LTBS). In LTBS, predictions and observations are log-transformed, and the model is fit in the log-domain. This results in the internal logtran engine parameter being set to 1.

  • FALSE: When the model has exactly one residual error model and it is LogAdditive, this setting results in the LogAdditive error being treated as a proportional/multiplicative error during fitting (by neglecting third and higher-order terms in the Taylor expansion of exp(epsilon)). This sets the internal logtran engine parameter to 0. For simulation, the error is treated as exp(epsilon).

For other model configurations, the logtran parameter is determined as follows:

  • If there are multiple residual error models or no residual error models, logtran is set to 0, irrespective of the logTransform value. (In the case of multiple errors, any LogAdditive errors present are treated as proportional).

  • If there is a single residual error model that is not LogAdditive:

    • For built-in models: logtran is set to 0.

    • For textual models: logtran reflects the logTransform setting (it becomes 1 if logTransform is NULL or TRUE, and 0 if logTransform is FALSE). A warning is issued if logTransform is NULL or TRUE in this scenario, highlighting that LTBS is typically for LogAdditive errors and that error type identification can be challenging in textual models.

numIntegratePtsAGQ

Integer; Specifies the number of quadrature points per dimension to use for Adaptive Gaussian Quadrature (AGQ). Only applicable to population models when method is "FOCE-ELS" or "Laplacian".

  • 1: Standard FOCE-ELS/LAPLACIAN computation (no AGQ).

  • >1: AGQ is performed. The total number of quadrature points used is (number of ETAs)^numIntegratePtsAGQ.

numIterNonParametric

Integer; Controls non-parametric (NP) optimization.

  • 0: Disables NP optimization.

  • 1: Enables NONMEM-style NP optimization using posthoc estimates as support points.

  • >1: Enables an evolutionary NP algorithm, using numIterNonParametric as the number of generations.

Only applicable to population models when method is not "Naive-Pooled".

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 method is "FOCE-ELS" or "Laplacian".

Accepted values:

FALSE

(Default) Disables automatic differentiation. Finite differences are used for all gradient and Hessian computations.

TRUE

Enables inner-loop automatic differentiation (equivalent to "InnerAD"). Provided for backward compatibility.

"InnerAD"

Enables automatic differentiation for the inner optimization loop (random effects / etas).

"OuterAD"

Enables inner-loop AD plus population-level (outer-loop) automatic differentiation.

numIterMAPNP

Integer; Specifies the number of iterations for a preliminary Naive-Pooled (NP) optimization run before the main estimation. Applicable when the method is not "NAIVE-POOLED".

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 "Naive-Pooled".

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 "FOCE-ELS" or "Laplacian" methods. Only applicable to population models.

numDigitBlup

Numeric; Specifies the optimization accuracy (NDIGIT) for the inner loop (optimization of etas). Also applies to the single optimization loop in the "NAIVE-POOLED" method.

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.

  • 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 mapAssist.

Only applicable to population models with method = "QRPEM".

iSample

Numeric; Specifies the number of sample points used in the QRPEM algorithm. Only applicable to population models with method = "QRPEM".

iAcceptRatio

Numeric; Specifies the acceptance ratio used in the QRPEM algorithm for scaling the covariance matrix. Only applicable to population models with method = "QRPEM".

impDist

Character; Specifies the importance sampling distribution used in the QRPEM algorithm. Options are: "Normal", "DoubleExponential", "Direct", "T", "Mixture-2", "Mixture-3". Only applicable to population models with method = "QRPEM". See Details for further information.

tDOF

Numeric; Specifies the degrees of freedom for the multivariate T distribution used in importance sampling. Only applicable when method = "QRPEM" and impDist = "T". Must be between 3 and 30.

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 method = "QRPEM".

numBurnIn

Numeric; Specifies the number of burn-in iterations in the QRPEM algorithm. During burn-in, omegas can be frozen (see freezeOmega parameter). Only applicable to population models with method = "QRPEM".

freezeOmega

Logical; Set to TRUE to freeze Omega but not Theta for the number of iterations specified in the numBurnIn. Only applicable to population models with method = "QRPEM".

MCPEM

Logical; Controls the sampling method used in the QRPEM algorithm.

  • FALSE: Quasi-Random sampling.

  • TRUE: Monte-Carlo sampling.

Only applicable to population models with method = "QRPEM".

runAllIterations

Logical; Set to TRUE to execute all requested iterations specified in numIterations. Only applicable to population models with method = "QRPEM".

scramble

Character; Specifies the scrambling method for quasi-random number generation in the QRPEM algorithm. Options are: "None", "Owen", "Faure-Tezuka". Only applicable to population models with method = "QRPEM".

emTolType

Numeric; QRPEM convergence check type. Options:

  • 0: Default (no rollout, LL & Theta and Sigma).

  • 1: LL & All Population Params (Theta, Omega, and Sigma) with rollout.

  • 2: LL with rollout.

  • 3: All Population Params with rollout.

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:

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):

Basis (how C is used):

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 missing, current working directory is used.

dataFileName

the name of the data file If missing, the default file name 'data1.txt' is used to prepare nlmeargsOutput file

mdlOutput

the name of the file to output PML code If missing, the default file name 'test.mdl' is used.

cols1Output

the name of the file to output columns defintion If missing, the default file name 'cols1.txt' is used.

nlmeargsOutput

the name of the file to output engine parameters If missing, the default file name 'nlmeargs.txt' is used.

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

read_mmdl()

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 hostParams. If missing, PhoenixMPIDir64 is given and MPI is installed, MPI local host with 4 threads is used. If MPI is not found, local host without parallelization is used.

params

Engine parameters. See engineParams. If missing, default parameters generated by engineParams(model) are used.

simpleTables

Optional list of simple tables. See tableParams. By default a table named 'posthoc.csv' is returned with structural parameters values for all source data rows.

runInBackground

Logical. When TRUE, the wrapper starts the engine asynchronously and returns a job object immediately; pass that object to collectJob() when the run has finished to obtain the typed result. When FALSE (the default), the wrapper blocks until the engine completes and returns the result directly.

Background execution is supported only on Linux hosts, whether local or remote: a local host whose hostType is "linux" (the default on Linux workstations), or a remote host with hostType "linux", "RHEL", or "UBUNTU". It is not supported on Windows (hostType = "windows", including the default local host when R runs on Windows): leave the argument at FALSE. Passing TRUE on a Windows host stops with an error. Remote Windows hosts are not supported at all.

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 Value section will be outputted to the model directory and loaded as returned value. Only those files listed in the Value section can be specified. Simple regex patterns are supported for the specification.

...

Additional arguments for hostParams or arguments available inside engineParams functions. If engineParams arguments are supplied through both params argument and additional argument (i.e., ellipsis), then the arguments in params will be ignored and only the additional arguments will be used with warning. If hostParams arguments are supplied through both the hostPlatform argument and the ellipses, values supplied to hostPlatform will be overridden by additional arguments supplied via the ellipses e.g., ....

saveResult

Logical; if TRUE (default), the returned list is written to <workingDir>/fitmodel_<sanitizedModelName>_<YYYYMMDD_HHMMSS>.rds so the run becomes self-describing on disk. sanitizedModelName is derived from model@modelInfo@modelName by replacing every character outside [A-Za-z0-9._-] with _; if the result is empty or contains no alphanumerics, the literal string model is used instead. The timestamp is the wall-clock start of the engine call, formatted as YYYYMMDD_HHMMSS in the local time zone. For runInBackground = TRUE, the save happens at collectJob() time rather than when fitmodel() returns. A failing write produces a warning, never an error.

Value

if runInBackground is FALSE, a list with main resulted dataframes is returned:

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:

For population models and the method specified is NOT Naive-Pooled, additional dataframes are returned:

If standard error computation was requested and it was successful, additional dataframes are returned:

If nonparametric method was requested (numIterNonParametric > 0) and the method specified in engineParams is NOT Naive-Pooled, additional dataframes are returned:

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:

Self-describing run context

The returned list also carries five run-context elements that make the object self-describing:

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 effect.

lowerBound

Numeric or numeric vector specifying the lower limit values of fixed effects. If supplying vector, must be in the same order as effect.

upperBound

Numeric or numeric vector specifying the upper limit values of fixed effects. If supplying vector, must be in the same order as effect.

isFrozen

Logical or logical vector. Set to TRUE to freeze the fixed effect to the specified initial value. If supplying vector, must be in the same order as effect.

unit

Character or character vector specifying units of measurement for the fixed effects. If supplying a vector, must be in the same order as effect.

Value

Modified NlmePmlModel object

See Also

update_Thetas()

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:

  • A search-result data frame (from shotgunSearch() / stepwiseSearch()) with a searchRunDir attribute.

  • A single-row data frame from listSCMRuns().

  • An NlmePmlModel (resolves the latest archived run in its working directory).

  • A character path to an archived run folder (selects best scenario).

  • A character path to a scenario subfolder (uses that exact scenario).

scenario

Optional scenario identifier (label or token). Only allowed when x resolves to a run folder (not a specific scenario).

enableIDs

Optional comma-separated string or integer vector of enable IDs to select a scenario by its active PML enable() groups (matches the enableIDs column of scenario_index.csv). Only allowed when x resolves to a run folder.

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 NlmePmlModel for 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 (resolved NlmeEngineExtraParams), runMode ("stepwise" or "shotgun"), runTime (wall-clock list), and RsNLMEVersion.

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 ⁠start_nlme_*⁠ call.

project_dir

Project root that owns the run (must match the one used to launch the job).

full_omega

When TRUE, also return the full symmetric omega matrix in fit_summary$random_effects_matrix. Default FALSE (diagonal only).

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 start_nlme_job().

project_dir

Project root.

wait_seconds

Optional server-side wait: block (polling every poll_interval seconds) until the job reaches a terminal state (succeeded/failed/dead/not_found) or this many seconds elapse, then return the latest status. Default 0 (single-shot, non-blocking). Capped at 600 so a tool handler never blocks indefinitely. For agent use prefer wait_for_nlme_job() instead of tuning this directly.

poll_interval

Seconds between internal polls while waiting (default 2, minimum 0.5). Ignored when wait_seconds <= 0.

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 ⁠<project_dir>/analysis-plan/⁠.

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 start_sequential_lrt().

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

character. The directory where temporary run folders are created. Defaults to the current working directory for local runs and to "~" for remote runs.

installationDirectory

character. The directory containing NLME libraries/scripts. Defaults to the INSTALLDIR environment variable for local runs and to file.path(sharedDirectory, "InstallDirNLME") for remote runs.

hostName

character. A display name for the host. Defaults to the system's network name (from Sys.info()[["nodename"]]) for local runs and to machineName for remote runs.

machineName

character. The IP address or network name of the host. Defaults to "127.0.0.1".

hostType

character. The host operating system. Defaults to the current OS (Sys.info()[["sysname"]]) for local runs and to "linux" for remote runs. While "windows" or "linux" are valid for local runs, for remote Linux hosts the following are officially supported: "RHEL" (for RHEL 8 and 9) and "UBUNTU" (for Ubuntu 22.04 and 24.04). Specifying one of these values correctly sets the PML_BIN_DIR variable.

numCores

numeric. The number of CPU cores to utilize. Defaults to 4.

parallelMethod

character. The parallel execution method. Options include: "None", "Multicore", "Multicore_MPI", "LOCAL_MPI", "SGE", "SGE_MPI", "TORQUE", "TORQUE_MPI", "LSF", "LSF_MPI", "SLURM", "SLURM_MPI". Defaults to "LOCAL_MPI".

mpiCoresPerJob

integer, optional. Per-scenario MPI rank for the "Multicore_MPI" parallel method. Leave at the default NA_integer_ to let NLME8 size the rank from the current batch (engine-aware auto policy). Set a positive integer to fix the per-job MPI width; it must divide numCores evenly. Ignored (with a warning) for other methods.

userName

character. The username for remote host authentication.

privateKeyFile

character. The path to an SSH private key file for remote authentication. See ssh::ssh_connect() for more details.

userPassword

character or function. The password or a callback function for remote authentication. See ssh::ssh_connect() for details.

scriptPath

character. The path to a script to run on a remote host before the main job starts. Ignored for local runs.

rLocation

character. The path to the Rscript executable on a remote host. Ignored for local runs.

isLocal

logical. Set to TRUE for a local host or FALSE for a remote host. Defaults to TRUE.

gridQueue

character, optional. Scheduler queue or partition to route grid jobs to (e.g. "bg.q" on SGE, "batch" on SLURM). This is the scheduler's queue/partition name for CPU jobs; it does not imply GPU or graphical execution. Empty (default) uses the cluster default queue. Used only by grid parallel methods ("SGE", "TORQUE", "LSF", "SLURM", and their ⁠_MPI⁠ variants); ignored (with a warning) otherwise.

gridWalltime

integer, optional. Wall-clock limit in seconds for grid jobs. Defaults to NA_integer_, which imposes no limit so long-running bootstrap/covariate-search work is not capped. Grid methods only.

gridMemory

character, optional. Memory request for grid jobs (e.g. "16G", mapped to SGE h_vmem / TORQUE vmem / SLURM --mem). Empty (default) requests no explicit memory. Grid methods only.

gridJobNamePrefix

character, optional. Prefix for the scheduler job name shown in qstat/squeue. Empty (default) derives a name from the workflow and job type. Restricted to letters, digits, and underscores. Grid methods only.

gridResourceExtra

character, optional. Additional site-specific resource request, emitted verbatim using each scheduler's native syntax: appended to a resource list for the PBS-style schedulers (SGE ⁠#$ -l <value>⁠, TORQUE ⁠#PBS -l <value>⁠, e.g. "h_data=4G"), or rendered as a standalone directive for SLURM (⁠#SBATCH <value>⁠, e.g. "--gres=gpu:1") and LSF (⁠#BSUB <value>⁠, e.g. "-R rusage[mem=4096]"). Empty (default) adds nothing. Grid methods only.

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

NlmePmlModel object. Must already have its covariate list populated (via addCovariate() for API-built models or textualmodel() for textual ones) and id mapped via colMapping().

data

Optional data.frame to impute. Defaults to model@inputData. Never mutated by reference; an internal deep copy is used throughout.

missingToken

Vector of sentinel values. Default c(-99). Supports numeric, NA, and character (e.g. c(-99, NA, ".")). Treated as a single missing-value predicate: a row is "missing" if its value matches any configured token. Tokens are not inferred: real NA values, ".", and blank cells are only imputed when you list them here. Leaving them undeclared is an error rather than a silent no-op, because the NLME engine reads all three as missing.

method

"subject" (default) uses the cascade described in Details; "population" skips subject-level lookups and fills every masked row from the population or stratum central value.

continuousFn

Function applied to a non-empty numeric vector returning a single value. Default median. Must return a length-1 finite numeric.

categoricalFn

Function applied to a non-empty vector (character, factor, or numeric for occasion / numeric-coded categorical) returning a single value. Default imputeMode() – the package's exported modal-value helper with deterministic tie-breaking by first appearance and factor-level preservation. Pass a custom function (e.g. function(x) sort(unique(x))[1]) to override. Validation is type-driven, not model-driven:

  • For factor columns, the returned value must already be a level of the input factor; factor levels are never extended implicitly. This is a technical R constraint (factor codes cannot encode an unknown label), not a model-semantic rule.

  • For character / numeric columns, the returned value is written into the data verbatim, even when it is not among the categories declared in model@covariateList[[name]]. NLME treats out-of-declaration values per the model's default category semantics; the function does not second-guess that behaviour. If you need strict membership, supply a categoricalFn that enforces it.

centralValueWeighting

How the population / stratum central value is pooled. "subject" (default) is two-stage: the aggregator is applied to each subject's values, then to the resulting vector of subject-level summaries, so every subject carries equal weight. "row" applies the aggregator once across all non-missing rows, so subjects with more records count more.

"subject" is the default because it matches how the NLME engine pools covariate values for mean() / median() centering (one summary per subject, then combined across subjects), and because row weighting otherwise tracks sampling density – a study-design artifact – rather than the population.

Under "subject" a custom continuousFn / categoricalFn is invoked once per contributing subject and once across the subject summaries; a trimmed mean, for instance, then trims subject means rather than raw rows. The setting does not affect the "propagated" donor value, which is by definition computed within a single subject.

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 0.1.

keepOriginal

If TRUE (default), the raw pre-imputation values of each modified data column are preserved as ⁠<dataCol>_orig⁠. A pre-existing backup column triggers an error to prevent corrupting traceability with stale data.

logFile

Path to write the imputation log. Default NULL resolves to file.path(model@modelInfo@workingDir, "imputeMissingCovariates.log"), creating the working directory if it does not exist yet (it usually will not, since the model has not been run). If the directory cannot be created, the log falls back to tempdir() with a warning. An explicit logFile is never given this treatment: its parent directory must already exist, so a typo fails loudly instead of scattering directories.

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):

  1. Block has at least one non-missing value – masked rows are left as NA (source "engine"). The engine fills them via fcovariate() / covariate() / interpolate().

  2. 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 / categoricalFn over the subject's non-missing values across all blocks (source "propagated").

  3. 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:

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 as.character() on both sides). Default NULL means no values are excluded.

Details

Properties:

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 NlmePmlModel object.

value

A data.frame to attach as the model input data.

Value

The updated NlmePmlModel with @inputData and @columnMapping set.

See Also

colMapping, read_mmdl

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

fixedEffect

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 .rds holding an NlmePmlModel.

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 NULL.

na_strings

Strings treated as missing (default c("NA", ".", "")).

max_dup_report

Max duplicate ⁠(ID, time)⁠ groups to list (default 20).

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 .mdl file.

data_path

Path to a CSV dataset to attach.

mappings_json

Optional JSON object string of model_term -> data_column applied with colMapping() after the build (e.g. ⁠{"id":"ID","CObs":"DV","BWT":"BWT"}⁠). Omit to keep the auto-mapping inferred from matching column names.

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 estimates is NULL).

compound_class

Optional class hint (e.g. "mAb", "small molecule").

sources

Optional character vector of article links (URL/DOI).

project_dir

Project root (for job_id).

fetch

If TRUE, request server-side retrieval; this provider defers that retrieval to the MCP host, since RsNLME does not bundle a web-fetch dependency.

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 NlmePmlModel object.

value

A single non-NA logical. TRUE for population mode, FALSE for individual mode.

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; NA is treated as non-numeric.

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

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 TRUE or individual model FALSE?

type

Model type. Options are "Constant", "Linear", "Quadratic".

data

Input dataset

columnMap

If TRUE (default) column mapping arguments are required. Set to FALSE to manually map columns after defining model using colMapping.

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 workingDir not specified.

...

Arguments passed on to linearmodel_MappingParameters

ID

Column mapping argument for input dataset column(s) that identify individual data profiles. Only applicable to population models isPopulation = TRUE.

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).

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 isPopulation = TRUE.

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:

  • A search-result data frame (from shotgunSearch() / stepwiseSearch()) with a searchRunDir attribute. Lists scenarios for that single archived run.

  • An NlmePmlModel. Scans the model's working directory for all archived covariate-search run folders.

  • A character path to an archived run folder (contains scenario_index.csv). Lists scenarios for that single run.

  • A character path to a working directory. Scans for all child stepwise_* and shotgun_* run folders.

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., INSTALLDIR environment variable. The cadlicensingtool executable is expected to be located within this directory, or within a subdirectory specified by the PML_BIN_DIR environment variable.

ForceAuth

A logical value indicating whether to force re-authentication even if already authenticated. Default is FALSE.

ForceLicenseGet

A logical value indicating whether to force obtaining the license even if already licensed. Default is FALSE.

verbose

A logical value indicating whether to print verbose output. Default is getOption("verbose").

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 .mdl/.pml/.txt file containing PML text.

model_rds

Path to an .rds file holding an NlmePmlModel.

md_base

Optional explicit Model Designer base URL; when supplied, the CAD environment lookup is skipped entirely.

open_browser

If TRUE (default), open the resulting URL with utils::browseURL() when status == "ok".

api_version

CAD API version for the environments endpoint (default "v4").

verbose

If TRUE (default), emit progress messages.

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 (NlmePmlModel) object

ForceRun

Set to TRUE to force run

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 NlmeParallelHost class definition. If missing, MPI local host with 4 threads is used for simple estimation mode, multicore host is used for the others.

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

Certara University


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 TRUE or individual model FALSE?

parameterization

Type of parameterization. Options are "Clearance", "Micro", "Macro", or "Macro1".

absorption

Type of absorption. Options are "Intravenous", "FirstOrder", "Gamma", "InverseGaussian", "Weibull" .

numCompartments

Value of either 1, 2, or 3.

isClosedForm

Set to TRUE to convert model from a differential equation to close form.

isTlag

Set to TRUE to add a lag time parameter to the model.

hasEliminationComp

Set to TRUE to add an elimination compartment to the model.

isFractionExcreted

Set to TRUE if elimination compartment (hasEliminationComp = TRUE) contains a fraction excreted parameter.

isSaturating

Set to TRUE to use Michaelis-Menten kinetics for elimination. Only applicable to models with paramteterization = "Clearance"

infusionAllowed

Set to TRUE if infusions allowed.

isDuration

Set to TRUE if infusions use duration instead of rate (must also set infusionAllowed = TRUE).

isSequential

Set to TRUE to freeze PK fixed effects and convert the corresponding random effects into covariates as well as remove the PK observed variable from the model.

isPkFrozen

Set to TRUE to freeze PK fixed effects and remove the corresponding random effects as well as the PK observed variable from the model.

hasEffectsCompartment

Set to TRUE to include an effect compartment into the model.

checkBaseline

Does Emax/Imax model have a baseline response?

checkFractional

Set to TRUE to modify the default form for the Emax/Imax model. Only applicable to models with checkBaseline = TRUE.

checkInhibitory

Set to TRUE to change the default Emax to Imax model.

checkSigmoid

Set to TRUE to change the Emax/Imax to its corresponding sigmoid form.

isEmaxFrozen

Set to TRUE to freeze PD fixed effects and remove the corresponding random effects as well as the PD observed variable from the model.

data

Input dataset

columnMap

If TRUE (default) column mapping arguments are required. Set to FALSE to manually map columns after defining model using colMapping.

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 workingDir not specified.

...

Arguments passed on to pkindirectmodel_MappingParameters

ID

Column mapping argument for input dataset column(s) that identify individual data profiles. Only applicable to population models isPopulation = TRUE.

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:

  • Models with absorption = "Intravenous" and parameterization set to either "Clearance","Micro", or "Macro"

  • Models with absorption set to either "Gamma", "InverseGaussian", or "Weibull"

Aa

Column mapping argument that represents the input dataset column for the amount of drug administered and only applicable to models with absorption = "FirstOrder".

A

Column mapping argument that represents the input dataset column for the amount of drug administered and only applicable to models with absorption = "Intravenous" and parameterization = "Macro1".

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:

  • Models with absorption = "Intravenous", infusionAllowed = TRUE and parameterization set to either "Clearance","Micro" or "Macro"

  • Models with absorption set to either "Gamma", "InverseGaussian", or "Weibull" and infusionAllowed = TRUE

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:

  • Models with absorption = "Intravenous", infusionAllowed = TRUE with isDuration = TRUE and parameterization set to either "Clearance","Micro" or "Macro"

  • Models with absorption set to either "Gamma", "InverseGaussian", or "Weibull" and infusionAllowed = TRUE with isDuration = TRUE

Aa_Rate

Column mapping argument that represents the input dataset column for the rate of drug administered and only applicable to models with absorption = "FirstOrder", infusionAllowed = TRUE.

Aa_Duration

Column mapping argument that represents the input dataset column for the duration of drug administered and only applicable to models with absorption = "FirstOrder", infusionAllowed = TRUE, and isDuration = TRUE.

A_Rate

Column mapping argument that represents the input dataset column for the rate of drug administered and only applicable to models with absorption = "Intravenous", infusionAllowed = TRUE, and parameterization = "Macro1".

A_Duration

Column mapping argument that represents the input dataset column for the duration of drug administered and only applicable to models with absorption = "Intravenous", infusionAllowed = TRUE, isDuration = TRUE, and parameterization = "Macro1".

A1Strip

Column mapping argument that represents the input dataset column for the stripping dose and only applicable to models with parameterization = "Macro".

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 parameterization being either set to either "Clearance" or "Micro".

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 parameterization being either set to either "Macro" or "Macro1".

A0Obs

Column mapping argument that represents the input dataset column for the observed amount of drug in the elimination compartment. (hasEliminationComp = TRUE).

EObs

Column mapping argument that represents the input dataset column for the observed drug effect.

nV

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nV.

nV2

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nV2.

nV3

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nV3.

nCl

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nCl.

nCl2

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nCl2.

nCl3

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nCl3.

nKa

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nKa.

nA

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nA.

nAlpha

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nAlpha.

nB

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nB.

nBeta

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nBeta.

nC

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nC.

nGamma

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nGamma.

nKe

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nKe.

nK12

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nK12.

nK21

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nK21.

nK13

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nK13.

nK31

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nK31.

nTlag

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nTlag.

nKm

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nKm.

nVmax

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nVmax.

nFe

If isSequential = TRUE and isFractionExcreted = TRUE, mapped to the input dataset column that lists the values for random effect nFe.

nMeanDelayTime

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nMeanDelayTime.

nShapeParam

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nShapeParam.

nShapeParamMinusOne

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nShapeParamMinusOne.

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 TRUE or individual model FALSE?

parameterization

Type of parameterization. Options are "Clearance", "Micro", "Macro", or "Macro1".

absorption

Type of absorption. Options are "Intravenous", "FirstOrder", "Gamma", "InverseGaussian", "Weibull" .

numCompartments

Value of either 1, 2, or 3.

isClosedForm

Set to TRUE to convert model from a differential equation to close form.

isTlag

Set to TRUE to add a lag time parameter to the model.

hasEliminationComp

Set to TRUE to add an elimination compartment to the model.

isFractionExcreted

Set to TRUE if elimination compartment (hasEliminationComp = TRUE) contains a fraction excreted parameter.

isSaturating

Set to TRUE to use Michaelis-Menten kinetics for elimination. Only applicable to models with paramteterization = "Clearance"

infusionAllowed

Set to TRUE if infusions allowed.

isDuration

Set to TRUE if infusions use duration instead of rate (must also set infusionAllowed = TRUE).

isSequential

Set to TRUE to freeze PK fixed effects and convert the corresponding random effects into covariates as well as remove the PK observed variable from the model.

isPkFrozen

Set to TRUE to freeze PK fixed effects and remove the corresponding random effects as well as the PK observed variable from the model.

hasEffectsCompartment

Set to TRUE to include an effect compartment into the model.

indirectType

Type of drug actions for the indirect response model. Options are "LimitedStimulation", "InfiniteStimulation", "LimitedInhibition", "InverseInhibition", "LinearStimulation", or "LogLinearStimulation".

isBuildup

Set to FALSE to have the drug actions affect the loss/degradation instead of the production.

isExponent

Set to TRUE to add an exponent parameter to the drug action term.

indirectFrozen

Set to TRUE to freeze PD fixed effects and remove the corresponding random effects as well as the PD observed variable from the model.

data

Input dataset

columnMap

If TRUE (default) column mapping arguments are required. Set to FALSE to manually map columns after defining model using colMapping.

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 workingDir not specified.

...

Arguments passed on to pkindirectmodel_MappingParameters

ID

Column mapping argument for input dataset column(s) that identify individual data profiles. Only applicable to population models isPopulation = TRUE.

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:

  • Models with absorption = "Intravenous" and parameterization set to either "Clearance","Micro", or "Macro"

  • Models with absorption set to either "Gamma", "InverseGaussian", or "Weibull"

Aa

Column mapping argument that represents the input dataset column for the amount of drug administered and only applicable to models with absorption = "FirstOrder".

A

Column mapping argument that represents the input dataset column for the amount of drug administered and only applicable to models with absorption = "Intravenous" and parameterization = "Macro1".

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:

  • Models with absorption = "Intravenous", infusionAllowed = TRUE and parameterization set to either "Clearance","Micro" or "Macro"

  • Models with absorption set to either "Gamma", "InverseGaussian", or "Weibull" and infusionAllowed = TRUE

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:

  • Models with absorption = "Intravenous", infusionAllowed = TRUE with isDuration = TRUE and parameterization set to either "Clearance","Micro" or "Macro"

  • Models with absorption set to either "Gamma", "InverseGaussian", or "Weibull" and infusionAllowed = TRUE with isDuration = TRUE

Aa_Rate

Column mapping argument that represents the input dataset column for the rate of drug administered and only applicable to models with absorption = "FirstOrder", infusionAllowed = TRUE.

Aa_Duration

Column mapping argument that represents the input dataset column for the duration of drug administered and only applicable to models with absorption = "FirstOrder", infusionAllowed = TRUE, and isDuration = TRUE.

A_Rate

Column mapping argument that represents the input dataset column for the rate of drug administered and only applicable to models with absorption = "Intravenous", infusionAllowed = TRUE, and parameterization = "Macro1".

A_Duration

Column mapping argument that represents the input dataset column for the duration of drug administered and only applicable to models with absorption = "Intravenous", infusionAllowed = TRUE, isDuration = TRUE, and parameterization = "Macro1".

A1Strip

Column mapping argument that represents the input dataset column for the stripping dose and only applicable to models with parameterization = "Macro".

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 parameterization being either set to either "Clearance" or "Micro".

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 parameterization being either set to either "Macro" or "Macro1".

A0Obs

Column mapping argument that represents the input dataset column for the observed amount of drug in the elimination compartment. (hasEliminationComp = TRUE).

EObs

Column mapping argument that represents the input dataset column for the observed drug effect.

nV

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nV.

nV2

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nV2.

nV3

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nV3.

nCl

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nCl.

nCl2

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nCl2.

nCl3

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nCl3.

nKa

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nKa.

nA

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nA.

nAlpha

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nAlpha.

nB

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nB.

nBeta

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nBeta.

nC

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nC.

nGamma

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nGamma.

nKe

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nKe.

nK12

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nK12.

nK21

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nK21.

nK13

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nK13.

nK31

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nK31.

nTlag

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nTlag.

nKm

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nKm.

nVmax

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nVmax.

nFe

If isSequential = TRUE and isFractionExcreted = TRUE, mapped to the input dataset column that lists the values for random effect nFe.

nMeanDelayTime

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nMeanDelayTime.

nShapeParam

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nShapeParam.

nShapeParamMinusOne

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nShapeParamMinusOne.

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 isPopulation = TRUE.

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:

  • Models with absorption = "Intravenous" and parameterization set to either "Clearance","Micro", or "Macro"

  • Models with absorption set to either "Gamma", "InverseGaussian", or "Weibull"

Aa

Column mapping argument that represents the input dataset column for the amount of drug administered and only applicable to models with absorption = "FirstOrder".

A

Column mapping argument that represents the input dataset column for the amount of drug administered and only applicable to models with absorption = "Intravenous" and parameterization = "Macro1".

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:

  • Models with absorption = "Intravenous", infusionAllowed = TRUE and parameterization set to either "Clearance","Micro" or "Macro"

  • Models with absorption set to either "Gamma", "InverseGaussian", or "Weibull" and infusionAllowed = TRUE

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:

  • Models with absorption = "Intravenous", infusionAllowed = TRUE with isDuration = TRUE and parameterization set to either "Clearance","Micro" or "Macro"

  • Models with absorption set to either "Gamma", "InverseGaussian", or "Weibull" and infusionAllowed = TRUE with isDuration = TRUE

Aa_Rate

Column mapping argument that represents the input dataset column for the rate of drug administered and only applicable to models with absorption = "FirstOrder", infusionAllowed = TRUE.

Aa_Duration

Column mapping argument that represents the input dataset column for the duration of drug administered and only applicable to models with absorption = "FirstOrder", infusionAllowed = TRUE, and isDuration = TRUE.

A_Rate

Column mapping argument that represents the input dataset column for the rate of drug administered and only applicable to models with absorption = "Intravenous", infusionAllowed = TRUE, and parameterization = "Macro1".

A_Duration

Column mapping argument that represents the input dataset column for the duration of drug administered and only applicable to models with absorption = "Intravenous", infusionAllowed = TRUE, isDuration = TRUE, and parameterization = "Macro1".

A1Strip

Column mapping argument that represents the input dataset column for the stripping dose and only applicable to models with parameterization = "Macro".

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 parameterization being either set to either "Clearance" or "Micro".

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 parameterization being either set to either "Macro" or "Macro1".

A0Obs

Column mapping argument that represents the input dataset column for the observed amount of drug in the elimination compartment. (hasEliminationComp = TRUE).

EObs

Column mapping argument that represents the input dataset column for the observed drug effect.

nV

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nV.

nV2

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nV2.

nV3

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nV3.

nCl

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nCl.

nCl2

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nCl2.

nCl3

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nCl3.

nKa

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nKa.

nA

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nA.

nAlpha

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nAlpha.

nB

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nB.

nBeta

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nBeta.

nC

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nC.

nGamma

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nGamma.

nKe

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nKe.

nK12

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nK12.

nK21

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nK21.

nK13

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nK13.

nK31

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nK31.

nTlag

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nTlag.

nKm

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nKm.

nVmax

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nVmax.

nFe

If isSequential = TRUE and isFractionExcreted = TRUE, mapped to the input dataset column that lists the values for random effect nFe.

nMeanDelayTime

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nMeanDelayTime.

nShapeParamMinusOne

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nShapeParamMinusOne.

nShapeParam

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nShapeParam.


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 TRUE or individual model FALSE?

parameterization

Type of parameterization. Options are "Clearance", "Micro", "Macro", or "Macro1".

absorption

Type of absorption. Options are "Intravenous", "FirstOrder", "Gamma", "InverseGaussian", "Weibull" .

numCompartments

Value of either 1, 2, or 3.

isClosedForm

Set to TRUE to convert model from a differential equation to close form.

isTlag

Set to TRUE to add a lag time parameter to the model.

hasEliminationComp

Set to TRUE to add an elimination compartment to the model.

isFractionExcreted

Set to TRUE if elimination compartment (hasEliminationComp = TRUE) contains a fraction excreted parameter.

isSaturating

Set to TRUE to use Michaelis-Menten kinetics for elimination. Only applicable to models with paramteterization = "Clearance"

infusionAllowed

Set to TRUE if infusions allowed.

isDuration

Set to TRUE if infusions use duration instead of rate (must also set infusionAllowed = TRUE).

isSequential

Set to TRUE to freeze PK fixed effects and convert the corresponding random effects into covariates as well as remove the PK observed variable from the model.

isPkFrozen

Set to TRUE to freeze PK fixed effects and remove the corresponding random effects as well as the PK observed variable from the model.

hasEffectsCompartment

Set to TRUE to include an effect compartment into the model.

linearType

Type of PD model; Options are "Constant", "Linear", "Quadratic".

isLinearFrozen

Set to TRUE to freeze PD fixed effects and remove the corresponding random effects as well as the PD observed variable from the model.

data

Input dataset

columnMap

If TRUE (default) column mapping arguments are required. Set to FALSE to manually map columns after defining model using colMapping.

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 workingDir not specified.

...

Arguments passed on to pkindirectmodel_MappingParameters

ID

Column mapping argument for input dataset column(s) that identify individual data profiles. Only applicable to population models isPopulation = TRUE.

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:

  • Models with absorption = "Intravenous" and parameterization set to either "Clearance","Micro", or "Macro"

  • Models with absorption set to either "Gamma", "InverseGaussian", or "Weibull"

Aa

Column mapping argument that represents the input dataset column for the amount of drug administered and only applicable to models with absorption = "FirstOrder".

A

Column mapping argument that represents the input dataset column for the amount of drug administered and only applicable to models with absorption = "Intravenous" and parameterization = "Macro1".

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:

  • Models with absorption = "Intravenous", infusionAllowed = TRUE and parameterization set to either "Clearance","Micro" or "Macro"

  • Models with absorption set to either "Gamma", "InverseGaussian", or "Weibull" and infusionAllowed = TRUE

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:

  • Models with absorption = "Intravenous", infusionAllowed = TRUE with isDuration = TRUE and parameterization set to either "Clearance","Micro" or "Macro"

  • Models with absorption set to either "Gamma", "InverseGaussian", or "Weibull" and infusionAllowed = TRUE with isDuration = TRUE

Aa_Rate

Column mapping argument that represents the input dataset column for the rate of drug administered and only applicable to models with absorption = "FirstOrder", infusionAllowed = TRUE.

Aa_Duration

Column mapping argument that represents the input dataset column for the duration of drug administered and only applicable to models with absorption = "FirstOrder", infusionAllowed = TRUE, and isDuration = TRUE.

A_Rate

Column mapping argument that represents the input dataset column for the rate of drug administered and only applicable to models with absorption = "Intravenous", infusionAllowed = TRUE, and parameterization = "Macro1".

A_Duration

Column mapping argument that represents the input dataset column for the duration of drug administered and only applicable to models with absorption = "Intravenous", infusionAllowed = TRUE, isDuration = TRUE, and parameterization = "Macro1".

A1Strip

Column mapping argument that represents the input dataset column for the stripping dose and only applicable to models with parameterization = "Macro".

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 parameterization being either set to either "Clearance" or "Micro".

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 parameterization being either set to either "Macro" or "Macro1".

A0Obs

Column mapping argument that represents the input dataset column for the observed amount of drug in the elimination compartment. (hasEliminationComp = TRUE).

EObs

Column mapping argument that represents the input dataset column for the observed drug effect.

nV

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nV.

nV2

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nV2.

nV3

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nV3.

nCl

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nCl.

nCl2

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nCl2.

nCl3

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nCl3.

nKa

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nKa.

nA

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nA.

nAlpha

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nAlpha.

nB

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nB.

nBeta

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nBeta.

nC

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nC.

nGamma

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nGamma.

nKe

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nKe.

nK12

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nK12.

nK21

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nK21.

nK13

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nK13.

nK31

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nK31.

nTlag

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nTlag.

nKm

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nKm.

nVmax

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nVmax.

nFe

If isSequential = TRUE and isFractionExcreted = TRUE, mapped to the input dataset column that lists the values for random effect nFe.

nMeanDelayTime

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nMeanDelayTime.

nShapeParam

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nShapeParam.

nShapeParamMinusOne

If isSequential = TRUE, mapped to the input dataset column that lists the values for random effect nShapeParamMinusOne.

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 TRUE or individual model FALSE?

parameterization

Type of parameterization. Options are "Clearance", "Micro", "Macro", or "Macro1".

absorption

Type of absorption. Options are "Intravenous", "FirstOrder", "Gamma", "InverseGaussian", "Weibull" .

numCompartments

Value of either 1, 2, or 3.

isClosedForm

Set to TRUE to convert model from a differential equation to close form.

isTlag

Set to TRUE to add a lag time parameter to the model.

hasEliminationComp

Set to TRUE to add an elimination compartment to the model.

isFractionExcreted

Set to TRUE if elimination compartment (hasEliminationComp = TRUE) contains a fraction excreted parameter.

isSaturating

Set to TRUE to use Michaelis-Menten kinetics for elimination. Only applicable to models with paramteterization = "Clearance"

infusionAllowed

Set to TRUE if infusions allowed.

isDuration

Set to TRUE if infusions use duration instead of rate (must also set infusionAllowed = TRUE).

isStdevFrozen

Set to TRUE to freeze value of standard deviation of residual error variable.

data

Input dataset

columnMap

If TRUE (default) column mapping arguments are required. Set to FALSE to manually map columns after defining model using colMapping.

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 workingDir not specified.

...

Arguments passed on to pkmodel_MappingParameters

ID

Column mapping argument for input dataset column(s) that identify individual data profiles. Only applicable to population models isPopulation = TRUE.

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:

  • Models with absorption = "Intravenous" and parameterization set to either "Clearance","Micro", or "Macro"

  • Models with absorption set to either "Gamma", "InverseGaussian", or "Weibull"

Aa

Column mapping argument that represents the input dataset column for the amount of drug administered and only applicable to models with absorption = "FirstOrder".

A

Column mapping argument that represents the input dataset column for the amount of drug administered and only applicable to models with absorption = "Intravenous" and parameterization = "Macro1".

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:

  • Models with absorption = "Intravenous", infusionAllowed = TRUE and parameterization set to either "Clearance","Micro" or "Macro"

  • Models with absorption set to either "Gamma", "InverseGaussian", or "Weibull" and infusionAllowed = TRUE

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:

  • Models with absorption = "Intravenous",infusionAllowed = TRUE with isDuration = TRUE and parameterization set to either "Clearance", "Micro" or "Macro"

  • Models with absorption set to either "Gamma", "InverseGaussian", or "Weibull" and infusionAllowed = TRUE with isDuration = TRUE

Aa_Rate

Column mapping argument that represents the input dataset column for the rate of drug administered and only applicable to models with absorption = "FirstOrder", infusionAllowed = TRUE.

Aa_Duration

Column mapping argument that represents the input dataset column for the duration of drug administered and only applicable to models with absorption = "FirstOrder", infusionAllowed = TRUE, and isDuration = TRUE.

A_Rate

Column mapping argument that represents the input dataset column for the rate of drug administered and only applicable to models with absorption = "Intravenous", infusionAllowed = TRUE, and parameterization = "Macro1".

A_Duration

Column mapping argument that represents the input dataset column for the duration of drug administered and only applicable to models with absorption = "Intravenous", infusionAllowed = TRUE, isDuration = TRUE, and parameterization = "Macro1".

A1Strip

Column mapping argument that represents the input dataset column for the stripping dose and only applicable to models with parameterization = "Macro".

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 parameterization being either set to either "Clearance" or "Micro".

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 parameterization being either set to either "Macro" or "Macro1".

A0Obs

Column mapping argument that represents the input dataset column for the observed amount of drug in the elimination compartment. (hasEliminationComp = TRUE).

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 isPopulation = TRUE.

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:

  • Models with absorption = "Intravenous" and parameterization set to either "Clearance","Micro", or "Macro"

  • Models with absorption set to either "Gamma", "InverseGaussian", or "Weibull"

Aa

Column mapping argument that represents the input dataset column for the amount of drug administered and only applicable to models with absorption = "FirstOrder".

A

Column mapping argument that represents the input dataset column for the amount of drug administered and only applicable to models with absorption = "Intravenous" and parameterization = "Macro1".

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:

  • Models with absorption = "Intravenous", infusionAllowed = TRUE and parameterization set to either "Clearance","Micro" or "Macro"

  • Models with absorption set to either "Gamma", "InverseGaussian", or "Weibull" and infusionAllowed = TRUE

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:

  • Models with absorption = "Intravenous",infusionAllowed = TRUE with isDuration = TRUE and parameterization set to either "Clearance", "Micro" or "Macro"

  • Models with absorption set to either "Gamma", "InverseGaussian", or "Weibull" and infusionAllowed = TRUE with isDuration = TRUE

Aa_Rate

Column mapping argument that represents the input dataset column for the rate of drug administered and only applicable to models with absorption = "FirstOrder", infusionAllowed = TRUE.

Aa_Duration

Column mapping argument that represents the input dataset column for the duration of drug administered and only applicable to models with absorption = "FirstOrder", infusionAllowed = TRUE, and isDuration = TRUE.

A_Rate

Column mapping argument that represents the input dataset column for the rate of drug administered and only applicable to models with absorption = "Intravenous", infusionAllowed = TRUE, and parameterization = "Macro1".

A_Duration

Column mapping argument that represents the input dataset column for the duration of drug administered and only applicable to models with absorption = "Intravenous", infusionAllowed = TRUE, isDuration = TRUE, and parameterization = "Macro1".

A1Strip

Column mapping argument that represents the input dataset column for the stripping dose and only applicable to models with parameterization = "Macro".

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 parameterization being either set to either "Clearance" or "Micro".

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 parameterization being either set to either "Macro" or "Macro1".

A0Obs

Column mapping argument that represents the input dataset column for the observed amount of drug in the elimination compartment. (hasEliminationComp = TRUE).

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 NlmeColumnMapping()

...

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 NlmeParallelHost object to print.

...

Additional arguments passed to the print function.

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 profileResult object.

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 rsnlme_boot object.

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 (... M more rows) footnote.

...

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 rsnlme_fit object.

n

Maximum parameter rows shown. Defaults to Inf; cap is defensive (typical fits have <30 parameters) and kept symmetric with print.rsnlme_boot's n argument. A truncated table gets a (... M more rows) footnote.

...

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 scmResult object.

...

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 scmSearchResult object.

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 summary.scmResult.

...

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 summary.scmSearchResult.

n

Maximum number of ranked scenarios to display. Defaults to 10, matching print.scmSearchResult. Use Inf to print every scenario in the digest.

...

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 (NlmeParallelHost).

params

Engine parameters (NlmeEngineExtraParams). Defaults to engineParams(model) when NULL.

profiles

Profiles to perturbate (ProfileParameters).

sortColumns

Optional list of columns to sort and fit (SortColumns).

scenarios

Optional list of scenarios to fit (NlmeScenario).

runInBackground

Logical. When TRUE, the wrapper starts the engine asynchronously and returns a job object immediately; pass that object to collectJob() when the run has finished to obtain the typed result. When FALSE (the default), the wrapper blocks until the engine completes and returns the result directly.

Background execution is supported only on Linux hosts, whether local or remote: a local host whose hostType is "linux" (the default on Linux workstations), or a remote host with hostType "linux", "RHEL", or "UBUNTU". It is not supported on Windows (hostType = "windows", including the default local host when R runs on Windows): leave the argument at FALSE. Passing TRUE on a Windows host stops with an error. Remote Windows hosts are not supported at all.

...

Reserved for future use.

saveResult

When TRUE (the default), collectJob() saves a self-describing <workingDir>/profile_<sanitizedModelName>_<YYYYMMDD_HHMMSS>.rds alongside the result. sanitizedModelName is derived from model@modelInfo@modelName by replacing every character outside [A-Za-z0-9._-] with _; if the result is empty or contains no alphanumerics, the literal string model is used instead. The timestamp is the wall-clock start of the engine call, formatted as YYYYMMDD_HHMMSS in the local time zone. Honoured on both foreground and background paths (background runs save the RDS at the user-facing collectJob(job) call).

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 = TRUE, or initial values for the lower triangular elements (including diagonal elements) of the covariance matrix (if isDiagonal = FALSE) in a row-wise order.

isDiagonal

Set to TRUE to if the covariance matrix of the specified random effects is a diagonal matrix. or FALSE if not.

isFrozen

Set to TRUE to freeze the covariance matrix of random effects.

...

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

update_Omegas()

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 .mmdl).

directoryToRun

Optional working directory for the created model. If NULL (default), a subfolder named after the metamodel is used.

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:


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 NULL all covariates will be removed from model.

paramName

Structural parameters for which to remove covariate effect(s) from. If NULL covariate effect will be removed from all structural parameters.

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., INSTALLDIR environment variable. The cadlicensingtool executable is expected to be located within this directory, or within a subdirectory specified by the PML_BIN_DIR environment variable.

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 NlmePmlModel

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 residualEffectNames.

errorType

Options are "Additive", "LogAdditive", "Multiplicative", "AdditiveMultiplicative", "MixRatio", "Power".

SD

Value for the standard deviation of the residual error variable.

isFrozen

Set to TRUE to freeze the standard deviation to the value specified for SD.

isBQL

Set to TRUE if BQL values present in the observation data.

staticLLOQ

Optional LLOQ value if isBQL = TRUE

EObsBQL

Column mapping argument that represents the input dataset column that contains the BQL flag for observation values corresponding to EObs. Only applicable to isBQL = TRUE.

CObsBQL

Column mapping argument that represents the input dataset column that contains the BQL flag for observation values corresponding to CObs. Only applicable to isBQL = TRUE.

C1ObsBQL

Column mapping argument that represents the input dataset column that contains the BQL flag for observation values corresponding to C1Obs. Only applicable to isBQL = TRUE.

A0ObsBQL

Column mapping argument that represents the input dataset column that contains the BQL flag for observation values corresponding to AObs. Only applicable to isBQL = TRUE.

exponent

Value of exponent. Only applicable to errorType = "Power".

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

update_Sigmas()

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

BootOverall

Per-replicate Scenario / Replicate / ReturnCode / LL.

BootTheta

Aggregated theta summary (Mean, Stderr, CV\ Median, percentile CIs).

BootOmega, BootOmegaCorrelation

Aggregated omega entries split out of BootOmega.csv by the Omega / Correlation sentinel rows.

BootOmegaStderr, BootVarCoVar

Standard errors and full var-covar matrix from the engine.

BootSecondary

Secondary parameters with the same aggregation columns as BootTheta.

BootThetaStacked, BootOmegaStacked, BootSigmaStacked

Per-replicate long stacks (Replicate, <label>, Value). Inputs to transform-aware downstream pipelines.

BootOmegaCI, BootSigmaCI

Per-parameter percentile CIs for omega and sigma (one row per upper-triangle entry). Diagonal marks variance vs covariance entries; print.rsnlme_boot shows omega rows except constrained-zero off-diagonal covariances (matching Original Fit) and diagonal sigma rows only.

BootEtaShrinkage, BootEpsShrinkage

Per-replicate long shrinkages (Replicate, Ranef|Observable, Shrinkage (%)). The CSVs on disk hold fractions (engine convention, 1 - SD) under a Shrinkage header; 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.

fitSummary

Compact prior-fit summary (Parameter, Type, Estimate, SE, %RSE, Shrinkage, Diagonal). Type is one of "the" (theta), "ome" (omega variance or block covariance), "sig" (sigma diagonal), or "sec" (secondary parameter). Estimate follows the prmTable convention used by Certara.Xpose.NLME: raw value for thetas, variance for omega diagonals, covariance for omega off-diagonals, standard deviation for sigmas, raw secondary value (engine output) for sec rows. Diagonal is TRUE except for omega off-diagonal covariance rows (block omega), which downstream variance-scale summaries (Certara.Xpose.NLME::get_summaryNlme()) exclude. Shrinkage is on the percent scale (the .parseEtaShrinkages / .parseEpsShrinkages helpers multiply by 100 at parse time), matching the post-ingestion BootEtaShrinkage / BootEpsShrinkage columns above and Certara.Xpose.NLME::get_summaryNlme()'s output; off-diagonal omega and secondary rows always carry NA since shrinkage is a per-eta concept. The print method labels the column Shrinkage (%) but does not rescale. Present only when the run was launched with initialEstimates = 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

runDir

Path to the directory holding the bootstrap CSVs.

engine

Engine method string derived from params@method.

numSamples

Number of bootstrap replicates requested.

numUsed

Number of replicates contributed to the aggregates, i.e. nrow(BootOverall). Matches NLME8's summarizeBootstrap.R behaviour, which feeds every parseable replicate into the percentile CIs regardless of ReturnCode.

numConverged

Number of replicates whose ReturnCode indicates convergence achieved (c(1L, 2L, 3L) per Certara.Xpose.NLME::get_term). Other codes (e.g. 0, 4, -4, -1) may still contribute parameter estimates to the bootstrap aggregates; see numUsed.

returnCodeBreakdown

Character 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 in print.rsnlme_boot.

confidenceLevel

Confidence level used for percentile CIs (numeric, e.g. 95).

hasFitSummary

TRUE when fitSummary is 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:

fitSummary

Compact prior-fit summary (Parameter, Type, Estimate, SE, %RSE, Shrinkage, Diagonal). Same shape and contract as the fitSummary embedded on rsnlme_boot when bootstrap(initialEstimates = TRUE) – raw scale, no transforms. Block-omega fits also list off-diagonal covariance rows (Type = "ome", Diagonal = FALSE); for transformed report-ready summaries use Certara.Xpose.NLME::get_summaryNlme(). NULL when dmp.txt could not be parsed.

Attributes

engine

Engine method string derived from params@method.

returnCode

Integer return code from dmp.txt$returnCode.

nSubj, nObs

Subject and observation counts from dmp.txt.

logLik

Log-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 missing, the mmdlfile base directory is used.

nlme_hostPath

json file with host definition for model execution. Generated by Pirana application. Consider using host argument when running from R.

host

NlmeParallelHost class instance.

Details

See Metamodel documentation.

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 ⁠<project_dir>/analysis-plan/⁠.

label

Optional short label recorded in the artifact.

data_path

Optional dataset path forwarded to validate_analysis_plan() for the same opportunistic column cross-check before saving.

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 draft_pml_from_nonmem().

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 validate_pml() / confirm_pml_structure() first.

data_path

Path to the CSV dataset. Written into the ⁠## DATA⁠ block (relative to output_path when given, otherwise absolute).

map

Named list or character vector of model_term = data_column pairs for the ⁠## MAP⁠ block. A multi-column id may be a character vector (e.g. id = c("Subject", "Occ")). Covariate terms map the same way (STUDY = "STUDYN"); categorical labels can be appended in the value (e.g. Sex = "Gender(female=0, male=1)").

coldef

Optional character vector of ⁠## COLDEF⁠ lines for column definitions that are not simple term=column pairs.

estargs

Optional ⁠## ESTARGS⁠ content: either a ready-made string or a named list (e.g. list(method = "FOCE-ELS", numIterations = 1000)).

tables

Optional character vector of ⁠## TABLES⁠ lines.

description, author

Optional metadata for the header blocks.

output_path

Optional path to write the .mmdl to. When omitted, only the text is returned (with an absolute ⁠## DATA⁠ path).

validate

When TRUE (default), parse the result with validate_mmdl() and attach the verdict (including data_available).

absolute_data_path

When TRUE, always write an absolute ⁠## DATA⁠ path even when output_path is given. Default FALSE (portable relative path).

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 scmSearchResult from stepwiseSearch or shotgunSearch, or a path to an archived run folder.

full

Logical. Include the degrees-of-freedom column (df, stepwise only). Default FALSE.

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 NlmePmlModel

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 hostParams. If missing, multicore local host with 4 threads is used.

params

Engine parameters. See engineParams. If missing, default parameters generated by engineParams(model) are used.

covariateModel

Covariate Effects Model providing the relationship between covariates and structural parameters to test (covariateModel(model)).

runInBackground

Logical. When TRUE, the wrapper starts the engine asynchronously and returns a job object immediately; pass that object to collectJob() when the run has finished to obtain the typed result. When FALSE (the default), the wrapper blocks until the engine completes and returns the result directly.

Background execution is supported only on Linux hosts, whether local or remote: a local host whose hostType is "linux" (the default on Linux workstations), or a remote host with hostType "linux", "RHEL", or "UBUNTU". It is not supported on Windows (hostType = "windows", including the default local host when R runs on Windows): leave the argument at FALSE. Passing TRUE on a Windows host stops with an error. Remote Windows hosts are not supported at all.

archiveResults

Logical. When TRUE (default), NLME8 archives per-scenario results into a self-contained run folder under the model working directory. The returned data frame carries a searchRunDir attribute pointing to the archive folder. Archive failures are non-fatal (warn only).

runLabel

Optional character string appended to the auto-generated timestamp in the archive folder name, e.g. "baseModel" produces shotgun_20260319_143045_baseModel. Must contain only letters, digits, dots, hyphens, or underscores. If the resulting folder already exists, a numeric suffix (_1, _2, ...) is added with a warning. Ignored (with a warning) when archiveResults = FALSE.

...

Additional arguments for hostParams or arguments available inside engineParams functions. If engineParams arguments are supplied through both params argument and additional argument (i.e., ellipsis), then the arguments in params will be ignored and only the additional arguments will be used with warning. If hostParams arguments are supplied through both the hostPlatform argument and the ellipses, values supplied to hostPlatform will be overridden by additional arguments supplied via the ellipses e.g., ....

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 NlmeSimulationParams. If missing, default parameters generated by NlmeSimulationParams() are used.

params

Engine parameters. See engineParams. The common parameters include: sort, ODE, rtolODE, atolODE, maxStepsODE. If missing, default parameters generated by engineParams(model) are used.

hostPlatform

Host definition for model execution. See hostParams. If missing, simple local host is used.

runInBackground

Logical. When TRUE, the wrapper starts the engine asynchronously and returns a job object immediately; pass that object to collectJob() when the run has finished to obtain the typed result. When FALSE (the default), the wrapper blocks until the engine completes and returns the result directly.

Background execution is supported only on Linux hosts, whether local or remote: a local host whose hostType is "linux" (the default on Linux workstations), or a remote host with hostType "linux", "RHEL", or "UBUNTU". It is not supported on Windows (hostType = "windows", including the default local host when R runs on Windows): leave the argument at FALSE. Passing TRUE on a Windows host stops with an error. Remote Windows hosts are not supported at all.

...

Additional class initializer arguments for NlmeSimulationParams, or arguments available inside hostParams or engineParams functions. If engineParams arguments are supplied through both params argument and additional argument (i.e., ellipsis), then the arguments in params will be ignored and only the additional arguments will be used with warning. If hostParams arguments are supplied through both hostPlatform argument and additional argument, then its slots will be overridden by additional arguments. In addition, if NlmeSimulationParams arguments are supplied through both simParams argument and additional argument, then its slots will be overridden by additional arguments.

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

collectJob, vpcmodel

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 hostParams. If missing, PhoenixMPIDir64 is given and MPI is installed, MPI local host with 4 threads is used. If MPI is not found, local host without parallelization is used.

params

Engine parameters. See engineParams. If missing, default parameters generated by engineParams(model) are used.

sortColumns

List of sort columns. See SortColumns. If missing, empty sort columns argument is used and NLME dataset is used as is.

scenarios

List of scenarios with different sets of covariates. See NlmeScenario If missing, all covariates effects are considered as enabled.

simpleTables

Optional list of simple tables. See tableParams. By default a table named 'posthoc.csv' is returned with structural parameters values for all source data rows.

runInBackground

Logical. When TRUE, the wrapper starts the engine asynchronously and returns a job object immediately; pass that object to collectJob() when the run has finished to obtain the typed result. When FALSE (the default), the wrapper blocks until the engine completes and returns the result directly.

Background execution is supported only on Linux hosts, whether local or remote: a local host whose hostType is "linux" (the default on Linux workstations), or a remote host with hostType "linux", "RHEL", or "UBUNTU". It is not supported on Windows (hostType = "windows", including the default local host when R runs on Windows): leave the argument at FALSE. Passing TRUE on a Windows host stops with an error. Remote Windows hosts are not supported at all.

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 Value section will be outputted to the model directory and loaded as returned value. Only those files listed in the Value section can be specified. Simple regex patterns are supported for the specification.

...

Additional arguments for hostParams or arguments available inside engineParams functions. If engineParams arguments are supplied through both params argument and additional argument (i.e., ellipsis), then the arguments in params will be ignored and only the additional arguments will be used with warning. If hostParams arguments are supplied through both the hostPlatform argument and the ellipses, values supplied to hostPlatform will be overridden by additional arguments supplied via the ellipses e.g., ....

saveResult

When TRUE (the default), collectJob() writes a self-describing <workingDir>/sortfit_<sanitizedModelName>_<YYYYMMDD_HHMMSS>.rds alongside the result. sanitizedModelName is derived from model@modelInfo@modelName by replacing every character outside [A-Za-z0-9._-] with _; if the result is empty or contains no alphanumerics, the literal string model is used instead. The timestamp is the wall-clock start of the engine call, formatted as YYYYMMDD_HHMMSS in the local time zone. Honoured on both foreground and background paths (background runs save the RDS at the user-facing collectJob(job) call).

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:

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 .rds holding an rsnlme_fit (its ⁠$model⁠ is used; ⁠$params⁠ is used unless params_rds/method/condition_number is supplied).

num_replicates

Number of bootstrap replicates (default 200; must be at least 2).

seed

Optional random number seed (default: BootstrapParams()'s own 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 BootstrapParams()).

params_rds

Optional .rds with an NlmeEngineExtraParams to override fit$params for the bootstrap replicates.

method

Optional estimation method override (ignored when params_rds is supplied).

condition_number

Optional condition-number basis override (ignored when params_rds is supplied); defaults to "CorrelationFull" like the other MCP-built engine params.

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 .mcp_workflow_gate()).

unplanned_reason

Optional reason accompanying unplanned_override (lineage only).

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 .mmdl file.

label

Short label.

project_dir

Project root.

strict

When TRUE (the default), stop before launching if the metamodel's ⁠## DATA⁠ file is unavailable - a data-less fit can "succeed" on an empty data1.txt, so refusing it by default is safer. Set FALSE to launch anyway with only a warning. A metamodel that cannot be checked (data_available = NA) still launches regardless.

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 unplanned_override (lineage only).

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: constructor (one of the seven built-ins or "textualmodel"), data (path to a CSV under the project), constructor_args (named list passed to the constructor; for textualmodel, must include pml), column_map (named mapping such as ID, Time, A1/Aa, CObs), optional covariates (list of ⁠{name, effect, type, direction, center, levels, labels}⁠ where effect is the structural parameter name(s) such as Cl/V, not tvCl/tvV), optional initials (named fixed-effect starts), method, and optional engine (ODE, numIterations, conditionNumber). When engine$conditionNumber is omitted, MCP defaults to "CorrelationFull" (NONMEM-comparable, scale-invariant) rather than engineParams()'s public "CovarianceFixef" default; an explicit value is never overridden. The spec is checked with validate_fit_spec() before the job launches.

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 .rds holding an NlmePmlModel.

params_rds

Optional path to an .rds holding an NlmeEngineExtraParams. When omitted, engine params are built from method/num_iterations/ode.

method

Optional estimation method (e.g. "Naive-Pooled", "QRPEM", "FOCE-ELS"). Used only when params_rds is not supplied.

num_iterations

Optional max iterations (used only without params_rds).

ode

Optional ODE solver (used only without params_rds).

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 structural_base, reference_model, covariate_model, final_candidate, qualification_vpc, structural_anchor (a Darwin search candidate refit for hybrid qualification), lrt_candidate (a single nested-effect test launched by advance_sequential_lrt())).

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 unplanned_override (lineage only).

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 expr is NULL).

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 (jobs.jsonl) and the returned metadata.

env

Optional named list/character vector of environment variables to export in the child process (e.g. a launch recipe's input .rds paths). Reserved names RUN_DIR / NLME_MCP_RUN_DIR are managed by the runner and cannot be set here.

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 .rds holding an rsnlme_fit (its ⁠$model⁠ and ⁠$params⁠ are used).

vpc_params_rds

Optional .rds with an NlmeEngineExtraParams to override fit$params for the simulation.

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 unplanned_override (lineage only).

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 validate_sequential_lrt(). Re-validated here; launch is refused on any validation error.

project_dir

Project root; the session directory is created under it.

user_confirmed

Explicit confirmation gate. TRUE here or spec$user_confirmed = TRUE is required to launch.

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 hostParams. If missing, multicore local host with 4 threads is used.

params

Engine parameters. See engineParams. If missing, default parameters generated by engineParams(model) are used.

covariateModel

Covariate Effects Model providing the relationship between covariates and structural parameters to test (covariateModel(model)).

stepwiseParams

Stepwise parameters defining decision tree. See StepwiseParams

runInBackground

Logical. When TRUE, the wrapper starts the engine asynchronously and returns a job object immediately; pass that object to collectJob() when the run has finished to obtain the typed result. When FALSE (the default), the wrapper blocks until the engine completes and returns the result directly.

Background execution is supported only on Linux hosts, whether local or remote: a local host whose hostType is "linux" (the default on Linux workstations), or a remote host with hostType "linux", "RHEL", or "UBUNTU". It is not supported on Windows (hostType = "windows", including the default local host when R runs on Windows): leave the argument at FALSE. Passing TRUE on a Windows host stops with an error. Remote Windows hosts are not supported at all.

archiveResults

Logical. When TRUE (default), NLME8 archives per-scenario results into a self-contained run folder under the model working directory. The returned data frame carries a searchRunDir attribute pointing to the archive folder. Archive failures are non-fatal (warn only).

runLabel

Optional character string appended to the auto-generated timestamp in the archive folder name, e.g. "baseModel" produces stepwise_20260319_143045_baseModel. Must contain only letters, digits, dots, hyphens, or underscores. If the resulting folder already exists, a numeric suffix (_1, _2, ...) is added with a warning. Ignored (with a warning) when archiveResults = FALSE.

updateInitialEstimates

Logical. When TRUE, after each stepwise selection the shared input model's initial estimates are rewritten from the winning scenario's dmp.txt so subsequent candidate runs start from the previous step's estimates. Speeds up convergence on later steps and tends to stabilise the search. Default FALSE preserves the existing behavior. Implementation lives in NLME8; this flag is forwarded via the NLME_SCM_UPDATE_INITIALS environment variable (also propagated to remote run scripts).

Notes:

  • When TRUE, the base (no-covariate) model runs on its own first and its converged estimates are written into the shared input model before the first forward-addition candidate batch, so that round starts from the base model's final estimates. When FALSE, the base model and the first-round candidates run together in a single parallel batch, because those candidate fits do not depend on the base estimates.

  • Every selection that updates the model invalidates the stepwise compile cache, so the next batch of candidate runs will recompile the NLME executable from the rewritten model. Expect a small per-step compile-time overhead in exchange for the convergence benefit.

  • The user's input .mdl file in the model working directory is snapshotted at the start of the search and restored on exit, so the working directory is left untouched regardless of how the search ends. The per-scenario archive (initial.mdl, wiped.mdl, final.mdl, etc.) is sourced from the per-scenario engine job directories and accurately reflects the evolving initials each scenario actually ran with.

  • Only candidate models that are evaluated for the first time after a selection take advantage of the carried-forward initials; any candidate whose covariate set was already evaluated in an earlier step is reused from the search history with its original estimates, so each unique covariate configuration is fit exactly once per search. This keeps each mask's OFV consistent across the forward and backward phases.

...

Additional arguments for hostParams or arguments available inside engineParams functions. If engineParams arguments are supplied through both params argument and additional argument (i.e., ellipsis), then the arguments in params will be ignored and only the additional arguments will be used with warning. If hostParams arguments are supplied through both the hostPlatform argument and the ellipses, values supplied to hostPlatform will be overridden by additional arguments supplied via the ellipses e.g., ....

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 start_sequential_lrt().

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.

  • "LogNormal" (Default): The structural parameter is defined as Product * exp(Eta)

  • "LogNormal1": The structural parameter is defined as Sum * exp(Eta)

  • "LogNormal2": The structural parameter is defined as exp(Sum + Eta)

  • "LogitNormal": The structural parameter is defined as ilogit(Sum + Eta)

  • "Normal": The structural parameter is defined as Sum + Eta)

Product denotes the product of the corresponding fixed effect and covariate effect terms (if exists), Eta represents the corresponding random effect, and Sum denotes the sum of its corresponding fixed effect and covariate effect terms (if exists).

hasRandomEffect

Set to FALSE to remove the corresponding random effect from the model. Only applicable to population models. If NULL the system will automatically set hasRandomEffect = TRUE for population models, and hasRandomEffect = FALSE for individual models.

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 NlmePmlModel

omitEmpties

Set to TRUE to omit empty names

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 job_id (from start_nlme_vpcmodel()).

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 scmResult object.

...

Unused.

Value

An object of class c("summary.scmResult", "list") with elements:

scenario

Scenario label.

status

Scenario status string (when available).

criteria

Named numeric vector with available -2LL / AIC / BIC values from $scenarioInfo.

fitmodelOutput

Header-level digest of the embedded fit (engine, return code, nSubj, nObs, logLik, -2LL, plus a nested runContext with method/runMode/elapsed/RsNLMEVersion). NULL when $fitmodelOutput is not self-describing – older archives or stub fixtures.

diagnostics

Named list with files (engine error/log lines) and missing (absent dmp.txt / final.mdl) when status is not SUCCESS; NULL otherwise.

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 scmSearchResult object.

...

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:

searchType

One of "stepwise", "shotgun", or NA when the type cannot be resolved.

searchRunDir

Archive folder path, or NULL for unarchived results.

nScenarios

Number of scenarios evaluated.

nBest

0L or 1L – whether a best scenario is recorded.

nFailed

Count of scenarios whose archive status is not SUCCESS.

nSucceeded

Count of scenarios whose archive status is SUCCESS.

bestScenario

A named list with the best scenario label, available -2LL / AIC / BIC criteria, and status when 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. NULL when no scenario is recorded.

topScenarios

A data frame with all ranked scenarios (same ordering as print.scmSearchResult), with best and failed logical columns.

scenarioIndex

Path to scenario_index.csv when searchRunDir is set; otherwise NULL.

runContext

Named 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 "keepSource=TRUE"

covrSet

Character; Vector of covariate names. Simulation point is added when the covariate value is set. See covariateNames

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 TRUE to keep the number of rows appearing in the table the same as the number of rows in the input dataset.

timeAfterDose

Set to TRUE to output time after dose.

IRES

Logical; Set to TRUE to output individual residuals. Valid only if whenObs is specified.

Weight

Logical; Set to TRUE to output the weight of current observation. Valid only if whenObs is specified.

IWRES

Logical; Set to TRUE to output individual weighted residuals. Valid only if whenObs is specified.

mode

Character; The mode of output. Options are "all" (default), "unique", "first". Only applicable to non time-based models for the case where only covrSet is defined or the case where only covrSet and variablesList are defined.

Option "all" (default): it outputs all the rows invoked by specified covariates. Option "unique": if the values in a row are the same as the ones in the previous row for the current subject, then the row is omitted; otherwise, it is printed out. Option "first": it outputs only the first row for each subject.

forSimulation

logical. Defining whether the table is for simulation purposes or for postprocessing after fit. Default is FALSE.

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 workingDir not specified.

data

Input dataset

mdl

File path specifying location of .mdl file. Cannot be used together with pml.

pml

PML code as a character string. Cannot be used together with mdl.

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:

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

randomEffect()

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

residualError()

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:

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

fixedEffect()

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 .rds holding an NlmePmlModel.

omegas_json

JSON object string with any of:

  • diagonal: object keyed by eta name, each value a number (initial value only) or an object with initial (alias value). freeze is not accepted here – omega freeze applies to the whole containing section, so use the freeze array below;

  • blocks: array of ⁠{names: [...], matrix: [[...], ...]}⁠ objects giving the full covariance matrix for an existing block/diagonal section, or for all random effects of an occasion covariate (row order matches names);

  • freeze / unfreeze: arrays of eta names whose containing section(s) should be frozen/unfrozen (built-in models only).

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 model_rds or output_path.

output_path

Optional explicit output .rds path (resolved against project_dir when relative); may not equal model_rds.

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 .rds holding an NlmePmlModel.

sigmas_json

JSON object string with:

  • values: object keyed by epsilon name (e.g. CEps), or by observation name (e.g. CObs) on built-in models only, each value a number (initial SD) or an object with initial (alias value), freeze (alias frozen);

  • freeze / unfreeze: arrays of epsilon/observation names (built-in models only).

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 model_rds or output_path.

output_path

Optional explicit output .rds path (resolved against project_dir when relative); may not equal model_rds.

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 .rds holding an NlmePmlModel.

thetas_json

JSON object string keyed by theta name; each value is a number (initial value only), a 3-element array ⁠[lower, initial, upper]⁠, or an object with any of lower, initial (alias value), upper, freeze (alias frozen), enable (textual models only). Omitted fields are preserved from the current model. enable must be a non-negative whole number (the enable ID), or false/null to remove the enable flag and disable the covariate effect; a negative or fractional value is an error rather than a silent truncation or no-op. A lower of -Inf or an upper of Inf removes that bound.

project_dir

Project root for resolving a relative model_rds or output_path.

output_path

Optional explicit output .rds path (resolved against project_dir when relative); may not equal model_rds.

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)

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.

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 class(data[[col]]). The first element is treated as primary, matching validate_cov_numeric_labels_mutex().

labels

Character vector of labels (possibly NULL or empty).

values

Optional raw vector of column values (passed untouched from inputData[[data_col]]). Factors are coerced via as.character() so their levels are what the engine will see. Omit / set NULL when values are not accessible – the check will defer rather than false-positive.

n_sample

Cap on how many leading values to inspect. Defaults to 500L, enough to guarantee coverage of realistic categorical columns (2-10 levels) while keeping the check trivially cheap on datasets with tens of thousands of rows.

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:

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 NULL or empty, the function short-circuits to ok = TRUE (nothing to validate).

id_col

Name of the subject column. Pass NULL when no ID is mapped; the per-subject scan is then skipped and ok = TRUE is returned.

data_col

Name of the covariate column.

labels

Optional character vector of labels.

Value

List with:


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 NULL.

levels

Numeric vector used only for the length check. Pass NULL to skip the length check (useful for standalone label validation in addLabel()).

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 levels argument (numeric or integer-like).

Value

List with fields:


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 class(data[[col]]) (or equivalent). Accepts the raw class() vector and tests its first element.

labels

Character vector of labels (possibly NULL or empty).

Value

List with ok, errors.


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 apply) to host the ⁠covariate-search/⁠ artifact directory.

data_path

Optional dataset path; when supplied, candidate covariate columns are cross-checked against the dataset header.

model_rds

Optional path to an .rds holding the built-in base NlmePmlModel; only used with apply = TRUE (falls back to spec$base_model$model_rds).

apply

When TRUE and the plan is valid and confirmed and a built-in base model is available, assemble and save the runnable artifacts.

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 start_nlme_fit_spec() for the field reference. Optional engine may include conditionNumber (defaults to "CorrelationFull" when omitted), ODE, and numIterations.

build_preflight

When TRUE, also build the model from the spec and run validate_nlme_model() for deeper checks (effect names against structural parameters, data attachment). Requires the dataset to be readable. Default FALSE (schema/semantic checks only).

project_dir

Project root used to resolve a relative spec$data path.

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 .mmdl file (used when text is NULL).

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 .rds holding an NlmePmlModel.

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: anchor (job_id XOR model_rds/mmdl_path, optional darwin_ofv and ofv_tolerance), operations (list of ⁠{id, action, df, distribution, effect_description, alpha, candidate_source}⁠), alpha_add (default 0.05), alpha_remove (default 0.10), fit_budget (default 30), host_resources ({max_concurrent_fits}), optional analysis_plan_id, and user_confirmed.

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 NlmeVpcParams. If missing, default values generated by NlmeVpcParams() are used.

params

Engine argument setup. See engineParams. The following arguments are the subject of interest: sort, ODE, rtolODE, atolODE, maxStepsODE. If missing, default values generated by engineParams(model) are used.

hostPlatform

Host definition for model execution. See hostParams. If missing, simple local host is used.

runInBackground

Logical. When TRUE, the wrapper starts the engine asynchronously and returns a job object immediately; pass that object to collectJob() when the run has finished to obtain the typed result. When FALSE (the default), the wrapper blocks until the engine completes and returns the result directly.

Background execution is supported only on Linux hosts, whether local or remote: a local host whose hostType is "linux" (the default on Linux workstations), or a remote host with hostType "linux", "RHEL", or "UBUNTU". It is not supported on Windows (hostType = "windows", including the default local host when R runs on Windows): leave the argument at FALSE. Passing TRUE on a Windows host stops with an error. Remote Windows hosts are not supported at all.

...

Additional class initializer arguments for NlmeVpcParams or hostParams, or arguments available inside engineParams functions. If engineParams arguments are supplied through both params argument and additional argument (i.e., ellipsis), then the arguments in params will be ignored and only the additional arguments will be used with warning. If hostParams arguments are supplied through both hostPlatform argument and additional argument, then its values will be overridden by additional arguments. In addition, if NlmeVpcParams arguments are supplied through both vpcParams argument and additional argument, then its slots will be overridden by additional arguments.

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

collectJob, simmodel

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 start_nlme_job().

project_dir

Project root.

max_wait_seconds

Optional direct-R override for the per-call watch budget (seconds), clamped to ⁠0..600⁠ AND to the launch-configured cap. When NULL (the default) the launch-configured budget is used; 0 makes the call a single-shot status check. Values above the cap are silently clamped to the cap.

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 ⁠start_nlme_*⁠ function).

project_dir

Project root the jobs were launched under.

max_wait_seconds

Optional direct-R override for the total wall-clock budget (seconds), clamped ⁠0..600⁠ AND to the same launch-configured cap used by wait_for_nlme_job(). NULL (default) uses the launch budget. Values above the cap are silently clamped to the cap.

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 ⁠## DATA⁠ block.

author

Optional author string to write into the metamodel.

engineParams

Optional NlmeEngineExtraParams object created by engineParams() to serialize into the ⁠## ESTARGS⁠ block. Only arguments that differ from engineParams() defaults for this model (and estimation method) are written, so the block lists explicit overrides only.

tableParams

Optional table definition(s) created by tableParams() (i.e., NlmeTableDef and/or NlmeSimTableDef, or a list of them) to serialize into the ⁠## TABLES⁠ block.

absolutePaths

Logical; how to write the datafile path into the ⁠## DATA⁠ block. FALSE (default) makes it relative to the metamodel directory (e.g. ./data.csv), producing portable metamodels. TRUE writes the normalized absolute path. When a relative path cannot be expressed (different Windows drive) the function warns and falls back to absolute.

Value

Invisible file.