Learn R Programming

campsismod

Installation

You can install the released version of campsismod from CRAN with:

install.packages("campsismod")

Alternatively, the package can also be installed with 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

The model can be exported to files using write.

model %>% write(file = "path_to_model_folder")

In this case, the model code will be contained in the model.campsis file. Parameters (THETA, OMEGA and SIGMA) will be stored in their respective CSV file.

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

Alternatively, the model can also be exported in JSON format into a single file:

model %>% write(file = "my_model.json")

Read and show Campsis model

The model can be loaded from the previously created folder:

model <- read.campsis(file = "path_to_model_folder")

Or, from the previously created JSON file:

model <- read.campsis(file = "my_model.json")

The model can then be output in the console using show:

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 <- simulate(model = model, dataset = dataset, dest = "rxode2", seed = 0)
mrgsolve <- simulate(model = model, dataset = dataset, dest = "mrgsolve", seed = 0)
spaghetti_plot(rxode, "CONC")
spaghetti_plot(mrgsolve, "CONC")

Copy Link

Version

Install

install.packages('campsismod')

Monthly Downloads

651

Version

1.4.2

License

GPL (>= 3)

Issues

Pull Requests

Stars

Forks

Maintainer

Nicolas Luyckx

Last Published

September 28th, 2026

Functions in campsismod (1.4.2)

OmegaBlock

Create a block of OMEGA's.
OmegaBlocks

Create a list of OMEGA blocks.
Position

Element position in list.
Omega

Create an OMEGA parameter.
Pattern

Create a pattern.
OdeRecord

Create ODE code record.
Parameters

Create a list of parameters.
Sigma

Create a SIGMA parameter.
Theta

Create a THETA parameter.
UnknownStatement

Create a new ordinary differential equation (ODE).
add_ode_compartment

Add ODE compartment to compartments object.
add_rse

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

Add element to list.
add_suffix

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

Unknown destination engine exception.
all_na

Check is vector has NA's only.
auto_replication_settings-class

Auto replication settings class.
appendCompartments

Append compartments.
auto_detect_nonmem

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

Campsis model class.
as.data.frame

As data frame method.
assert_single_character_string

Assert the given character vector is a single character string.
append_comment

Append comment.
append_code_records

Append code records
appendModel

Append model (or simply add).
add_properties

Add properties to compartments object.
check_matrix_is_positive_definite

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

Compartment infusion rate class.
VariablePattern

Create a variable pattern.
compartment_initial_condition-class

Compartment initial condition class.
double_array_parameter-class

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

Compartment class.
comment-class

Comment class. A statement starting with #.
append_parameters

Append parameters.
compartment_lag_time-class

Compartment lag time class.
compartment_properties-class

Compartment properties class.
disable

Disable.
delete

Delete an element from this list.
compartment_bioavailability-class

Compartment bioavailability class.
compartment_property-class

Compartment property class.
compartment_infusion_duration-class

Compartment infusion duration class.
compartments-class

Compartments class.
convert_outvars_to_capture

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

Export type class.
extract_rhs

Extract right-hand-side expression.
extract_text_between_brackets

Extract text between brackets.
export

Export function.
duration_record-class

(Infusion)-duration record class.
equation-class

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

Check if an element exists in list.
convert_any_comment

Convert Campsis comment style to C/C++ code. Only the first # is translated to //.
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)
error_record-class

Error record class.
find

Find an element in list.
default

Get default element from list.
f_record-class

Bioavailability record class.
extract_lhs

Extract left-hand-side expression.
getByIndex

Get element by index.
fix_omega

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

Get Campsismod option logic.
get_name_in_model

Get the name of the given parameter in the Campsis model.
getName

Get element names from list.
flag_sampled_parameter_rows

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

Get the Campsismod options (R options).
getByName

#' Get an element from a list by name.
:=

Colon-equals operator.
fixOmega

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

Get element by index.
get_compartment_index

Get the compartment index for the specified compartment name.
getUncertainty

Get uncertainty on the parameters.
get_compartments

Detect all compartments names from the code records. Only for model instantiation. Not exported.
getNames

Get element names from list.
getCompartmentIndex

Get the compartment index for the specified compartment name.
get_record_delimiter

Get record delimiter.
get_var_cov

Get variance-covariance matrix.
get_names

Get element names from list.
get_name

Get element name.
export_to_json

Export the given object to a JSON object, ready to be written to files.
%>%

Magritt operator for piping.
getNameInModel

Get the name of the given parameter in the Campsis model.
get_record_name

Get record name.
get_by_name

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

Get record equation names
get_mapping_matrix

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

Get the right block of OMEGA's.
get_nonmem_name

Get NONMEM name.
get_prefix

Get prefix.
get_uncertainty

Get uncertainty on the parameters.
get_omega_indexes

Get the indexes of the omegas.
index_of

Get the index of an element in list.
has_off_diagonal_omegas

Has off-diagonal omegas.
has_comment

Check if string contains Campsis-style comments.
is_block_fixed

Say if the block is fixed (i.e. all parameters are fixed).
init_record-class

Init record class.
is_if_statement

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

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

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

Get the index of an element in list.
if_statement_pattern_str

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

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

Is diagonal.
is_strict_record_delimiter

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

Is matrix positive definite
has_exact_method

Has exact method allows to check the existence of a S4 method in Campsis based on its signature.
json_element-class

JSON element class.
is_comment

Check if string is a Campsis comment (i.e. not an equation).
json_to_parameter

JSON to Campsis parameter.
lag_record-class

Lag record class.
json_to_campsis_model

JSON to Campsis dataset.
is_diag

Is diagonal.
json_to_off_diag_parameter

Convert JSON correlation parameter (OMEGA or SIGMA) into a Campsis parameter.
jsonToParameter

JSON to Campsis parameter.
load_from_json

Fill-in S4 object from the JSON content.
is_equation

Say if line in record is an equation not.
is_empty_line

Check if string is an empty line.
line_break-class

Line-break class. A linebreak in the model.
length,pmx_list-method

Return the length of this list.
loadFromJSON

Fill-in S4 object from the JSON content.
if_statement-class

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

Max index.
map_json_properties_to_s4_slots

Map JSON properties to S4 slots.
manual_replication_settings-class

Manual replication settings class.
main_record-class

Main record class.
map_s4_slots_to_json_properties

Map S4 slots to JSON properties.
match_double_array_parameter

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

Max index.
mapS4SlotsToJSONProperties

Map S4 slots to JSON properties.
match_single_array_parameter

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

Map JSON properties to S4 slots.
min_index

Min index.
move

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

Campsis model suite.
min_max_default

Min/max default values for the given parameter.
mrgsolve_block

Convert code record for mrgsolve.
mrgsolve_capture

Get the CAPTURE block for mrgsolve.
model_statement-class

Model statement class. Any statement in a code record.
model_statements-class

Model statements class. A list of statements.
methods_global_functions

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

Mrgsolve export type class.
ode-class

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

Get the OMEGA/SIGMA matrix for mrgsolve.
mrgsolve_ode

Get the ODE block for mrgsolve.
ode_record-class

ODE record class.
omega-class

Omega parameter class.
minIndex

Min index.
mrgsolve_table

Get the TABLE block for mrgsolve.
pmx_position_by_element-class

PMX position by element class.
mrgsolve_param

Get the parameters block for mrgsolve.
pmx_position-class

PMX position class.
process_json_double_array_parameter

Process JSON double array parameter.
mrgsolve_compartment

Get the compartment block for mrgsolve.
parameter-class

Parameter class. Any parameter in a pharmacometric model.
pmx_element-class

PMX element class.
mrgsolve_main

Get the MAIN block for mrgsolve.
processExtraArg

Process extra arguments.
pmx_list-class

PMX list class.
open_json

Open JSON file.
parameters-class

Parameters class.
parse_if_statement

Parse IF-statement. Assumption: is_if_statement method already called and returned TRUE.
read.allparameters

Read all parameters files at once.
read.campsis

Read a Campsis model.
processDoubleArrayArguments

Process double array arguments.
replace

Replace element by another in list.
read

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

PMX position by index class.
read.pmxmod

Read a Campsis model (deprecated).
replaceAll

Replace all occurrences in object.
process_extra_arg

Process extra arguments.
rxode_matrix

Get the OMEGA/SIGMA matrix for rxode2.
read.parameters

Read parameters file.
properties_record-class

Properties record class.
read.model

Read model file.
replicated_campsis_model-class

Replicated Campsis model class.
rate_record-class

(Infusion)-rate record class.
parse_statements

Parse statements code and return Campsis statements.
pattern-class

Pattern class.
read.varcov

Read variance-covariance file.
rxodeMatrix

Get the OMEGA/SIGMA matrix for rxode2.
remove_na_column

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

Remove all trailing line breaks.
replace_all

Replace all occurrences in object.
replicate

Replicate generic object.
rxode_params

Get the parameters vector for rxode2.
replication_settings-class

Replication settings interface.
rxode_type-class

RxODE/rxode2 export type class.
sort

Sort the specified list.
sample_from_inverse_chi_squared_core

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

Get code for rxode2
sample_from_multivariate_normal_distribution

Sample from a multivariate normal distribution.
sample_generic

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

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

Sample from multivariate normal distribution (core method).
sample_from_inverse_wishart_core

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

Shift OMEGA indexes.
set_min_max

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

Statements record class.
select

Get a subset of an object.
single_array_parameter-class

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

to_string generic method.
update_compartments

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

Standardise.
to_string

to_string generic method.
sigma-class

Sigma parameter class.
updateCompartments

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

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

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.
theta-class

Theta parameter class.
unknown_statement-class

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

Trim character vector. Remove all leading and trailing spaces.
write_parameters

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

Write variance-covariance matrix.
variable_pattern-class

Variable pattern class.
write

Write generic object to files.
variable_pattern_str

Return the variable pattern (string form).
write_record_delimiter

Write record delimiter line.
variable_pattern_no_start_str

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

Create ERROR code record.
CodeRecords

Create a list of code records.
CampsisModel

Create a new Campsis model.
Compartment

Create a compartment.
Compartments

Create a list of compartments
IfStatement

Create a new IF-statement.
Comment

Create a new comment.
Equation

Create a new equation.
Bioavailability

Create a bioavailability for the specified compartment.
AutoReplicationSettings

Create auto replication settings.
InfusionRate

Create an infusion rate.
LagTime

Create a lag time for the specified compartment.
InfusionDuration

Create an infusion duration.
ModelStatements

Create an empty list of model statements.
Ode

Create a new ordinary differential equation (ODE).
MainRecord

Create MAIN code record.
JSONElement

Instantiate a JSON element.
InitialCondition

Create an initial condition.
ManualReplicationSettings

Create manual replication settings.
LineBreak

Create a new line break.