Learn R Programming

campsismod

Installation

Install the latest stable release using devtools:

devtools::install_github("Calvagone/campsismod")

Basic examples

Load example from model library

Load 2-compartment PK model from built-in model library:

library(campsismod)
model <- model_suite$pk$`2cpt_fo`

Write CAMPSIS model

model %>% write(file="path_to_model_folder")
list.files("path_to_model_folder")
#> [1] "model.campsis" "omega.csv"     "sigma.csv"     "theta.csv"

Read and show CAMPSIS model

model <- read.campsis(file="path_to_model_folder")
show(model)
#> [MAIN]
#> TVBIO=THETA_BIO
#> TVKA=THETA_KA
#> TVVC=THETA_VC
#> TVVP=THETA_VP
#> TVQ=THETA_Q
#> TVCL=THETA_CL
#> 
#> BIO=TVBIO
#> KA=TVKA * exp(ETA_KA)
#> VC=TVVC * exp(ETA_VC)
#> VP=TVVP * exp(ETA_VP)
#> Q=TVQ * exp(ETA_Q)
#> CL=TVCL * exp(ETA_CL)
#> 
#> [ODE]
#> d/dt(A_ABS)=-KA*A_ABS
#> d/dt(A_CENTRAL)=KA*A_ABS + Q/VP*A_PERIPHERAL - Q/VC*A_CENTRAL - CL/VC*A_CENTRAL
#> d/dt(A_PERIPHERAL)=Q/VC*A_CENTRAL - Q/VP*A_PERIPHERAL
#> 
#> [F]
#> A_ABS=BIO
#> 
#> [ERROR]
#> CONC=A_CENTRAL/VC
#> if (CONC <= 0.001) CONC=0.001
#> CONC_ERR=CONC*(1 + EPS_PROP_RUV)
#> 
#> 
#> THETA's:
#>   name index value   fix                            label unit
#> 1  BIO     1     1 FALSE                  Bioavailability <NA>
#> 2   KA     2     1 FALSE                  Absorption rate  1/h
#> 3   VC     3    10 FALSE    Volume of central compartment    L
#> 4   VP     4    40 FALSE Volume of peripheral compartment    L
#> 5    Q     5    20 FALSE           Inter-compartment flow  L/h
#> 6   CL     6     3 FALSE                        Clearance  L/h
#> OMEGA's:
#>   name index index2 value   fix type
#> 1   KA     1      1    25 FALSE  cv%
#> 2   VC     2      2    25 FALSE  cv%
#> 3   VP     3      3    25 FALSE  cv%
#> 4    Q     4      4    25 FALSE  cv%
#> 5   CL     5      5    25 FALSE  cv%
#> SIGMA's:
#>       name index index2 value   fix type
#> 1 PROP_RUV     1      1   0.1 FALSE   sd
#> No variance-covariance matrix
#> 
#> Compartments:
#> A_ABS (CMT=1)
#> A_CENTRAL (CMT=2)
#> A_PERIPHERAL (CMT=3)

Simulate with rxode2 or mrgsolve

library(campsis)

dataset <- Dataset(5) %>%
  add(Bolus(time=0, amount=1000, ii=12, addl=2)) %>%
  add(Observations(times=0:36))

rxode <- model %>% simulate(dataset=dataset, dest="rxode2", seed=0)
mrgsolve <- model %>% simulate(dataset=dataset, dest="mrgsolve", seed=0)
spaghettiPlot(rxode, "CONC")
spaghettiPlot(mrgsolve, "CONC")

Copy Link

Version

Install

install.packages('campsismod')

Monthly Downloads

531

Version

1.2.1

License

GPL (>= 3)

Issues

Pull Requests

Stars

Forks

Maintainer

Nicolas Luyckx

Last Published

March 17th, 2025

Functions in campsismod (1.2.1)

LineBreak

Create a new line break.
CodeRecords

Create a list of code records.
ManualReplicationSettings

Create manual replication settings.
ErrorRecord

Create ERROR code record.
IfStatement

Create a new IF-statement.
ModelStatements

Create an empty list of model statements.
Comment

Create a new comment.
addODECompartment

Add ODE compartment to compartments object.
Ode

Create a new ordinary differential equation (ODE).
MainRecord

Create MAIN code record.
OdeRecord

Create ODE code record.
Omega

Create an OMEGA parameter.
Sigma

Create a SIGMA parameter.
LagTime

Create a lag time for the specified compartment.
InitialCondition

Create an initial condition.
addProperties

Add properties to compartments object.
Bioavailability

Create a bioavailability for the specified compartment.
OmegaBlock

Create a block of OMEGA's.
addRSE

Add relative standard error (RSE) to the specified parameter.
OmegaBlocks

Create a list of OMEGA blocks.
InfusionDuration

Create an infusion duration.
Theta

Create a THETA parameter.
Compartment

Create a compartment.
Pattern

Create a pattern.
allNa

Check is vector has NA's only.
Parameters

Create a list of parameters.
addSuffix

Generic function to add a suffix to various objects like parameters, code records, compartment names or a model (all previous objects at the same time). This makes it an extremely powerful function to combine 2 models or more (using function 'add'), that have similar equation, parameter or compartment names.
appendModel

Append model (or simply add).
appendCodeRecords

Append code records
autoDetectNONMEM

Auto-detect special variables from NONMEM as compartment properties. Bioavailabilities, infusion durations/rates and lag times will be automatically detected.
compartment_lag_time-class

Compartment lag time class.
appendParameters

Append parameters.
auto_replication_settings-class

Auto replication settings class.
compartment_properties-class

Compartment properties class.
Position

Element position in list.
compartment_property-class

Compartment property class.
compartments-class

Compartments class.
equation-class

Equation class. Any statement in the form A = B.
export

Export function.
export_type-class

Export type class.
InfusionRate

Create an infusion rate.
error_record-class

Error record class.
UnknownStatement

Create a new ordinary differential equation (ODE).
VariablePattern

Create a variable pattern.
UnsupportedDestException

Unknown destination engine exception.
appendComment

Append comment.
find

Find an element in list.
comment-class

Comment class. A statement starting with #.
add

Add element to list.
code_record-class

Code record class. See this code record as an abstract class. 2 implementations are possible: - properties record (lag, duration, rate & bioavailability properties) - statements record (main, ode & error records)
getUncertainty

Get uncertainty on the parameters.
:=

Colon-equals operator.
campsis_model-class

Campsis model class.
getVarCov

Get variance-covariance matrix.
compartment-class

Compartment class.
double_array_parameter-class

Double-array parameter class. This parameter has 2 indexes. It can thus be used to define correlations between parameters.
delete

Delete an element from this list.
init_record-class

Init record class.
disable

Disable.
getByName

Get an element from a list by name. Never return more than 1 element.
checkMatrixIsPositiveDefinite

Check OMEGA/SIGMA matrix for positive definiteness.
duration_record-class

(Infusion)-duration record class.
compartment_infusion_rate-class

Compartment infusion rate class.
flagSampledParameterRows

Flag all parameter rows that have at least one parameter out of the specified range or that have a non positive definite OMEGA or SIGMA matrix.
fixOmega

Fix omega matrix for SAME OMEGA parameters that have NA values due to imperfections in Pharmpy import.
getByIndex

Get element by index.
compartment_initial_condition-class

Compartment initial condition class.
convertOutvarsToCapture

Convert outvars argument to capture. Variables that are already in error block will be discarded.
isODE

Say if line(s) in record is/are ODE or not.
isBlockFixed

Say if the block is fixed (i.e. all parameters are fixed).
isRecordDelimiter

Is record delimiter. A record delimiter is any line starting with [...].
move

Move element 'x' from object to a certain place.
getCompartmentIndex

Get the compartment index for the specified compartment name.
mrgsolveBlock

Convert code record for mrgsolve.
getOmegaBlock

Get the right block of OMEGA's.
getOmegaIndexes

Get the indexes of the omegas.
default

Get default element from list.
getNONMEMName

Get NONMEM name.
mrgsolveTable

Get the TABLE block for mrgsolve.
appendCompartments

Append compartments.
extractLhs

Extract left-hand-side expression.
as.data.frame

As data frame method.
getPrefix

Get prefix.
extractRhs

Extract right-hand-side expression.
%>%

Magritt operator for piping.
assertSingleCharacterString

Assert the given character vector is a single character string.
mrgsolve_type-class

Mrgsolve export type class.
getRecordDelimiter

Get record delimiter.
omega-class

Omega parameter class.
getName

Get element name.
compartment_bioavailability-class

Compartment bioavailability class.
getRecordEquationNames

Get record equation names
hasComment

Check if string contains CAMPSIS-style comments.
isComment

Check if string is a CAMPSIS comment (i.e. not an equation).
isDiag

Is diagonal.
parameter-class

Parameter class. Any parameter in a pharmacometric model.
getNameInModel

Get the name of the given parameter in the CAMPSIS model.
isEmptyLine

Check if string is an empty line.
getNames

Get element names from list.
line_break-class

Line-break class. A linebreak in the model.
manual_replication_settings-class

Manual replication settings class.
getRecordName

Get record name.
matchDoubleArrayParameter

Match double array parameter from list based on the name instead of the index. If a match is found, its indexes are automatically copied.
isEquation

Say if line in record is an equation not.
rate_record-class

(Infusion)-rate record class.
isRxODE

Check if the destination engine is RxODE or rxode2. Note that rxode2 is the successor of RxODE.
contains

Check if an element exists in list.
compartment_infusion_duration-class

Compartment infusion duration class.
main_record-class

Main record class.
parameters-class

Parameters class.
isStrictRecordDelimiter

Is strict record delimiter. A strict record delimiter is any line starting with [...] and followed by nothing but spaces or a possible comment.
methodsGlobalFunctions

A empty method only used to declare some of the global function definitions contained in the package 'methods', which are used intensively.
read

Generic read method to read data from a file or a folder.
model_statements-class

Model statements class. A list of statements.
removeTrailingLineBreaks

Remove all trailing line breaks.
removeNaColumn

Remove given column(s) if it has only NA's.
parseIfStatement

Parse IF-statement. Assumption: isIfStatement method already called and returned TRUE.
pmx_position_by_index-class

PMX position by index class.
processDoubleArrayArguments

Process double array arguments.
replication_settings-class

Replication settings interface.
extractTextBetweenBrackets

Extract text between brackets.
convertAnyComment

Convert CAMPSIS comment style to C/C++ code. Only the first # is translated to //.
f_record-class

Bioavailability record class.
if_statement-class

If-statement class. Any statement in the form if (condition) A = B.
rxodeCode

Get code for rxode2
minIndex

Min index.
mrgsolveMain

Get the MAIN block for mrgsolve.
model_suite

CAMPSIS model suite.
indexOf

Get the index of an element in list.
sampleFromMultivariateNormalDistribution

Sample from a multivariate normal distribution.
lag_record-class

Lag record class.
mrgsolveOde

Get the ODE block for mrgsolve.
getCompartments

Detect all compartments names from the code records. Only for model instantiation. Not exported.
length,pmx_list-method

Return the length of this list.
mrgsolveMatrix

Get the OMEGA/SIGMA matrix for mrgsolve.
sampleGeneric

Generic function for parameter sampling according to the minimum and maximum values. This function will sample parameters a first time and check if some parameters are out of range. Based on the success rate, it will sample more parameters to reach the desired number of rows.
pmx_position-class

PMX position class.
getMappingMatrix

Return a matrix filled in with OMEGA/SIGMA names to be mapped with the values. Nonexistent parameters are filled in with the empty string.
sampleFromMultivariateNormalDistributionCore

Sample from multivariate normal distribution (core method).
select

Get a subset of an object.
mrgsolveParam

Get the parameters block for mrgsolve.
pmx_position_by_element-class

PMX position by element class.
read.model

Read model file.
toString

ToString generic method.
trim

Trim character vector. Remove all leading and trailing spaces.
read.parameters

Read parameters file.
read.pmxmod

Read a Campsis model (deprecated).
read.varcov

Read variance-covariance file.
parseStatements

Parse statements code and return CAMPSIS statements.
sampleFromInverseChiSquaredOrWishart

Sample parameters from inverse scaled chi-squared or wishart distribution(s).
minMaxDefault

Min/max default values for the given parameter.
pattern-class

Pattern class.
read.allparameters

Read all parameters files at once.
read.campsis

Read a CAMPSIS model.
replace

Replace element by another in list.
sigma-class

Sigma parameter class.
unknown_statement-class

Unknown statement class. Any statement not recognized by campsismod.
sampleFromInverseWishartCore

Sample from scaled inverse Wishart distribution (core method).
replaceAll

Replace all occurrences in object.
setMinMax

Set the minimum and maximum value on a model parameter.
model_statement-class

Model statement class. Any statement in a code record.
shiftOmegaIndexes

Shift OMEGA indexes.
updateOMEGAs

Update OMEGAs that are same. Same OMEGAs are written as follows: OMEGA1 same is FALSE (first one, estimated) OMEGA2 same is TRUE OMEGA3 same is TRUE, etc. OMEGA2 and OMEGA3 will take the same value as OMEGA1.
single_array_parameter-class

Single-array parameter class. This parameter has a single index value.
writeParameters

Write subset of parameters (theta, omega or sigma).
writeRecordDelimiter

Write record delimiter line.
updateParameters

Update model parameters based on the parameters issued from the model replication.
hasOffDiagonalOmegas

Has off-diagonal omegas.
mrgsolveCapture

Get the CAPTURE block for mrgsolve.
writeVarcov

Write variance-covariance matrix.
updateCompartments

Update compartments list from the persisted records. Exported especially for package campsistrans. However, this method should not be called.
ifStatementPatternStr

Return the IF-statement pattern (string form).
isIfStatement

Say if line in record is an IF-statement.
isMatrixPositiveDefinite

Is matrix positive definite. Same check as mvtnorm does.
matchSingleArrayParameter

Match single array parameter from list based on the name instead of the index. If a match is found, its index is automatically copied.
maxIndex

Max index.
mrgsolveCompartment

Get the compartment block for mrgsolve.
replicate

Replicate generic object.
ode-class

ODE class. Any statement in the form d/dt(A_CMT) = B.
replicated_campsis_model-class

Replicated Campsis model class.
rxodeMatrix

Get the OMEGA/SIGMA matrix for rxode2.
ode_record-class

ODE record class.
rxodeParams

Get the parameters vector for rxode2.
pmx_element-class

PMX element class.
standardise

Standardise.
sort

Sort the specified list.
pmx_list-class

PMX list class.
variable_pattern-class

Variable pattern class.
processExtraArg

Process extra arguments.
write

Write generic object to files.
properties_record-class

Properties record class.
rxode_type-class

RxODE/rxode2 export type class.
sampleFromInverseChiSquaredCore

Sample from scaled inverse chi-squared distribution (core method).
statements_record-class

Statements record class.
theta-class

Theta parameter class.
variablePatternNoStartStr

Return the variable pattern (string form), without the first character.
variablePatternStr

Return the variable pattern (string form).
AutoReplicationSettings

Create auto replication settings.
Compartments

Create a list of compartments
CampsisModel

Create a new Campsis model.
Equation

Create a new equation.