Type: Package
Title: PKPD, PBPK, and Systems Pharmacology Modeling Tools
Version: 2.1.0
Maintainer: John Harrold <john.m.harrold@gmail.com>
Description: Complete work flow for the analysis of pharmacokinetic pharmacodynamic (PKPD), physiologically-based pharmacokinetic (PBPK) and systems pharmacology models including: creation of ordinary differential equation-based models, pooled parameter estimation, individual/population based simulations, rule-based simulations for clinical trial design and modeling assays, deployment with a customizable 'Shiny' app, and non-compartmental analysis. System-specific analysis templates can be generated and each element includes integrated reporting with 'PowerPoint' and 'Word'.
URL: https://r.ubiquity.tools
SystemRequirements: Perl
BugReports: https://github.com/john-harrold/ubiquity/issues
License: BSD_2_clause + file LICENSE
Encoding: UTF-8
Depends: R (≥ 4.2.0)
Imports: cli, deSolve, dplyr (≥ 1.0.0), digest, doParallel, flextable, foreach, ggplot2, knitr, MASS, onbrand (≥ 1.0.2), optimx, PKNCA, pso, readxl, rmarkdown, rhandsontable, scales, stats, stringr, shiny,
Suggests: babelmixr2, GA, GGally, gridGraphics, gridExtra, grid, officer, rxode2, webshot, ggrepel, rstudioapi, testthat
VignetteBuilder: knitr
RoxygenNote: 7.3.2
NeedsCompilation: no
Packaged: 2025-01-06 23:16:53 UTC; jmh
Author: John Harrold ORCID iD [aut, cre]
Repository: CRAN
Date/Publication: 2025-01-07 14:30:02 UTC

Calculate AUC for Sparse Data

Description

This is an implementation of Bailors method for calculating AUCs with sparse sampling. It is taken from the following publication:

Nedelman, J. R., Gibiansky, E., & Lau, D. T. (1995). Applying Bailer's method for AUC confidence intervals to sparse sampling Pharmaceutical Research, 12(1), 124-128.

Usage

AUC_Bailers_method(
  conc_data = NULL,
  dsmap = list(NTIME = "NTIME", CONC = "CONC", ID = "ID")
)

Arguments

conc_data

data frame containing the sparse data

dsmap

list with names specifying the columns:

  • NTIME Nominal time since last dose; "NTIME" (default)

  • CONC Concentration data; "CONC" (default)

  • ID Subject ID; ("ID" (default)

Value

list with the following elements


Wrapper for system_log_entry Used in ShinyApp

Description

Called from the ShinyApp to add a log entry with "App" prepended to the log entry

Usage

GUI_log_entry(cfg, text)

Arguments

cfg

ubiquity system object

text

string to print/log

Value

Boolean variable indicating success (TRUE) or failure (FALSE)


Extracts Covariates for a Subject from a Subject Data File

Description

This function is used when stochastic simulations are being performed using a data file for the subject level information. If the data file contains covariate information, this function will update the system for each subjects covariates.

Usage

apply_sub_file_COV(
  tmpcfg,
  cov_found,
  sub_dataset,
  sub_ID_col,
  sub_TIME_col,
  file_ID
)

Arguments

tmpcfg

ubiquity system object

cov_found

list of covariates found in dataset

sub_dataset

name of dataset with subject parameters

sub_ID_col

name of column in dataset with subject IDs

sub_TIME_col

name of column in dataset with simulation time

file_ID

subject ID to extract covariates for

Value

ubiquity system object with the covariates set to those for the current subject


Archive Estimation Results

Description

Archives the estimation results by moving the output files to the same file names with 'name' prepended to them. This prevents them from being overwritten in a different analysis script the following files are archived:

Example:

archive_estimation('mysoln', cfg)

Would rename the files above

Usage

archive_estimation(name, cfg)

Arguments

name

analysis name

cfg

ubiquity system object

Value

Boolean variable indicating success (TRUE) or failure (FALSE)


Build the System File

Description

Builds the specified system file creating the targets for R and other languages as well as the templates for performing simulations and estimations.

Usage

build_system(
  system_file = "system.txt",
  distribution = "automatic",
  perlcmd = "perl",
  output_directory = file.path(".", "output"),
  temporary_directory = file.path(".", "transient"),
  verbose = TRUE,
  ubiquity_app = FALSE,
  debug = TRUE
)

Arguments

system_file

name of the file defining the system in the ubiquity format (default = 'system.txt'), if the file does not exist a template will be created and compiled.

distribution

indicates weather you are using a 'package' or a 'stand alone' distribution of ubiquity. If set to 'automatic' the build script will first look to see if the ubiquity R package is installed. If it is installed it will use the package. Otherwise, it will assume a "sand alone" distribution.

perlcmd

system command to run perl ("perl")

output_directory

location to store analysis outputs (file.path(".", "output"))

temporary_directory

location to templates and otehr files after building the system (file.path(".", "transient"))

verbose

enable verbose messaging (TRUE)

ubiquity_app

set to TRUE when building the system to be used with the ubiquty App (FALSE)

debug

Boolean variable indicating if debugging information should be displayed (TRUE)

Value

initialized ubiquity system object

Examples


fr = system_new(file_name        = "system.txt", 
                system_file      = "mab_pk", 
                overwrite        = TRUE, 
                output_directory = tempdir())
cfg = build_system(system_file  = file.path(tempdir(), "system.txt"),
      output_directory          = file.path(tempdir(), "output"),
      temporary_directory       = tempdir())


Calculate the halflife of data

Description

Determines the terminal halflife of a sequence of corresponding times and values with optional minimum and maximum times to censor data.

Usage

calculate_halflife(times = NULL, values = NULL, tmin = NULL, tmax = NULL)

Arguments

times

- sequence of times

values

- corresponding sequence of values

tmin

- minimum time to include (NULL)

tmax

- maximum time to include (NULL)

Value

List with the following names

Examples

x     = c(0:100)
y     = exp(-.1*x)
th    = calculate_halflife(times=x, values=y)
thalf = th$thalf 

Calculates the Value of the Specified Objective Function

Description

For a given set of system parameters the objective function will be calculated based on defined cohorts and variance models.

Usage

calculate_objective(parameters, cfg, estimation = TRUE)

Arguments

parameters

system parameters

cfg

ubiquity system object

estimation

boolean variable to indicate if the objective function is being called during parameter estimation

Value

If estimation is TRUE it will return the objective function value, if it is FALSE it will return a list with an element value containing the objective function value and an element named isgood that is TRUE if the objective function was successful.


GA Wrapper for calculate_objective

Description

Converts the parameter vector to a named list and returns the negative of the objective (turning the maximization into a minimization)

Usage

calculate_objective_ga(pvect, cfg)

Arguments

pvect

system parameters

cfg

ubiquity system object

Value

objective function value


pso Wrapper for calculate_objective

Description

The psoptim objective function assumes parameters will be a vector and this function converts it to a named list to be consistent with the ubiquity optmization routines.

Usage

calculate_objective_pso(pvect, cfg)

Arguments

pvect

system parameters

cfg

ubiquity system object

Value

objective function value


Calculates the Variance in od_general

Description

Takes the variance specified as a string and evaluates it locally, and returns that value

Usage

calculate_variance(
  SIMINT_parameters,
  SIMINT_varstr,
  SIMINT_odchunk,
  SIMINT_cfg
)

Arguments

SIMINT_parameters

system parameters

SIMINT_varstr

string containing variance calculation

SIMINT_odchunk

chunk of observation details containing predictions, observations and the time

SIMINT_cfg

ubiquity system object

Value

Variance calculated for a given set of parameters in a model


Verify System Steady State

Description

Takes the output run_simulation_ubiquity and verifies that the system is running at steady state by analyzing the timecourse of all of the states in the system

Usage

check_steady_state(cfg, som)

Arguments

cfg

ubiquity system object

som

output of run_simulation_ubiquity

Value

list with name steady_state (boolean indicating weather the system was at steady state) and states a vector of states that have steady state offset.


Compares Estimate to Bounds

Description

Compares the parameter estimate to the bounds and indicates if the estimate is near the bound.

Usage

compare_estimate(cfg, parameters, pname)

Arguments

cfg

ubiquity system object

parameters

list of parameter estimates

pname

name of parameter to compare

Value

L - near the lower bound, U - near the upper bound


Performs parameter estimation

Description

Performs the actual parameter estimation

Usage

estimate_parameters(cfg)

Arguments

cfg

ubiquity system object

Value

list with elements:


Create Full Parameter Vector from Estimation Subset

Description

Can be used to take a subset of parameters (those being estimated and returned from ' system_estimate_parameters) into a full list of system parameters.

Usage

fetch_full_parameters(pest, cfg)

Arguments

pest

list containing subset of parameters being estimated

cfg

ubiquity system object

Details

This function is used to build a full parameter set from a subset, and is normally used during parameter estimation in the observation details function when the entire parameter vector is needed to simulate the system.

The function select_set pulls out a parameter set and can optionally select only a subset for estimation:

pnames = c('Vp', 'CL')
cfg = system_select_set(cfg, "default", pnames)

The default values of this subset can be accessed in the following way:

pest = system_fetch_guess(cfg)

The estimation routines will work with this reduced parameter set, but to run simulations the full set is needed. The full values can be retrieved using the following:

parameters = fetch_full_parameters(pest, cfg) 

Value

Full list of parameters with default values for the currently selected parameter set and the values in pest merged

See Also

system_fetch_guess, system_select_set


Parse Prototype Functions for Arguments

Description

Parses strings to find abstract functions (of the format SIFUNC[ARG1][ARG2][ARG3] and extract the arguments from that function and replace it with actual functions and any additional arguments needed

Usage

find_bracketed_arguments(str, pattern, replace = "", narg, op = "[", cp = "]")

Arguments

str

string containing the prototype function call

pattern

string indicating the start of the function eg. "SI_TT_BOLUS["

replace

string to replace pattern with

narg

number of arguments to prototype function

op

string used to indicating open parenthesis

cp

string used to indicating close parenthesis

Value

string containing the actual function call/code built from the prototype function


Generates a Parameter Based on <IIV:?> in the System File

Description

Internal function used to generate parameters based on IIV information

Usage

generate_parameter(
  SIMINT_parameters,
  SIMINT_cfg,
  SIMINT_PARAMETER_TV,
  SIMINT_IIV_VALUE,
  SIMINT_equation
)

Arguments

SIMINT_parameters

parameters vector containing the typical values

SIMINT_cfg

ubiquity system object

SIMINT_PARAMETER_TV

Typical value of the parameter in question

SIMINT_IIV_VALUE

sample from mvr distribution

SIMINT_equation

equation relating IIV and typical value to the parameter value with variability

Value

parameter value with the variability applied


Generate Text Report with Estimation Results

Description

Internal function used to generate a report of estimation results

Usage

generate_report(parameters, ss, cfg, conv_desc)

Arguments

parameters

list of parameter estimates

ss

output from solution_statistics

cfg

ubiquity system object

conv_desc

description of convergence criteria

Value

List with the following elements:


Generate Subject

Description

Generates subject with variability specified using the <IIV:?> descriptor in the system file

Usage

generate_subject(parameters, cfg)

Arguments

parameters

vector of nominal parameter values

cfg

ubiquity system object

Value

List with a field named parameters containing a sample representing a subject


Make Pretty ggplot x- or y-Axis Log 10 Scale

Description

used to convert the x and y-axis of a ggplot to a log 10 scale that is more visually satisfying than the ggplot default.

Usage

gg_axis(
  fo,
  yaxis_scale = TRUE,
  xaxis_scale = TRUE,
  ylim_min = NULL,
  ylim_max = NULL,
  xlim_min = NULL,
  xlim_max = NULL,
  x_tick_label = TRUE,
  y_tick_label = TRUE
)

Arguments

fo

ggplot figure object

yaxis_scale

TRUE indicates that the y-axis should be log10 scaled

xaxis_scale

TRUE indicates that the x-axis should be log10 scaled

ylim_min

set to a number to define the lower bound of the y-axis

ylim_max

set to a number to define the upper bound of the y-axis

xlim_min

set to a number to define the lower bound of the x-axis

xlim_max

set to a number to define the upper bound of the x-axis

x_tick_label

TRUE to show x tick labels, FALSE to hide the x tick labels

y_tick_label

TRUE to show y tick labels, FALSE to hide the y tick labels

Value

ggplot object with formatted axis

See Also

gg_log10_xaxis and gg_log10_yaxis

Examples

library("ggplot2")
df = data.frame(x = seq(0.01,10,.01),
               y = seq(0.01,10,.01)^2)
p       = ggplot(df, aes(x=x, y=y)) + geom_line()
# pretty up the axes
p       = prepare_figure(fo=p, purpose="print")
# pretty log10 y-axis 
p_logy  = gg_log10_yaxis(fo=p)
# pretty log10 x-axis 
p_logx  = gg_log10_xaxis(fo=p)
# pretty log10 yx-axis 
p_logxy = gg_axis(fo=p)

Make Pretty ggplot x-Axis Log 10 Scale

Description

Wrapper for gg_axis to create a log 10 x-axis

Usage

gg_log10_xaxis(
  fo,
  xlim_min = NULL,
  xlim_max = NULL,
  y_tick_label = TRUE,
  x_tick_label = TRUE
)

Arguments

fo

ggplot figure object

xlim_min

set to a number to define the lower bound of the x-axis

xlim_max

set to a number to define the upper bound of the x-axis

y_tick_label

TRUE to show y tick labels, FALSE to hide the y tick labels

x_tick_label

TRUE to show x tick labels, FALSE to hide the x tick labels

Value

ggplot object with formatted axis

See Also

gg_axis and gg_log10_xaxis

Examples

library("ggplot2")
df = data.frame(x = seq(0.01,10,.01),
               y = seq(0.01,10,.01)^2)
p       = ggplot(df, aes(x=x, y=y)) + geom_line()
# pretty up the axes
p       = prepare_figure(fo=p, purpose="print")
# pretty log10 y-axis 
p_logy  = gg_log10_yaxis(fo=p)
# pretty log10 x-axis 
p_logx  = gg_log10_xaxis(fo=p)
# pretty log10 yx-axis 
p_logxy = gg_axis(fo=p)

Make Pretty ggplot y-Axis Log 10 Scale

Description

Wrapper for gg_axis to create a log 10 y-axis

Usage

gg_log10_yaxis(
  fo,
  ylim_min = NULL,
  ylim_max = NULL,
  y_tick_label = TRUE,
  x_tick_label = TRUE
)

Arguments

fo

ggplot figure object

ylim_min

set to a number to define the lower bound of the y-axis

ylim_max

set to a number to define the upper bound of the y-axis

y_tick_label

TRUE to show y tick labels, FALSE to hide the y tick labels

x_tick_label

TRUE to show x tick labels, FALSE to hide the x tick labels

Value

ggplot object with formatted axis

See Also

gg_axis and gg_log10_xaxis

Examples

library("ggplot2")
df = data.frame(x = seq(0.01,10,.01),
               y = seq(0.01,10,.01)^2)
p       = ggplot(df, aes(x=x, y=y)) + geom_line()
# pretty up the axes
p       = prepare_figure(fo=p, purpose="print")
# pretty log10 y-axis 
p_logy  = gg_log10_yaxis(fo=p)
# pretty log10 x-axis 
p_logx  = gg_log10_xaxis(fo=p)
# pretty log10 yx-axis 
p_logxy = gg_axis(fo=p)

Implementation of the linspace Function from Matlab

Description

Creates a vector of n elements equally spaced apart.

Usage

linspace(a, b, n = 100)

Arguments

a

initial number

b

final number

n

number of elements (integer >= 2)

Value

vector of numbers from a to b with n linearly spaced apart

Examples

linspace(0,100, 20)

Implementation of the logspace Function from Matlab

Description

Creates a vector of n elements logarithmically spaced apart.

Usage

logspace(a, b, n = 100)

Arguments

a

initial number

b

final number

n

number of elements (integer >=2)

Value

vector of numbers from a to b with n logarithmically (base 10) spaced apart

Examples

logspace(-2, 3,20)

Makes Forcing Function From Times and Values

Description

Takes a list of times, values, and an interpolation method

Usage

make_forcing_function(
  times,
  values,
  type,
  output_times,
  sample_delta_mult = 0.001
)

Arguments

times

time values for the forcing function

values

magnitude for each time (same length of time)

type

string indicating the type of forcing function can be one of the following:

  • "step" for constant values that switch to new values at the times

  • "linear" to linearly interpolate between the points

output_times

vector of simulation output times

sample_delta_mult

multiplier used to control the magnitude of spacing around event times

Value

matrix with two columns: first column is a vector of times and the second column is a vector of values


Select Records from NONMEM-ish Data Set

Description

Retrieves a subset of a NONMEM-ish data set based on a list containing filtering information.

Usage

nm_select_records(cfg, values, filter)

Arguments

cfg

ubiquity system object

values

dataframe containing the dataset with column headers

filter

list with element names as headers for values with values from the same header OR'd and values across headers AND'd

Details

If the dataset has the headings ID, DOSE and SEX and filter has the following format:

filter = list()
filter$ID   = c(1:4)
filter$DOSE = c(5,10)
filter$SEX  = c(1)

It would be translated into the boolean filter:

((ID==1) | (ID==2) | (ID==3) | (ID==4)) & ((DOSE == 5) | (DOSE==10)) & (SEX == 1)

Value

subset of dataset


Pad String with Spaces

Description

Adds spaces to the beginning or end of strings until it reaches the maxlength. Used for aligning text.

Usage

pad_string(str, maxlength = 1, location = "beginning")

Arguments

str

string

maxlength

length to pad to

location

either "beginning" to pad the left or "end" to pad the right

Value

Padded string

Examples

pad_string("bob", maxlength=10)
pad_string("bob", maxlength=10, location="end")

Parse String for Prototype Functions

Description

A string can contain any number of prototype functions, and this function will find them and replace them with the actual R code.

Usage

parse_patterns(cfg, str)

Arguments

cfg

ubiquity system object

str

string

Value

String with the prototype functions replaced


Make ggplot Figure Pretty

Description

Takes a ggplot object and alters the line thicknesses and makes other cosmetic changes to make it more appropriate for exporting.

Usage

prepare_figure(
  purpose = "present",
  fo,
  y_tick_minor = FALSE,
  y_tick_major = FALSE,
  x_tick_minor = FALSE,
  x_tick_major = FALSE
)

Arguments

purpose

either "present" (default), "print" or "shiny"

fo

ggplot figure object

y_tick_minor

Boolean value to control grid lines

y_tick_major

Boolean value to control grid lines

x_tick_minor

Boolean value to control grid lines

x_tick_major

Boolean value to control grid lines

Value

ggplot object

Examples

library("ggplot2")
df = data.frame(x = seq(0.01,10,.01),
               y = seq(0.01,10,.01)^2)
p       = ggplot(df, aes(x=x, y=y)) + geom_line()
# pretty up the axes
p       = prepare_figure(fo=p, purpose="print")
# pretty log10 y-axis 
p_logy  = gg_log10_yaxis(fo=p)
# pretty log10 x-axis 
p_logx  = gg_log10_xaxis(fo=p)
# pretty log10 yx-axis 
p_logxy = gg_axis(fo=p)

Simulate With Titration or Rule-Based Inputs

Description

Provides an interface to run_simulation_ubiquity to start and stop simulations and apply rules to control dosing and state-resets.

Usage

run_simulation_titrate(SIMINT_p, SIMINT_cfg, SIMINT_dropfirst = TRUE)

Arguments

SIMINT_p

list of system parameters

SIMINT_cfg

ubiquity system object

SIMINT_dropfirst

when TRUE it will drop the first sample point (prevents bolus doses from starting at 0)

Value

som

See Also

system_new_tt_rule, system_set_tt_cond and the titration vignette (vignette("Titration", package = "ubiquity"))


Simulate Individual Response

Description

Controls the execution of individual simulations with deSolve using either R scripts or loadable C libraries.

Usage

run_simulation_ubiquity(SIMINT_parameters, SIMINT_cfg, SIMINT_dropfirst = TRUE)

Arguments

SIMINT_parameters

vector of parameters

SIMINT_cfg

ubiquity system object

SIMINT_dropfirst

when TRUE it will drop the first sample point (prevents bolus doses from starting at 0)

Value

The simulation output is mapped (som) is a list. time-course is stored in the simout element.

See Also

Simulation vignette (vignette("Simulation", package = "ubiquity"))


Define Sample Times Around Events

Description

When events, such as bolus doses, are applied to the system rapid changes can occur. If the system is not sampled heavily around these times, these changes may be missed in the output profiles. Based on the total duration of the sample times, extra samples can be added near these events.

Usage

sample_around(tvals, ot, sample_delta_mult = 1e-06)

Arguments

tvals

vector of event times

ot

simualtion output times

sample_delta_mult

multiplier used to control the magnitude of spacing around and following event times

Details

For more information on setting options for population simulation see the stochastic section of the system_set_option help file.

Value

vector of event times and added samples


Run Population Simulations

Description

Used to run Population/Monte Carlo simulations with subjects generated from either provided variance/covariance information or a dataset.

Usage

simulate_subjects(
  parameters,
  cfg,
  show_progress = TRUE,
  progress_message = "Simulating Subjects:"
)

Arguments

parameters

list containing the typical value of parameters

cfg

ubiquity system object

show_progress

Boolean value controlling the display of a progress indicator (TRUE)

progress_message

text string to prepend when called from the ShinyApp

Details

Failures due to numerical instability or other integration errors will be captured within the function. Data for those subjects will be removed from the output. Their IDs will be displayed as messages and stored in the output.

For more information on setting options for population simulation see the stochastic section of the system_set_option help file.

Value

Mapped simulation output with individual predictions, individual parameters, and summary statistics of the parameters. The Vignettes below details on the format of the output.

See Also

Vignette on simulation (vignette("Simulation", package = "ubiquity")) titration (vignette("Titration", package = "ubiquity")) as well as som_to_df


Calculate Solution Statistics

Description

Attempts to determine the variance/covariance matrix, confidence intervals and CV percent for a list of parameter estimates parameters. This method was taken from the ADAPT 5 User's Guide chapter 3.

Usage

solution_statistics(parameters, cfg)

Arguments

parameters

list of parameter estimates

cfg

ubiquity system object

Details

The returned list has the following format:

Value

list containing information about the provided estimates

See Also

Vignette on estimation (vignette("Estimation", package = "ubiquity"))


Converts the Wide/Verbose Output Simulation Functions into Data Frames

Description

The functions run_simulation_ubiquity, simulate_subjects, or run_simulation_titrate provide outputs in a more structured format, but it may be useful to convert this "wide" format to a tall/skinny format.

Usage

som_to_df(cfg, som)

Arguments

cfg

ubiquity system object

som

simulation output from run_simulation_ubiquity, simulate_subjects, or run_simulation_titrate

Value

Data frame of the format:

When applied to the output of run_simulation_ubiquity or run_simulation_titrate

When applied to the output of simulate_subjects

(* - field present when titration is enabled)

See Also

run_simulation_titrate internally when running simulations.


Check For Perl and C Tools

Description

Check the local installation for perl and verify C compiler is installed and working.

Usage

system_check_requirements(
  checklist = list(perl = list(check = TRUE, perlcmd = "perl"), C = list(check = TRUE)),
  verbose = TRUE
)

Arguments

checklist

list with names corresponding to elements of the system to check.

verbose

enable verbose messaging

Value

List fn result of all packages

Examples


invisible(system_check_requirements())


Verify System Steady State

Description

Takes the ubiquity system object and other optional inputs to verify the system is running at steady state. This also provides information that can be helpful in debugging systems not running at steady state.

Usage

system_check_steady_state(
  cfg,
  parameters = NULL,
  zero_rates = TRUE,
  zero_bolus = TRUE,
  output_times = seq(0, 100, 1),
  offset_tol = .Machine$double.eps * 100,
  derivative_tol = .Machine$double.eps * 100,
  derivative_time = 0
)

Arguments

cfg

ubiquity system object

parameters

optional set of parameters (NULL) to check at steady state (if set to NULL then the parameters for the currently selected parameter set will be used)

zero_rates

Boolean value to control removing all rate inputs (TRUE)

zero_bolus

Boolean value to control removing all bolus inputs (TRUE)

output_times

sequence of output times to simulate for offset determination (seq(0,100,1))

offset_tol

maximum percent offset to be considered zero (.Machine$double.eps*100)

derivative_tol

maximum derivative value to be considered zero (.Machine$double.eps*100)

derivative_time

time to evaluate derivatives to identify deviations (0), set to NULL to skip derivative evaluation

Value

List with the following names


Clear all Cohorts

Description

Clear previously defined cohorts

Usage

system_clear_cohorts(cfg)

Arguments

cfg

ubiquity system object

Value

ubiquity system object with no cohorts defined


Define Estimation Cohort

Description

Define a cohort to include in a parameter estimation

Usage

system_define_cohort(cfg, cohort)

Arguments

cfg

ubiquity system object

cohort

list with cohort information

Details

Each cohort has a name (eg d5mpk), and the dataset containing the information for this cohort is identified (the name defined in system_load_data)

cohort = list(
  name         = "d5mpk",
  dataset      = "pm_data",
  inputs       = NULL,
  outputs      = NULL)

Next if only a portion of the dataset applies to the current cohort, you can define a filter (cf field). This will be applied to the dataset to only return values relevant to this cohort. For example, if we only want records where the column DOSE is 5 (for the 5 mpk cohort). We can use the following:

cohort[["cf"]]   = list(DOSE   = c(5))

If the dataset has the headings ID, DOSE and SEX and cohort filter had the following format:

cohort[["cf"]]   = list(ID    = c(1:4),
                        DOSE  = c(5,10),
                        SEX   = c(1))

It would be translated into the boolean filter:

(ID==1) | (ID==2) | (ID==3) | (ID==4)) & ((DOSE == 5) | (DOSE==10)) & (SEX == 1)

Optionally you may want to fix a system parameter to a different value for a given cohort. This can be done using the cohort parameter (cp) field. For example if you had the body weight defined as a system parameter (BW), and you wanted to fix the body weight to 70 for the current cohort you would do the following:

cohort[["cp"]]   = list(BW        = c(70))

Note that you can only fix parameters that are not being estimated.

By default the underlying simulation output times will be taken from the general output_times option (see system_set_option). However It may also be necessary to specify simulation output times for a specific cohort. The output_times field can be used for this. Simply provide a vector of output times:

cohort[["output_times"]]   = seq(0,100,2)

Next we define the dosing for this cohort. It is only necessary to define those inputs that are non-zero. So if the data here were generated from animals given a single 5 mpk IV at time 0. Bolus dosing is defined using <B:times> and <B:events>. If Cp is the central compartment, you would pass this information to the cohort in the following manner:

cohort[["inputs"]][["bolus"]] = list()
cohort[["inputs"]][["bolus"]][["Cp"]] = list(TIME=NULL, AMT=NULL)
cohort[["inputs"]][["bolus"]][["Cp"]][["TIME"]] = c( 0) 
cohort[["inputs"]][["bolus"]][["Cp"]][["AMT"]]  = c( 5)

Inputs can also include any infusion rates (infusion_rates) or covariates (covariates). Covariates will have the default value specified in the system file unless overwritten here. The units here are the same as those in the system file

Next we need to map the outputs in the model to the observation data in the dataset. Under the outputs field there is a field for each output. Here the field ONAME can be replaced with something more useful (like PK).

cohort[["outputs"]][["ONAME"]] = list()

If you want to further filter the dataset. Say for example you have two outputs and the cf applied above reduces your dataset down to both outputs. Here you can use the "of" field to apply an "output filter" to further filter the records down to those that apply to the current output ONAME.

cohort[["outputs"]][["ONAME"]][["of"]] = list(
       COLNAME          = c(),
       COLNAME          = c())

If you do not need further filtering of data, you can you can just omit the field.

Next you need to identify the columns in the dataset that contain your times and observations. This is found in the obs field for the current observation:

cohort[["outputs"]][["ONAME"]][["obs"]] = list(
         time           = "TIMECOL",
         value          = "OBSCOL",
         missing        = -1)

The times and observations in the dataset are found in the ’TIMECOL’ column and the ’OBSCOL’ column (optional missing data option specified by -1).

These observations in the dataset need to be mapped to the appropriate elements of your model defined in the system file. This is done with the model field:

cohort[["outputs"]][["ONAME"]][["model"]] = list(
         time           = "TS",       
         value          = "MODOUTPUT",
         variance       = "PRED^2")

First the system time scale indicated by the TS placeholder above must be specfied. The time scale must correspond to the data found in TIMECOL above. Next the model output indicated by the MODOUTPUT placeholder needs to be specified. This is defined in the system file using <O> and should correspond to OBSCOL from the dataset. Lastly the variance field specifies the variance model. You can use the keyword PRED (the model predicted output) and any variance parameters. Some examples include:

The following controls the plotting aspects associated with this output. The color, shape and line values are the values used by ggplot functions.

cohort[["outputs"]][["ONAME"]][["options"]] = list(
        marker_color   = "black",
        marker_shape   = 16,
        marker_line    = 1 )

If the cohort has multiple outputs, simply repeat the process above for the. additional cohorts. The estimation vignettes contains examples of this.

Note: Output names should be consistent between cohorts so they will be grouped together when plotting results.

Value

ubiquity system object with cohort defined

See Also

Estimation vignette (vignette("Estimation", package = "ubiquity"))


Define Cohorts from NONMEM Input File

Description

This function allows the user to define cohorts automatically from a NONMEM dataset

Usage

system_define_cohorts_nm(
  cfg,
  DS = "DSNAME",
  col_ID = "ID",
  col_CMT = "CMT",
  col_DV = "DV",
  col_TIME = "TIME",
  col_AMT = "AMT",
  col_RATE = "RATE",
  col_EVID = "EVID",
  col_GROUP = NULL,
  filter = NULL,
  INPUTS = NULL,
  OBS = NULL
)

Arguments

cfg

ubiquity system object

DS

Name of the dataset loaded using system_load_data

col_ID

Column of unique subject identifier

col_CMT

Compartment column

col_DV

Column with observations or ’.’ for input

col_TIME

Column with system time of each record

col_AMT

Infusion/dose amounts (these need to be in the same units specified in the system.txt file)

col_RATE

Rate of infusion or ’.’ for bolus

col_EVID

EVID (0 - observation, 1 dose)

col_GROUP

Column name to use for defining similar cohorts when generating figures.

filter

List used to filter the dataset or NULL if the whole dataset is to be used (see filter rules or nm_select_records or a description of how to use this option)

INPUTS

List mapping input information in the dataset to names used in the system.txt file

OBS

List mapping obseravation information in the dataset to nams used in the system.txt file

Details

NOTE: to use this function it is necessary that a timescale be define for the system time scale. For example, if the system time scale was days, something like the following is needed:

<TS:days> 1

Include all records in the dataset

filter = NULL

Include only records matching the following filter

filter = list()
filter$COLNAME = c()

Mapping information:

The inputs mapping information (INPUTMAP) is alist with a field for each type of input: input:

From a coding perspective it looks like this:

INPUTMAP = list()
INPUTMAP$bolus$SPECIES$CMT_NUM            =  1
INPUTMAP$infusion_rates$RATE$CMT_NUM      =  1
INPUTMAP$covariates$CVNAME$col_COV        = 'CNAME'

The observation mapping information (OBSMAP) is a list with elements for each output as described in for system_define_cohort. Each output is a list with the following names:

From a coding perspective it looks like this:

OBSMAP = list()
OBSMAP$ONAME=list(variance     = 'PRED^2',
                 CMT          =  1,
                 output       = '<O>',
                 missing      =  NULL )

Value

ubiquity system object with cohorts defined.

See Also

Estimation vignette (vignette("Estimation", package = "ubiquity"))


Control Estimation Process

Description

Manages the flow of parameter estimation using data specified with system_define_cohort.

Usage

system_estimate_parameters(
  cfg,
  flowctl = "plot guess",
  analysis_name = "my_analysis",
  archive_results = TRUE
)

Arguments

cfg

ubiquity system object

flowctl

string to control what the flow of the function

analysis_name

string containing the name of the analysis

archive_results

boolean variable to control whether results will be archived

Details

The flowctl argument can have the following values

Value

parameter estimates


Fetch System Timescale

Description

Reads through the system information and tries to determine the system time scale (the timescale that has a value of 1)

Usage

system_fetch_TSsys(cfg)

Arguments

cfg

ubiquity system object

Value

Name of the system timescale or NULL if it was not found


Fetch Current Parameter Guesses

Description

Fetch a list of the guesses for the current parameter set and parameters selected for estimation

Usage

system_fetch_guess(cfg)

Arguments

cfg

ubiquity system object

Value

list of current parameter gauesses


Fetch Variability Terms

Description

Extract elements of the current variance/covariance matrix specified in the system file with <IIV:?:?> ?, <IIVCOR:?:?>?, <IIVSET:?:?> ?, <IIVCORSET:?:?>?

Usage

system_fetch_iiv(cfg, IIV1, IIV2)

Arguments

cfg

ubiquity system object

IIV1

row name of the variance/covariance matrix

IIV2

column name of the variance/covariance matrix

Value

Value from the variance/covariance matrix

See Also

system_set_iiv

Examples


# Creating a system file from the mab_pk example
fr = system_new(file_name        = "system.txt", 
                system_file      = "mab_pk", 
                overwrite        = TRUE, 
                output_directory = tempdir())

# Building the system 
cfg = build_system(system_file  = file.path(tempdir(), "system.txt"),
      output_directory          = file.path(tempdir(), "output"),
      temporary_directory       = tempdir())

# Covariance term for ETACL and ETAVc
val = system_fetch_iiv(cfg, IIV1="ETACL", IIV2="ETAVc")


Fetch NCA Results

Description

Fetches the NCA summary from the ubiquity system object.

Usage

system_fetch_nca(cfg, analysis_name = "analysis")

Arguments

cfg

ubiquity system object

analysis_name

string containing the name of the NCA analysis (default 'analysis')

Value

List with a data frame of the NCA results (NCA_summary), the raw output from PKNCA (PKNCA_results), and also a list element indicating the overall success of the function call (isgood)

See Also

Vignette on NCA (vignette("NCA", package = "ubiquity"))


Columns in NCA Analysis

Description

Show the columns available in a given NCA analysis

Usage

system_fetch_nca_columns(cfg, analysis_name = "analysis")

Arguments

cfg

ubiquity system object

analysis_name

string containing the name of the NCA analysis (default 'analysis')

Value

list with the following elements:

See Also

Vignette on NCA (system_nca_parameters_meta)


Fetch System Parameters

Description

Fetch the parameters of the currently selected parameter set. To switch between parameter sets use system_select_set

Usage

system_fetch_parameters(cfg)

Arguments

cfg

ubiquity system object

Value

List of parameters for the selected parameter set

Examples


# Creating a system file from the mab_pk example
fr = system_new(file_name        = "system.txt", 
                system_file      = "mab_pk", 
                overwrite        = TRUE, 
                output_directory = tempdir())

# Building the system 
cfg = build_system(system_file  = file.path(tempdir(), "system.txt"),
      output_directory          = file.path(tempdir(), "output"),
      temporary_directory       = tempdir())

# Fetching the default parameter set
parameters = system_fetch_parameters(cfg)


Extracts the officer Object From the Specified ubiquity Report

Description

This will extract an officer object from the ubiqiuty system object for the specified report name.

Usage

system_fetch_rpt_officer_object(cfg, rptname = "default")

Arguments

cfg

ubiquity system object

rptname

ubiquity report name

Value

officer report object

See Also

system_set_rpt_officer_object


Extracts the onbrand Object From the Specified ubiquity Report

Description

This will extract an onbrand object from the ubiqiuty system object for the specified report name.

Usage

system_fetch_rpt_onbrand_object(cfg, rptname = "default")

Arguments

cfg

ubiquity system object

rptname

ubiquity report name

Value

onbrand report object

See Also

system_set_rpt_onbrand_object


Fetch Mathematical Set

Description

Fetch the elements of the specified mathematical set that was defined in the system file.

Usage

system_fetch_set(cfg, set_name = NULL)

Arguments

cfg

ubiquity system object

set_name

name of mathematical set

Value

A sequence containing the elements of the parameter set or NULL if if there was a problem.

Examples


# Creating a system file from the pbpk example
fr = system_new(file_name        = "system.txt", 
                system_file      = "pbpk", 
                overwrite        = TRUE, 
                output_directory = tempdir())

# Building the system 
cfg = build_system(system_file  = file.path(tempdir(), "system.txt"),
      output_directory          = file.path(tempdir(), "output"),
      temporary_directory       = tempdir())

# Fetching the contents of the ORG mathematical set
ORG_elements = system_fetch_set(cfg, "ORG")


Create New Analysis Template

Description

Building a system file will produce templates for R and other languages. This function provides a method to make local copies of these templates.

Usage

system_fetch_template(
  cfg,
  template = "Simulation",
  overwrite = FALSE,
  output_directory = getwd()
)

Arguments

cfg

ubiquity system object

template

template type

overwrite

if TRUE the new system file will overwrite any existing files present

output_directory

directory where workshop files will be placed (getwd())

Details

The template argument can have the following values for the R workflow:

And this will create files to use in other software:

Value

List with vectors of template sources, destinations and corresponding write success (write_file), also a list element indicating the overall success of the function call (isgood)

Examples


# Creating a system file from the mab_pk example
fr = system_new(file_name        = "system.txt", 
                system_file      = "mab_pk", 
                overwrite        = TRUE, 
                output_directory = tempdir())

# Building the system 
cfg = build_system(system_file  = file.path(tempdir(), "system.txt"),
      output_directory          = file.path(tempdir(), "output"),
      temporary_directory       = tempdir())

# Creating a simulation template
fr =  system_fetch_template(cfg, 
      template         = "Simulation", 
      output_directory = tempdir())


Initialize GLP study design

Description

Creates a new GLP study design

Usage

system_glp_init(cfg, study_title = "Study Title", study_name = "default")

Arguments

cfg

ubiquity system object

study_title

String containing descriptive information about the study

study_name

short name used to identify the study in other functions ("default")

Value

cfg ubiquity system object with the study initialized


Design GLP Study For a Scenario

Description

Identifies the top dose required in a GLP tox study in order to match human metrics (Cmax and AUCs) within a specified multiplier.

For a given set of human parameters the human doses required to hit the target Cmin and AUC (both or one) will be identified. The Cmax and AUC associated with the largest of those doses will be determined and the corresponding doses for a tox species (and provided parameters) will be determined for specific tox multipliers.

Optionally, simulations can be be run by specifying doses for either/or the human or tox species. Sample times can also be specified to generate annotated figures and tables to be given to analysts to facilitate assay design.

The system file requires the following components:

- Output for the drug concentration - Output for the cumulative AUC - Bolus dosing defined in a specific compartment - Timescale specified for the system timescale (e.g. if the timescale is hours then you need <TS> hours = 1.0)

Usage

system_glp_scenario(
  cfg,
  output_Conc = NULL,
  output_AUC = NULL,
  timescale = NULL,
  units_Conc = "",
  units_AUC = "",
  study_scenario = "Tox Study",
  human_sim_times = NULL,
  study_name = "default",
  human_parameters = NULL,
  human_bolus = NULL,
  human_ndose = 1,
  human_dose_interval = 1,
  human_Cmin = NULL,
  human_AUC = NULL,
  human_sample_interval = NULL,
  human_sim_doses = NULL,
  human_sim_samples = NULL,
  tox_species = "Tox",
  tox_sim_times = NULL,
  tox_parameters = NULL,
  tox_bolus = NULL,
  tox_ndose = 1,
  tox_dose_interval = 1,
  tox_Cmax_multiple = 10,
  tox_AUC_multiple = 10,
  tox_sample_interval = NULL,
  tox_sim_doses = NULL,
  tox_sim_samples = NULL,
  annotate_plots = TRUE
)

Arguments

cfg

ubiquity system object

output_Conc

model output specified with <O> containing the concentration associated with drug exposure.

output_AUC

model output specified with <O> containing the cumulative exposure

timescale

system timescale specified with <TS> used for AUC comparisons and plotting

units_Conc

units of concentration ('')

units_AUC

units of AUC ('')

study_scenario

string containing a descriptive name for the tox study

human_sim_times

user-specified simulation output times for humans (same timescale as the system)

study_name

name of the study to append the scenario to set with 'system_glp_init()' ('default'): When a report is initialized using system_rpt_read_template the report name is 'default' unless otherwise specified. To disable reporting set this to NULL, and to use a different report specify the name here.

human_parameters

list containing the human parameters

human_bolus

string containing the dosing state for human doses (specified with <B:?>)

human_ndose

number of human doses to simulate

human_dose_interval

dosing interval in humans (time units specified with <B:?>)

human_Cmin

target Cmin in humans (corresponding to output_Conc above)

human_AUC

target AUC in humans (corresponding to output_AUC above)

human_sample_interval

time interval in units specified by timescale above to evaluate the trough concentration and AUC (e.g c(1.99, 4.001) would consider the interval between 2 and 4)

human_sim_doses

optional list of doses into human_bolus to simulate (see Details below)

human_sim_samples

optional list of sample times in units specified by timescale above to label on plots of simulated doses (the default NULL will disable labels)

tox_species

optional name of the tox species ("Tox")

tox_sim_times

user-specified simulation output times for the tox species (same timescale as the system)

tox_parameters

list containing the parameters for the tox species

tox_bolus

string containing the dosing state for tox species doses (specified with <B:?>)

tox_ndose

number of tox doses to simulate

tox_dose_interval

dosing interval in the tox species (time units specified with <B:?>)

tox_Cmax_multiple

for each target (Cmin and AUC) the dose in the tox species will be found to cover this multiple over the projected Cmax in humans (10)

tox_AUC_multiple

for each target (Cmin and AUC) the dose in the tox species will be found to cover this multiple over the projected AUC in humans (10)

tox_sample_interval

interval to consider the AUC and Cmax for comparing the human prediction to the tox multiple

tox_sim_doses

optional list of doses into tox_bolus to simulate (see Details below)

tox_sim_samples

optional list of sample times in units specified by timescale above to label on plots of simulated doses (the default NULL will disable labels)

annotate_plots

Boolean switch to indicate if human_sim_samples and tox_sim_samples should be labeled on their respective plots (TRUE)

Details

Both human_sim_doses and tox_sim_doses are lists with names corresponding to the label of the dose. Each element has an AMT and TIME element which corresponds to the dosing times and amounts in the units specified with <B:?> in the system file.

For example if you wanted to simulate four weekly doses of 20 mg to a 70 kg person and the units of bolus doses were days and mg/kg for the times and amounts you would do the following:

 human_sim_doses = list()
 human_sim_doses[["20 mg QW"]]$TIME = c(     0,      7,     14,     21)
 human_sim_doses[["20 mg QW"]]$AMT  = c(0.2857, 0.2857, 0.2857, 0.2857)

Value

cfg ubiquity system object with the scenario added if successful


Loading Datasets

Description

Loads datasets at the scripting level from a variable if data_file is a data.frame or from the following formats (based on the file extension)

Multiple datasets can be loaded as long as they are given different names. Datasets should be in a NONMEM-ish format with the first row containing the column header names.

Usage

system_load_data(cfg, dsname, data_file, data_sheet)

Arguments

cfg

ubiquity system object

dsname

short name of the dataset to be used to link this dataset to different operations

data_file

the file name of the dataset or a data frame containing the data

data_sheet

argument identifying the name of the sheet in an excel file

Value

Ubiquity system object with the dataset loaded


Save variables to files

Description

Triggered when debugging is enabled, this function will save the contents of values to the specified file name in the ubiquity temporary directory.

Usage

system_log_debug_save(cfg, file_name = "my_file", values = NULL)

Arguments

cfg

ubiquity system object

file_name

name of the save file without the ".RData" extension

values

named list of variables to save

Value

Boolean variable indicating success

Examples


# Creating a system file from the mab_pk example
fr = system_new(file_name        = "system.txt", 
                system_file      = "mab_pk", 
                overwrite        = TRUE, 
                output_directory = tempdir())

# Building the system 
cfg = build_system(system_file  = file.path(tempdir(), "system.txt"),
      output_directory          = file.path(tempdir(), "output"),
      temporary_directory       = tempdir())

# enable debugging:
cfg=system_set_option(cfg,group = "logging", 
                         option = "debug", 
                         value  = TRUE)

# Saving the cfg variable 
system_log_debug_save(cfg, 
   file_name = 'my_file',
   values = list(cfg=cfg))



Add Log Entry

Description

Appends a specified line to the analysis log

Usage

system_log_entry(cfg, entry)

Arguments

cfg

ubiquity system object

entry

string containing the log entry

Value

Boolean variable indicating success (TRUE) or failure (FALSE)

Examples


# Creating a system file from the mab_pk example
fr = system_new(file_name        = "system.txt", 
                system_file      = "mab_pk", 
                overwrite        = TRUE, 
                output_directory = tempdir())

# Building the system 
cfg = build_system(system_file  = file.path(tempdir(), "system.txt"),
      output_directory          = file.path(tempdir(), "output"),
      temporary_directory       = tempdir())

# Initialzing the log file
system_log_entry(cfg, "Text of log entry")


Initialize System Log File

Description

Initializes the currently specified system log file.

Usage

system_log_init(cfg)

Arguments

cfg

ubiquity system object

Value

ubiquity system object with logging enabled

Examples


# Creating a system file from the mab_pk example
fr = system_new(file_name        = "system.txt", 
                system_file      = "mab_pk", 
                overwrite        = TRUE, 
                output_directory = tempdir())

# Building the system 
cfg = build_system(system_file  = file.path(tempdir(), "system.txt"),
      output_directory          = file.path(tempdir(), "output"),
      temporary_directory       = tempdir())

# Initialzing the log file
cfg = system_log_init(cfg)


List NCA parameters, text names and descriptions

Description

Provides a verbose information about NCA parameters

Usage

system_nca_parameters_meta(cfg)

Arguments

cfg

ubiquity system object

Value

List with the following elements:

See Also

Vignette on NCA (vignette("NCA", package = "ubiquity"))


Automatic NCA

Description

Performs NCA in an automated fashion

Usage

system_nca_run(
  cfg,
  dsname = "PKDS",
  dscale = 1,
  NCA_options = NULL,
  NCA_min = 4,
  analysis_name = "analysis",
  dsfilter = NULL,
  extrap_C0 = TRUE,
  extrap_N = 2,
  sparse = FALSE,
  dsmap = list(TIME = "TIME", NTIME = "NTIME", CONC = "CONC", DOSE = "DOSE", ID = "ID",
    ROUTE = "ROUTE", DOSENUM = NULL, BACKEXTRAP = NULL, SPARSEGROUP = NULL),
  dsinc = NULL
)

Arguments

cfg

ubiquity system object

dsname

name of dataset loaded with (system_load_data)

dscale

factor to multiply the dose to get it into the same units as concentration (default 1): if you are dosing in mg/kg and your concentrations is in ng/ml, then dscale = 1e6

NCA_options

specify a list of options for PKNCA to overwrite the defaults (default NULL will use defaults). For example if you want to set the maximum extrapolation of AUCinf to 10 half-life half-life of 0.8 you would use: list(max.aucinf.pext=10, min.hl.r.squared=.9)

NCA_min

minimum number of points required to perform NCA for a given subset (default 4)

analysis_name

string containing the name of the analysis (default 'analysis') to archive to files and reference results later

dsfilter

list of names corresponding to the column names in the dataset and values are a sequence indicating values to keep (default NULL. Multiple names are and-ed together. For example the following would keep all of the records where dose is 1, 2, or 5 and the dose_number is 1

 dsfilter = list(dose=c(1,2,5), dose_number = c(1))
extrap_C0

Boolean variable to enable automatic determination of initial drug concentration if no value is specified; the rules used by WinNonlin will be used:

  • If the route is "iv infusion" or "extra-vascular" and the data is single dose data, then a concentration of zero will be used. If repeat dosing is used, the minimum value from the previous dosing interval will be used.

  • If the route is "iv bolus" then log-linear regression of the number of observations specified by extrap_N will be used. If the slope of these points is positive the first positive observation will be used as an estimate of C0

extrap_N

number of points to use for back extrapolation (default 2); this number can be overwritten for each subject using the BACKEXTRAP column in the dataset

sparse

Boolean variable used to indicate data used sparse sampling and the analysis should use the average at each time point (the SPARSEGROUP column must be specified in the dsmap below)

dsmap

list with names specifying the columns in the dataset (* required):

  • TIME* Time since the first dose; "TIME" (default)

  • NTIME* Nominal time since last dose; "NTIME" (default)

  • CONC* Concentration data; "CONC" (default)

  • DOSE* Dose given; ("DOSE" (default)

  • ID* Subject ID; ("ID" (default)

  • ROUTE* Route of administration; "ROUTE" (default), can be either "iv bolus", "iv infusion" or "extra-vascular". Variants such as "IV_bolus" and "extravascular" should work as well.

  • DOSENUM Numeric dose (starting at 1) used for grouping multiple dose data; optional, NULL (default) for single dose data)

  • BACKEXTRAP Specifying the number of points to use to extrapolate the initial concentration for "iv bolus" dosing; optoinal f NULL (default) will use the value defined in extrap_N (note this value must be <= NCA_min)

  • SPARSEGROUP Column containing a unique value grouping cohorts for pooling data. Needed when sparse is set to TRUE; optional, NULL (default)

dsinc

(NOT CURRENTLY IMPLEMENTED) optional character vector of columns from the dataset to include in the output summary (default NULL)

Value

cfg ubiquity system object with the NCA results and if the analysis name is specified:

See Also

Vignette on NCA (vignette("NCA", package = "ubiquity"))


Summarize NCA Results in Tabular Format

Description

Creates tabular summaries of NCA results

Usage

system_nca_summary(
  cfg,
  analysis_name = "analysis",
  treat_as_factor = c("ID", "Dose_Number", "Dose"),
  params_include = c("ID", "cmax", "tmax", "auclast"),
  params_header = NULL,
  rptname = "default",
  label_format = NULL,
  summary_stats = NULL,
  summary_labels = list(MEAN = "Mean", STD = "Std Dev", MEDIAN = "Median", N = "N obs",
    SE = "Std Err."),
  summary_location = NULL,
  ds_wrangle = NULL,
  digits = 3,
  table_theme = "theme_zebra"
)

Arguments

cfg

ubiquity system object

analysis_name

string containing the name of the analysis (default 'analysis') that was previously run

treat_as_factor

sequence of column names to be treated as factors (default c("ID", "Dose_Number", "Dose")). Use this to report values without added decimals.

params_include

vector with names of parameters to include (default c("ID", "cmax", "tmax", "auclast"))

params_header

list with names of parameters followed by a vector of headers. You can use the placeholder "<label>" to include the standard label (e.g. list(cmax=c("<label>", "(ng/ml)"))), with a default of NULL.

rptname

report name (either PowerPoint or Word) that this table will be used in ("default")

label_format

string containing the format in which headers and labels are being specified, either "text", or "md" (default NULL assumes "text" format)

summary_stats

list with strings as names containing placeholders for summary statistics and the values indicate the parameters to apply those statistics to. for example, if you want to calculate mean and standard deviation of AUClast you could use list("<MEAN> (<STD>)"=c("auclast"). This would create a row at the bottom of the table with this information for just the listed parameters. To split this up across two rows just do the following: list("<MEAN>"=c("auclast"), "<STD>"=c("auclast")). Any NA values will be ignored when calculating statistics. The allowed summary statistics are the mean (<MEAN>), median (<MEDIAN>), standard deviation (<STD>), standard error (<SE>), and the number of observations used to calculate statistics. (<N>). The default value of NULL prevents any summary statistics from being included.

summary_labels

list containing the mapping of summary statistics defined by summary_stats with their text labels in the output tables:

list(MEAN   = "Mean", 
     STD    = "Std Dev", 
     MEDIAN = "Median", 
     N      = "N obs", 
     SE     = "Std Err.")
summary_location

column where to put the labels (e.g. Mean (Std)) for summary statistic. The default (NULL) will leave these labels off. If you set this to the "ID" column it will put them under the subject IDs.

ds_wrangle
 ds_wrangle = list(Dose=c(30), Dose_Number = c(1))
digits

number of significant digits to report (3) or NULL to prevent rounding

table_theme

flextable theme see the flextable package for available themes, and set to NULL to prevent themes from being applied. (default="theme_zebra")

Value

list with the following elements

See Also

Vignette on NCA (vignette("NCA", package = "ubiquity"))


Create New system.txt File

Description

Copy a blank template (system_file="template") file to the working directory or an example by specifying the following:

Usage

system_new(
  file_name = "system.txt",
  system_file = "template",
  overwrite = FALSE,
  output_directory = getwd()
)

Arguments

file_name

name of the new file to create

system_file

name of the system file to copy

overwrite

if TRUE the new system file will overwrite any existing files present

output_directory

getwd() directory where system file will be placed

Details

References

Value

TRUE if the new file was created and FALSE otherwise

Examples


# To create an example system file named example_system.txt:
system_new(system_file      = "mab_pk", 
           file_name        = "system_example.txt", 
           overwrite        = TRUE,  
           output_directory = tempdir())


Fetch List of Available System Templates

Description

Returns a list of internal templates with descriptions of their contents and file locations

Usage

system_new_list()

Value

list with the template names as the keys

Examples

# To get a list of systems
systems = system_new_list()

Titration Rules

Description

Defines a new titration rule and the times when that rule is evaluated

Usage

system_new_tt_rule(cfg, name, times, timescale)

Arguments

cfg

ubiquity system object

name

name for the titration rule

times

list of times when the rule will be evaluated

timescale

time scale associated with the titration times (as defined by <TS:?>)

Details

cfg = system_new_tt_rule(cfg,
                        name      = "rname",
                        times     = c(0, 2, 4),
                        timescale = "weeks")'

A titration rule identifies a set of times (times) and an associated time scale (timescale) in which titration events can potentially occur. Any times scale, as defined in the system file with <TS:?>, can be used in place of "weeks" above. The name, "rname" above, is used to link the titration rule to different conditions discussed below. The name should be a string beginning with a letter, and it can contain any combination of numbers, letters, and underscores. With the rule created we can then add conditions to that rule.'

Value

Ubiquity system object with the titration rule created

See Also

system_set_tt_cond, run_simulation_titrate


Check NONMEM Dataset for Automatic Definitions

Description

Checks the dataset against the information specified by system_define_cohorts_nm for validity

Usage

system_nm_check_ds(
  cfg,
  DS = "DSNAME",
  col_ID = "ID",
  col_CMT = "CMT",
  col_DV = "DV",
  col_TIME = "TIME",
  col_AMT = "AMT",
  col_RATE = "RATE",
  col_EVID = "EVID",
  col_GROUP = NULL,
  filter = NULL,
  INPUTS = NULL,
  OBS = NULL
)

Arguments

cfg

ubiquity system object

DS

Name of the dataset loaded using system_load_data

col_ID

Column of unique subject identifier

col_CMT

Compartment column

col_DV

Column with observations or ’.’ for input

col_TIME

Column with system time of each record

col_AMT

Infusion/dose amounts (these need to be in the same units specified in the system.txt file)

col_RATE

Rate of infusion or ’.’ for bolus

col_EVID

EVID (0 - observation, 1 dose)

col_GROUP

Column name to use for defining similar cohorts when generating figures.

filter

List used to filter the dataset or NULL if the whole dataset is to be used (see filter rules or nm_select_records or a description of how to use this option)

INPUTS

List mapping input information in the dataset to names used in the system.txt file

OBS

List mapping obseravation information in the dataset to names used in the system.txt file

Value

list with the following elements


General Observation Details Function

Description

Used to calculate observation details based on cohorts created with system_define_cohort

Usage

system_od_general(pest, cfg, estimation = TRUE, details = FALSE)

Arguments

pest

vector of parameters to be estimated

cfg

ubiquity system object

estimation

TRUE when called during an estimation and FALSE when called to test objective function or generate observation information for plotting

details

TRUE to display information about cohorts as they are simulated (useful for debugging when passed through system_simulate_estimation_results)

Value

If estimation is TRUE then the output is a matrix of observation details of the format:

od$pred  = [TIME, OBS, PRED, VAR, OUTPUT, COHORT] 

The values are the observed (OBS) data, predicted values (PRED) and variance (VAR) at the given TIME. The columns OUTPUT and COHORT can be used for sorting. These should be unique numbers.

When estimation is FALSE we output od$pred is a data frame with the following headings:

od$pred  = [TIME, OBS, PRED, VAR, SMOOTH, OUTPUT, COHORT] 

The TIME, OBS, PRED and VAR are the same as those listed above. The SMOOTH variable is FALSE for rows that correspond to records in the dataset and TRUE when the PRED represents the smooth predictions. The OUTPUT and COHORT columns here are text values used when defining the cohorts.

Also the od$all list item is created with all of the simulation information stored for each cohort:

od$all = [ts.time, ts.ts1, ... ts.tsn, pred, name, cohort]

Lastly the field isgood will be set to FALSE if any problems are encountered, and TRUE if everything worked.

od$isgood = TRUE

See Also

system_define_cohort and system_simulate_estimation_results


Plot Estimation Results

Description

Generates figures for each cohort/output for a given set of parameter estimates.

Usage

system_plot_cohorts(
  erp,
  plot_opts = c(),
  cfg,
  analysis_name = "analysis",
  archive_results = TRUE,
  prefix = NULL
)

Arguments

erp

output from system_simulate_estimation_results

plot_opts

list controling how predictions and data are overlaid

cfg

ubiquity system object

analysis_name

string containing the name of the analysis

archive_results

boolean variable to control whether results will be archived

prefix

depreciated input mapped to analysis_name

Details

The general format for a plot option for a given output (OUTPUT) is:

plot_opts$outputs$OUTPUTt$option = value

The following options are:

It is also possible to control the height and width of the time course tc and observed vs predicted op file by specifying the following in the default units of ggsave.

To control the figures that are generated you can set the purpose to either "print", "present" (default) or "shiny".

plot_opts$purpose = "present"

Value

List of plot outputs containing two elements timecourse and obs_pred, for the time course of and observed vs predicted, respectively. Both of these fields contain three elements for a given output. For example, say there is an output named PK the both the timecourse and obs_pred elements will have a field named PK containing a ggplot object and two fields PK_png and PK_pdf containing the paths to the files containing that figure in the respective formats.

See Also

The estimation vignette (vignette("Estimation", package = "ubiquity"))


Require Suggested Packages

Description

Used to ensure packages are loaded as they are needed for the stand alone distribution of ubiquity. If the ubiquity package is being used this function simply returns 'TRUE' if the packages are installed and FALSE if if not.

Usage

system_req(pkgs)

Arguments

pkgs

character vector of package names to check

Value

Boolean result of the loaded (stand alone) or installed (package) status for all of the packages


Adds Content to a Word Report

Description

Appends content to an open ubiquity Word report.

Usage

system_rpt_add_doc_content(
  cfg,
  type = NULL,
  content = NULL,
  rptname = "default"
)

Arguments

cfg

ubiquity system object

type

Type of content to add. See the onbrand function report_add_doc_content for the allowed content types.

content

List with content to add to the report. See the onbrand function report_add_doc_content format of this list.

rptname

Report name

Value

ubiquity system object with the content added to the specified report

See Also

report_add_doc_content and Reporting vignette (vignette("Reporting", package = "ubiquity"))


Add Slide to a Powerpoint Report

Description

Adds a slide to a ubiquity report.

Usage

system_rpt_add_slide(
  cfg,
  template = NULL,
  elements = NULL,
  rptname = "default"
)

Arguments

cfg

ubiquity system object

template

Name of slide template to use

elements

List with content to populate placeholders in the slide. See the onbrand functions report_add_slide and add_pptx_ph_content for details on the expected format of this list.

rptname

Report name

Value

ubiquity system object with the slide added to the specified report

See Also

report_add_slide, add_pptx_ph_content, and Reporting vignette (vignette("Reporting", package = "ubiquity"))


Generate a Report from Parameter Estimation

Description

This will take the output generated during a parameter estimation and append those results to a specified report.

Usage

system_rpt_estimation(cfg, rptname = "default", analysis_name = NULL)

Arguments

cfg

ubiquity system object

rptname

report name ("default")

analysis_name

string containing the name of the estimation analysis and used as a prefix to store the results

Value

ubiquity system object with estimation report appended

See Also

system_rpt_read_template, the reporting vignette (vignette("Reporting", package = "ubiquity")) and the estimation vignette (vignette("Estimation", package = "ubiquity"))


Report NCA

Description

Appends the results of NCA to a report

Usage

system_rpt_nca(
  cfg,
  rptname = "default",
  analysis_name = "analysis",
  rows_max = 10,
  table_headers = TRUE
)

Arguments

cfg

ubiquity system object

rptname

report name (either PowerPoint or Word)

analysis_name

string containing the name of the NCA analysis (default 'analysis')

rows_max

maximum number of rows per slide when generating tabular data

table_headers

Boolean variable to add descriptive headers to output tables (default TRUE)

Value

cfg ubiquity system object with the NCA results appended to the specified report and if the analysis name is specified:

See Also

Vignette on NCA (vignette("NCA", package = "ubiquity"))


Initialize a New Report

Description

Creates a new officer report based either on the ubiquity template or one specified by the user. Once created, content can then be added.

Usage

system_rpt_read_template(
  cfg,
  template = "PowerPoint",
  mapping = NULL,
  rptname = "default"
)

Arguments

cfg

ubiquity system object

template

Type of internal template to use ("PowerPoint" or "Word") or path to template file.

mapping

Path to an onbrand yaml mapping file: If an internal ubiquity template has been supplied, this argument will be ignored and the yaml file from ubiquity will be used.

rptname

report name

Details

The 'template' and 'mapping' inputs can specify either the internal ubiquity templates or user-defined templates If you specify 'template' values of 'PowerPoint' or 'Word' then the internal ubiquity templates for PowerPoint or Word will be used and the mapping information will be ignored.

If templates other than the values above are specified you will need also supply a yaml mapping file for an 'onbrand' reporting template. The vignette below highlights how to go about creating these files.

Value

ubiquity system object with and empty report initialized

See Also

Reporting vignette (vignette("Reporting", package = "ubiquity"))

Custom Office Template vignette (vignette("Custom_Office_Templates", package="onbrand"))


Save Report to a File

Description

Saves a ubiquity report to the specified file.

Usage

system_rpt_save_report(cfg, output_file = NULL, rptname = "default")

Arguments

cfg

ubiquity system object

output_file

File to save the report to (must be either .pptx or .docx depending on the type of report)

rptname

ubiquity report name

Value

list with the follwoing elements

See Also

Reporting vignette (vignette("Reporting", package = "ubiquity"))


Generate Details about Report Template

Description

Wrapper for the onbrand::template_details function, see the help for that function for more information

Usage

system_rpt_template_details(cfg, rptname = "default")

Arguments

cfg

ubiquity system object

rptname

Report name

Value

list with template information, see template_details for information on the structure of this list.

See Also

template_details and Reporting vignette (vignette("Reporting", package = "ubiquity"))


Selecting Parameter Sets

Description

The system file can contain multiple parameterizations using the <PSET:?:?>? notation. This function provides the means for switching between these parameterizations, and (optionally) specifying a subset of parameters estimated when performing parameter estimation.

Usage

system_select_set(cfg, set_name = "default", parameter_names = NULL)

Arguments

cfg

ubiquity system object

set_name

string containing the name of the parameter set

parameter_names

list of parameter names to be estimated

Value

Ubiquity system object with the specified parameter set active

Examples


# Creating a system file from the mab_pk example
fr = system_new(file_name        = "system.txt", 
                system_file      = "mab_pk", 
                overwrite        = TRUE, 
                output_directory = tempdir())

# Building the system 
cfg = build_system(system_file  = file.path(tempdir(), "system.txt"),
      output_directory          = file.path(tempdir(), "output"),
      temporary_directory       = tempdir())

# Selecting the default parameter set
cfg = system_select_set(cfg, "default")


Set Bolus Inputs

Description

Defines infusion rates specified in the system file using <B:times> and <B:events>

Usage

system_set_bolus(cfg, state, times, values)

Arguments

cfg

ubiquity system object

state

name of the state to apply the bolus

times

list of injection times

values

corresponding list injection values

Value

Ubiquity system object with the bolus information set

See Also

system_zero_inputs

Examples


# Creating a system file from the mab_pk example
fr = system_new(file_name        = "system.txt", 
                system_file      = "mab_pk", 
                overwrite        = TRUE, 
                output_directory = tempdir())

# Building the system 
cfg = build_system(system_file  = file.path(tempdir(), "system.txt"),
      output_directory          = file.path(tempdir(), "output"),
      temporary_directory       = tempdir())

# Clearing all inputs
cfg = system_zero_inputs(cfg)

# SC dose of 200 mg
cfg = system_set_bolus(cfg, state   ="At", 
                            times   = c(  0.0),  #  day
                            values  = c(200.0))  #  mg


Set Covariate Values

Description

Covariates specified in the system file using <CV:?> and <CVSET:?:?> will have their default values for a given parameter set. This function is a means to overwrite those values.

Usage

system_set_covariate(cfg, covariate, times, values)

Arguments

cfg

ubiquity system object

covariate

name of the covariate

times

list of times (system time units)

values

corresponding list of values

Value

Ubiquity system object with the covariate set

Examples


# Creating a system file from the mab_pk example
fr = system_new(file_name        = "system.txt", 
                system_file      = "mab_pk", 
                overwrite        = TRUE, 
                output_directory = tempdir())

# Building the system 
cfg = build_system(system_file  = file.path(tempdir(), "system.txt"),
      output_directory          = file.path(tempdir(), "output"),
      temporary_directory       = tempdir())

# Setting the covariate WT to 50
cfg = system_set_covariate(cfg, 
                           covariate = "WT",
                           times     = c(0), 
                           values    = c(50))


Alter Initial Guess and Parameter Bounds

Description

Default values for parameters are taken from the system.txt file either when the parameter was defined (<P>) or when it was reassigned for a parameter set (<PSET:?:?>?). These can be altered at the scripting level using this function.

Usage

system_set_guess(cfg, pname, value, lb = NULL, ub = NULL)

Arguments

cfg

ubiquity system object

pname

name of parameter to set

value

value to assign

lb

optionally change the lower bound (NULL)

ub

optionally change the upper bound (NULL)

Details

When performing a parameter estimation, the initial guess will be the value specified in the system.txt file for the currently selected parameter set. The following command can be used after the parameter set has been selected to specify the value (VALUE) of the parameter PNAME and optionally the lower (lb) and upper (ub) bounds:

cfg = system_set_guess(cfg, pname="PNAME", value=VALUE, lb=NULL, ub=NULL)

To set the initial guess for the parameter Vc to a value of 3, the following would be used:

cfg = system_set_guess(cfg, "Vc", value=3)

To specify the guess and overwrite the upper bound on Vc and set it to 5

cfg = system_set_guess(cfg, "Vc", value=3, ub=5) 

Value

cfg ubiquity system object with guess and bounds assigned


Set Variability Terms

Description

Set elements of the current variance covariance matrix specified in the system file with <IIV:?:?> ?, <IIVCOR:?:?>?, <IIVSET:?:?> ?, <IIVCORSET:?:?>?

Usage

system_set_iiv(cfg, IIV1, IIV2, value)

Arguments

cfg

ubiquity system object

IIV1

row name of the variance/covariance matrix

IIV2

column name of the variance/covariance matrix element

value

value to assign to the variance/covariance matrix element

Value

Ubiquity system object with IIV information set

See Also

system_fetch_iiv

Examples


# Creating a system file from the mab_pk example
fr = system_new(file_name        = "system.txt", 
                system_file      = "mab_pk", 
                overwrite        = TRUE, 
                output_directory = tempdir())

# Building the system 
cfg = build_system(system_file  = file.path(tempdir(), "system.txt"),
      output_directory          = file.path(tempdir(), "output"),
      temporary_directory       = tempdir())

# Clearing all inputs
cfg = system_zero_inputs(cfg)

# Setting the covariance element for CL and Vc to 0.03
cfg = system_set_iiv(cfg,
                     IIV1 = "ETACL",
                     IIV2 = "ETAVc",
                     value=0.03)


Setting Analysis Options

Description

Different options associated performing analyses (e.g running simulations, performing parameter estimation, logging, etc.) can be set with this function

Usage

system_set_option(cfg, group, option, value)

Arguments

cfg

ubiquity system object

group

options are grouped together by the underlying activity being performed: "estimation", "general", "logging", "simulation", "solver", "stochastic", or "titration"

option

for each group there are a set of options

value

corresponding value for the option

Details

group="estimation"

The default estimation in R is performed using either the optim or optimx libraries. This is selected by setting the optimizer option:

cfg = system_set_option(cfg, 
                       group  = "estimation",
                       option = "optimizer",
                       value  = "optim")

The optimization routine then specified using the method. By default this option is set to Nelder-Mead.

cfg = system_set_option(cfg, 
                       group  = "estimation",
                       option = "method",
                       value  = "Nelder-Mead")

And different attributes are then selected using the control.

cfg = system_set_option(cfg, 
                       group  = "estimation",
                       option = "control",
                       value  = list(trace  = TRUE,
                                     maxit  = 500,
                                     REPORT = 10))

For the different methods and control options, see the documentation for the optim and optimx libraries.

To perform a global optimization you can install either the particle swarm (pso) genetic algorithm (GA) libraries. To use the particle swarm set the optimizer and method:

cfg = system_set_option(cfg, 
                       group  = "estimation",
                       option = "optimizer",
                       value  = "pso")

cfg = system_set_option(cfg, 
                       group  = "estimation",
                       option = "method",
                       value  = "psoptim")

The control option is a list described pso documentation.

To use the genetic algorithm set the optimizer and method:

cfg = system_set_option(cfg, 
                       group  = "estimation",
                       option = "optimizer",
                       value  = "ga")

cfg = system_set_option(cfg, 
                       group  = "estimation",
                       option = "method",
                       value  = "ga")

The control option is a list and the list elements are the named options in the GA documentation. Use the following as an example:

cfg = system_set_option(cfg, 
                       group  = "estimation",
                       option = "control",
                       value  = list(maxiter  = 10000,
                                    optimArgs = list(
                                      method  = "Nelder-Mead",
                                      maxiter = 1000)))

To alter initial guesses see: system_set_guess

When performing parameter estimation, the internal function system_od_general is used. This is the function that simulates your system at the conditions defined for the different cohorts. This is pretty flexible but if you want to go beyond this you can set the observation_function option:

cfg = system_set_option(cfg, 
                       group  = "estimation",
                       option = "observation_function",
                       value  = "my_od")

That will instruct the optimziation routines to use the user defined function my_od. You will need to construct that function to have the same input/output format as system_od_general.

group=general

group=logging

By default ubiquity prints different information to the console and logs this information to a log file. The following options can be used to control this behavior:

To enable debugging of different functions (like when performing esitmation), set the debug option to TRUE. Important function calls will be trapped and information will be logged and reported to the console.

cfg = system_set_option(cfg, 
                       group  = "estimation",
                       option = "debug",
                       value  = FALSE)

group="simulation"

group=solver

Depending on the solver, different options can be set. The documentation for deSolve lists the different solvers. For a full list of options, see the documentation for the specific solver (e.g. ?lsoda). Some common options to consider are:

To select the vode solver and set the maximum step size to 0.01, the following would be used:

cfg=system_set_option(cfg,
                     group  = "simulation",
                     option = "solver", 
                     value  = "vode")

cfg=system_set_option(cfg,
                     group  = "solver",
                     option = "hmax", 
                     value  = 0.01)

group="stochastic"

When running stochastic simulations (inter-individual variability applied to system parameters) it can be useful to specify the following:

If you wanted to generate 1000 subjects but only wanted the parameters, you would use the following:

cfg = system_set_option(cfg,
                       group  = "stochastic", 
                       option = "nsub ",
                       value  = 1000)

cfg = system_set_option(cfg,
                       group  = "stochastic", 
                       option = "ponly",
                       value  = TRUE )

If you wanted to exclude both states and secondary parameters, while only including the output Cp_nM, you would do the following:


cfg = system_set_option (cfg, 
                        group  = "stochastic",
                        option = "ssp",
                        value  = list())

cfg = system_set_option (cfg, 
                        group  = "stochastic",
                        option = "states",
                        value  = list())

cfg = system_set_option (cfg, 
                        group  = "stochastic",
                        option = "outputs",
                        value  = c("Cp_nM")) 

To pull subject information from a data file instead of generating the subject parameters from IIV information the sub_file option can be used. The value here SUBFILE_NAME is the name given to a dataset loaded with (system_load_data):

cfg=system_set_option(cfg, 
                     group  = "stochastic",
                     option = "sub_file",
                     value  = "SUBFILE_NAME")

Sampling from the dataset can be controlled using the sub_file_sample option:

cfg=system_set_option(cfg, 
                     group  = "stochastic",
                     option = "sub_file_sample",
                     value  = "with replacement")

Sampling can be done sequentially ("sequential"), with replacement ("with replacement"), or without replacement ("without replacement")

group="titration"

"titrate" - By default titration is disable (set to FALSE). If you are going to use titration, enable it here by setting this option to TRUE. This will force #' simulate_subjects to use run_simulation_titrate internally when running simulations.

Value

Ubiquity system object with the option set


Set Value for Parameter

Description

Assigns a value for a named parameter in a parameter list.

Usage

system_set_parameter(cfg, parameters, pname, value)

Arguments

cfg

ubiquity system object

parameters

vector of parameters

pname

parameter name

value

value

Details

To set the parameter Vc to a value of 3, the following would be used:

parameters = system_fetch_parameters(cfg) 
parameters = system_set_parameter(cfg, parameters, pname = 'Vc', value = 3) 

Value

parameters vector with pname set to value


Set Infusion Rate Inputs

Description

Defines infusion rates specified in the system file using <R:?>

Usage

system_set_rate(cfg, rate, times, levels)

Arguments

cfg

ubiquity system object

rate

name of infusion rate

times

list of time values

levels

corresponding list of infusion values

Value

Ubiquity system object with the infusion rate set

See Also

system_zero_inputs

Examples


# Creating a system file from the mab_pk example
fr = system_new(file_name        = "system.txt", 
                system_file      = "mab_pk", 
                overwrite        = TRUE, 
                output_directory = tempdir())

# Building the system 
cfg = build_system(system_file  = file.path(tempdir(), "system.txt"),
      output_directory          = file.path(tempdir(), "output"),
      temporary_directory       = tempdir())

# Clearing all inputs
cfg = system_zero_inputs(cfg)

# 5 minute infusion at 10 mg/min
cfg = system_set_rate(cfg,
           rate   = "Dinf",
           times  = c(0,  5), 
           levels = c(10, 0))


Sets the officer Object for the Specified ubiquity Report

Description

This will replace the officer object in the ubiqiuty system object for the specified report name with the value supplied.

Usage

system_set_rpt_officer_object(cfg, rpt = NULL, rptname = "default")

Arguments

cfg

ubiquity system object

rpt

officer report object

rptname

ubiquity report name

Value

ubiquity system object with the replaced officer object

See Also

system_fetch_rpt_officer_object


Sets the onbrand Object for the Specified ubiquity Report

Description

This will reset the onbrand object in the ubiqiuty system object for the specified report name.

Usage

system_set_rpt_onbrand_object(cfg, obnd = NULL, rptname = "default")

Arguments

cfg

ubiquity system object

obnd

onbrand report object

rptname

ubiquity report name

Value

ubiquity system object with onbrand report set

See Also

system_fetch_rpt_onbrand_object


Actual Function Called by SI_TT_BOLUS

Description

The prototype function SI_TT_BOLUS provides an interface to this function. Based on the input from SI_TT_BOLUS bolus inputs will be updated for the current titration time.

Usage

system_set_tt_bolus(
  cfg,
  state,
  values,
  times,
  tt_ts,
  tsinfo,
  repdose = "none",
  interval = 1,
  number = 0
)

Arguments

cfg

ubiquity system object

state

dosing state/compartment (Defined in <B:events>)

values

vector of dosing amounts (in dosing units defined by <B:events>)

times

vector of dosing times relative to the current titration time (in # time units defiend by <B:times>)

tt_ts

list of timescale values for the current titration time

tsinfo

list with timescale information for inputs (bolus, rates, etc)

repdose

"none", "last", "all"

interval

interval to repeat in the units defined in <B:times>

number

number of times to repeat

Value

ubiquity system object with the bolus dosing updated.


Define Titration Triggers and Actions

Description

Once a rule has been defined using system_new_tt_rule, it can then be used by specifying checks at each of the titration time points that, when true, will perform some actions.

Usage

system_set_tt_cond(cfg, name, cond, action, value = "-1")

Arguments

cfg

ubiquity system object

name

string containing the name for the titration rule to which this condition applies

cond

string that evaluates a boolean value that is TRUE when the action should be triggered

action

stringing that evaluates to what should be done when the condition is met (e.g. changing the dose, state change, etc)

value

code to be stored in the titration history to track when this condition has been triggered

Details

The general syntax for setting a new condition is:

cfg = system_new_tt_cond(cfg,
                        name   = "rname",
                        cond   = "BOOLEAN EXPRESSION",
                        action = "EXPRESSION",
                        value  = "VALUE")

The name input will associate this condition with a previously defined rule. For each time defined when the rule was created, the condition (cond) will be evaluated. If that condition evaluates as TRUE then the action will be evaluated. Lastly, when a condition action is evaluated, the value is stored in the titration history.

Multiple conditions can be associated with a rule. The internal titration history will track each one where a condition has been evaluated as true, but the simulation output will only show the last condition to be evaluated as true.

The cond field is a string that, when evaluated, will produce a boolean value (TRUE or FALSE). If you simply want to force an action at each of the times for a given rule you can use: cond = "TRUE". Alternatively you can provide mathematical expressions or even complicated user defined functions.

The action field is evaluated when cond is true. To modify how a simulation is going to be performed, you will want to modify the SIMINT_cfgtt variable using the different system commands. Certain common tasks have prototype functions created to make it easier for the user:

Note: Protype functions are strings but sometimes it is necessary to specify strings within this string. For the main string use double quotes (") and for the internal strings use single quotes (')

SI_TT_BOLUS

The simplest way to apply a bolus when the condition is true is to use the following:

action = "SI_TT_BOLUS[state=’At’, 
                     values=c(10, 10, 10), 
                     times=c(0, 1, 2)]"

The values and times are vectors of numbers of equal length. The dosing and time units are those specified in the system.txt file for the <B:?> delimiter. The times are relative to the titration time. So 0 above means at the titration time.

It’s possible to specify an interval and a number of times to repeat the last dose using the following:

action = "SI_TT_BOLUS[state    = ’At’, 
                     values   = c(5, 5, 10), 
                     times    = c(0, 2, 4), 
                     repdose  = ’last’, 
                     number   = 7, 
                     interval = 4]"

This will give a dose of 5 at the titration point and 2 time units later. The dose of 10 at time 4 will be repeated 7 times every 4 time units. So a total of 8 (7 + 1) doses at 10 will be administered. Remember the time units were those defined in <B:?>. The input repdose can be either ’last’ or ’none’.

Note: The main string is in double quotes " " but the strings in the protype argument (e.g. ’last’) are in single quotes ’ ’.

SI_TT_RATE

If you created an infusion named Dinf using <R:?> and the infusion units are min (times) and mg/min (rates). To have a 60 minute infusion of 20 mg/min then we would do the following:

action = "SI_TT_RATE[rate=’Dinf’, times=c(0, 60), levels=c(20.0, 0)]"

If we wanted to do this every day for 9 more days (a total of 10 days) we can repeat the sequence:

action = "SI_TT_RATE[rate     = ’Dinf’, 
                    times    = c(0, 60), 
                    levels   = c(20, 0), 
                    repdose  = ’sequence’, 
                    number   = 9, 
                    interval = 24*60]"

The input repdose can be either ’sequence’ or ’none’.

Note: The time units and dosing rate are those specified using <R:?>.

SI_TT_STATE

To provide fine control over states at titration points the state reset prototype is provided. For example, if you are modeling an assay where there is a wash step and you want to drop a concentration to zero. If you have a state named Cc defined in your system.txt and you want to set it to 0.0 in a condition the following action would work.

action = "SI_TT_STATE[Cc][0.0]"

The value here is a number but you can use any mathematical combination of variables available in the titration environment. Also you can create your own user function and place the function call within the brackets above.

Titration Environment

The cond, action, and value statements can use any variables available in the titration environment. If you want to perform complicated actions, you can simply create a user defined functions and pass it the variables from the titration environment that you need. These include named variables from the model as well as internal variables used to control the titration.

States and Parameters

System parameters (<P>), static secondary parameters (<As>) and the initial value of covariates are available. Also the state values (at the current titration time) can be used. These are all available as the names specified in the system.txt file. Since system resets (SI_TT_STATE) are processed first, any changes made to states are the values that are active for other actions.

Internal Simulation Variables

Internal variables are used to control titration activities. These variables can also be used in the conditions and actions.

Individual Simulations

To run an individual titration simulation use the following:

som = run_simulation_titrate(parameters, cfg)

This provides the same output as run_simulation_ubiquity with two extra fields. The first, som$titration, contains three columns for each titration rule. The columns will have a length equal and corresponding to the simulation times. If the rule name is rname, then the column headers will have the following names and meanings:

The second field is som$titration_history which contains a summary list of all of the titration events that were triggered.

To convert this structured list into a data frame the som_to_df command can be used:

sdf = som_to_df(cfg, som)

To run stochastic titration simulations, the same function is used:

som = simulate_subjects(parameters, cfg)

This will add a data a list element called som$titration with three fields for each titration rule:

Each of these fields is a matrix with an entry for each simulation time (column) and each subject (row). This data structure can also be converted to a data frame using som_to_df.

Value

Ubiquity system object with the titration condition defined

See Also

system_new_tt_rule, run_simulation_titrate, som_to_df, simulate_subjects


Actual Function Called by SI_TT_RATE

Description

The prototype function SI_TT_RATE provides an abstract interface to this function. Based on the input from SI_TT_RATE infusion rate inputs will be updated for the current titration time.

Usage

system_set_tt_rate(
  cfg,
  rate,
  times,
  levels,
  tt_ts,
  tsinfo,
  repdose = "none",
  interval = 1,
  number = 0
)

Arguments

cfg

ubiquity system object

rate

name of the infusion rate to update(Defined in <R:?>)

times

vector of switching times relative to the current titration time (in time units defined by <R:?>)

levels

vector of infusion rates (in dosing units defined by <R:?>)

tt_ts

list of timescale values for the current titration time

tsinfo

list with timescale information for inputs (bolus, rates, etc)

repdose

"none" or "sequence"

interval

interval to repeat in the units defined in <R:?>

number

number of times to repeat

Value

ubiquity system object with the infusion rates updated.


Simulate Results at Estimates

Description

Simulates the system at the parameter estimates pest for creating diagnostic plots

Usage

system_simulate_estimation_results(pest, cfg, details = FALSE)

Arguments

pest

vector of parameters

cfg

ubiquity system object

details

set TRUE to display information about cohorts as they are simulated (useful for debugging)

Value

observations in a list, see system_od_general when estimation=FALSE

See Also

system_define_cohort, system_plot_cohorts and the vignette on parameter estimation (vignette("Estimation", package = "ubiquity"))


Convert Time in Timescale to Simulation Time

Description

converts a time specified in a defined timescale (say weeks) to the timescale of the simulation (say hours if the rates are in 1/hr units)

Usage

system_ts_to_simtime(cfg, tstime, ts)

Arguments

cfg

ubiquity system object

tstime

numeric time of the timescale

ts

string containing the timescale

Value

tstime in the system timescale units


View Information About the System

Description

Displays information (dosing, simulation options, covariates, etc) about the system.

Usage

system_view(cfg, field = "all", verbose = FALSE)

Arguments

cfg

ubiquity system object

field

string indicating the aspect of the system to display

verbose

Boolean variable that when set to true will echo the information to the screen

Value

sequence of strings with system in formation (one line per element)

The field

Examples

# To log and display the current system information:

# Creating a system file from the mab_pk example
fr = system_new(file_name        = "system.txt", 
                system_file      = "mab_pk", 
                overwrite        = TRUE, 
                output_directory = tempdir())

# Building the system 
cfg = build_system(system_file  = file.path(tempdir(), "system.txt"),
      output_directory          = file.path(tempdir(), "output"),
      temporary_directory       = tempdir())

  msgs = system_view(cfg, verbose=TRUE)


Zero All Model Inputs

Description

Multiple default inputs can be specified in the system file. At the scripting level this function can be used to set all inputs to zero. Then only the subsequently specified inputs will be applied.

Usage

system_zero_inputs(cfg, bolus = TRUE, rates = TRUE)

Arguments

cfg

ubiquity system object

bolus

Boolean value indicating weather bolus inputs should be set to zero

rates

Boolean value indicating weather infusion rate inputs should be set to zero

Value

Ubiquity system object with the specified inputs set to zero

See Also

system_set_rate, system_set_bolus

Examples


# Creating a system file from the mab_pk example
fr = system_new(file_name        = "system.txt", 
                system_file      = "mab_pk", 
                overwrite        = TRUE, 
                output_directory = tempdir())

# Building the system 
cfg = build_system(system_file  = file.path(tempdir(), "system.txt"),
      output_directory          = file.path(tempdir(), "output"),
      temporary_directory       = tempdir())

# Clear only infusion rates
cfg = system_zero_inputs(cfg, bolus=TRUE, rates=FALSE)

# Clear all inputs:
cfg = system_zero_inputs(cfg)


Implementation of Matlab tic() command

Description

Used in conjunction with toc() to find the elapsed time when code is executed.

Usage

tic(type = c("elapsed", "user.self", "sys.self"))

Arguments

type

can be either "elapsed" "user.self" or "sys.self"

Value

time tic was called

See Also

toc

Examples

tic()
Sys.sleep(3)
toc()

Calculate Timecourse Statistics for a Matrix of Responses

Description

Given a matrix (d) of time courses (each row is an individual and each column is a time point) and a confidence interval (ci) this will calculate the mean, median, confidence intervals and a vector of values for creating patches.

Usage

timecourse_stats(d, ci)

Arguments

d

matrix of responses (each row an individual and each column a time point)

ci

confidence interval in percent (eg, 95)

Value

List with the following elements:


Implementation of Matlab toc() command

Description

Used in conjunction with tic() to find the elapsed time when code is executed.

Usage

toc()

Value

time in seconds since tic() was called

See Also

tic

Examples

tic()
Sys.sleep(3)
toc()

Check Names of Cohorts, Analyses, Reports, etc.

Description

Checks names specified for different analysis aspects (cohorts, analyses, reports, etc.) to make sure that they start with a letter and contain only letters, numbers and _

Usage

ubiquity_name_check(test_name)

Arguments

test_name

string containing the name to be tested

Value

List with Boolean element isgood that is TRUE when the name tests correct, FALSE when it fails. The element msgs contains a verbose message on why it fails.


Converts Numeric Variables into Padded Strings

Description

Mechanism for converting numeric variables into strings for reporting.

Usage

var2string(vars, maxlength = 0, nsig_e = 3, nsig_f = 4)

Arguments

vars

numeric variable or a vector of numeric variables

maxlength

if this value is greater than zero spaces will be added to the beginning of the string until the total length is equal to maxlength

nsig_e

number of significant figures for scientific notation

nsig_f

number of significant figures for numbers (2.123)

Value

Number as a string padded

Examples

var2string(pi, nsig_f=20)
var2string(.0001121, nsig_e=2, maxlength=10)

Convert R Objects to Strings

Description

Mechanism for converting R objects strings for reporting.

Usage

var2string_gen(var)

Arguments

var

R variable

Value

Variable in string form

Examples

var2string_gen(c(1,2,3))

Print and Log Messages

Description

Used to print messages to the screen and the log file.

Usage

vp(cfg, str, fmt = "alert")

Arguments

cfg

ubiquity system object

str

sequence of strings to print

fmt

string format should be one of the following: "h1", "h2", "h3", "verbatim", "alert" (default), "warning", "danger".

Value

Boolean variable indicating success (TRUE) or failure (FALSE)

Examples


# Creating a system file from the mab_pk example
fr = system_new(file_name        = "system.txt", 
                system_file      = "mab_pk", 
                overwrite        = TRUE, 
                output_directory = tempdir())

# Building the system 
cfg = build_system(system_file  = file.path(tempdir(), "system.txt"),
      output_directory          = file.path(tempdir(), "output"),
      temporary_directory       = tempdir())

# Initialzing the log file
vp(cfg, "Message that will be logged")


Fetch Ubiquity Workshop Sections

Description

With the ubiquity package this function can be used to fetch example files for different sections of the workshop.

Usage

workshop_fetch(
  section = "Simulation",
  overwrite = FALSE,
  copy_files = TRUE,
  output_directory = getwd()
)

Arguments

section

Name of the section of workshop to retrieve ("Simulation")

overwrite

if TRUE the new workshop files will overwrite any existing files present (FALSE)

copy_files

if TRUE the files will be written to the output_directory, if FALSE only the names and locations of the files will be returned (TRUE)

output_directory

directory where workshop files will be placed (getwd())

Details

Valid sections are "Simulation", "Estimation", "In Vitro", "Titration" "Reporting", and "NCA"

Value

list

Examples


workshop_fetch("Estimation", output_directory=tempdir(), overwrite=TRUE)