| Title: | Pmetrics for Population Modeling and Simulation |
|---|---|
| Description: | Pmetrics is short for pharmacometrics, the discipline of modeling drug kinetics and effects on biologic systems, including disease progression. Models can be used to simulate novel therapeutic dosing regimens and/or populations, informing trial design and dosing strategies. The package supports primarily non-parametric but also parametric pharmacometric modeling and simulation with functions to run and analyze the output from all three components of the Pmetrics software suite for population pharmacometric data analysis: 1) IT2B (Iterative Two-Stage Bayesian) for parametric models; 2) NPAG (Non-parametric Adaptive Grid) for non-paramametric models; 3) Simulator for semi-parametric Monte-Carlo simulations. |
| Authors: | Michael Neely [aut, cre], Julián Otálvaro [aut], Markus Hovd [aut], Walter Yamada [ctb], Alan Schumitzky [ctb], Rong Chen [ctb], Michael van Guilder [ctb], David Bayard [ctb], Robert Leary [ctb] |
| Maintainer: | Michael Neely <[email protected]> |
| License: | GPL (>= 3) |
| Version: | 3.1.3 |
| Built: | 2026-05-12 20:08:38 UTC |
| Source: | https://github.com/LAPKB/Pmetrics |
Define primary model parameter initial values as range. For nonparametric, this range will be absolutely respected. For parametric, the range serves to define the mean (midpoint) and standard deviation (1/6 of the range) of the initial parameter value distribution.
ab(min, max)ab(min, max)
min |
Minimum value. |
max |
Maximum value. |
Analogous to abline, draws horizontal, vertical or sloped reference lines.
ab_line(a = NULL, b = NULL, h = NULL, v = NULL, line = TRUE)ab_line(a = NULL, b = NULL, h = NULL, v = NULL, line = TRUE)
a |
Intercept y value in relative coordinates, i.e. 0 (bottom) to 1 (top). The x value is 0. |
b |
Slope |
h |
Y-intercept of horizontal line, in absolute coordinates |
v |
X-intercept of vertical line, in absolute coordinates |
line |
Controls characteristics of lines. This argument maps to plotly line attributes.
Example: |
This function creates a line shape that can be added a plotly plot. See schema() > layout > layoutAttributes > shapes for details. Use only one of the following:
a and b to specify a line with intercept and slope
h to specify a horizontal line with y-intercept at h
v to specify a vertical line with x-intercept at v
If using this function to add a line to an existing plot, it must be used with add_shapes. If used for a new plot, it can be included as an element in the layout list.
## Not run: # add to an existing plot NPex$op$plot() %>% add_shapes(shapes = ab_line(v = 12)) # add to a new plot plotly::plot_ly(x = 1:10, y = 1:10, type = "scatter", mode = "lines+markers") %>% plotly::layout(shapes = ab_line(h = 5, line = list(color = "red", dash = "solid"))) ## End(Not run)## Not run: # add to an existing plot NPex$op$plot() %>% add_shapes(shapes = ab_line(v = 12)) # add to a new plot plotly::plot_ly(x = 1:10, y = 1:10, type = "scatter", mode = "lines+markers") %>% plotly::layout(shapes = ab_line(h = 5, line = list(color = "red", dash = "solid"))) ## End(Not run)
Adds columns to PM_data object for creatinine clearance or estimated glomerular filtration rate (eGFR).
Creatinine clearance can be estimated by:
The Jelliffe equation for paired creatinines
The Cockcroft-Gault equation using a single creatinine.
eGFR can be estimated by:
The MDRD equation
The CKD-EPI equation
The Schwartz equation for children
add_renal( x, method, id = "id", wt = "wt", ht = "ht", male = "male", age = "age", black = "black", scr = "scr", bun = "bun", cysC = "cysC", SI = F )add_renal( x, method, id = "id", wt = "wt", ht = "ht", male = "male", age = "age", black = "black", scr = "scr", bun = "bun", cysC = "cysC", SI = F )
x |
A PM_data data object |
method |
A character vector defining the method to use. Options are
|
id |
A character vector with the name
of the id column in |
wt |
A character vector with the name of the weight
column in |
ht |
A character vector with the name of the height column in |
male |
A character vector with the name of the column defining sex in |
age |
A character vector with the name of the age column in |
black |
A character vector with the name of a column defining black race in |
scr |
A character vector with the name of the serum creatinine column in |
bun |
A character vector with the name of the blood urea nitrogen column in |
cysC |
A character vector with the name of the cystatin C column in |
SI |
Boolean value, if true, will expect serum creatinine to be in micromol/L and BUN reported
as micromol/L of urea.
Default is |
Note: In all the equations below, age is in years, weight is in kilograms, height is in meters,
and cystatin C (cysC) is in mg/L. Serum creatinine (Scr) is in mg/dL and blood urea nitrogen (BUN)
is in mg/L. However, if SI = TRUE, then
serum creatinine is in micromol/L and BUN is in micromol/L of urea.
Missing covariate values are interpolated using linear interpolation within each subject.
The Jelliffe equation depends on age, sex, weight, and serum creatinine. It uniquely uses two serum creatinine values separated by time to estimate changing renal function.
for males
for females
in ml/min/1.73m^2
The Cockroft-Gault equation is a point estimate of creatinine clearance. It depends on the same variables as Jelliffe except it does not require paired creatinines.
is 1 for males and 0.85 for females
The MDRD equation estimates GFR. It depends on age, sex, black race, and serum creatinine.
Multiply by 1.212 if black.
The CKD-EPI equation estimates GFR. It depends on the same variables as MDRD, except black is
no longer required in the 2021 version used here.
Multiply by 1.1018 if female.
The Schwartz equation estimates GFR in children. The equation used depends on which covariates are included in the data.
height and serum creatinine: (updated Scwartz equation)
height, serum creatinine, and cystatin C: (Equation 1a)
height, serum creatinine, and BUN: (Equation 1b)
height, serum creatinine, cystatin C, and BUN: (Equation II)
height, serum creatinine, cystatin C, BUN, and male: (Equation III)
Discussion of the strengths and weaknesses of these equations are beyond the scope of this documentation.
A column added to the x data object with the name of the method used and calcuated values.
Michael Neely
Modifies the layout object of an existing plot to include a new shape.
add_shapes(p = plotly::last_plot(), shapes)add_shapes(p = plotly::last_plot(), shapes)
p |
The plot to which the shape should be added. Default is the
|
shapes |
A list of attributes that specify a shape. Note that only one
shape can be added for each call, but to be consistent with the |
This function adds a shape to the layout element of a plotly plot.
Type schema() in the console and expand the list for
layout > layoutAttributes > shapes for details on how
to specify a shape. A convenient Pmetrics helper function to add line shapes
is ab_line. Other shapes such as circles, rectangles and paths can be added,
but must be done manually as outlined in the plotly schema documentation.
An example of a circle shape is below in examples.
#' ## Not run: NPex$op$plot() %>% add_shapes(shapes = ab_line(v = 12)) NPex$data$plot() %>% add_shapes(shapes = list(type = "circle", x0 = 125, y0 = 10, x1 = 135, y1 = 15)) ## End(Not run)#' ## Not run: NPex$op$plot() %>% add_shapes(shapes = ab_line(v = 12)) NPex$data$plot() %>% add_shapes(shapes = list(type = "circle", x0 = 125, y0 = 10, x1 = 135, y1 = 15)) ## End(Not run)
Modifies an existing plot to include a regression line with confidence interval.
add_smooth( p = plotly::last_plot(), x = NULL, y = NULL, data = NULL, method = c("lm", "loess"), span = 0.75, line = TRUE, ci = 0.95, stats = TRUE )add_smooth( p = plotly::last_plot(), x = NULL, y = NULL, data = NULL, method = c("lm", "loess"), span = 0.75, line = TRUE, ci = 0.95, stats = TRUE )
p |
The plot to which the shape should be added. Default is the
|
x |
X value for regression if not the original x value of the plot. Be
sure to specify as a formula, e.g. |
y |
Y value for regression if not the original y value of the plot. Be
sure to specify as a formula, e.g. |
data |
A secondary data object to use for regression other than the original plot data. |
method |
The tegression method, currently either "lm" (the default) for linear regression, or "loess" for loess regression. |
span |
Only used for |
line |
Controls characteristics of lines. This argument maps to plotly line attributes.
Example: |
ci |
Confidence interval for regressions. Default is 0.95. It can be suppressed by setting to 0. |
stats |
Add the statistics from linear regression to the plot. Ignored if
|
This function adds a regression line to an existing plotly plot.
The default is to use the x and y values in the plot, but this can be overridden
by specifying a data object. If another data object is used, values for x and y
must also be specified. Alternatively, the original data can be used and new columns
selected for regression by omitting the data argument and specifying new x and
y values. The intent of this function is to replicate the behavior of
ggplot::geom_smooth().
## Not run: plotly::plot_ly(mtcars, x = ~hp, y = ~mpg, type = "scatter", mode = "markers", showlegend = FALSE ) %>% add_smooth() plotly::plot_ly(iris, x = ~Sepal.Length, y = ~Petal.Length, type = "scatter", mode = "markers", showlegend = FALSE ) %>% add_smooth(method = "loess", ci = 0.9, line = list(color = "red", dash = "dash")) ## End(Not run)## Not run: plotly::plot_ly(mtcars, x = ~hp, y = ~mpg, type = "scatter", mode = "markers", showlegend = FALSE ) %>% add_smooth() plotly::plot_ly(iris, x = ~Sepal.Length, y = ~Petal.Length, type = "scatter", mode = "markers", showlegend = FALSE ) %>% add_smooth(method = "loess", ci = 0.9, line = list(color = "red", dash = "dash")) ## End(Not run)
Create an additive (lambda) error model
additive(initial, coeff, fixed = FALSE)additive(initial, coeff, fixed = FALSE)
initial |
Initial value for lambda |
coeff |
Vector of coefficients defining assay error polynomial |
fixed |
Estimate if |
Checks if all values in a vector are numeric.
all_is_numeric(x, what = c("test", "vector", "nonnum"), extras = c(".", "NA"))all_is_numeric(x, what = c("test", "vector", "nonnum"), extras = c(".", "NA"))
x |
A vector to check. |
what |
A character string indicating what to return. Can be "test", "vector", or "nonnum". The default is "test". |
extras |
A character vector of extra values to exclude from the check. The default is c(".", "NA"). |
The function checks if all values in a vector are numeric. It can be used to check if a vector contains only numeric values. It can also be used to check if a vector contains any non-numeric values.
A logical value indicating if all values are numeric.
If what is "vector", a numeric vector is returned.
If what is "nonnum", a character vector of non-numeric values is returned.
If what is "test", a logical value is returned.
## Not run: all_is_numeric(c("1", "2", "3")) all_is_numeric(c("1", "2", "a")) all_is_numeric(c("1", "2", "3"), what = "vector") all_is_numeric(c("1", "2", "a"), what = "nonnum") ## End(Not run)## Not run: all_is_numeric(c("1", "2", "3")) all_is_numeric(c("1", "2", "a")) all_is_numeric(c("1", "2", "3"), what = "vector") all_is_numeric(c("1", "2", "a"), what = "nonnum") ## End(Not run)
lit_sim(), model_lib(), and pm_plot() launch specific packaged
apps from inst/apps.
lit_sim(launch.browser = TRUE) pm_plot(launch.browser = TRUE) apps(launch.browser = TRUE)lit_sim(launch.browser = TRUE) pm_plot(launch.browser = TRUE) apps(launch.browser = TRUE)
launch.browser |
Logical. Should the app launch in a browser? |
apps() shows an interactive numbered menu (via cli) and launches the
selected app using readline() input.
Invisibly returns the value from shiny::runApp() for launcher
functions. apps() returns invisibly NULL on cancel/invalid input.
Example data set for an NPAG/IT2B run, which has been corrupted with errors.
badDatabadData
Errors include missing covariate on first line for subject 1, alphanumeric covariate for gender, and trailing dose for subject 1.
Michael Neely
Centers for Disease Control Pediatric and Adolescent BMI Table
cdc_bmicdc_bmi
A data frame with the following 9 columns: Sex (1 = male), Agemos; L, M, S (coefficients for calculating z-scores), P3, P5, P10, P25, P50, P75, P85, P90, P95, P97: age and sex specific BMI percentiles
Coefficients to calculate sex-specific BMI z-scores and percentiles. Downloaded from . Tables were last updated in 2000, based on data through 1994. Definitions of overweight and obese come from these data, based on BMI percentile >=85 for overweight and >=95 for obese. See ger_bmi for percentiles based on more modern NHANES data.
Michael Neely
Performs an on-demand check for newer Pmetrics and R releases.
This function is intended for interactive use and avoids running network
checks automatically during package attach.
check_updates(verbose = interactive(), timeout = 2)check_updates(verbose = interactive(), timeout = 2)
verbose |
Logical. If |
timeout |
Numeric scalar. Network timeout in seconds used for this check. |
An invisible list with installed/latest versions and outdated flags.
Adds click functionality to a plotly plot to highlight traces when clicked.
click_plot(p, highlight_color = "#1f77b4")click_plot(p, highlight_color = "#1f77b4")
p |
The plotly plot to which the click functionality should be added.
Default is the |
highlight_color |
The color to use for traces that are highlighted. Colors for non-highlighted
traces will be preserved but dimmed to 20% opacity. Default highlight color is |
This function modifies a plotly plot to allow clicking on traces to highlight them.
Clicking on a trace will highlight it in orange (default) and dim all other traces.
Clicking on the same trace again will deselect it and restore the original colors.
Clicking on the background will also restore all traces to their original colors.
The function uses the htmlwidgets::onRender function from the htmlwidgets package to add
JavaScript code that handles the click events on the plotly plot.
Michael Neely
Converts a correlation matrix to a covariance matrix using standard deviations.
cor2cov(cor, sd)cor2cov(cor, sd)
cor |
A correlation matrix. |
sd |
A vector of standard deviations corresponding to the variables in the correlation matrix. |
Uses matrix multiplication to convert a correlation matrix to a covariance matrix.
A covariance matrix.
Michael Neely
Example data set for an NPAG/IT2B run.
dataExdataEx
Data are kindly supplied by Chuck Peloquin, PharmD. They consist of multiple rifapentine oral doses followed by 6-7 concentrations in 20 adult subjects. Covariates include weight (kg), africa (origin), age (years), gender (1 = male), and height (cm).
Michael Neely
Downloads the latest R installer (or source tarball on Linux) for the current
platform to the user's Downloads folder.
downloadR(r_info = latestR(), destdir = path.expand("~/Downloads"))downloadR(r_info = latestR(), destdir = path.expand("~/Downloads"))
r_info |
Optional API response list. Defaults to |
destdir |
Destination directory. Defaults to the user's Downloads folder. |
The file path of the downloaded installer/tarball.
Wrapper around plotly::save_image().
export_plotly( p, file, width = NULL, height = NULL, scale = NULL, units = "px", show = TRUE )export_plotly( p, file, width = NULL, height = NULL, scale = NULL, units = "px", show = TRUE )
p |
The plot to which the shape should be added. Default is the
|
file |
A file path with a suitable file extension (png, jpg, jpeg, webp, svg, or pdf).
Unlike |
width, height
|
The width/height of the exported image in pixels,
mutliplied by |
scale |
The scale factor to use when exporting the figure. Default is 1.0.
A scale factor larger than 1.0 will increase the image size,
and less than 1.0 will decrease the image size. Note that the documentation
for |
units |
Units for |
show |
Show the exported image in R via |
This function improves the experience with the native plotly method of exporting plots to static images. Much of the online documentation points towards using the orca package, but the R help indicates that this method has been superseded by the kaleido python package, made accesible in R via the reticulate package and installation of the miniconda package manager.
These steps are all outlined in the help for plotly::save_image(), but one step
is neglected. It is necessary to execute the following line of code at the end:
reticulate::py_run_string("import sys").
This function will check to see that all installations are in place and offer to install if not.
Many of the arguments are the same as for save_image and are passed directly
to that function.
Plot p will be exported to file with format determined by the
extension for file.
Michael Neely
## Not run: NPex$op$plot(stats = list(x = 0.9)) %>% export_plotly(file = "op.png", width = 12, height = 6, units = "in") ## End(Not run)## Not run: NPex$op$plot(stats = list(x = 0.9)) %>% export_plotly(file = "op.png", width = 12, height = 6, units = "in") ## End(Not run)
Revised Pediatric and Adolescent BMI Table
ger_bmiger_bmi
A data frame with the following 9 columns: Sex (1 = male), Agemos; L, M, S (coefficients for calculating z-scores), P3, P5, P10, P25, P50, P75, P85, P90, P95, P97: age and sex specific BMI percentiles
Coefficients to calculate sex-specific BMI z-scores and percentiles based on the supplemental data published by Gerhart et al: Gerhart, Jacqueline G., Fernando O. Carreño, Andrea N. Edginton, Jaydeep Sinha, Eliana M. Perrin, Karan R. Kumar, Aruna Rikhi, et al. “Development and Evaluation of a Virtual Population of Children with Obesity for Physiologically Based Pharmacokinetic Modeling.” Clinical Pharmacokinetics 61, no. 2 (February 2022): 307–20. doi:10.1007/s40262-021-01072-4. These data are in the same format as cdc_bmi but are derived from more recent NHANES data.
Michael Neely
Extracts covariate information from a Pmetrics data object.
getCov(mdata)getCov(mdata)
mdata |
A PM_data object. It can be other data frames but the results will likely not be meaningful. |
The function subtracts the number of fixed columns in a standard data format,
currently 14, from the total number of columns in mdata and queries
the remaining columns. When given a PM_data object, will return a list
with the number of covariates, their names, and the starting and
ending column numbers
A list with named items: ncov, covnames, covstart, covend.
Michael Neely
## Not run: getCov(dataEx) ## End(Not run)## Not run: getCov(dataEx) ## End(Not run)
Generate list of default color names.
getDefaultColors(n)getDefaultColors(n)
n |
The number of colors to return from the list. |
Used for Pmetrics plots. The following list is recycled as necessary to generate the
requested number of colors:
c(red(), green(), blue(), brown(), black(), purple(), pink(), gold(), orange(), gray()).
Each value is a function that returns a color name.
A character vector of color names, which is recycled as needed.
Michael Neely
## Not run: getDefaultColors(6) ## End(Not run)## Not run: getDefaultColors(6) ## End(Not run)
Returns the number of fixed columns (non-covariate) in Pmetrics data objects.
getFixedColNum()getFixedColNum()
An integer with the number of fixed columns.
Michael Neely
## Not run: getFixedColNum() ## End(Not run)## Not run: getFixedColNum() ## End(Not run)
Generate list of palettes for plots.
getPalettes()getPalettes()
If RColorBrewer package is installed, will return the list of palette names from RColorBrewer::brewer.pal.info. If not, will return the current list as of April 2024.
A character vector of palette names.
Michael Neely
## Not run: getPalettes() ## End(Not run)## Not run: getPalettes() ## End(Not run)
Get user options for Pmetrics
getPMoptions(opt, warn = TRUE, quiet = FALSE)getPMoptions(opt, warn = TRUE, quiet = FALSE)
opt |
The option to retrieve. If omitted, all option values will be returned. |
warn |
Warn if options file doesn't exist. Default |
quiet |
Suppress warning messages. Default |
This function will get user options for Pmetrics. It will look for a PMoptions.json file in a hidden folder outside of the Pmetrics package. If that does not exist, it will look for a default options file in the package options folder. See setPMoptions for details on where the options file is stored and how to set options.
A list with the current options.
Michael Neely
Centers for Disease Control Pediatric and Adolescent Growth Data Table
growthgrowth
A data frame with the following 9 columns: KNOT (integer age in months); A, B1, B2, B3 (coefficients for calculating percentiles), SEX, AGE, PERCENTILE, and CHART (length x age, wt x age, wt x length, hc x age, or ht x age).
Coefficients to calculate sex-specific percentiles of length, weight and head cicumference data
in children from 0 to 18 years. Downloaded and combined from .
Used with the qgrowth() function to generate height and weight percentiles for the purposes of simulation.
Michael Neely
Declare whether covariates in the data are to have interpolation between values or not.
interp(type = "lm")interp(type = "lm")
type |
If |
A value of 1 for "lm" and 0 for "none", which will be passed to Rust.
## Not run: cov <- c( wt = interp(), # same as interp("lm") or interp("linear") visit = interp("none") ) ## End(Not run)## Not run: cov <- c( wt = interp(), # same as interp("lm") or interp("linear") visit = interp("none") ) ## End(Not run)
Retrieves metadata for the latest R release available for the current
platform from the r-hub rversions API.
latestR()latestR()
A list containing all fields returned by the API response.
Pmetrics locales
localeslocales
Dataframe with languages and iso693 two- and three-letter codes.
Michael Neely
Calculates AUC from a variety of inputs
make_AUC( data = NULL, formula = NULL, include = NULL, exclude = NULL, start = 0, end = Inf, icen = "median", outeq = 1, block = 1, method = "linear", addZero = F ) makeAUC( data = NULL, formula = NULL, include = NULL, exclude = NULL, start = 0, end = Inf, icen = "median", outeq = 1, block = 1, method = "linear", addZero = F )make_AUC( data = NULL, formula = NULL, include = NULL, exclude = NULL, start = 0, end = Inf, icen = "median", outeq = 1, block = 1, method = "linear", addZero = F ) makeAUC( data = NULL, formula = NULL, include = NULL, exclude = NULL, start = 0, end = Inf, icen = "median", outeq = 1, block = 1, method = "linear", addZero = F )
data |
A suitable data object, i.e. PM_pop, PM_post, PM_op,
PM_sim, or some other suitable dataframe
with at least time/observation columns referred to by |
formula |
A formula of the form |
include |
A vector of subject IDs to include in the plot, e.g. c(1:3,5,15) |
exclude |
A vector of subject IDs to exclude in the plot, e.g. c(4,6:14,16:20) |
start |
Specify the time to begin AUC calculations. Default is 0. |
end |
Specify the time to end AUC calculations so that AUC is calculated
from |
icen |
Can be either "median" for the predictions based on medians of |
outeq |
Which output equation to plot. Default is 1. |
block |
Which block to plot, where blocks are defined by dose reset events (EVID = 4) in the data. |
method |
Default is "linear" for AUC trapezoidal calculation. Any other value will result in linear up, log down. |
addZero |
Boolean to add a zero concentration at time 0. Default is |
Calculates the area under the time concentration curve using the
trapezoidal approximation from a variety of inputs.
If a PM_pop, PM_post, PM_op, or PMsim object is specified,
formula is not required.
A dataframe of class PMauc, which has 2 columns:
group - Subject identification, usually "id"
tau - AUC from start to end
Michael Neely
## Not run: NPex$cov$plot(V ~ wt) NPex$cov$plot(Ke ~ wt, line = list(lm = TRUE, ref = FALSE, loess = FALSE)) NPex$cov$plot(Ke ~ wt, line = list(loess = list(ci = 0.9, color = "green"))) NPex$cov$plot(V ~ time, marker = list(color = "blue")) NPex$cov$plot(V ~ wt, line = list(lm = TRUE, loess = FALSE), stats = list(x = 0.5, y = 0.2, font = list(size = 7, color = "blue")) ) ## End(Not run)## Not run: NPex$cov$plot(V ~ wt) NPex$cov$plot(Ke ~ wt, line = list(lm = TRUE, ref = FALSE, loess = FALSE)) NPex$cov$plot(Ke ~ wt, line = list(loess = list(ci = 0.9, color = "green"))) NPex$cov$plot(V ~ time, marker = list(color = "blue")) NPex$cov$plot(V ~ wt, line = list(lm = TRUE, loess = FALSE), stats = list(x = 0.5, y = 0.2, font = list(size = 7, color = "blue")) ) ## End(Not run)
Performs a non-compartmental analysis from a PM_result object using
observed concentrations in the raw data
file PM_result$data$standard_data or from an individual
Bayesian posterior predicted
time-observation profiles PM_result$post$data generated automatically after an NPAG run
and loaded with PM_load .
make_NCA( x, postPred = F, include, exclude, input = 1, icen = "median", outeq = 1, block = 1, start = 0, end = Inf, first = NA, last = NA, terminal = 3 )make_NCA( x, postPred = F, include, exclude, input = 1, icen = "median", outeq = 1, block = 1, start = 0, end = Inf, first = NA, last = NA, terminal = 3 )
x |
PM_data object to analyze. |
postPred |
Boolean switch to use the posterior predictions rather than the observed.
concentrations. Default is |
include |
A vector of subject IDs to include in the NCA, e.g. |
exclude |
A vector of subject IDs to exclude in the NCA, e.g. |
input |
The number of the input (e.g. drug) to analyze; default 1. |
icen |
If |
outeq |
The number of the output equation to analyze; default 1 |
block |
The number of the observation block within subjects, with each block delimited by EVID=4 in the data file; default 1 |
start |
The beginning of the time interval to look for doses and observations,
e.g. 120. It can be a vector to allow for individual start times per subject,
e.g. |
end |
Analogous to |
first |
Alternative way to specify time interval for NCA by choosing dose number,
e.g. 1 or 3. May be a numeric vector, like |
last |
The complement to |
terminal |
Number of observations to use for terminal curve fitting (i.e. to estimate k). Default is 3. |
If concentrations from multiple dose intervals are included in the start to end time interval,
make_NCA will superpose the concentrations using the time after dose. An error will be generated if
different doses are within this interval as superposition would no longer be valid.
A minimum of 5 concentrations must be available to perform NCA for any given subject. Fewer than this will suppress all results for that subject.
A dataframe of class PMnca with columns
id |
Subject identification |
auc |
Area under the time-observation curve, using the trapezoidal approximation, from time 0 until the second dose, or if only one dose, until the last observation |
aumc |
Area under the first moment curve |
k |
Slope by least-squares linear regression of the final 3 log-transformed observations vs. time. If the final 3 concentrations are not decreasing such that linear regression results in a positive slope, this value and all others that depend on k will be suppressed. |
auclast |
Area under the curve from the time of the last observation to infinity, calculated as |
aumclast |
Area under the first moment curve from the time of the last observation to infinity.
This value will be suppressed if |
aucinf |
Area under the curve from time 0 to infinity, caluculated as auc + auclast |
aumcinf |
Area under the first moment curve from time 0 to infinity |
mrt |
Mean residence time, calculated as 1/k |
cmax |
Maximum predicted concentration after the first dose |
tmax |
Time to cmax |
cl |
Clearance, calculated as dose/aucinf |
vdss |
Volume of distribution at steady state, calculated as cl*mrt |
thalf |
Half life of elimination, calculated as ln(2)/k |
dose |
Dose for each subject |
Michael Neely
Estimate coefficients for the polynomial to describe assay error.
makeErrorPoly( obs, sd, data, outeq = 1, col = "red", cex = 3, pch = "+", lcol = "blue", lwd = 2, ref = T, legend = T, ... )makeErrorPoly( obs, sd, data, outeq = 1, col = "red", cex = 3, pch = "+", lcol = "blue", lwd = 2, ref = T, legend = T, ... )
obs |
A vector of observations |
sd |
A vector of standard deviations obtained from repeated measurements at each
observation in |
data |
A Pmetrics data file. From this, the maximum and mininimum observations will be retrieved. This is useful to ensure that calculated standard deviations are not negative at any observation in the dataset. If not specified, the default is the maximum obs. |
outeq |
The output equation in data. Default is 1. |
col |
Color of the data points. Default is red. |
cex |
Relative size of the data points. Default is 3. See |
pch |
Ploting symbol. Default is “+”. See |
lcol |
Color of the fitted polynomial lines. Default is blue. |
lwd |
Width of the lines. Default is 2. |
ref |
Add a reference line at SD 0 to help evaluate that all fitted SDs are >0. Default is true. |
legend |
Boolean argument to plot legend. Default is |
... |
Other plotting parameters as in |
This function plots first, second, and third order polynomial functions fitted to pairs of observations and associated standard deviations for a given output assay. In this way, the standard deviation associated with any observation may be calculated and used to appropriately weight that observation in the model building process. Observations are weighted by the reciprocal of the variance, or squared standard deviation.
A plot of the measured observations and fitted polynomial curves and a list with the first, second, and third order coefficients
Michael Neely
makeErrorPoly(obs = c(0, 5, 50, 100, 250, 500, 1000), sd = c(1, 0.4, 4.5, 12, 34, 60, 190))makeErrorPoly(obs = c(0, 5, 50, 100, 250, 500, 1000), sd = c(1, 0.4, 4.5, 12, 34, 60, 190))
Generates an object of class PMpta.targ which can
be used in the $new() method for PM_pta or $pta() method for PM_sim for targets sampled from a distribution.
makePTAtarget(x)makePTAtarget(x)
x |
A data.frame or name of .csv file in working directory whose first two columns are targets and the number of samples for each target. An example can be seen for Staphylococcus aureus susceptibility to vancomycin at EUCAST. |
A data frame with two columns named targets and n, of class PMpta.targ.
## Not run: makePTAtarget(mic1) ## End(Not run)## Not run: makePTAtarget(mic1) ## End(Not run)
Example MIC data
mic1mic1
An R data frame containing example MIC distribution data in two columns:
mic Minimum inhibitory concentration
n Number of organisms with the given MIC
This data frame contains MIC data for vancomycin against S. aureus. It was obtained from the EUCAST website at . Select the organism or drug, and then select the desired row of the resulting table to see a histogram (top) and table (bottom) of MIC distributions.
Copy the table into excel, save as a .csv file, and read into R using a function like
read.csv() or readr::read_csv(). Then use makePTAtarget().
Michael Neely
Launches a Shiny app for browsing all available pharmacokinetic model
templates in the Pmetrics library. Select a model to view its parameters,
compartment structure, differential equations, and ready-to-use
PM_model$new() code. Use the Copy button to send the code to the
clipboard. Individual creator functions such as one_comp_iv() return a
compiled PM_model and copy the code automatically.
model_lib(show = TRUE, launch.browser = TRUE)model_lib(show = TRUE, launch.browser = TRUE)
show |
Logical. If |
launch.browser |
Logical. Passed to |
Invisibly, a tibble of all model templates.
Example model for an NPAG/IT2B run. There are 4 parameters in the model: lag time of absorption (Tlag1), rate constant of absorption (Ka), volume (V) and rate constant of elmination (Ke). There are 5 covariates: weight in kg (WT), whether from Africa or not (AFRICA), age in years (AGE), 1 for male (GENDER), and height in cm (HEIGHT). There is one output equation, and the model uses gamma plus an error polynomial derived from the assay.
modExmodEx
R6 PM_model
Michael Neely
Define primary model parameter initial values as mean and standard deviation, which translate to a range. The mean serves as the midpoint of the range, with 3 standard deviations above and below the mean to define the min and max of the range. For nonparametric, this range will be absolutely respected. For parametric, values can be estimated beyond the range.
msd(mean, sd)msd(mean, sd)
mean |
Initial mean. |
sd |
Initial standard deviation. |
Multivariate two-sample test based on k-nearest neighbors
mtsknn.eq(x, y, k, clevel = 0.05, getpval = TRUE, print = TRUE)mtsknn.eq(x, y, k, clevel = 0.05, getpval = TRUE, print = TRUE)
x |
A matrix or data frame. |
y |
A matrix or data frame. |
k |
k An integer. |
clevel |
The confidence level. Default value is 0.05. |
getpval |
Logic value. If it is set to be TRUE the p value of test will be calcuated and reported; if it is set to be false the p value will not be calculated. |
print |
Boolean value. If it is set to be TRUE the test result will be reported; if it is set to be FALSE the test result will not be reported. |
This function tests whether two samples share the same underlying distribution based on k-nearest-neighbors approach. Matrices or data frames x and y are the two samples to be tested. Each row consists of the coordinates of a data point. The integer k is the number of nearest neighbors to choose in the testing procedure. This approach is robust in the unbalanced case.
A list consists of the test statistics, normalized Z score and corresponding P value.
Lisha Chen (Yale), Peng Dai (Stonybrook) and Wei Dou (Yale)
Schilling, M. F. (1986). Multivariate two-sample tests based on nearest neighbors. J. Amer. Statist. Assoc., 81 799-806. Henze, N. (1988). A multivariate two-sample test based on the number of nearest neighbor type coincidences.Ann. Statist., 16 772-783. Chen, L. and Dou W. (2009). Robust multivariate two-sample tests based on k nearest neighbors for unbalanced designs. manuscripts.
NM2PM will convert NONMEM .csv data files to Pmetrics csv data files.
NM2PM(data, ctl)NM2PM(data, ctl)
data |
The name and extension of a NONMEM data (e.g. .csv) file in the working directory, or the full path to a file. |
ctl |
The name and extension of a NONMEM control (e.g. .ctl) file in the working directory, or the full path to a file. |
The format of NONMEM and Pmetrics data .csv files are similar, but not quite identical. A major difference is that the order of the columns are fixed in Pmetrics (not including covariates), while they are user-determined in NONMEM, and specified in a control (.ctl) file.
A list of other differences follows by data item.
ID This item is the same in both formats and is required.
EVID This is the same in both formats but is not required in NONMEM. Doses have an EVID of 1 and observations 0. EVID=4 (dose/time reset) is the same in Pmetrics and NONMEM. EVID=2 (other event) and EVID=3 (dose reset) are not directly supported in Pmetrics, but if included in a NONMEM file, will be converted into covariate values. Specifically the value in the CMT variable will be the covariate value for EVID=2, while for EVID=3, the covariate will be 1 at the time of the EVID=3 entry and 0 othewise. This allows for handling of these events in the Pmetrics model file using conditional statements.
DATE Pmetrics does not use dates, but will convert all NONMEM dates and times into relative times.
TIME Pmetrics uses relative times (as does NONMEM), but the NONMEM pre-processor will convert clock times
to relative times, as does NM2PM.
RATE NONMEM RATE items are converted by this function to Pmetrics DURation values.
AMT becomes DOSE in Pmetrics
ADDL is supported in both formats. However, if NONMEM files contain an SS flag, it will be incorporated as ADDL=-1 according to Pmetrics style.
II is the same in both formats.
INPUT in Pmetrics is similar to CMT in NONMEM for doses.
DV in NONMEM becomes OUT in Pmetrics. Ensure that the units of OUT are consistent with the units of DOSE.
OUTEQ In Pmetrics, this is roughly equivalent to CMT in NONMEM for observation events. The lowest CMT value for any observation becomes OUTEQ=1; the next lowest becomes OUTEQ=2, etc.
SS Steady state dosing is incorporated into Pmetrics as ADDL=-1.
MDV Missing DV in NONMEM become OUT=-99 in Pmetrics.
Covariates These are copied from NONMEM to Pmetrics. Note that Pmetrics does not allow missing covariates at time 0 for each subject.
DROP Items marked as DROP in the NONMEM control file will not be included in the Pmetric data file.
It is strongly suggested to run PMcheck on the returned object for final adjusting.
A Pmetrics style PMmatrix data.frame.
Michael Neely
PMcheck, PMwriteMatrix, PMwrk2csv
Example output from an NPAG run with validation.
NPexNPex
R6 PM_result
This is an R6 Pmetrics PM_result object created with PM_load() after an NPAG run.
The run consisted of a model with an absorptive compartment and a central compartment.
There were 4 parameters in the model: lag time of absorption (Tlag1),
rate constant of absorption (Ka), volume (V) with weight as a covariate, and
rate constant of elmination (Ke).
There were 20 subjects in the dataset. The run was
100 cycles long and did not converge. It was then validated with the $validate
method for PM_result objects.
Michael Neely
Create a PM_model object for the one_comp_bolus model template.
one_comp_bolus()one_comp_bolus()
A PM_model object.
Create a PM_model object for the one_comp_bolus_cl model template.
one_comp_bolus_cl()one_comp_bolus_cl()
A PM_model object.
Create a PM_model object for the one_comp_iv model template.
one_comp_iv()one_comp_iv()
A PM_model object.
Create a PM_model object for the one_comp_iv_cl model template.
one_comp_iv_cl()one_comp_iv_cl()
A PM_model object.
Finds an opposite color with maximum contrast to the input color.
opposite_color( col, method = c("complement", "complement_maxcontrast", "bw_maxcontrast"), degrees = 180 )opposite_color( col, method = c("complement", "complement_maxcontrast", "bw_maxcontrast"), degrees = 180 )
col |
A color name or hex string (e.g. "red", "#FF0000", "#FF0000FF"). |
method |
The method to use for finding the opposite color. One of "complement", "complement_maxcontrast", or "bw_maxcontrast". Default is "complement". |
degrees |
The degree offset for the hue complement. Default is 180. |
This function takes a color input (name or hex) and returns an opposite color using one of three methods:
"complement": strict 180 degrees hue complement
"complement_maxcontrast": 180 degrees hue complement adjusted for maximum contrast
"bw_maxcontrast": black or white, whichever has higher contrast The function uses the WCAG relative luminance and contrast ratio formulas to determine contrast.
A hex color string in the format "#RRGGBBAA".
Plot PMcov objects
## S3 method for class 'PM_cov' plot( x, formula, line = list(lm = NULL, loess = NULL, ref = NULL), marker = TRUE, colors, icen = "median", include = NULL, exclude = NULL, legend, log = FALSE, grid = TRUE, xlab, ylab, title, stats = TRUE, xlim, ylim, print = TRUE, ... )## S3 method for class 'PM_cov' plot( x, formula, line = list(lm = NULL, loess = NULL, ref = NULL), marker = TRUE, colors, icen = "median", include = NULL, exclude = NULL, legend, log = FALSE, grid = TRUE, xlab, ylab, title, stats = TRUE, xlim, ylim, print = TRUE, ... )
x |
The name of an PM_cov data object
and loaded with PM_load as a PM_result, e.g. |
formula |
This is a mandatory formula of the form |
line |
Controls characteristics of lines. Unlike
some other Pmetrics plots, but like plot.PM_op,
|
marker |
Controls the plotting symbol for observations. This argument maps to the plotly marker object. It can be boolean or a list.
Example: |
colors |
to use for subjects when time is set as the x parameter.
This can be a palette or a vector of colors.
For accepted palette names see |
icen |
Can be either "median" for the predictions based on medians of |
include |
A vector of subject IDs to include in the plot, e.g. c(1:3,5,15) |
exclude |
A vector of subject IDs to exclude in the plot, e.g. c(4,6:14,16:20) |
legend |
Not used for this function. |
log |
Boolean operator to plot the y axis in log base 10. This argument maps to the yaxis type value in the layout object in plotly. Use the plotly Example: |
grid |
Controls grid display. This argument maps to the xaxis and yaxis layout objects in plotly. Use the plotly Examples:
|
xlab |
Value for x axis label. This argument maps to the the xaxis title element of the layout object in plotly. It can simply be a character vector of length 1 that specifies the name of the axis, or it can be a list for greater control. Use the plotly Examples:
If missing, will default to the name of the x variable in the formula. |
ylab |
Value for y axis label. This argument maps to the the yaxis title element of the layout object in plotly. See If missing, will default to the name of the y variable in the formula. |
title |
Plot title. This argument maps to the the title layout object in plotly. It can simply be a character vector of length 1 that specifies the name of the plot title, or it can be a list for greater control. Use the plotly Examples:
Default is to have no title. |
stats |
Add the statistics from linear regression to the plot. If
|
xlim |
Limits of the x axis as a vector. This argument maps to the the xaxis range in the layout object in plotly. Use the plotly Example: |
ylim |
Limits of the y axis as a vector. This argument maps to the the yaxis range in the layout object in plotly. Use the plotly Example: |
print |
If |
... |
Other attributes which can be passed to the layout > xaxis/yaxis in a plotly plot to further control formatting. Note that Examples:
. |
This method will plot any two columns, specified using a formula, of a PMcov object, which contains covariate and Bayesian posterior parameter information
for each subject. Specifiying any two variables that do not include time will result in a scatter plot with optional regression and reference lines. If
time is included as the x variable, the y variable will be plotted vs. time, aggregated by subject. This can be useful to see time varying parameters,
although a formula within formula approach may be required, e.g. $plot(I(cl_0*wt**0.75) ~ time) in order to see the change in cl over time according to
the change in wt over time, even though cl_0 is constant for a given subject.
Plots the object.
Michael Neely
Other PMplots:
plot.PM_cycle(),
plot.PM_data(),
plot.PM_final(),
plot.PM_model(),
plot.PM_op(),
plot.PM_opt(),
plot.PM_pop(),
plot.PM_post(),
plot.PM_pta(),
plot.PM_sim(),
plot.PM_valid()
#' ## Not run: NPex$cov$plot(V ~ wt) NPex$cov$plot(Ke ~ wt, line = list(lm = TRUE, ref = FALSE, loess = FALSE)) NPex$cov$plot(Ke ~ wt, line = list(loess = list(ci = 0.9, color = "green"))) NPex$cov$plot(V ~ time, marker = list(color = "blue")) NPex$cov$plot(V ~ wt, line = list(lm = TRUE, loess = FALSE), stats = list(x = 0.5, y = 0.2, font = list(size = 7, color = "blue")) ) ## End(Not run)#' ## Not run: NPex$cov$plot(V ~ wt) NPex$cov$plot(Ke ~ wt, line = list(lm = TRUE, ref = FALSE, loess = FALSE)) NPex$cov$plot(Ke ~ wt, line = list(loess = list(ci = 0.9, color = "green"))) NPex$cov$plot(V ~ time, marker = list(color = "blue")) NPex$cov$plot(V ~ wt, line = list(lm = TRUE, loess = FALSE), stats = list(x = 0.5, y = 0.2, font = list(size = 7, color = "blue")) ) ## End(Not run)
Plot PM_cycle objects. These objects are created by as part of a PM_result object when PM_load is run.
## S3 method for class 'PM_cycle' plot( x, line = TRUE, marker = TRUE, colors, linetypes, omit, grid = TRUE, xlab, ylab, print = TRUE, ... )## S3 method for class 'PM_cycle' plot( x, line = TRUE, marker = TRUE, colors, linetypes, omit, grid = TRUE, xlab, ylab, print = TRUE, ... )
x |
The name of a PM_cycle object, e.g. |
line |
Controls characteristics of lines. This argument maps to plotly line attributes.
Example: |
marker |
Controls the plotting symbol for observations. This argument maps to the plotly marker object. It can be boolean or a list.
Example: |
colors |
to use for normalized parameter value line traces. This can be a palette or a vector of colors.
For accepted palette names see |
linetypes |
to use for normalized parameter value line traces.
See |
omit |
Decimal between 0 and 1 specifying the proportion of "burn-in" cycles to omit from the plots. If missing, the first 20% will be omitted. |
grid |
Controls grid display. This argument maps to the xaxis and yaxis layout objects in plotly. Use the plotly Examples:
|
xlab |
Controls the formatting of the x-axis label. The text is fixed by the function and cannot be altered.
Use the plotly
|
ylab |
Format for y-axis label.
This argument maps to the the yaxis title element of the layout object in plotly.
See |
print |
If |
... |
Additional R plotting parameters. |
Plots a panel with the following windows: -2 times the log-likelihood at each cycle, gamma/lambda at each cycle; Akaike Information Criterion at each cyle and Bayesian (Schwartz) Information Criterion at each cycle, the mean parameter values at each cycle (normalized to starting values); the normalized standard deviation of the population distribution for each parameter at each cycle; and the normalized median parameter values at each cycle.
Michael Neely
Other PMplots:
plot.PM_cov(),
plot.PM_data(),
plot.PM_final(),
plot.PM_model(),
plot.PM_op(),
plot.PM_opt(),
plot.PM_pop(),
plot.PM_post(),
plot.PM_pta(),
plot.PM_sim(),
plot.PM_valid()
## Not run: NPex$cycle$plot() NPex$cycle$plot(omit = 0, marker = list(symbol = "cross"), line = list(width = 1)) NPex$cycle$plot( linetypes = "dash", colors = "Blues", marker = list(size = 1), line = list(width = 3) ) NPex$cycle$plot( grid = FALSE, xlab = list(bold = FALSE, font = list(color = "red", family = "Arial", size = 10)) ) ## End(Not run)## Not run: NPex$cycle$plot() NPex$cycle$plot(omit = 0, marker = list(symbol = "cross"), line = list(width = 1)) NPex$cycle$plot( linetypes = "dash", colors = "Blues", marker = list(size = 1), line = list(width = 3) ) NPex$cycle$plot( grid = FALSE, xlab = list(bold = FALSE, font = list(color = "red", family = "Arial", size = 10)) ) ## End(Not run)
Plots the raw data (
class: PM_cycle_data) from a PM_cycle object in the same way as plotting a PM_cycle object.
Both use plot.PM_cycle.
## S3 method for class 'PM_cycle_data' plot(x, ...)## S3 method for class 'PM_cycle_data' plot(x, ...)
x |
A |
... |
Additional arguments passed to plot.PM_cycle |
# There is no example we can think of to filter or otherwise process a PM_cycle object, # but we provide this function for completeness. NPex$cycle$data %>% plot()# There is no example we can think of to filter or otherwise process a PM_cycle object, # but we provide this function for completeness. NPex$cycle$data %>% plot()
Plots PM_data objects
## S3 method for class 'PM_data' plot( x, include = NULL, exclude = NULL, line = list(join = TRUE, pred = FALSE), marker = TRUE, group = NULL, group_names = NULL, mult = 1, outeq = 1, out_names = NULL, block = 1, tad = FALSE, overlay = TRUE, legend, log = FALSE, grid = FALSE, xlab = "Time", ylab = "Output", title = "", xlim, ylim, print = TRUE, ... )## S3 method for class 'PM_data' plot( x, include = NULL, exclude = NULL, line = list(join = TRUE, pred = FALSE), marker = TRUE, group = NULL, group_names = NULL, mult = 1, outeq = 1, out_names = NULL, block = 1, tad = FALSE, overlay = TRUE, legend, log = FALSE, grid = FALSE, xlab = "Time", ylab = "Output", title = "", xlim, ylim, print = TRUE, ... )
x |
The name of an |
include |
A vector of subject IDs to include in the plot, e.g. c(1:3,5,15) |
exclude |
A vector of subject IDs to exclude in the plot, e.g. c(4,6:14,16:20) |
line |
Controls characteristics of lines as for all plotly plots.
Here
**Note:**The color of the joining line
is the same as the marker color for that line. To avoid confusion, the line
color cannot be changed. Change the
To format the predictions, supply
|
marker |
Formats the symbols plotting observations. Controls the plotting symbol for observations. This argument maps to the plotly marker object. It can be boolean or a list.
Example: |
group |
Character vector naming one column in |
group_names |
A character vector of names to label the groups if |
mult |
Multiplication factor for y axis, e.g. to convert mg/L to ng/mL |
outeq |
Which output equation to plot. Default is 1.
Default is 1, but can be multiple if present in the data, e.g. |
out_names |
Character vector of names to label the outputs if |
block |
Which block to plot, where blocks are defined by dose reset events (EVID = 4) in the data.
Default is 1, but can be multiple if present in the data, as for |
tad |
Boolean operator to use time after dose rather than time after start. Default is |
overlay |
Operator to overlay all time concentration profiles in a single plot.
The default is |
legend |
Controls display of legend. This argument maps to the plotly layout showlegend and legend arguments. It is either a boolean operator (most common) or a list of parameters to be supplied to plotly. See Examples:
Default is |
log |
Boolean operator to plot the y axis in log base 10. This argument maps to the yaxis type value in the layout object in plotly. Use the plotly Example: |
grid |
Controls grid display. This argument maps to the xaxis and yaxis layout objects in plotly. Use the plotly Examples:
|
xlab |
Value for x axis label. This argument maps to the the xaxis title element of the layout object in plotly. It can simply be a character vector of length 1 that specifies the name of the axis, or it can be a list for greater control. Use the plotly Examples:
Default is "Time". |
ylab |
Value for y axis label. This argument maps to the the yaxis title element of the layout object in plotly. See Default is "Output". |
title |
Plot title. This argument maps to the the title layout object in plotly. It can simply be a character vector of length 1 that specifies the name of the plot title, or it can be a list for greater control. Use the plotly Examples:
Default is to have no title. |
xlim |
Limits of the x axis as a vector. This argument maps to the the xaxis range in the layout object in plotly. Use the plotly Example: |
ylim |
Limits of the y axis as a vector. This argument maps to the the yaxis range in the layout object in plotly. Use the plotly Example: |
print |
If |
... |
Other attributes which can be passed to the layout > xaxis/yaxis in a plotly plot to further control formatting. Note that Examples:
. |
This function will plot raw and fitted time and concentration data with a variety of options.
By default markers are included and have the following plotly properties:
list(symbol = "circle", color = "red", size = 10, opacity = 0.5, line = list(color = "black", width = 1)).
Markers can be joined by lines, default is FALSE. If chosen to be TRUE,
the joining lines will have the following properties:
list(color = "dodgerblue", width = 1, dash = "solid".
The grid and legend are omitted by default.
Plots the object.
Michael Neely
Other PMplots:
plot.PM_cov(),
plot.PM_cycle(),
plot.PM_final(),
plot.PM_model(),
plot.PM_op(),
plot.PM_opt(),
plot.PM_pop(),
plot.PM_post(),
plot.PM_pta(),
plot.PM_sim(),
plot.PM_valid()
## Not run: # basic spaghetti plot dataEx$plot() # format line and marker dataEx$plot( marker = list(color = "blue", symbol = "square", size = 12, opacity = 0.4), line = list(join = list(color = "orange")) ) # include predictions with default format and suppress joining lines dataEx$plot( line = list(join = FALSE, pred = NPex$post), xlim = c(119, 146) ) # customize prediction lines dataEx$plot( line = list( pred = list(NPex$post, color = "slategrey", dash = "dash"), join = FALSE ) ) ## End(Not run)## Not run: # basic spaghetti plot dataEx$plot() # format line and marker dataEx$plot( marker = list(color = "blue", symbol = "square", size = 12, opacity = 0.4), line = list(join = list(color = "orange")) ) # include predictions with default format and suppress joining lines dataEx$plot( line = list(join = FALSE, pred = NPex$post), xlim = c(119, 146) ) # customize prediction lines dataEx$plot( line = list( pred = list(NPex$post, color = "slategrey", dash = "dash"), join = FALSE ) ) ## End(Not run)
Allows plotting of altered PM_data objects.
## S3 method for class 'PM_data_data' plot(x, ...)## S3 method for class 'PM_data_data' plot(x, ...)
x |
A data frame in the format of the |
... |
Additional arguments passed to plot.PM_data |
This is useful if you want to modify the data in a PM_data object, e.g. to filter the data, but still want to use the plotting capabilities of plot.PM_data. See plot.PM_data for details on how to format the plot.
A plot of the data.
Michael Neely
## Not run: # filter then plot the standard_data data frame from a PM_data object dataEx$standard_data %>% filter(gender == 0) %>% plot() ## End(Not run)## Not run: # filter then plot the standard_data data frame from a PM_data object dataEx$standard_data %>% filter(gender == 0) %>% plot() ## End(Not run)
Plot R6 PM_final objects loaded as a field in the
PM_result object, e.g. PM_result$final.
## S3 method for class 'PM_final' plot( x, formula = NULL, line, marker = TRUE, standardize, legend, log, grid = TRUE, xlab, ylab, zlab, title, xlim, ylim, print = TRUE, ... )## S3 method for class 'PM_final' plot( x, formula = NULL, line, marker = TRUE, standardize, legend, log, grid = TRUE, xlab, ylab, zlab, title, xlim, ylim, print = TRUE, ... )
x |
The name of an PM_final data object as a field in a PM_result R6
object, e.g |
formula |
An optional formula of the form |
line |
Controls characteristics of lines. This argument maps to plotly line attributes.
Example:
|
marker |
See details for which objects the
|
standardize |
Standardize the normal parameter distribution plots from IT2B to the same scale x-axis. Ignored for NPAG output. |
legend |
Ignored for this plot. |
log |
Boolean operator to plot the y axis in log base 10. This argument maps to the yaxis type value in the layout object in plotly. Use the plotly Example: |
grid |
Controls grid display. This argument maps to the xaxis and yaxis layout objects in plotly. Use the plotly Examples:
|
xlab |
Value for x axis label. This argument maps to the the xaxis title element of the layout object in plotly. It can simply be a character vector of length 1 that specifies the name of the axis, or it can be a list for greater control. Use the plotly Examples:
Default is the name of the plotted x-variable. Formatting can be controlled, but the text is recommended to not be changed. |
ylab |
Value for y axis label. This argument maps to the the yaxis title element of the layout object in plotly. See Default is "Probability" for univariate plots, and the name of the plotted y-variable for bivariate plots. Formatting can be controlled, but the text is recommended to not be changed. |
zlab |
Only for bivariate plots. Default is "Probability". Can be a list
to control formatting or default text, as for |
title |
Plot title. This argument maps to the the title layout object in plotly. It can simply be a character vector of length 1 that specifies the name of the plot title, or it can be a list for greater control. Use the plotly Examples:
Default is to have no title on plots. |
xlim |
Limits of the x axis as a vector. This argument maps to the the xaxis range in the layout object in plotly. Use the plotly Example: |
ylim |
Limits of the y axis as a vector. This argument maps to the the yaxis range in the layout object in plotly. Use the plotly Example: |
print |
If |
... |
Other attributes which can be passed to the layout > xaxis/yaxis in a plotly plot to further control formatting. Note that Examples:
. |
This is a function usually called by the $plot() method for PM_final objects
within a PM_result to generate a plot the parameter value probability densities
after completion of a model fitting.
The function can be called directly on a PM_final object.
If formula is omitted, this will generate a marginal plot for each parameter.
For NPAG data, this will be a histogram of marginal values for each parameter and the associated probability
of that value. For IT2B, this will be a series of normal distributions with mean and standard deviation
equal to the mean and standard deviation of each parameter marginal distribution.
On the other hand, if formula is specified as two parameters, e.g. CL~V, this will generate a bivariate plot.
For NPAG data, it will be support point with size proportional to the probability
of each point. For IT2B, it will be an elliptical distribution of a bivariate normal distribution centered at the mean
of each plotted variable and surrounding quantiles of the bivariate distribution plotted in decreasing shades of grey.
Mulitvariate normal density code is borrowed from the mvtnorm package.
Plots the object.
Michael Neely
Other PMplots:
plot.PM_cov(),
plot.PM_cycle(),
plot.PM_data(),
plot.PM_model(),
plot.PM_op(),
plot.PM_opt(),
plot.PM_pop(),
plot.PM_post(),
plot.PM_pta(),
plot.PM_sim(),
plot.PM_valid()
## Not run: # NPAG NPex$final$plot() NPex$final$plot(line = TRUE) NPex$final$plot(Ke ~ V) # IT2B ITex$final$plot() ITex$final$plot(Ke ~ V) ## End(Not run)## Not run: # NPAG NPex$final$plot() NPex$final$plot(line = TRUE) NPex$final$plot(Ke ~ V) # IT2B ITex$final$plot() ITex$final$plot(Ke ~ V) ## End(Not run)
Plots the raw data (
class: PM_final_data) from a PM_final object in the same way as plotting a PM_final object.
Both use plot.PM_final.
## S3 method for class 'PM_final_data' plot(x, ...)## S3 method for class 'PM_final_data' plot(x, ...)
x |
A 'PM_final_data“ object |
... |
Additional arguments passed to plot.PM_final |
NPex$final$data %>% plot()NPex$final$data %>% plot()
Plots a PM_model based on differential equations using ggplot.
## S3 method for class 'PM_model' plot(x, marker = TRUE, line = TRUE, explicit, implicit, print = TRUE, ...)## S3 method for class 'PM_model' plot(x, marker = TRUE, line = TRUE, explicit, implicit, print = TRUE, ...)
x |
The name of an PM_model object. |
marker |
Controls the characteristics of the compartments (nodes).
It can be boolean or a list.
Example: |
line |
Controls characteristics of arrows (edges).
Example: |
explicit |
A data frame or tibble containing two columns named |
implicit |
Similar to |
print |
If |
... |
Not used. |
This accepts a PM_model object and creates a network plot where nodes are compartments and edges are arrows connecting compartments.
A plot object of the model.
Markus Hovd, Julian Otalvaro, Michael Neely
Other PMplots:
plot.PM_cov(),
plot.PM_cycle(),
plot.PM_data(),
plot.PM_final(),
plot.PM_op(),
plot.PM_opt(),
plot.PM_pop(),
plot.PM_post(),
plot.PM_pta(),
plot.PM_sim(),
plot.PM_valid()
## Not run: NPex$model$plot() ## End(Not run)## Not run: NPex$model$plot() ## End(Not run)
Plot PM_op objects
## S3 method for class 'PM_op' plot( x, line = list(lm = NULL, loess = NULL, ref = NULL), marker = TRUE, resid = FALSE, icen = "median", pred.type = "post", outeq = 1, block, include, exclude, mult = 1, legend, log = FALSE, grid = TRUE, xlab, ylab, title, stats = TRUE, print = TRUE, xlim, ylim, ... )## S3 method for class 'PM_op' plot( x, line = list(lm = NULL, loess = NULL, ref = NULL), marker = TRUE, resid = FALSE, icen = "median", pred.type = "post", outeq = 1, block, include, exclude, mult = 1, legend, log = FALSE, grid = TRUE, xlab, ylab, title, stats = TRUE, print = TRUE, xlim, ylim, ... )
x |
The name of a PM_op data object
and loaded with PM_load as a field in a PM_result, e.g. |
line |
Controls characteristics of lines. Unlike
some other Pmetrics plots, for plot.PM_op,
|
marker |
Controls the plotting symbol for observations. This argument maps to the plotly marker object. It can be boolean or a list.
Example: |
resid |
Boolean operator to generate a plot of weighted prediction error vs. time, a plot of weighted prediction error vs. prediction. Prediction error is pred - obs. By default a loess regression will indicate deviation from zero prediction error. |
icen |
Can be either "median" for the predictions based on medians of |
pred.type |
Either 'post' for a posterior object or 'pop' for a population object. Default is 'post'. |
outeq |
Which output equation to plot. Default is 1. |
block |
Which block to plot, where blocks are defined by dose reset events (EVID = 4) in the data. Default is missing, which results in all blocks included. |
include |
A vector of subject IDs to include in the plot, e.g. c(1:3,5,15) |
exclude |
A vector of subject IDs to exclude in the plot, e.g. c(4,6:14,16:20) |
mult |
Multiplication factor for y axis, e.g. to convert mg/L to ng/mL |
legend |
Ignored for this plot. |
log |
Boolean operator to plot the y axis in log base 10. This argument maps to the yaxis type value in the layout object in plotly. Use the plotly Example: |
grid |
Controls grid display. This argument maps to the xaxis and yaxis layout objects in plotly. Use the plotly Examples:
|
xlab |
Value for x axis label. This argument maps to the the xaxis title element of the layout object in plotly. It can simply be a character vector of length 1 that specifies the name of the axis, or it can be a list for greater control. Use the plotly Examples:
If missing, will default to "Predicted" for
plots when |
ylab |
Value for y axis label. This argument maps to the the yaxis title element of the layout object in plotly. See If missing, will default to "Observed" for
plots when |
title |
Plot title. This argument maps to the the title layout object in plotly. It can simply be a character vector of length 1 that specifies the name of the plot title, or it can be a list for greater control. Use the plotly Examples:
Default is to have no title. |
stats |
Add the statistics from linear regression to the plot. If
|
print |
If |
xlim |
Limits of the x axis as a vector. This argument maps to the the xaxis range in the layout object in plotly. Use the plotly Example: |
ylim |
Limits of the y axis as a vector. This argument maps to the the yaxis range in the layout object in plotly. Use the plotly Example: |
... |
Other attributes which can be passed to the layout > xaxis/yaxis in a plotly plot to further control formatting. Note that Examples:
. |
This is a function usually called by the $plot() method for PM_op objects
within a PM_result to generate a plot of Observed vs. Predicted observations.
The function can be called directly on a PM_op object. The default
is to generate an observed vs. predicted plot of predictions based on the
median of the Bayesian posterior distributions for each subject.
Missing observations are excluded. Observations reported as BLQ (below the limit of quantification)
are indicated as downward triangles, and colored differently from other observations. They are plotted
at the reported LOQ on the observed axis and the predicted value on the predicted axis. They are not
included in any regression lines or statistics.
Clicking on a point in the plot will highlight all points from that subject. The color of the highlight is 180 degrees different on the color wheel from the color of the other points (opposite_color), ensuring good contrast. Clicking on the plot background will remove the highlighting.
Plots the object.
Michael Neely
Other PMplots:
plot.PM_cov(),
plot.PM_cycle(),
plot.PM_data(),
plot.PM_final(),
plot.PM_model(),
plot.PM_opt(),
plot.PM_pop(),
plot.PM_post(),
plot.PM_pta(),
plot.PM_sim(),
plot.PM_valid()
## Not run: NPex$op$plot() NPex$op$plot(pred.type = "pop") NPex$op$plot(line = list(lm = TRUE, ref = TRUE, loess = FALSE)) NPex$op$plot(line = list(loess = list(ci = 0.9, color = "green"))) NPex$op$plot(marker = list(color = "blue")) NPex$op$plot(resid = TRUE) NPex$op$plot(stats = list(x = 0.5, y = 0.2, font = list(size = 7, color = "blue"))) ## End(Not run)## Not run: NPex$op$plot() NPex$op$plot(pred.type = "pop") NPex$op$plot(line = list(lm = TRUE, ref = TRUE, loess = FALSE)) NPex$op$plot(line = list(loess = list(ci = 0.9, color = "green"))) NPex$op$plot(marker = list(color = "blue")) NPex$op$plot(resid = TRUE) NPex$op$plot(stats = list(x = 0.5, y = 0.2, font = list(size = 7, color = "blue"))) ## End(Not run)
Plots the raw data (
class: PM_op_data) from a PM_op object in the same way as plotting a PM_op object.
Both use plot.PM_op.
## S3 method for class 'PM_op_data' plot(x, ...)## S3 method for class 'PM_op_data' plot(x, ...)
x |
A 'PM_op_data“ object |
... |
Additional arguments passed to plot.PM_op |
## Not run: NPex$op$data %>% dplyr::filter(pred > 5) %>% dplyr::filter(pred < 10) %>% plot() ## End(Not run)## Not run: NPex$op$data %>% dplyr::filter(pred > 5) %>% dplyr::filter(pred < 10) %>% plot() ## End(Not run)
Plots PM_opt objects
## S3 method for class 'PM_opt' plot(x, line = list(probs = NA), times = T, print = TRUE, ...)## S3 method for class 'PM_opt' plot(x, line = list(probs = NA), times = T, print = TRUE, ...)
x |
A PM_opt object |
line |
Passed to plot.PM_sim with default as |
times |
Format the vertical lines for optimal times. Default is dashed red line. r template("line")' |
print |
If |
... |
Other parameters to pass to plot.PM_sim. |
probs |
Default is NA. See plot.PM_sim for details. |
Simulated observations are plotted on the y-axis vs. time on the x.axis.
Optimal sampling times are indicated as vertical lines. Defaults for optimal
sample times are red, dash, width 2. Defaults for the line format are as
for plot.PM_sim.
Plots the simulation profiles with MM optimal times indicated as vertical lines.
Michael Neely
Other PMplots:
plot.PM_cov(),
plot.PM_cycle(),
plot.PM_data(),
plot.PM_final(),
plot.PM_model(),
plot.PM_op(),
plot.PM_pop(),
plot.PM_post(),
plot.PM_pta(),
plot.PM_sim(),
plot.PM_valid()
Plots PM_pop objects
## S3 method for class 'PM_pop' plot( x, include = NULL, exclude = NULL, line = list(join = TRUE), marker = FALSE, out_names = NULL, mult = 1, icen = "median", outeq = 1, block = 1, overlay = TRUE, legend = FALSE, log = FALSE, grid = FALSE, xlab = "Time", ylab = "Output", title = "", xlim, ylim, print = TRUE, ... )## S3 method for class 'PM_pop' plot( x, include = NULL, exclude = NULL, line = list(join = TRUE), marker = FALSE, out_names = NULL, mult = 1, icen = "median", outeq = 1, block = 1, overlay = TRUE, legend = FALSE, log = FALSE, grid = FALSE, xlab = "Time", ylab = "Output", title = "", xlim, ylim, print = TRUE, ... )
x |
The name of a PM_pop object, e.g. |
include |
A vector of subject IDs to include in the plot, e.g. c(1:3,5,15) |
exclude |
A vector of subject IDs to exclude in the plot, e.g. c(4,6:14,16:20) |
line |
Controls characteristics of lines as for all plotly plots.
It can either be a boolean or a list. If set to |
marker |
Formats the symbols plotting observations. Controls the plotting symbol for observations. This argument maps to the plotly marker object. It can be boolean or a list.
Example: Marker colors control group display colors. When multiple output equations are displayed
(via |
out_names |
A character vector of names to label the output equations if |
mult |
Multiplication factor for y axis, e.g. to convert mg/L to ng/mL |
icen |
Can be |
outeq |
Which output equation to plot. Default is 1.
Default is 1, but can be multiple if present in the data, e.g. |
block |
Which block to plot, where blocks are defined by dose reset events (EVID = 4) in the data.
Default is 1, but can be multiple if present in the data, as for |
overlay |
Operator to overlay all time prediction profiles in a single plot.
The default is |
legend |
Not used for this plot. |
log |
Boolean operator to plot the y axis in log base 10. This argument maps to the yaxis type value in the layout object in plotly. Use the plotly Example: |
grid |
Controls grid display. This argument maps to the xaxis and yaxis layout objects in plotly. Use the plotly Examples:
|
xlab |
Value for x axis label. This argument maps to the the xaxis title element of the layout object in plotly. It can simply be a character vector of length 1 that specifies the name of the axis, or it can be a list for greater control. Use the plotly Examples:
Default is "Time". |
ylab |
Value for y axis label. This argument maps to the the yaxis title element of the layout object in plotly. See Default is "Output". |
title |
Plot title. This argument maps to the the title layout object in plotly. It can simply be a character vector of length 1 that specifies the name of the plot title, or it can be a list for greater control. Use the plotly Examples:
Default is to have no title. |
xlim |
Limits of the x axis as a vector. This argument maps to the the xaxis range in the layout object in plotly. Use the plotly Example: |
ylim |
Limits of the y axis as a vector. This argument maps to the the yaxis range in the layout object in plotly. Use the plotly Example: |
print |
If |
... |
Other attributes which can be passed to the layout > xaxis/yaxis in a plotly plot to further control formatting. Note that Examples:
. |
This is a function usually called by the $plot() method for PM_pop objects
within a PM_result to generate the plot.
However, the function can be called directly on a PM_pop object.
This function will plot time and population predictions with a variety of options.
By default markers are included and have the following plotly properties:
list(symbol = "circle", color = "red", size = 10, opacity = 0.5, line = list(color = "black", width = 1)).
Markers are omitted by default.
If enabled, markers can be joined by lines, default is line = list(join = TRUE).
If joined,
the joining lines will have the following properties:
list(color = "dodgerblue", width = 1, dash = "solid".
The grid and legend are omitted by default.
Plots the object.
Michael Neely
Other PMplots:
plot.PM_cov(),
plot.PM_cycle(),
plot.PM_data(),
plot.PM_final(),
plot.PM_model(),
plot.PM_op(),
plot.PM_opt(),
plot.PM_post(),
plot.PM_pta(),
plot.PM_sim(),
plot.PM_valid()
## Not run: # basic spaghetti plot NPex$pop$plot() # format line and marker NPex$pop$plot( marker = list(color = "blue", symbol = "square", size = 12, opacity = 0.4), line = list(color = "orange") ) ## End(Not run)## Not run: # basic spaghetti plot NPex$pop$plot() # format line and marker NPex$pop$plot( marker = list(color = "blue", symbol = "square", size = 12, opacity = 0.4), line = list(color = "orange") ) ## End(Not run)
Plots PM_post objects
## S3 method for class 'PM_post' plot( x, include = NULL, exclude = NULL, line = list(join = TRUE), marker = FALSE, out_names = NULL, mult = 1, icen = "median", outeq = 1, block = 1, overlay = TRUE, legend = FALSE, log = FALSE, grid = FALSE, xlab = "Time", ylab = "Output", title = "", print = TRUE, xlim, ylim, ... )## S3 method for class 'PM_post' plot( x, include = NULL, exclude = NULL, line = list(join = TRUE), marker = FALSE, out_names = NULL, mult = 1, icen = "median", outeq = 1, block = 1, overlay = TRUE, legend = FALSE, log = FALSE, grid = FALSE, xlab = "Time", ylab = "Output", title = "", print = TRUE, xlim, ylim, ... )
x |
The name of a PM_post object, e.g. |
include |
A vector of subject IDs to include in the plot, e.g. c(1:3,5,15) |
exclude |
A vector of subject IDs to exclude in the plot, e.g. c(4,6:14,16:20) |
line |
Controls characteristics of lines as for all plotly plots.
It can either be a boolean or a list. If set to |
marker |
Formats the symbols plotting observations. Controls the plotting symbol for observations. This argument maps to the plotly marker object. It can be boolean or a list.
Example: Marker colors control group display colors. When multiple output equations are displayed
(via |
out_names |
A character vector of names to label the output equations if |
mult |
Multiplication factor for y axis, e.g. to convert mg/L to ng/mL |
icen |
Can be |
outeq |
Which output equation to plot. Default is 1.
Default is 1, but can be multiple if present in the data, e.g. |
block |
Which block to plot, where blocks are defined by dose reset events (EVID = 4) in the data.
Default is 1, but can be multiple if present in the data, as for |
overlay |
Operator to overlay all time prediction profiles in a single plot.
The default is |
legend |
Not used for this plot. |
log |
Boolean operator to plot the y axis in log base 10. This argument maps to the yaxis type value in the layout object in plotly. Use the plotly Example: |
grid |
Controls grid display. This argument maps to the xaxis and yaxis layout objects in plotly. Use the plotly Examples:
|
xlab |
Value for x axis label. This argument maps to the the xaxis title element of the layout object in plotly. It can simply be a character vector of length 1 that specifies the name of the axis, or it can be a list for greater control. Use the plotly Examples:
Default is "Time". |
ylab |
Value for y axis label. This argument maps to the the yaxis title element of the layout object in plotly. See Default is "Output". |
title |
Plot title. This argument maps to the the title layout object in plotly. It can simply be a character vector of length 1 that specifies the name of the plot title, or it can be a list for greater control. Use the plotly Examples:
Default is to have no title. |
print |
If |
xlim |
Limits of the x axis as a vector. This argument maps to the the xaxis range in the layout object in plotly. Use the plotly Example: |
ylim |
Limits of the y axis as a vector. This argument maps to the the yaxis range in the layout object in plotly. Use the plotly Example: |
... |
Other attributes which can be passed to the layout > xaxis/yaxis in a plotly plot to further control formatting. Note that Examples:
. |
This is a function usually called by the $plot() method for PM_post objects
within a PM_result to generate the plot.
However, the function can be called directly on a PM_post object.
This function will plot time and posterior predictions with a variety of options.
Markers are omitted by default. When enabled, markers have default plotly properties:
list(symbol = "circle", color = "red", size = 10, opacity = 0.5, line = list(color = "black", width = 1)).
Markers can be joined by lines, with default line = list(join = TRUE).
When joined, line colors are automatically matched to marker colors.
The joining lines have the following default properties:
list(color = "dodgerblue", width = 1, dash = "solid").
The grid and legend are omitted by default.
Plots the object.
Michael Neely
Other PMplots:
plot.PM_cov(),
plot.PM_cycle(),
plot.PM_data(),
plot.PM_final(),
plot.PM_model(),
plot.PM_op(),
plot.PM_opt(),
plot.PM_pop(),
plot.PM_pta(),
plot.PM_sim(),
plot.PM_valid()
## Not run: # basic spaghetti plot NPex$post$plot() # format line and marker NPex$post$plot( marker = list(color = "blue", symbol = "square", size = 12, opacity = 0.4), line = list(color = "orange") ) ## End(Not run)## Not run: # basic spaghetti plot NPex$post$plot() # format line and marker NPex$post$plot( marker = list(color = "blue", symbol = "square", size = 12, opacity = 0.4), line = list(color = "orange") ) ## End(Not run)
This function will plot the percent target attainment for associated with simulations.
## S3 method for class 'PM_pta' plot( x, at = "intersect", include, exclude, type = "pta", mult = 1, outeq = 1, line = TRUE, marker = TRUE, ci = 0.9, legend = TRUE, log = FALSE, grid = TRUE, xlab, ylab, title, xlim, ylim, print = TRUE, ... )## S3 method for class 'PM_pta' plot( x, at = "intersect", include, exclude, type = "pta", mult = 1, outeq = 1, line = TRUE, marker = TRUE, ci = 0.9, legend = TRUE, log = FALSE, grid = TRUE, xlab, ylab, title, xlim, ylim, print = TRUE, ... )
x |
The name of an PM_pta data object |
at |
Which object in the PM_pta result list to plot. By default "intersect" if
an intersection is present due to creation of the object with multiple target types, or
1 if no intersection is present, which means only 1 target type was selected. If
"intersect" is present in the object, the default can be overridden with a number to
plot one of the individual PTAs, e.g. |
include |
A vector of subject IDs to include in the plot, e.g. c(1:3,5,15) |
exclude |
A vector of subject IDs to exclude in the plot, e.g. c(4,6:14,16:20) |
type |
Character vector controlling type of plot. Default is "pta", which plots proportion with success on the y-axis and target on the x-axis. The other choice is "pdi", which plots the median pdi (pharmacodynamic index), e.g. AUC/MIC, on the y-axis, and target on the x-axis. |
mult |
Multiplication factor for y axis, e.g. to convert mg/L to ng/mL |
outeq |
Which output equation to plot. Default is 1. |
line |
Controls characteristics of lines.
This argument maps to the plotly line object.
It can be boolean or a list.
|
marker |
Controls the plotting symbol.
This argument maps to the plotly marker object.
It can be boolean or a list.
|
ci |
Confidence interval around curves on |
legend |
Controls display of legend. This argument maps to the plotly layout showlegend and legend arguments. It is either a boolean operator (most common) or a list of parameters to be supplied to plotly. See Examples:
Default will be the labeled regimen names as an argument when creating a PM_pta object, or if missing, "Regimen 1, Regimen 2,...Regimen n", where n is the number of regimens in the PM_pta object. |
log |
Boolean operator to plot the x axis in log base 10. This argument maps to
the xaxis type value in the layout object in plotly. Many other Pmetrics plots map this
argument to the y axis, but for PTA plots, the x axis is the more common axis to log transform.
Use the plotly |
grid |
Controls grid display. This argument maps to the xaxis and yaxis layout objects in plotly. Use the plotly Examples:
|
xlab |
Value for x axis label. This argument maps to the the xaxis title element of the layout object in plotly. It can simply be a character vector of length 1 that specifies the name of the axis, or it can be a list for greater control. Use the plotly Examples:
Default is "Target" when targets are discrete, and "Regimen" when targets are sampled. |
ylab |
Value for y axis label. This argument maps to the the yaxis title element of the layout object in plotly. See Default is "Proportion with success" for
plot |
title |
Plot title. This argument maps to the the title layout object in plotly. It can simply be a character vector of length 1 that specifies the name of the plot title, or it can be a list for greater control. Use the plotly Examples:
Default is to have no title. |
xlim |
Limits of the x axis as a vector. This argument maps to the the xaxis range in the layout object in plotly. Use the plotly Example: |
ylim |
Limits of the y axis as a vector. This argument maps to the the yaxis range in the layout object in plotly. Use the plotly Example: |
print |
If |
... |
Other attributes which can be passed to the layout > xaxis/yaxis in a plotly plot to further control formatting. Note that Examples:
. |
PM_pta objects are made with the $pta method for PM_sim or
with PM_pta$new().
Plots the object.
Michael Neely
Other PMplots:
plot.PM_cov(),
plot.PM_cycle(),
plot.PM_data(),
plot.PM_final(),
plot.PM_model(),
plot.PM_op(),
plot.PM_opt(),
plot.PM_pop(),
plot.PM_post(),
plot.PM_sim(),
plot.PM_valid()
## Not run: pta1 <- simEx$pta( simlabels <- c("600 mg daily", "1200 mg daily", "300 mg bid", "600 mg bid"), targets = c(0.25, 0.5, 1, 2, 4, 8, 16, 32), target.type = "time", success = 0.6, start = 120, end = 144 ) pta1$summary() pta1$plot() ## End(Not run)## Not run: pta1 <- simEx$pta( simlabels <- c("600 mg daily", "1200 mg daily", "300 mg bid", "600 mg bid"), targets = c(0.25, 0.5, 1, 2, 4, 8, 16, 32), target.type = "time", success = 0.6, start = 120, end = 144 ) pta1$summary() pta1$plot() ## End(Not run)
Plots PM_sim objects with the option to perform a visual and numerical predictive check
## S3 method for class 'PM_sim' plot( x, include, exclude, mult = 1, ci = 0.95, binSize = 0, outeq = 1, line = TRUE, marker = FALSE, obs, quiet = FALSE, legend = FALSE, log = TRUE, grid = FALSE, xlab, ylab, title, xlim, ylim, print = TRUE, ... )## S3 method for class 'PM_sim' plot( x, include, exclude, mult = 1, ci = 0.95, binSize = 0, outeq = 1, line = TRUE, marker = FALSE, obs, quiet = FALSE, legend = FALSE, log = TRUE, grid = FALSE, xlab, ylab, title, xlim, ylim, print = TRUE, ... )
x |
The name of an PM_sim data object generated by PM_sim |
include |
A vector of subject IDs to include in the plot, e.g. c(1:3,5,15) . |
exclude |
A vector of subject IDs to exclude in the plot, e.g. c(4,6:14,16:20) . |
mult |
Multiplication factor for y axis, e.g. to convert mg/L to ng/mL |
ci |
Width of confidence interval bands around simulated quantiles, from 0 to 1. If 0, or nsim<100, will not plot. Default is 0.95, i.e. 95th percentile with tails of 2.5 percent above and below excluded. |
binSize |
Width of binning interval for simulated concentrations, in time units, e.g. hours.
A |
outeq |
Which output equation to plot. Default is 1. |
line |
Controls the appearance of lines. It can be specified in several ways.
|
marker |
Controls the plotting symbol for observations. This argument maps to the plotly marker object. It can be boolean or a list.
Example: |
obs |
The name of a PM_result data object or the PM_op field in the
PM_result object, all generated by PM_load. For example, if
|
quiet |
If |
legend |
Controls display of legend. This argument maps to the plotly layout showlegend and legend arguments. It is either a boolean operator (most common) or a list of parameters to be supplied to plotly. See Examples:
Default is |
log |
Boolean operator to plot the y axis in log base 10. This argument maps to the yaxis type value in the layout object in plotly. Use the plotly Example: |
grid |
Controls grid display. This argument maps to the xaxis and yaxis layout objects in plotly. Use the plotly Examples:
Default is |
xlab |
Value for x axis label. This argument maps to the the xaxis title element of the layout object in plotly. It can simply be a character vector of length 1 that specifies the name of the axis, or it can be a list for greater control. Use the plotly Examples:
Default is "Time". |
ylab |
Value for y axis label. This argument maps to the the yaxis title element of the layout object in plotly. See Default is "Output". |
title |
Plot title. This argument maps to the the title layout object in plotly. It can simply be a character vector of length 1 that specifies the name of the plot title, or it can be a list for greater control. Use the plotly Examples:
Default is to have no title. |
xlim |
Limits of the x axis as a vector. This argument maps to the the xaxis range in the layout object in plotly. Use the plotly Example: |
ylim |
Limits of the y axis as a vector. This argument maps to the the yaxis range in the layout object in plotly. Use the plotly Example: |
print |
If |
... |
Other attributes which can be passed to the layout > xaxis/yaxis in a plotly plot to further control formatting. Note that Examples:
. |
Simulated observations are plotted as quantiles on the y-axis vs. time on the x.axis. If measured
observations are included, a visual and numerical predictive check will be performed.
The default plot is to omit markers, but if the marker argument is set to TRUE,
the resulting marker will have the following plotly properties:
list(symbol = "circle-open", color = "black", size = 8). By default a grid is
omitted. The legend is also omitted by default, but if included,
clicking on a quantile item in the legend will hide it in the plot,
and double clicking will hide all other quantiles.
Plots the simulation object. If obs is included, a list will be returned with
the folowing items:
npc A dataframe with three columns: quantile, prop_less, pval.
** quantile are those specified by the probs argument to the plot call
** prop_less are the proportion of simulated
observations at all times less than the quantile
** pval is the P-value of the difference in the
prop.less and quantile by the beta-binomial test.
simsum A dataframe with the quantile concentration at each simulated time, with lower and upper confidence intervals
obs A data frame similar to a the $data field of a PM_op object
with the addition of the quantile for each observation
Michael Neely
Other PMplots:
plot.PM_cov(),
plot.PM_cycle(),
plot.PM_data(),
plot.PM_final(),
plot.PM_model(),
plot.PM_op(),
plot.PM_opt(),
plot.PM_pop(),
plot.PM_post(),
plot.PM_pta(),
plot.PM_valid()
## Not run: simEx$plot() simEx$plot(log = FALSE, line = list(color = "orange")) ## End(Not run)## Not run: simEx$plot() simEx$plot(log = FALSE, line = list(color = "orange")) ## End(Not run)
Usually called by the
$plot method for PM_valid objects, which are in turn typically added
to a PM_result object by the $validate method. For example:
NPex$validate(limits = c(0, 3)) # creates a PM_valid object and adds it to the $valid field of NPex NPex$valid$plot(type = "vpc", tad = TRUE, log = TRUE) # now we can plot it
Plot PM_valid objects.
## S3 method for class 'PM_valid' plot( x, type = "vpc", tad = FALSE, outeq = 1, line = TRUE, marker = TRUE, legend = FALSE, log = FALSE, grid = TRUE, xlab, ylab, title, xlim, ylim, print = TRUE, ... )## S3 method for class 'PM_valid' plot( x, type = "vpc", tad = FALSE, outeq = 1, line = TRUE, marker = TRUE, legend = FALSE, log = FALSE, grid = TRUE, xlab, ylab, title, xlim, ylim, print = TRUE, ... )
x |
The name of an PM_valid data object, which is usually called by
the |
type |
Default is "vpc" for a visual predictive check, but could be
"pcvpc" for a prediction-corrected visual predictive check, or
"npde" for a normalized prediction distribution error analysis/plot.
Choosing npde will call npde::plot.NpdeObject. To modify this plot,
supply argmuents as a named list: |
tad |
Boolean operator to use time after dose rather than time after start. Default is |
outeq |
Which output equation to plot. Default is 1. |
line |
A list of three elements
|
marker |
Controls the plotting symbol for observations. This argument maps to the plotly marker object. It can be boolean or a list.
Example: |
legend |
Controls display of legend. This argument maps to the plotly layout showlegend and legend arguments. It is either a boolean operator (most common) or a list of parameters to be supplied to plotly. See Examples:
Default is |
log |
Boolean operator to plot the y axis in log base 10. This argument maps to the yaxis type value in the layout object in plotly. Use the plotly Example: |
grid |
Controls grid display. This argument maps to the xaxis and yaxis layout objects in plotly. Use the plotly Examples:
|
xlab |
Value for x axis label. This argument maps to the the xaxis title element of the layout object in plotly. It can simply be a character vector of length 1 that specifies the name of the axis, or it can be a list for greater control. Use the plotly Examples:
Default is "Time" or "Time after dose" if |
ylab |
Value for y axis label. This argument maps to the the yaxis title element of the layout object in plotly. See Default is "Output". |
title |
Plot title. This argument maps to the the title layout object in plotly. It can simply be a character vector of length 1 that specifies the name of the plot title, or it can be a list for greater control. Use the plotly Examples:
Default is to have no title. |
xlim |
Limits of the x axis as a vector. This argument maps to the the xaxis range in the layout object in plotly. Use the plotly Example: |
ylim |
Limits of the y axis as a vector. This argument maps to the the yaxis range in the layout object in plotly. Use the plotly Example: |
print |
If |
... |
If Examples:
.
.
However, if |
Generates a plot of outputs (typically concentrations) on the y axis and time
on the x axis. If tad was set to TRUE
when make_valid was called, then time may be either absolute (default) or time
after dose, controlled by the tad argument to this plot function.
The following items are included in the plot:
Observed outputs. These may be either as measured for type = "vpc" or
prediction corrected for type = "pcvpc". Format of the observations is
controlled by the marker argument. The default is
list(color = "black", symbol = "circle-open", size = 8).
Quantiles vs. time for observations. These are plotted by default as dashed
blue lines for the 2.5th and 97.5th percentiles and a solid red line for the
median. Formatting and the value for each quantile can be controlled
with the upper, mid, and lower arguments.
95% CI around the same quantiles of combined simulations from each subject.
The values and formatting for these quantile CIs are the same as for the observations,
and also controlled with the upper, mid, and lower arguments.
Good vpc/pcvpc plots are considered to be those where the quantile lines for the oberservations lie within the 95%CI quantile regions for simulations, indicated that the model is "centered" on the data and faithfully captures the variability in the data. For an npde plot, one expects to see approximately normally distributed normalized prediction errors.
Plots and returns the plotly object
Michael Neely
Other PMplots:
plot.PM_cov(),
plot.PM_cycle(),
plot.PM_data(),
plot.PM_final(),
plot.PM_model(),
plot.PM_op(),
plot.PM_opt(),
plot.PM_pop(),
plot.PM_post(),
plot.PM_pta(),
plot.PM_sim()
## Not run: # VPC NPex$valid$plot() # pcVPC NPex$valid$plot(type = "pcvpc") # modify median line and marker NPex$valid$plot( line = list(mid = list(color = "orange", dash = "dashdot")), marker = list( color = "blue", size = 12, symbol = "diamond", line = list(color = "navy") ) ) ## End(Not run)## Not run: # VPC NPex$valid$plot() # pcVPC NPex$valid$plot(type = "pcvpc") # modify median line and marker NPex$valid$plot( line = list(mid = list(color = "orange", dash = "dashdot")), marker = list( color = "blue", size = 12, symbol = "diamond", line = list(color = "navy") ) ) ## End(Not run)
This is largely now a legacy plotting function, with a variety of options. It has been superseded by plot.PM_valid.
## S3 method for class 'PMvalid' plot( x, type = "vpc", tad = FALSE, icen = "median", outeq = 1, lower = 0.025, upper = 0.975, log = FALSE, pch.obs = 1, col.obs = "black", cex.obs = 1, data_theme = "color", plot_theme = theme_grey(), col.obs.ci = "blue", col.obs.med = "red", col.sim.ci = "dodgerblue", col.sim.med = "lightpink", axis.x = NULL, axis.y = NULL, ... )## S3 method for class 'PMvalid' plot( x, type = "vpc", tad = FALSE, icen = "median", outeq = 1, lower = 0.025, upper = 0.975, log = FALSE, pch.obs = 1, col.obs = "black", cex.obs = 1, data_theme = "color", plot_theme = theme_grey(), col.obs.ci = "blue", col.obs.med = "red", col.sim.ci = "dodgerblue", col.sim.med = "lightpink", axis.x = NULL, axis.y = NULL, ... )
x |
The name of an PMvalid data object generated by |
type |
Default is “vpc” for a visual prective check, but could be “pcvpc” for a prediction-corrected visual predictive check. |
tad |
Plot using time after dose if |
icen |
Can be either “median” for the predictions based on medians of the population parameter value distributions, or “mean”. Default is “median”. |
outeq |
The number of the output equation to simulate/test. Default is 1. |
lower |
The lower quantile displayed for the observed and simulated profiles. Default is 0.025. |
upper |
The upper quantile displayed for the observed and simulated profiles. Default is 0.975. |
log |
Boolean operator to plot in semilog space. The default is |
pch.obs |
Control the plotting character used for observations. Default is 1, i.e. an open circle.
See |
col.obs |
Color for observations. Default is black. |
cex.obs |
Size for observatins. Default is 1. |
data_theme |
Default is “color”, but could be “grey” or “gray”. |
plot_theme |
Default is |
col.obs.ci |
Color of the observation confidence interval (set by |
col.obs.med |
Color of the observation median. Default is red. |
col.sim.ci |
Color of the simulation confidence interval (set by |
col.sim.med |
Color of the simulation median. Default is lightpink. |
axis.x |
List of |
axis.y |
List of |
... |
Not currently used |
Plots the object using ggplot2.
Michael Neely
make_valid, plot, par, points
Converts a plotly object to a ggplot object. It is the inverse of
plotly::ggplotly().
plotlygg(p, print = TRUE)plotlygg(p, print = TRUE)
p |
A plotly object to convert. |
print |
If |
This function extracts the data and layout from a plotly object and constructs a ggplot object with the same data. It supports various trace types including scatter, bar, and line traces.
A ggplot object.
Compile Rust source code used by Pmetrics.
Compile Rust source code used by Pmetrics.
PM_build()PM_build()
Michael Neely and Julian Otalvaro
r lifecycle::badge("stable")
Compare convergence, -2*log likelihood, AIC/BIC, bias, imprecision, and regression statistics of population and posterior predictions. Additionally, compare distributions of support points between models (see details)
PM_compare(..., icen = "median", outeq = 1, plot = FALSE)PM_compare(..., icen = "median", outeq = 1, plot = FALSE)
... |
PM_result objects to compare. See details. |
icen |
Can be either "median" for the predictions based on medians of
|
outeq |
Number of the output equation to compare; default is 1. |
plot |
Boolean indicating whether to generate and open the comparison report; default is FALSE |
Objects can be specified separated by commas, e.g. PM_compare(run1, run2, run3).
P-values are based on comparison using the nearest neighbors
approach if all models are non-parametrics. Models may only be compared on
parameters that are included in the first model. The P-value is the
comparison between each model and the first model in
the list. Missing P-values are when a model has no parameter names
in common with the first model, and for the first model compared to itself.
Significant P-values indicate
that the null hypothesis should be rejected, i.e. the joint distributions
between the two compared models for that parameter are significantly different.
A highlighted table comparing the selected models with the following columns. In each metric column, the best value is highlighted in red. In the final best column, the red highlighting applies to the model with the most "best" metrics. For bias, imprecision, and regression intercept, the best value is the one closest to zero. For regression slope and R-squared, the best value is the one closest to 1. For -2*LL, AIC, and BIC, the best value is the lowest.
run The run number of the data
nvar Number of random parameters in the model
converged Boolean value if convergence occurred.
-2*ll Final cycle -2*Log-likelihood
One of the following, depending on the option set in setPMoptions:
aic Final cycle Akaike Information Criterion OR
bic Final cycle Bayesian (Schwartz) Information Criterion
popBias Bias, calculated by the method set in setPMoptions, of the predictions based on icen population parameters
popImp Imprecision, calculated by the method set in setPMoptions, of the predictions based on icen population parameters
postBias Bias, calculated by the method set in setPMoptions, of the predictions based on icen posterior parameters
postImp Imprecision, calculated by the method set in setPMoptions, of the predictions based on icen posterior parameters
popInt Intercept of observed vs. population predicted values regression
postInt Intercept of observed vs. posterior predicted values regression
popSl Slope of observed vs. population predicted values regression
postSl Slope of observed vs. posterior predicted values regression
popR2 R-squared of observed vs. population predicted values regression
postR2 R-squared of observed vs. posterior predicted values regression
pval P-value for each model compared to the first. See details.
best Number of times each model was the best (lowest) in the above bias/imprecision, likelihood, and regression metrics.
Michael Neely
Contains a data frame with subject-specific covariate data output.
The PM_cov object is both a data field within a PM_result, and itself an R6 object comprising data fields and associated methods suitable for analysis and plotting relationships between covariates and posterior parameters, covariates over time, or parameter values over time.
Because PM_cov objects are automatically added to the PM_result at the end of a successful run, it is generally not necessary for users to generate PM_cov objects themselves.
The results are contained in the $data field,
and it is this field which is passed to the $plot and $summary methods.
You can use this $data field for custom manipulations, although usually this
is better done on the summary object, e.g.,
run1$cov$summary() %>% select(africa, gender) %>% table().
If you are unfamiliar with the %>% pipe function, please type help("%>%", "magrittr")
into the R console and look online for instructions/tutorials in tidyverse, a
powerful approach to data manipulation upon which Pmetrics is built.
This output of this function is suitable for exploration of covariate- parameter, covariate-time, or parameter-time relationships.
dataA data frame with the following columns
id Subject identification
time Times of covariate observations
covnames... Columns with each covariate observations in the dataset for each subject and time
parnames... Columns with each parameter in the model and the icen summary
for each subject, replicated as necessary for covariate observation times and duplicated for Bayesian
parameter means and medians
icen The type of summarized Bayesian posterior individual parameter values: mean or median
PM_cov$new()Create new object populated with covariate-parameter information
PM_cov$new(PMdata = NULL, path = ".", ...)
PMdatainclude Saved, parsed output of prior run, used when source files are not available. .
pathinclude Path to the folder containing the raw results of the run. Default is the current working directory. .
...Not currently used.
Creation of new PM_cov object is automatic and not generally necessary
for the user to do.
PM_cov$step()Stepwise linear regression of covariates and Bayesian posterior parameter values
PM_cov$step(...)
...Arguments passed to PM_step
See PM_step.
PM_cov$summary()Summary method
PM_cov$summary(...)
...Arguments passed to summary.PM_cov
See summary.PM_cov.
PM_cov$plot()Plot method
PM_cov$plot(...)
...Arguments passed to plot.PM_cov
See plot.PM_cov.
PM_cov$print()Print method
PM_cov$print(...)
...Arguments passed to print
Print method for PM_cov
PM_cov$clone()The objects of this class are cloneable with this method.
PM_cov$clone(deep = FALSE)
deepWhether to make a deep clone.
Michael Neely, Julian Otalvaro
Contains the cycle information after a run.
The PM_cycle object is both a data field within a PM_result, and itself an R6 object comprising data fields and associated methods suitable for analysis and plotting of cycle information generated during the run.
Because PM_cycle objects are automatically added to the PM_result at the end of a successful run, it is generally not necessary for users to generate PM_cycle objects themselves.
The main results are contained in the $data field,
and it is this field which is passed to the $plot and $summary methods.
You can use this $data field for custom manipulations, e.g. last <- run1$cycle$data$aic %>% tail(1).
This will report the last cycle aic.
If you are unfamiliar with the %>% pipe function, please type help("%>%", "magrittr")
into the R console and look online for instructions/tutorials in tidyverse, a
powerful approach to data manipulation upon which Pmetrics is built.
To provide a more traditional experience in R,
the $data field is also separated by list items into the other data fields within the R6 object,
e.g. mean or gamlam. This
allows you to access them in an S3 way, e.g. run1$cycle$mean if run1 is a
PM_result object.
dataA list with the following elements, which can also be extracted by name.
e.e. run1$cycle$objective, which is equivalent to run1$cycle$data$objective.
names Vector of names of the random parameters
objective A tibble of -2*Log-likelihood, AIC and BIC at each cycle
gamlam A tibble of cycle number and gamma or lambda at each cycle for each output equation
mean A tibble of cycle number and the mean of each random parameter at each cycle, normalized to initial mean
median A tibble of cycle number and the median of each random parameter at each cycle, normalized to initial median
sd A tibble of cycle number and the standard deviation of each random parameter at each cycle, normalized to initial standard deviation
status Status of the last cycle: "Converged", "Maximum cycles reached", or "Posterior".
namesVector of names of the random parameters
objectiveA tibble of -2*Log-likelihood, AIC and BIC at each cycle
gamlamA tibble of cycle number and gamma or lambda at each cycle for each output equation
meanA tibble of cycle number and the mean of each random parameter at each cycle, normalized to initial mean
medianA tibble of cycle number and the median of each random parameter at each cycle, normalized to initial median
sdA tibble of cycle number and the standard deviation of each random parameter at each cycle, normalized to initial standard deviation
statusStatus of the last cycle: "Converged", "Maximum cycles reached", or "Posterior"
PM_cycle$new()Create new object populated with cycle information
PM_cycle$new(PMdata = NULL, path = ".", ...)
PMdatainclude Saved, parsed output of prior run, used when source files are not available. .
pathinclude Path to the folder containing the raw results of the run. Default is the current working directory. .
...Not currently used.
Creation of new PM_cycle object is automatic and not generally necessary
for the user to do.
PM_cycle$plot()Plot method
PM_cycle$plot(...)
...Arguments passed to plot.PM_cycle
See plot.PM_cycle.
PM_cycle$summary()Summary method
PM_cycle$summary(...)
...Arguments passed to summary.PM_cycle
See summary.PM_cycle.
PM_cycle$print()Print method
PM_cycle$print()
Prints the last cycle summary information.
PM_cycle$clone()The objects of this class are cloneable with this method.
PM_cycle$clone(deep = FALSE)
deepWhether to make a deep clone.
Michael Neely, Julian Otalvaro
PM_data R6 objects containing raw, standardized and valid data, and methods to process the data
PM_data objects are passed to the $fit method of compiled PM_model objects to initiate a
population analysis. The object is created by reading a delimited file in
the current working directory. The data will be transformed into the standard
format which is the same for all engines, with a report of any assumptions
that were necessary to standardize the data. PMcheck is called
on the standard data to evaluate for errors. If dates and times are converted
to relative decimal times in the standard data, automatic detection of the correct
format will be attempted using lubridate::parse_date_time(). In the case of failure
due to an unusual format, use the 'dt' argument to specify the correct format in your
data. In the case of successful automatic detection, the format used will be
included in the standardization report generated upon creation of a new PM_data
object. Check carefully to make sure the correct format was chosen. Note that if
your clock times did not include seconds, they were appended as ":00" to the end
of each time and will appear that way in the copy of the original data.
There are a number of methods defined for a PM_data object, including to write the standard data back to a file for future use, to summarize and to plot the object, to conduct a non-compartmental analysis on the raw data using make_NCA, to calculate an AUC using make_AUC, and to add event rows, which is particularly useful for making simulation templates on the fly.
dataData frame containing the data to be modeled
standard_dataData frame containing standardized version of the data
popThe $data field from a PM_pop object. This makes it easy to add population predictions to a raw data plot. This field will be NULL until the PM_data object is added to the PM_result after a run. As examples:
dat <- PM_data$new("data.csv"). Here, dat$pop will be NULL.
run1 <- PM_load(1). Here, run1$data$pop will be the same as run1$pop$data.
postThe $data field from a PM_post object. See details in the pop argument above.
PM_data$new()Create new data object
PM_data$new(data = NULL, dt = NULL, quiet = FALSE, validate = TRUE, ...)
dataA quoted name of a file with full path if not in the working directory, an unquoted name of a data frame in the current R environment, or a PM_data object, which will rebuild it.
dtPmetrics will try a variety of date/time formats. If all 16 of them fail, use this parameter to specify the correct format as a character vector whose first element is date format and second is time. Use the following abbreviations:
Y = 4 digit year
y = 2 digit year
m = decimal month (1, 2, ..., 12)
d = decimal day (1, 2, ..., 31)
H = hours (0-23)
M = minutes (0-59)
Example: format = c("myd", "mh"). Not one of the tried combinations!
Always check to make sure that dates/times were parsed correctly and the
relative times in the PM_data$standard_data field look correct.
Other date/time formats are possible. See lubridate::parse_date_time() for these.
quietQuietly validate. Default is FALSE.
validateCheck for errors. Default is TRUE. Strongly recommended.
...Other arguments (not currently used).
Creation of a new PM_data objects from a file or a data frame. Data will be standardized and checked automatically to a fully specified, valid data object.
PM_data$save()Save data to file
PM_data$save(file_name, ...)
file_nameA quoted name of the file to create with full path if not in the working directory.
...Arguments passed to PMwriteMatrix
Saves a delimited file (e.g. comma-separated)
from the standard_data field
PM_data$auc()Calculate AUC
PM_data$auc(...)
...Arguments passed to make_AUC.
See make_AUC.
PM_data$nca()Perform non-compartmental analysis
PM_data$nca(...)
...Arguments passed to make_NCA.
See make_NCA.
PM_data$plot()Plot method
PM_data$plot(...)
...Arguments passed to plot.PM_data
See plot.PM_data.
PM_data$print()Print method
PM_data$print(standard = F, viewer = T, ...)
standardDisplay the standardized data if TRUE.
Default is FALSE.
viewerDisplay the Viewer if TRUE.
Default is TRUE.
...Other arguments to print.data.frame. Only
passed if viewer = FALSE.
Displays the PM_data object in a variety of ways.
PM_data$summary()Summary method
PM_data$summary(...)
...Arguments passed to summary.PM_data.
See summary.PM_data.
PM_data$addEvent()Add events to PM_data object
PM_data$addEvent(..., dt = NULL, quiet = FALSE, validate = FALSE)
...Column names and values.
dtPmetrics will try a variety of date/time formats. If all 16 of them fail, use this parameter to specify the correct format as a character vector whose first element is date format and second is time. Use the following abbreviations:
Y = 4 digit year
y = 2 digit year
m = decimal month (1, 2, ..., 12)
d = decimal day (1, 2, ..., 31)
H = hours (0-23)
M = minutes (0-59)
Example: format = c("myd", "mh"). Not one of the tried combinations!
Always check to make sure that dates/times were parsed correctly and the
relative times in the PM_data$standard_data field look correct.
Other date/time formats are possible. See lubridate::parse_date_time() for these.
quietQuietly validate. Default is FALSE.
validateValidate the new row or not. Default is FALSE as a new row
added to a blank will result in a one-row data object, which is invalid. Also,
only one event type (dose or observation) should be added at a time, so if the
new object contains only doses while building, this would cause an error. You
should set validate = TRUE for the final addition.
Add lines to a PM_data object by supplying named columns and values.
ID is always required. Time is handled differently depending on
the sequence of addEvent calls (see Chaining below).
It is required for the first call to addEvent and should be 0.
For example: For example: dat <- PM_data$new()$addEvent(id = 1, time = 0, dose = 100, addl = 5, ii = 24)
For subsequent calls to addEvent with specific times it should be included.
For example: dat <- PM_data$new()$addEvent(id = 1, time = 0, dose = 100, addl = 5, ii = 24)$addEvent(id = 1, time = 144, out = -1)
Here, because out wasn't in the original call and the next call contains a value for
time, an out value of -1 will be added at time 144 and out will be set to NA for all the
previous rows.
In contrast, the behavior is different if you omit time when your
data object already has rows. In this case
the arguments in the call to addEvent (without a value for time)
will add those arguments as columns in the prior data with the specified value
or replace values in those columns if they
already exist. Be sure this is what you want.
For example, building on the prior example: dat$addEvent(id = 1, dur = 0.5).
Note that we can chain to the previously created dat object. Here, a duration of 0.5 hours
will be added to every previous row in dat to create the new dat object, but no new
row is added since there is no time associated with it.
Adding covariates is supported, but since valid subject records in Pmetrics
with covariates must contain non-missing values at time 0, covariates should
be included with the first call to $addEvent().
As we have seen in the examples above, ADDL and II are supported.
Chaining Multiple $addEvent() calls can be chained with PM_data$new()
to create a blank data object and then add rows.
This can be particularly useful for creating simulation templates.
See the example.
PM_data$new()$addEvent(id = 1, time = 0, dose = 100, addl = 4, ii = 12, out = NA, wt = 75)$addEvent(id = 1, time = 60, out = -1)
PM_data$clone()The objects of this class are cloneable with this method.
PM_data$clone(deep = FALSE)
deepWhether to make a deep clone.
## ------------------------------------------------ ## Method `PM_data$addEvent()` ## ------------------------------------------------ ## Not run: PM_data$new()$addEvent(id = 1, time = 0, dose = 100, addl = 4, ii = 12, out = NA, wt = 75)$addEvent(id = 1, time = 60, out = -1) ## End(Not run)## ------------------------------------------------ ## Method `PM_data$addEvent()` ## ------------------------------------------------ ## Not run: PM_data$new()$addEvent(id = 1, time = 0, dose = 100, addl = 4, ii = 12, out = NA, wt = 75)$addEvent(id = 1, time = 60, out = -1) ## End(Not run)
Contains final cycle information from run.
The PM_final object is both a data field within a PM_result, and itself an R6 object comprising data fields and associated methods suitable for analysis and plotting of final cycle parameters.
Because PM_final objects are automatically added to the PM_result at the end of a successful run, it is generally not necessary for users to generate PM_final objects themselves.
The main results are contained in the $data field,
and it is this field which is passed to the $plot and $summary methods.
You can use this $data field for custom manipulations, e.g. probs <- run1$final$data$popPoints %>% select(prob).
This will select the probabilities of the support points.
If you are unfamiliar with the %>% pipe function, please type help("%>%", "magrittr")
into the R console and look online for instructions/tutorials in tidyverse, a
powerful approach to data manipulation upon which Pmetrics is built.
To provide a more traditional experience in R,
the $data field is also separated by list items into the other data fields within the R6 object,
e.g. popMean or nsub. This
allows you to access them in an S3 way, e.g. run1$final$popMean if run1 is a
PM_result object.
dataA list with the following elements, which can also be extracted by name.
popPoints (NPAG only) Data frame of the final cycle joint population density of grid points with column names equal to the name of each random parameter plus prob for the associated probability of that point
popMean The final cycle mean for each random parameter distribution
popSD The final cycle standard deviation for each random parameter distribution
popCV The final cycle coefficient of variation (SD/Mean) for each random parameter distribution
popVar The final cycle variance for each random parameter distribution
popCov The final cycle random parameter covariance matrix
popCor The final cycle random parameter correlation matrix
popMed The final cycle median values for each random parameter, i.e. those that have unknown mean and unknown variance, both of which are fitted during the run
postPoints (NPAG only) Data frame of posterior population points for each of the first 100 subject, with columns id, point, parameters and probability. The first column is the subject, the second column has the population point number, followed by the values for the parameters in that point and the probability.
postMean A nsub x npar data frame containing the means of the posterior distributions for each parameter.
postSD A nsub x npar data frame containing the SDs of the posterior distributions for each parameter.
postVar A nsub x npar data frame containing the variances of the posterior distributions for each parameter.
postCov NPAG only: An list of length nsub, each element with an npar x npar data frame that contains the posterior parameter value covariances for that subject.
postCor NPAG only: An list of length nsub, each element with an npar x npar data frame that contains the posterior parameter value correlations for that subject.
postMed A nsub x npar data frame containing the medians of the posterior distributions for each parameter.
shrinkage A data frame with the shrinkage for each parameter.
gridpts (NPAG only) Initial number of support points
nsub Number of subjects
ab Tibble/data frame of boundaries for random parameter values with columns: name, lower, upper.
popPoints(NPAG only) Data frame of the final cycle joint population density of grid points with column names equal to the name of each random parameter plus prob for the associated probability of that point
popMeanThe final cycle mean for each random parameter distribution
popSDThe final cycle standard deviation for each random parameter distribution
popCVThe final cycle coefficient of variation (SD/Mean) for each random parameter distribution
popVarThe final cycle variance for each random parameter distribution
popCovThe final cycle random parameter covariance matrix
popCorThe final cycle random parameter correlation matrix
popMedThe final cycle median values for each random parameter, i.e. those that have unknown mean and unknown variance, both of which are fitted during the run
postPoints(NPAG only) Data frame of posterior population points for each of the first 100 subject, with columns id, point, parameters and probability. The first column is the subject, the second column has the population point number, followed by the values for the parameters in that point and the probability.
postMeanA nsub x npar data frame containing the means of the posterior distributions for each parameter.
postSDA nsub x npar data frame containing the SDs of the posterior distributions for each parameter.
postVarA nsub x npar data frame containing the variances of the posterior distributions for each parameter.
postCovNPAG only: An list of length nsub, each element with an npar x npar data frame that contains the posterior parameter value covariances for that subject.
postCorNPAG only: An list of length nsub, each element with an npar x npar data frame that contains the posterior parameter value correlations for that subject.
postMedA nsub x npar data frame containing the medians of the posterior distributions for each parameter.*
shrinkageA data frame with the shrinkage for each parameter. The total population variance for a parameter is comprised of variance(EBE) plus average variance(EBD), where each subject's EBE is the Empirical Bayes Estimate or mean posterior value for the parameter. EBD is the Empirical Bayes Distribution, or the full Bayesian posterior parameter value distribution for each subject.
The typical definition of shrinkage is
or ,
where is the EBE and is the population variance of .
In parametric modeling approaches is the interindividual variability around
the typical (mean) value of the parameter in the population, usually referred to
as . In nonparametric approaches, there is no assumption of normality, so
simply becomes each subject's mean parameter value estimate.
Here is how Pmetrics derives and then calculates shrinkage for a given parameter.
Shrinkage is therefore a fraction between 0 and 1. If Bayesian posterior distributions are wide
for a given parameter and is high due to sparse or uninformative sampling,
then most of the population variance is due
to this variance and shrinkage is high, i.e., individual posterior estimates (EBE)
shrink towards the population mean. Be aware, however, that a Bayesian posterior
parameter value distribution for a given subject who is sparsely sampled may also
be a single support point with no variance. Therefore EBD under nonparametric
assumptions is not always large with uninformative sampling. This means that shrinkage
is not as readily interpretable in nonparametric population modeling.
An alternative is to consider the number of support points relative to the number of subjects. Highly informed, distinct subjects will result in the maximum possible number of support points, N, which is the same as the number of subjects. In contrast, badly undersampled subjects can result in only one support point. There is no formal criterion for this statistic, but it can be used in combination with shrinkage to assess the information content of the data.
gridpts(NPAG only) Initial number of support points
nsubNumber of subjects
abMatrix of boundaries for random parameter values
PM_final$new()Create new object populated with final cycle information
PM_final$new(PMdata = NULL, path = ".", ...)
PMdatainclude Saved, parsed output of prior run, used when source files are not available. .
pathinclude Path to the folder containing the raw results of the run. Default is the current working directory. .
...Not currently used.
Creation of new PM_final object is automatic and not generally necessary
for the user to do.
PM_final$plot()Plot method
PM_final$plot(...)
...Arguments passed to plot.PM_final
See plot.PM_final.
PM_final$summary()Summary method
PM_final$summary(...)
...Arguments passed to summary.PM_final
See summary.PM_final.
PM_final$clone()The objects of this class are cloneable with this method.
PM_final$clone(deep = FALSE)
deepWhether to make a deep clone.
Michael Neely, Julian Otalvaro
This function displays system information useful for debugging and provides a link to the GitHub repository for reporting bugs or requesting help.
PM_help(copy = TRUE)PM_help(copy = TRUE)
copy |
Logical. If |
When you encounter bugs or need help, this function collects relevant system information that will help maintainers diagnose the issue. The information includes OS version, R version, RStudio version (if applicable), package version, Rust and Cargo versions (if available).
Invisibly returns a list containing the system information.
## Not run: # Display help information PM_help() # Copy information to clipboard PM_help(copy = TRUE) ## End(Not run)## Not run: # Display help information PM_help() # Copy information to clipboard PM_help(copy = TRUE) ## End(Not run)
Loads all the data from a prior Pmetrics run.
PM_load(run, path = ".", file = "PMout.Rdata")PM_load(run, path = ".", file = "PMout.Rdata")
run |
The numerical value of the folder in |
path |
include Path to the folder containing the raw results of the run. Default is the current working directory. . |
file |
Default is "PMout.Rdata", which is created after a Pmetrics run,
but it could also be the name of an .Rdata file created by running the
|
A combination of run, path, and file are used to locate the results.
If run is provided, it is assumed that the results are in a subfolder
/outputs of the folder named by run within the path folder.
If run is missing, the results are assumed to be in the path folder.
The file name is the name of the Rdata file containing the results.
Default is "PMout.Rdata", which is created by Pmetrics after a run.
If both run and path are missing, the current working directory is used
for path.
If both run and file are missing, the current working directory is used
for path and "PMout.Rdata" is used for file.
If both path and file are missing, the current working directory is used
for path and run is required.
If all three are missing, the current working directory is used for path
and "PMout.Rdata" is used for file.
An R6 PM_result.
Michael Neely and Julian Otalvaro
PM_final, PM_cycle, PM_op, PM_cov, PM_pop, PM_post
## Not run: run1 <- PM_load(1) # loads from ./1/outputs/PMout.Rdata, where "." is the current working directory run2 <- PM_load(2, path = "Pmetrics/MyRuns") # loads from Pmetrics/MyRuns/2/outputs/PMout.Rdata run3 <- PM_load(path = "Pmetrics/MyRuns/3", file = "MyResults.Rdata") # loads from Pmetrics/MyRuns/3/MyResults.Rdata run4 <- PM_load(file = "Pmetrics/MyRuns/4/outputs/PMout.Rdata") # loads from Pmetrics/MyRuns/4/outputs/PMout.Rdata run5 <- PM_load() # loads from ./PMout.Rdata ## End(Not run)## Not run: run1 <- PM_load(1) # loads from ./1/outputs/PMout.Rdata, where "." is the current working directory run2 <- PM_load(2, path = "Pmetrics/MyRuns") # loads from Pmetrics/MyRuns/2/outputs/PMout.Rdata run3 <- PM_load(path = "Pmetrics/MyRuns/3", file = "MyResults.Rdata") # loads from Pmetrics/MyRuns/3/MyResults.Rdata run4 <- PM_load(file = "Pmetrics/MyRuns/4/outputs/PMout.Rdata") # loads from Pmetrics/MyRuns/4/outputs/PMout.Rdata run5 <- PM_load() # loads from ./PMout.Rdata ## End(Not run)
Opens the Pmetrics User reference online
PM_manual()PM_manual()
Help for Pmetrics.
PM_model objects contain the variables, covariates, equations and error models necessary to run a population analysis.
PM_model objects are one of two fundamental objects in Pmetrics, along with
PM_data() objects. Defining a PM_model allows for fitting it to the data
via the $fit() method to conduct a
population analysis, i.e. estimating the probability distribution of model equation
paramter values in the population. The PM_model object is created using the
a model building app (coming soon), by defining a list
directly in R, or by reading a model text file. When reading a model text file,
the list code is generated and copied to the clipboard for pasting in to scripts.
Model files will be deprecated in future versions of Pmetrics.
Some notes on the example at the end of this help page:
It's a complete example of a three compartment model with delayed absorption.
We show the method of defining the model first and embedding the PM_model$new() within
a dontrun block to avoid automatic compilation.
Since this model can also be solved analytically with algebra, we could have used
eqn = function(){three_comp_bolus}.
model_listA list containing the model components built by translating the original arguments into Rust
arg_listA list containing the original arguments passed to the model
binary_pathThe full path and filename of the compiled model
PM_model$new()This is the method to create a new PM_model object.
The first argument allows creation of a model from a variety of pre-existing sources, and if used, all the subsequent arguments will be ignored. If a model is defined on the fly, the arguments form the building blocks. Blocks are of two types:
Lists define primary parameters, covariates, and error models. These portions of the model have specific and defined creator functions and no additional R code is permissible. They take this form:
block_name = list( var1 = creator(), var2 = creator() )
Note the comma separating the creator functions, "c(" to open the vector and ")" to close the vector.
Names are case-insensitive and are converted to lowercase for Rust.
Functions define the other parts of the model, including secondary (global) equations, model equations (e.g. ODEs), lag time, bioavailability, initial conditions, and outputs. These parts of the model are defined as R functions without arguments, but whose body contains any permissible R code.
block_name = function() {
# any valid R code
# can use primary or secondary parameters and covariates
# lines are not separated by commas
}
Note the absence of arguments between the "()", the opening curly brace "{" to start
the function body and the closing curly brace "}" to end the body.
Again, all R code will be converted to lowercase prior to translation into Rust.
Important: All models must have pri, eqn, out, and err blocks.
PM_model$new( x = NULL, pri = NULL, cov = NULL, sec = NULL, eqn = NULL, lag = NULL, fa = NULL, ini = NULL, out = NULL, err = NULL, solver = NULL, ... )
xAn optional argument, but if specified, all the subsequent
arguments will be ignored. x creates a PM_model from
existing appropriate input, which can be one of the following:
Quoted name of a model text file in the working directory which will be read and passed to Rust engine. Note: Model text files are being deprecated in future versions of Pmetrics.
List that defines the model directly in R. This will be in the same format as if all the subsequent arguments were used. For example:
mod_list <- list(
pri = list(...),
eqn = function(){...},
out = function(){...},
err = c(...)
)
mod <- PM_model$new(mod_list)
PM_model object, which will simply rebuild it, e.g. carrying on the
prior example: PM_model$new(mod)
See the user manual PM_manual() for more help on directly defining models in R.
priThe first of the arguments used if x is not specified. This is
a named list of primary parameters, which are the model parameters that
are estimated in the population analysis. They are specified
by one of two creator functions: ab() or msd(). For example,
pri = list( Ke = ab(0, 5), V = msd(100, 10) )
The ab() creator specifies the
initial range [a, b] of the parameter, while the msd() creator specifies
the initial mean and standard deviation of the parameter.
covA list whose names are some or all of the covariates in the data file.
Unlike prior versions of Pmetrics, as of 3.0.0, they do not have to be listed in the same order
as in the data file, and they do not need to be all present.
Only those covariates you wish to use in model equations or analyze for relationships to model parameters need to be declared here.
Values for each element in the covariate vector are the interp() creator function to declare
how each covariate is interpolated between entries in the data. The default argument
for interp() is "lm" which means that values will be linearly interpolated
between entries, like the R linear model function stats::lm(). The alternative is "none",
which holds the covariate value the same as the previous entry until it changes,
i.e., a carry-forward strategy.
For example:
cov = list(
wt = interp(), # will be linear by default
visit = interp("none")
)
Note that wt = interp() is equivalent to wt = interp("lm"), since "lm" is the default.
secA function defining the secondary (global) equations in the model. Values are not estimated for these equations but they are available to every other block in the model. For example:
sec = function() {
V = V0 * (wt/70)
}
Note that the function
must be defined with no arguments between the parentheses,
and the body must be in R syntax. Any number of lines and R code, e.g.
if - else statements, etc. are permissible.
eqnA function defining the model equations. The function must have no arguments. The body of the function may contain three kinds of equations, written in R syntax.
Implicit equations referenced by calling the name of a Pmetrics model library object
detailed in model_lib(). The Pmetrics model library contains a number of template models
solved analytically (algebraically) and may include user-defined models. For example, to use
a two-compartment model with intavenous input:
eqn = function(){
two_comp_iv
}
Required parameters for library models are listed for each model and must be
included in model blocks exactly as named. For example, in a one-compartment model
Ke is a required parameter. Thus, if Ke is a function of a covariate called "crcl",
here is a code snippet illustrating the inclusion of the required parameter.
mod <- PM_model$new(
pri = list(
ke0 = ab(0, 5),
v = ab(0, 100)
),
cov = list(
crcl = interp()
),
eqn = function(){
one_comp
ke = ke0 * crcl # the required parameter, ke, is defined
},
... # more model blocks, including out, err
)
Explicit equations are ordinary differential equations that directly define a model. Use the following notation in equations:
dx[i] for the change in amount with respect to time (i.e., ),
where i is the compartment number,
x[i] for the compartment amount, where i is the compartment number.
rateiv[j] for the infusion rate of input j, where j is the input number
in the data corresponding to doses for that input.
Bolus doses are indicated by DUR = 0 for dose events in the
data. Currently only one bolus input is allowed, which goes into compartment 1
and is not modifiable. It does not appear in the differential equations.
For example,
eqn = function() {
dx[1] = -ka * x[1]
dx[2] = rateiv[1] + ka * x[1] - ke * x[2]
}
Additional equations in R code can be defined in this block, which are similar to
the sec block, but will only be available within the eqn block as opposed
to global availability when defined in sec. They can be added to either
lagA function defining the lag time (delayed absorption) for the bolus input.
The function must have no arguments,
and the equations must be defined
in R syntax The equations must be defined in the form of
lag[i] = par, where lag[i] is the lag for drug (input) i and
par is the lag parameter used in the pri block.
For example, if
antacid is a covariate in the data file, and lag1 is a primary parameter,
this code could be used to model delayed absorption if an antacid is present.
lag = function() {
lag[1] = if(antacid == 1) lag1 else 0
}
As for eqn, additional equations in R code can be defined in this block,
but will only be available within the lag block.
faA function defining the bioavailability (fraction absorbed) equations,
similar to lag.
Example:
fa = function() {
fa[1] = if(antacid == 1) fa1 else 1
}
As for eqn, additional equations in R code can be defined in this block,
but will only be available within the fa block.
iniA function defining the initial conditions for a compartment
in the model. Structure is similar to lag and fa.
Example:
ini = function() {
x[2] = init2 * V
}
This sets the initial amount of drug in compartment 2 to the value
of a covariate init2 multiplied by the volume of the compartment,
V, assuming V is either a primary parameter or defined in the
sec block.
As for eqn, additional equations in R code can be defined in this block,
but will only be available within the ini block.
outA function defining the output equations, which are the predictions from the model. The function must have no arguments, and the equations for predictions must be defined in R syntax.
Use the following notation in equations:
y[i] for the predicted value, where i is the output equation number,
typically corresponding to an observation with outeq = i in the data, but not
always (see Note below).
x[j] for the compartment amount, where j is the compartment number.
As with all function blocks, secondary equations are permitted,
but will be specific to the out block.
For example,
out = function() {
V = V0 * wt # only needed if not included in sec block
y[1] = x[1]/V
#Vp and Vm must be defined in pri or sec blocks
y[2] = x[2]/Vp
y[3] = x[3]/Vm
}
This assumes V, Vp, and Vm are either primary parameters or defined in the
sec block.
Note that as of Pmetrics 3.0.0, you can have more output equations
than values for outeq in the data. This is not possible with prior
versions of Pmetrics. Outputs without corresponding observations
are not used in the fitting, but do generate predictions.
For example, this snippet is part of a model that calculates AUC:
eqn = function(){
dx[1] = -ka * x[1]
dx[2] = rateiv[1] + ka * x[1] - ke * x[2]
dx[3] = x[2] - x[3]
dx[4] = x[1] / v
},
out = function(){
y[1] = x[1]/v
y[2] = x[4]
},
err = list(
proportional(2, c(0.1, 0.15, 0, 0))
)
If the data only contain observations for y[1], i.e. the concentration
of drug in the plasma compartment with outeq = 1, the model will
use that information to optimize the parameter values, but will also
generate predictions for y[2], which is the AUC of the drug in compartment 1,
even though there is no outeq = 2 in the data. There is only one err
equation since there is only one source of observations: plasma concentration.
AUC (y[2]) is not fitted to any observations; it is a calculation based on
the model state, given the optimized parameter values. It's not required, but
shown here for illustrative purposes.
errAn unammed vector of error models for each of the output equations
with observations, i.e. those that have an outeq number associated with them in
the data.
Each error model is defined by the proportional() creator or
the additive() creator, relative to the observation error.
For example, if there are three output equations corresponding to three
sources of observations in the data, the error models
could be defined as:
err = list( proportional(2, c(0.1, 0.15, 0, 0)), proportional(3, c(0.05, 0.1, 0, 0)), additive(1, c(0.2, 0.25, 0, 0)) )
This defines the first two output equations to have proportional error with initial values of 2 and 3, respectively, and the third output equation to have additive error with initial value of 1. Each output is measured by a different assay with different error characteristics.
If all the output equations have the same error model, you can
simply use a single error model embedded in replicate() , e.g.,
for 3 outputs with the same error model:
err = list( replicate(3, proportional(2, c(0.1, 0.15, 0, 0))) )
solverOptional ODE solver for user-defined ODE models. Supported values are "BDF", "TRBDF2", "ESDIRK34", and "TSIT45". This is ignored for analytical library models.
...Not currently used.
PM_model$print()Print the model summary.
PM_model$print(...)
...Not used.
This method prints a summary of the model.
PM_model$plot()Plot the model.
PM_model$plot(...)
...Additional arguments passed to the plot function.
This method plots the model using the
plot.PM_model() function.
PM_model$fit()This is the main method to run a population analysis.
PM_model$fit(
data = NULL,
path = ".",
run = NULL,
include = NULL,
exclude = NULL,
cycles = 100,
prior = "sobol",
points = 100,
idelta = 0.1,
tad = 0,
seed = 23,
overwrite = FALSE,
algorithm = "NPAG",
report = getPMoptions("report_template"),
quiet = FALSE
)
dataEither the name of a PM_data
object in memory or the quoted filename (with or without a path) of a Pmetrics
data file. If the path is not specified, the file is assumed to be in the current working directory,
unless the path argument below is also specified as a global option for the fit.
The file will be used to create a PM_data
object on the fly. However, if created on the fly, this object
will not be available to other
methods or other instances of $fit().
pathOptional full path or relative path from current working directory
to the folder where data and model are located if specified as filenames without
their own paths,
and where the output will be saved. Default is the current working directory.
runSpecify the run number of the output folder. Default if missing is the next available number.
includeVector of subject id values in the data file to include in the analysis. The default (missing) is all.
excludeA vector of subject IDs to exclude in the analysis, e.g. c(4,6:14,16:20)
cyclesNumber of cycles to run. Default is 100.
priorThe distribution for the initial support points, which can be one of several options.
The default is "sobol", which is a semi-random distribution. This is the distribution typically used when fitting a new model to the data. An example of this is on our website.
The following all specify non-random, informative prior distributions. They
are useful for either continuing a previous
run which did not converge or for fitting a model to new data, whether to simply
calculate Bayesian posteriors with cycles = 0 or to revise the model to a new
covergence with the new data.
The name of a suitable PM_result object from a prior run loaded with PM_load.
This starts from the non-uniform, informative distribution obtained at the end of a prior NPAG run.
Example: run1 <- PM_load(1); fit1$run(prior = run1).
A character string with the filename of a csv file containing a prior distribution with
format as for 'theta.csv' in the output folder of a prior run: column headers are parameter
names, and rows are the support point values. A final column with probabilities
for each support point is not necessary, but if present will be ignored, as these
probabilities are calculated by the engine. Note that the parameter names must match the
names of the primary variables in the model. Example: fit1$run(prior = "mytheta.csv").
The number of a previous run with theta.csv in the output folder which will be read
as for the filename option above. Example: fit1$run(prior = 2).
A data frame obtained from reading an approriate file, such that the data frame
is in the required format described in the filename option above. Example:
mytheta <- read_csv("mytheta.csv"); fit1$run(prior = mytheta).
pointsThe number of initial support points if one of
the semi-random, uniform distributions are selected in the prior argument
above. Default is 100. The initial points are
spread through the hyperspace defined by the random parameter ranges
and begin the search for the optimal
parameter value distribution (support points) in the population.
If there are fewer than 2 points per unit range for any parameter,
Pmetrics will suggest the minimum number of points that should be tried.
The greater the initial number of points, the less chance of
missing the globally maximally likely parameter value distribution,
but the slower the run.
ideltaHow often to generate posterior predictions in units of time.
Default is 0.1, which means a prediction is generated every 0.1 hours (6 minutes)
if the unit of time is hours. Predictions are made at this interval until the time
of the last event (dose or observation) or until tad if that value is greater
than the time of the last dose or observation in the data.
tadLength of time after the last dose event to add additional predictions
at frequency idelta. Default is 0, which means no additional predictions
beyond the last dose, assuming the dose is the last event. . If the
last observation in the data is after tad, then a prediction will be generated at
time = tad after the last dose
seedSeed used if prior = "sobol". Ignored otherwise.
overwriteBoolean operator to overwrite existing run result folders. Default is FALSE.
algorithmThe algorithm to use for the run. Default is "NPAG" for the Non-Parametric Adaptive Grid. Alternatives: "NPOD".
reportIf missing, the default Pmetrics report template as specified in getPMoptions is used. Otherwise can be "plotly", "ggplot", or "none".
quietBoolean operator to suppress messages during the run. Default is FALSE.
internRun NPAG in the R console without a batch script. Default is TRUE.
As of Pmetrics 3.0.0, models contain compiled code to fit the model equations to the data, optimizing the parameter value probability distributions in the population to maximize their likelihood, or more precisely, minimize the objective function, which is -2*log-likelihood.
The $fit() method is the means of running that compiled
code to conduct to fitting procedure. At a minimum, it requires
a PM_data object, which can be created with
PM_data$new(). There are a number of additional arguments
to control the fitting procedure, such as the number of cycles
to run, the initial number of support points,
and the algorithm to use, among others.
The $fit() method is the descendant of the legacy
NPrun function, which is maintained as a wrapper to $fit()
for backwards compatibility.
A successful run will result in creation of a new folder in the working directory with the results inside the folder.
PM_model$map()Calculate posteriors from a fitted model. #' @details This method calculates posteriors from a compiled model. It is not necessary to have run the model first, but it is necessary to have an informative prior distribution. This prior will typically be the result of a previous run, but may also be a file containing support points, with each column named as a parameter in the model plus a final column for probability. Each row contains values for the parameters and the associated probability for those parameter values. The file can be saved as a csv file.
To calculate the posteriors, map() calls the fit() method with the cycles argument set to 0
and the algorithm argument set to "POSTPROB". If data are not provided as an argument to
map(), the model's data field is used instead. If data is provided, it must be a
PM_data object or the pathname of a file which can be loaded as a PM_data object.
PM_model$map(...)
...Arguments passed to the fit method. Note that the cycles argument is set to 0,
and the algorithm argument is set to "POSTPROB" automatically.
PM_model$sim()Simulate data from the model using a set of parameter values.
PM_model$sim(data, theta, quiet = FALSE)
dataA PM_data object containing the dosing and observation information.
thetaA matrix of parameter values to use for the simulation.
The theta matrix should have the same number of columns as the number of primary parameters in the model.
Each row of theta represents a different set of parameter values.
quietLogical, if TRUE, suppresses messages during simulation.
This method simulates output from the model using a set of parameter values
provided in the theta matrix and the template for dosing/observations in
the data object.
PM_model$compile()Compile the model to a binary file.
PM_model$compile(quiet = FALSE)
quietLogical, if TRUE, suppresses messages during compilation.
This method write the model to a Rust file in a temporary path,
updates the binary_path field for the model, and compiles that
file to a binary file that can be used for fitting or simulation.
PM_model$save()Save model to file (deprecated).
PM_model$save()
This method is deprecated. Existing or manually created model files may be read with PM_model$new(filename),
but including model code in scripts is preferred, as this makes models used in runs transparent and more easily edited.
Use the PM_model$copy() method instead to copy the model code to the clipboard and paste into scripts.
PM_model$copy()Copy model code to clipboard.
PM_model$copy()
This method copies the R code to create the model to the clipboard. This is useful for saving the model code in a script.
PM_model$clone()The objects of this class are cloneable with this method.
PM_model$clone(deep = FALSE)
deepWhether to make a deep clone.
Michael Neely
mod_list <- list( pri = list( CL = ab(10, 200), V0 = ab(0, 100), ka = ab(0, 3), k23 = ab(0, 5), k32 = ab(0, 5), lag1 = ab(0, 2) ), cov = list( wt = interp() ), sec = function() { V <- V0 * (wt / 70) ke <- CL / V # define here to make eqn simpler }, eqn = function() { dx[1] <- -ka * x[1] dx[2] <- rateiv[1] + ka * x[1] - (ke + k23) * x[2] + k32 * x[3] dx[3] <- k23 * x[2] - k32 * x[3] dx[4] <- x[1] / V }, lag = function() { tlag[1] <- lag1 }, out = function() { y[1] <- x[1] / V y[2] <- x[4] # AUC, not fitted to any data, not required }, err = list( proportional(2, c(0.1, 0.15, 0, 0)) # only applies to y[1] ) ) ## Not run: mod <- PM_model$new(mod_list) ## End(Not run)mod_list <- list( pri = list( CL = ab(10, 200), V0 = ab(0, 100), ka = ab(0, 3), k23 = ab(0, 5), k32 = ab(0, 5), lag1 = ab(0, 2) ), cov = list( wt = interp() ), sec = function() { V <- V0 * (wt / 70) ke <- CL / V # define here to make eqn simpler }, eqn = function() { dx[1] <- -ka * x[1] dx[2] <- rateiv[1] + ka * x[1] - (ke + k23) * x[2] + k32 * x[3] dx[3] <- k23 * x[2] - k32 * x[3] dx[4] <- x[1] / V }, lag = function() { tlag[1] <- lag1 }, out = function() { y[1] <- x[1] / V y[2] <- x[4] # AUC, not fitted to any data, not required }, err = list( proportional(2, c(0.1, 0.15, 0, 0)) # only applies to y[1] ) ) ## Not run: mod <- PM_model$new(mod_list) ## End(Not run)
Contains observed vs. predicted data after a run, typically a field in a PM_result
The PM_op object is both a data field within a PM_result, and itself an R6 object comprising data fields and associated methods suitable for analysis and plotting of observed vs. population or individual predicted outputs.
Because PM_op objects are automatically added to the PM_result at the end of a successful run, it is generally not necessary for users to generate PM_op objects themselves.
The main results are contained in the $data field,
and it is this field which is passed to the $plot and $summary methods.
You can use this $data field for custom manipulations, e.g. trough <- run1$op$data %>% filter(time == 24).
If you are unfamiliar with the %>% pipe function, please type help("%>%", "magrittr")
into the R console and look online for instructions/tutorials in tidyverse, a
powerful approach to data manipulation upon which Pmetrics is built.
To provide a more traditional experience in R,
the $data field is also separated by columns into the other data fields within the R6 object,
e.g. id or time. This
allows you to access them in an S3 way, e.g. run1$op$time if run1 is a
PM_result object.
idsubject identification
timeobservation time in relative units, usually hours
obsobservation
censcensoring information: "none" for observed, "bloq" for below limit of quantification, "aloq" for above limit of quantification
predprediction
pred.typePopulation predictions based on Bayesian prior parameter value distribution, or individual predictions based on Bayesian posterior parameter value distributions
icenPredictions based on mean or median of Bayesian pred.typeparameter values
outeqoutput equation number
blockdosing block number for each subject, as defined by dose resets (evid=4).
obsSDstandard deviation of the observation based on the assay error polynomial
dprediction error, pred - obs
dssquared prediction error
wdweighted prediction error, which is the prediction error divided by the obsSD
wdsweighted squared prediction error
dataA data frame of class PM_op_data combining all the above fields as its columns
PM_op$new()Create new object populated with observed vs. predicted data
PM_op$new(PMdata = NULL, path = ".", ...)
PMdatainclude Saved, parsed output of prior run, used when source files are not available. .
pathinclude Path to the folder containing the raw results of the run. Default is the current working directory. .
...Not currently used.
Creation of new PM_op object is automatic at the end of a run and not generally necessary
for the user to do.
PM_op$plot()Plot method
PM_op$plot(...)
...Arguments passed to plot.PM_op
See plot.PM_op.
PM_op$summary()Summary method
PM_op$summary(...)
...Arguments passed to summary.PM_op
See summary.PM_op.
PM_op$auc()Calculate AUC
PM_op$auc(...)
...Arguments passed to make_AUC
dataThe object to use for AUC calculation
See make_AUC
PM_op$clone()The objects of this class are cloneable with this method.
PM_op$clone(deep = FALSE)
deepWhether to make a deep clone.
Michael Neely, Julian Otalvaro
Contains optimal sampling times for a given model and dosage regimen.
This object contains the methods to create and results from optimal sampling algorithms. Currently the only option multiple-model optimization. This algorithm calculates the requested number of sample times where the concentration time profiles are the most separated, thereby minimizing the risk of choosing the incorrect Bayesian posterior for an individual. Future updates will add D-optimal sampling times.
sampleTimeThe optimal sample times, based on requested type
argument to $new creation method.
bayesRiskOnly present for MM-optimal sampling. The Bayesian risk of mis-classifying a subject based on the sample times. This is more useful for comparisons between sampling strategies, with minimization the goal.
simdataA PM_sim object with the simulated profiles
mmIntA list with the mmInt values, NULL if mmInt argument
to $new is missing.
PM_opt$new()Determine optimal sample times which are the most informative about the model parameters.
PM_opt$new( poppar, model, data, nsamp = 1, weight = list(none = 1), predInt = 0.5, mmInt, algorithm = "mm", outeq = 1, ... )
popparThere are several choices for the population parameters.
A PM_sim object, in which case the simulated data will be used to calculate optimal sampling times.
Here model and data are not required, as they will be extracted from the PM_sim object.
A PM_result loaded with PM_load, in which case the $final field
will be used, e.g. run1 <- PM_load(1) and poppar = run1.
A PM_final object, typically as a field in a PM_result, e.g.,
poppar = run1$final.
A data frame of support points in rows, where the columns contain the parameter values for each support point.
The first row has the parameter names.
Compatible model and data objects must be specified to simulate the output profiles from each support point.
A list containing three items in this order,
but of any name: vector of weights, vector of mean parameter values, and a
covariance matrix. If only one distribution is to be specified the
weights vector should be of length 1 and contain a 1. If multiple
distributions are to be sampled, the weights vector should be of
length equal to the number of distributions and its values should sum to 1,
e.g. c(0.25,0.05,0.7). The means matrix may be a vector for a
single distribution, or a matrix with length(weights) rows and
number of columns equal to the number of parameters.
Compatible model and data objects must be specified to simulate the output profiles from the support points
generated by sampling from the specified distributions.
modelA PM_model object, required or optional depending on the poppar argument.
When poppar is a PM_sim object, model is ignored.
When poppar is a PM_result object, model is optional.
If missing, the model from the $model field of the PM_result will be used. If specified, model
must be compatible with the primary support point parameter names and values in poppar.
When poppar is a PM_final object, model is mandatory and must be compatible with the
primary support point parameter names and values in poppar.
When poppar is a data frame of support points, model is mandatory and must be compatible with the
parameter names and values in the data frame.
When poppar is a list of weights, means, and covariance, model is mandatory and must be compatible with the
parameter names and values.
dataA PM_data object, required or optional depending on the poppar argument.
When poppar is a PM_sim object, data is ignored.
When poppar is a PM_result object, data is optional. If missing, the data from the $data field of the PM_result will be used.
If specified, data must be compatible with the model that is either in the PM_result or as specified by model.
When poppar is a PM_final object, data is mandatory and must be compatible with the model that is specified by model.
When poppar is a data frame of support points, data is mandatory and must be compatible with the model that is specified by model.
When poppar is a list of weights, means, and covariance, data is mandatory and must be compatible with the model that is specified by model.
For any choice of data, the value for outputs
can be coded as any number(s) other than -99.
The number(s) will be replaced in the simulator output with the simulated values. Good practice is to use -1 for out values to be simulated.
nsampThe number of MM-optimal sample times to compute; default is 1, but can be any number. Values >4 will take an exponentially longer time.
weightList whose names indicate the type of weighting, and values indicate the relative weight. Values should sum to 1. Names can be any of the following:
none The default. MMopt times will be chosen to maximally discriminate all responses at all times.
AUC MMopt times will be chosen to maximally discriminate AUC, regardless of the shape of the response profile.
max MMopt times will be chosen to maximally discriminate maximum, regardless of the shape of the response profile.
min MMopt times will be chosen to maximally discriminate minimum, regardless of the shape of the response profile.
Any combination of AUC, max, and min can be chosen. If "none" is specified, other
weight types will be ignored and the relative value will be set to 1.
For example,list(auc = 0.5,max = 0.5) or list(auc = 0.2, min = 0.8).
The default is list(none = 1).
predIntThe interval in fractional hours for simulated predicted outputs at times other than those specified in the template data.
The default is 0.5, which means there will be simulated outputs every 30 minutes from time 0 up
to the maximal time in the template file. You may also specify predInt
as a vector of 3 values, e.g. c(1,4,1), similar to the R command seq, where the
first value is the start time, the second is the stop time, and the third is the
step value. Outputs for times specified in the template file will also be simulated.
To simulate outputs only at the output times in the template data (i.e. EVID=0 events), use predInt = 0.
Note that the maximum number of predictions total is 594, so the interval must be sufficiently large to accommodate this for a given
number of output equations and total time to simulate over. If predInt is set so that this cap is exceeded, predictions will be truncated.
mmIntSpecify the time intervals from which MMopt times can be selected.
These should only include simulated times specified by predInt.
algorithmOptimal sampling algorithm. Currently not modifiable and the only option is "mm".
outeqOutput equation to optimize
...Other parameters to pass to PM_sim$new(). Most are not necessary,
but usePost = TRUE can be used to calculate individual MMopt times.
In this case, the number of posterior distributions contained in
poppar$final$postPoints needs to match the number of subjects in data.
You can also pass include and exclude to limit the subjects used in
data. This will work whether usePost is TRUE or FALSE.
Note that the following arguments to PM_sim$new cannot be modified.
nsim is zero
outname is "MMsim"
combine is TRUE
cleanBoolean parameter to specify whether temporary files made in the
course of the simulation run should be deleted. Defaults to TRUE.
This is primarily used for debugging.
Currently, the only option is the multiple-model optimization algorithm.
PM_opt$plot()Plot method
PM_opt$plot(...)
...Arguments passed to plot.PM_opt
See plot.PM_opt.
PM_opt$print()Print method
PM_opt$print()
Prints the optimal sampling times and Bayes Risk.
PM_opt$clone()The objects of this class are cloneable with this method.
PM_opt$clone(deep = FALSE)
deepWhether to make a deep clone.
Michael Neely
Bayard, David S. & and Neely, Michael. (2017). Experiment Design for Nonparametric Models Based on Minimizing Bayes Risk: Application to Voriconazole. Journal of Pharmacokinetics and Pharmacodynamics, 44(2): 95–111. https://doi.org/10.1007/s10928-016-9498-5.
Contains the population predictions at short intervals
specified as an argument to the $fit method of PM_model. Default is every 12 minutes.
#' The PM_pop object is both a data field within a PM_result, and itself an R6 object comprising data fields and associated methods suitable for analysis and plotting of population predictions generated during the run.
Because PM_pop objects are automatically added to the PM_result at the end of a successful run, it is generally not necessary for users to generate PM_pop objects themselves.
The main results are contained in the $data field,
and it is this field which is passed to the $plot and $summary methods.
data frame with population predicted outputs for all subjects.
To provide a more traditional experience in R,
the data frame is separated by columns into fields, e.g. id or time. This
allows you to access them in an S3 way, e.g. run1$pop$time if run1 is a
PM_result object.
However, if you wish to manipulate the entire data frame,
use the data field, e.g. trough <- run1$pop$data %>% filter(time == 24). If
you are unfamiliar with the %>% pipe function, please type help("%>%", "magrittr")
into the R console and look online for instructions/tutorials in tidyverse, a
powerful approach to data manipulation upon which Pmetrics is built.
dataA data frame with the following columns:
id Subject id
time Time of predictions in decimal hours
icen Prediction based on mean or median of Bayesian posterior parameter distribution
outeq Output equation number
pred Predicted output for each outeq
block Observation blocks within subjects as defined by EVID=4 dosing events
PM_pop$new()Create new object populated with population predicted data at regular, frequent intervals
PM_pop$new(PMdata = NULL, path = ".", ...)
PMdatainclude Saved, parsed output of prior run, used when source files are not available. .
pathinclude Path to the folder containing the raw results of the run. Default is the current working directory. .
...Not currently used.
Creation of new PM_pop object is automatic and not generally necessary
for the user to do.
PM_pop$plot()Plot method
PM_pop$plot(...)
...Arguments passed to plot.PM_pop
See plot.PM_pop.
PM_pop$summary()Summary method
PM_pop$summary(...)
...Arguments passed to summary.PM_pop
See summary.PM_pop.
PM_pop$auc()Calculate AUC
PM_pop$auc(...)
...Arguments passed to make_AUC
dataThe object to use for AUC calculation
See make_AUC
PM_pop$clone()The objects of this class are cloneable with this method.
PM_pop$clone(deep = FALSE)
deepWhether to make a deep clone.
Michael Neely, Julian Otalvaro
Contains the Bayesian posterior predictions at short intervals
specified as an argument to the $fit method of PM_model. Default is every 12 minutes.
#' The PM_post object is both a data field within a PM_result, and itself an R6 object comprising data fields and associated methods suitable for analysis and plotting of posterior predictions generated during the run.
Because PM_post objects are automatically added to the PM_result at the end of a successful run, it is generally not necessary for users to generate PM_post objects themselves.
The main results are contained in the $data field,
and it is this field which is passed to the $plot and $summary methods.
data frame with population predicted outputs for all subjects.
To provide a more traditional experience in R,
the data frame is separated by columns into fields, e.g. id or time. This
allows you to access them in an S3 way, e.g. run1$post$time if run1 is a
PM_result object.
However, if you wish to manipulate the entire data frame,
use the data field, e.g. trough <- run1$post$data %>% filter(time == 24). If
you are unfamiliar with the %>% pipe function, please type help("%>%", "magrittr")
into the R console and look online for instructions/tutorials in tidyverse, a
powerful approach to data manipulation upon which Pmetrics is built.
dataA data frame with the following columns:
id Subject id
time Time of predictions in decimal hours
icen Prediction based on mean or median of Bayesian posterior parameter distribution
outeq Output equation number
pred Predicted output for each outeq
block Observation blocks within subjects as defined by EVID=4 dosing events
PM_post$new()Create new object populated with Bayesian posterior predicted data at regular, frequent intervals
PM_post$new(PMdata = NULL, path = ".", ...)
PMdatainclude Saved, parsed output of prior run, used when source files are not available. .
pathinclude Path to the folder containing the raw results of the run. Default is the current working directory. .
...Not currently used.
Creation of new PM_post object is automatic and not generally necessary
for the user to do.
PM_post$plot()Plot method
PM_post$plot(...)
...Arguments passed to plot.PM_pop
See plot.PM_pop.
PM_post$summary()Summary method
PM_post$summary(...)
...Arguments passed to summary.PM_pop
See summary.PM_post.
PM_post$auc()Calculate AUC
PM_post$auc(...)
...Arguments passed to make_AUC
dataThe object to use for AUC calculation
See make_AUC
PM_post$clone()The objects of this class are cloneable with this method.
PM_post$clone(deep = FALSE)
deepWhether to make a deep clone.
Michael Neely, Julian Otalvaro
Generates a report from a specified Rmd template
PM_report(x, template, path, show = TRUE, quiet = TRUE)PM_report(x, template, path, show = TRUE, quiet = TRUE)
x |
|
template |
If missing, the default Pmetrics report template as specified in getPMoptions
is used. It can be changed with setPMoptions. Otherwise, the value for |
path |
The path for the generated report, defaults to a temporary folder. |
show |
Controls if the report should be automatically opened on generation, defaults to |
quiet |
If |
Generates an HTML-report in the folder specified by path.
Markus Hovd, Julian Otalvaro, and Michael Neely
This function is largely superseded as it is accessed through the $step methods
for PM_result and PM_cov objects. There is rarely a need to call it directly
any longer.
PM_step(x, icen = "median", direction = "both")PM_step(x, icen = "median", direction = "both")
x |
A PMcov object which is the |
icen |
A character vector to summarize covariate values. Default is "median", but can also be "mean". |
direction |
The direction for covariate elmination can be "backward", "forward", or "both" (default). |
It will perform stepwise linear regressions on a PM_cov object. Every covariate in the model will be tested in a stepwise linear regression for their relationships to each parameter in the model. Bayesian posterior parameters and individual covariates are used.
A matrix with covariates in the rows and parameters in the columns. Values for the matrix are the multi-variate P-values.
A value of NA indicates that the variable was not retained in the final model.
Michael Neely
Sets up a directory tree for a new Pmetrics project
PM_tree(project = "NewProject", path = getwd()) PMtree(...)PM_tree(project = "NewProject", path = getwd()) PMtree(...)
project |
A character string of a new project name, e.g. "DrugX" |
path |
The full path to the root folder for the new project. Default is the current working directory. |
... |
Arguments passed to PM_tree. |
This function will create a new project folder tree with appropriate subfolders and a skeleton R script. You can edit the folder names and add new ones as you wish.
A new folder with the name in project and the following subfolders:
Rscript The folder containing a skeleton Analysis.R script for the project.
Runs The folder for all Pmetrics runs, which will be sequentially numbered.
Sim The folder for all simulations related to the project.
src The folder for source data files in their original format, to preserve integrity and for audit purposes.
Michael Neely
## Not run: PM_tree("DrugX") ## End(Not run)## Not run: PM_tree("DrugX") ## End(Not run)
Introductory tutorial to Pmetrics
PM_tutorial()PM_tutorial()
This function will create a Learn folder in the current working directory or one you specify. The folder will contain all files and subfolders necessary to conduct the tutorial found at https://lapkb.github.io/PM_tutorial/. After the Learn folder is created, open the Rscript/Learn.R script to begin the tutorial.
Contains results of internal validation by simulation to permit generation of visual predictive checks (VPCs), prediction corrected visual predictive checks, (pcVPCs), normalized prediction distribution errors (NPDE), and numerical predictive checks. This is typically a field in a PM_result
The PM_valid object is both a data field within a PM_result, and itself an R6 object comprising data fields and associated methods suitable for analysis and plotting of observed vs. population or individual predicted outputs.
Because PM_valid objects are automatically added to the PM_result by calling the
$validate() method of a PM_result after a
successful run, it is generally not necessary for users to generate PM_valid objects
themselves.
simdataSimulated data created in the validation process
timeBinMedianMedian times for cluster bins
tadBinMedianMedian times after previous doses for cluster bins
opDFObserved-predicted data frame
npdeData for Normalized Prediction Distribution Error
npde_tadData for Normalized Prediction Distribution Error using Time After Dose if available
npde_statsCaptured NPDE console summaries for later replay
PM_valid$new()This function will create an object suitable for plotting visual predictive checks (VPCs) and prediction-corrected visual predictive checks (pcVPCs).
PM_valid$new(result, tad = FALSE, binCov, doseC, timeC, tadC, limits, ...)
resultThe result of a prior run, usually supplied by calling the
$validate() method of a PM_result at the end of a run, or later loaded with PM_load.
tadBoolean operator to use time after dose rather than time after start. Default is FALSE.
binCovA character vector of the names of covariates which are included in the model, i.e. in the
model equations and which need to be binned. For example binCov='wt' if "wt" is included in a
model equation like V=V0*wt, or binCov=c( 'wt', 'crcl') if both "wt" and "crcl"
are included in model equations.
doseCAn integer with the number of dose/covariate bins to cluster, if known from a previous run of this function. Including this value will skip the clustering portion for doses/covariates.
timeCAn integer with the number of observation time bins to cluster, if known from a previous run of this function. Including this value will skip the clustering portion for observation times.
tadCAn integer with the number of time after dose bins to cluster, if known from a previous run of
this function. Including this value will skip the clustering portion for time after dose. This argument
will be ignored if tad=FALSE.
limitsLimits on simulated parameters. See PM_sim.
...Other parameters to be passed to PM_sim, especially limits.
The function will guide the user
through appropriate clustering of doses, covariates and sample times for
prediction correction using the methods of Bergstrand et al (2011).
NOTE: Including tad is only
valid if steady state conditions exist for each patient.
This means that dosing is stable and regular
for each patient, without changes in amount or timing, and that
sampling occurs after the average concentrations
are the same from dose to dose. Otherwise observations are NOT
superimposable and tad should
NOT be used, i.e. should be set to FALSE.
An R6 object of class PM_valid, which is a list with the following.
simdata The combined, simulated files for all subjects using the population mean values and each subject as a template. This object will be automatically saved to the run, to be loaded with PM_load next time.
timeBinMedian A data frame with the median times for each cluster bin.
tadBinMedian A data frame with the median time after dose (tad) for each cluster bin.
This will be NA if tad = FALSE.
opDF A data frame with observations, predicitons, and bin-corrected predictions for each subject.
ndpe An object with results of normalized distrubition of prediction errors analysis.
npde_tad NPDE with time after dose rather than absolute time, if tad = TRUE
npde_stats Captured NPDE console summary text, replayable with $show_npde_stats().
valid <- NPex$validate(limits = c(0, 3))
PM_valid$show_npde_stats()Replay captured NPDE summary statistics.
PM_valid$show_npde_stats(outeq = 1, tad = FALSE)
outeqOutput equation number to replay.
tadLogical; replay TAD-based NPDE stats.
PM_valid$summary()Summarize a PM_valid object. Reports NPDE distribution statistics and a Numerical Predictive Check (NPC) for each output equation. TAD-based results are included automatically when TAD validation was performed.
PM_valid$summary(probs = c(0.05, 0.5, 0.95))
probsNumeric vector of quantile cut-points for the NPC.
Default is c(0.05, 0.5, 0.95).
PM_valid$plot()Plot method. Calls plot.PM_valid.
PM_valid$plot(...)
...Arguments to pass to [plot.PM_valid].
PM_valid$clone()The objects of this class are cloneable with this method.
PM_valid$clone(deep = FALSE)
deepWhether to make a deep clone.
Michael Neely
## ------------------------------------------------ ## Method `PM_valid$new()` ## ------------------------------------------------ ## Not run: valid <- NPex$validate(limits = c(0, 3)) ## End(Not run)## ------------------------------------------------ ## Method `PM_valid$new()` ## ------------------------------------------------ ## Not run: valid <- NPex$validate(limits = c(0, 3)) ## End(Not run)
This function is largely superseded as it is called automatically when data are initialized as a PM_data object. It can still be called independently of this route and will check for data errors.
PMcheck(data, path = ".", fix = FALSE, quiet = FALSE)PMcheck(data, path = ".", fix = FALSE, quiet = FALSE)
data |
The name of a Pmetrics .csv matrix file in the current working directory, the full path to one not in the current working directory, or a data.frame containing the output of a previous PMreadMatrix command. |
path |
The path of the data if originally a file |
fix |
Boolean operator; if |
quiet |
Boolean operator to suppress printed output. Default is false. |
It will check the data for errors
which would cause the analysis to fail. Note that as of
Pmetrics Version 2, this function is called automatically when a new PM_data
object is created, and users generally no longer need to call the function directly.
In PM_data$new(), the data object is first standardized to contain all required columns,
since only "ID", "TIME", "DOSE" and "OUT" are required at minimum, and then checked with PMcheck.
If calling PMcheck directly, either a filename or a Pmetrics data object in memory are accepted as data.
Because there is no standardization with direct calls, in this case the format of the .csv matrix file is fairly rigid.
It must have the following features. Text is case-sensitive.
A header in row 1 with the appropriate version, currently "POPDATA DEC_11"
Column headers in row 2. These headers are: #ID, EVID, TIME, DUR, DOSE, ADDL, II, INPUT, OUT, CENS, OUTEQ, C0, C1, C2, C3.
No cell should be empty. It should either contain a value or "." as a placeholder.
Columns after C3 are interpreted as covariates.
All subject records must begin with TIME=0.
All dose events (EVID=1) must have entries in ID, EVID, TIME, DUR, DOSE and INPUT. ADDL and II are optional, but if ADDL is not 0 or missing, then II is mandatory.
All observation events (EVID=0) must have entries in ID, EVID, TIME, OUT, OUTEQ. If an observation is missing, use -99; otherwise use a "." as a placeholder in cells that are not required (e.g. INPUT for an observation event).
If covariates are present in the data, there must be an entry for every covariate at time 0 for each subject.
All covariates must be numeric.
All times within a subject ID must be monotonically increasing.
All subject IDs must be contiguous.
All rows must have EVID and TIME values.
All columns must be numeric except ID which may be alpha-numeric.
All subjects must have at least one observation, which could be missing, i.e. -99.
Cells which are not needed (e.g. dose on an observation event, EVID=0), should contain ".".
To use this function, see the example below.
After running PMcheck and looking at the errors in the errors.xlsx file, you can fix the
errors manually directly in the errors.xlsx file and resave it as a .csv file.
Alternatively, you could then try to fix the problem(s) with mdata2 <- PMcheck(mdata,fix=T). Note that we are now returning
a PMmatrix data object called mdata2 (hopefully cleaned of errors) rather than the PMerr object returned when fix=FALSE.
Pmetrics handles each of the errors in the following ways.
If the columns are simply out of order, they will be reordered. If some are missing, the fix must be done by the user, i.e. manually.
All id and covariate values are truncated to 11 characters.
Missing observations are set to -99 (not ".").
Incomplete dose records are flagged for the user to fix manually.
Incomplete observation records are flagged for the user to fix manually.
Subjects without an EVID=1 as first event are flagged for the user to fix manually.
Subjects with TIME != 0 as first event have dummy dose=0 events inserted at time 0.
Subjects with a missing covariate at time 0 are flagged for the user to fix manually.
Non-numeric covariates are converted to numeric (via factor()).
Non-ordered times are sorted within a subject if there are no EVID=4 events; otherwise the user must fix manually.
Non-contiguous subject ID rows are combined and sorted if there are no EVID=4 events; otherwise the user must fix manually.
Rows missing an EVID are assigned a value of 0 if DOSE is missing, 1 otherwise.
Rows missing a TIME value are flagged for the user to fix manually.
Cells with malformed NA values are attempted to be fixed.
Columns that are non-numeric which must be numeric are flagged for the user to fix manually. These are all columns except ID. Covariate columns are fixed separately (see above).
Dose events with censoring will be set to uncensored, with a warning to the user.
If fix=TRUE, then PMcheck returns
The original data if no errors are found, or
A PMmatrix data object which has been cleaned of errors as much as possible, displaying a report on the console.
If fix=FALSE, then PMcheck creates a file in the working directory called "errors.xlsx".
This file can be opened by Microsoft Excel or any other program that is capable of reading .xlsx files. This file
contains highlighted areas that are erroneous, with clarifying comments. You can correct the errors in the file
and then re-save as a .csv file.
When fix=FALSE, the function also returns a list of objects of class PMerr. Each object is itself a list whose
first object ($msg) is a character vector with "OK" plus a brief description if there is no error, or the error.
The second object ($results) is a vector of the row numbers that contain that error.
colorder The first 14 columns must be named id, evid, time, dur, dose, addl, ii, input, out, outeq, c0, c1, c2, and c3 in that order.
maxcharCol All column names should be less than or equal to 11 characters.
maxcharID All id values should be less than or equal to 11 characters.
missEVID Ensure that all rows have an EVID value.
missTIME Ensure that all rows have a TIME value.
doseDur Make sure all dose records are complete, i.e. contain a duration.
doseDose Make sure all dose records are complete, i.e. contain a dose.
doseInput Make sure all dose records are complete, i.e. contain an input number.
obsOut Make sure all observation records are complete, i.e. contain an output.
obsOuteq Make sure all observation records are complete, i.e. contain and outeq number.
T0 Make sure each subject's first time=0.
covT0 Make sure that there is an non-missing entry for each covariate at time=0 for each subject.
timeOrder Ensure that all times within a subject ID are monotonically increasing.
contigID Ensure that all subject IDs are contiguous.
nonNum Ensure that all columns except ID are numeric.
noObs Ensure that all subjects have at least one observation, which could be missing, i.e. -99.
mal_NA Ensure that all NA values are ".", not ". ", " .", "..", or other malformations.
Michael Neely and Patrick Nolain
## Not run: err <- PMcheck(badData) # look at the errors.xlsx file in the working directory # try to automatically fix what can be fixed goodData <- PMcheck(badCSV, fix = T) PMcheck(goodData) # you have to fix manually problems which require data entry ## End(Not run)## Not run: err <- PMcheck(badData) # look at the errors.xlsx file in the working directory # try to automatically fix what can be fixed goodData <- PMcheck(badCSV, fix = T) PMcheck(goodData) # you have to fix manually problems which require data entry ## End(Not run)
Convert dates/times to relative times. This function is largely superseded as it is called automatically when data are initialized as a PM_data object. There is rarely a need to call it directly any longer.
PMmatrixRelTime( data, idCol = "id", dateCol = "date", timeCol = "time", evidCol = "evid", format, split = F )PMmatrixRelTime( data, idCol = "id", dateCol = "date", timeCol = "time", evidCol = "evid", format, split = F )
data |
The name of an R data object. |
idCol |
A character vector with the name
of the id column in |
dateCol |
A character vector with the name of the date
column in |
timeCol |
A character vector with the name of the time
column in |
evidCol |
A character vector with the name of the event id
column in |
format |
Format of the date and time columns; default is m/d/y and h:m:s, as specified in the chron::chron function. Note the separators in each case (/ for dates and : for times). For dates, m is months in digits and can be one or two digits; d is the day of the month, again as one or two digits; y is the year in 2 or 4 digits. For times, all values can be one or two digits, but time is in 24-hour format, and s is required to avoid ambiguity. |
split |
If true, |
PMmatrixRelTime will convert absolute dates and times in a dataset
into relative hours, suitable for Pmetrics analysis. Additionally, the user has
the option to split subjects into pseudosubjects every time a dose reset (evid=4)
is encountered.
Returns a dataframe with columns id, evid, relTime.
If split=T all evid values that were previously 4 will be converted to 1.
Michael Neely
Download and install Pmetrics patches from LAPK website
PMpatch()PMpatch()
A Pmetrics patch which will be installed via source
Michael Neely
Reads a Pmetrics .csv matrix input file into R.
This function is largely superseded as the function is called automatically
when data are intialized as a PM_data object with PM_data$new(). There
is rarely need to call PMreadMatrix() directly any longer.
PMreadMatrix( file, sep = getPMoptions("sep"), dec = getPMoptions("dec"), quiet = FALSE, ... )PMreadMatrix( file, sep = getPMoptions("sep"), dec = getPMoptions("dec"), quiet = FALSE, ... )
file |
The name of the file to be loaded, including the full path if not in the current working directory (check with getwd). |
sep |
Delimiter between columns, which is a comma by default, but can be changed with setPMoptions. |
dec |
Decimal separator, which is a period by default, but can be changed with setPMoptions. |
quiet |
Default is |
... |
Other parameters to be passed to |
As of Pmetrics version 2, the structure of a valid .csv file relaxed.
Minimal required columns are id, time, dose, and out. This function is now included
as part of the PM_data R6 object to create new PM_data objects. Users should
rarely have a need to call PMreadMatrix as a standalone function unless they
continue to use Pmetrics in its legacy mode (versions < 2.0). Note that support
for legacy Pmetrics will eventually wither as the package evolves.
There are a number of other options for columns in the data input. Details can be found in the documentation.
PMreadMatrix returns a data frame of class "PMmatrix".
If the file is successfully read and quiet=F,
the column headers will be reported to the console as a validation check.
Note that this function converts the column headers in the
file from upper to lowercase for convenient referencing in R.
Michael Neely
PMwriteMatrix, PMcheck, and plot.PM_data
Check Pmetrics fortran installation by trying to compile sample files
PMtest()PMtest()
Michael Neely
This function is largely superseded as the function is accessed with
the $save() method for PM_data objects. There is rarely a need to call
it directly. It is the companion function to PMreadMatrix.
It will write an appropriate R data object to a formatted .csv file.
PMwriteMatrix( data, filename, override = FALSE, version = "DEC_11", header = FALSE )PMwriteMatrix( data, filename, override = FALSE, version = "DEC_11", header = FALSE )
data |
Must be a data.frame with appropriate structure (see PMcheck). |
filename |
Name of file to create. |
override |
Boolean operator to write even if errors are detected. Default is |
version |
Which matrix data format version to write. Default is the current version. |
header |
Is there a header row? Default is |
PMwriteMatrix will first run PMcheck to determine
if there are any errors in the structure of data. If the error check
fails, the file will not be written and a message will be printed on the console.
Returns the error report (see PMcheck for details).
Michael Neely
PM_data, PMcheck, PMreadMatrix
## Not run: # write to the current directory NPex$data$save("data.csv") ## End(Not run)## Not run: # write to the current directory NPex$data$save("data.csv") ## End(Not run)
Convert old-style, USC*PACK single drug working copy files into a PM_data object and write a .csv file to the current working directory.
PMwrk2csv(prefix, ext = NULL, nsub)PMwrk2csv(prefix, ext = NULL, nsub)
prefix |
The alphabetic prefix of the working copy files to be converted, as a character vector. |
ext |
The extension of the working copy files files, if it exists. Does not have to be specified. |
nsub |
The number of subjects, or working copy files to read. |
This function will determine if the working copy files are old and convert them. New, multi-drug working copy files will be ignored. IDs will be suffixed with .1 to .9 for <10 subjects, .01 to .99 for <100 subjects and .001 to .999 for <1000 subjects, as needed to ensure unique ID numbers.
A new file will be created with the name equal to prefix and
an extension of "csv".
Michael Neely
r lifecycle::badge("stable")
Prints a summary of the PM_compare object.
## S3 method for class 'PM_compare' print(x, ...)## S3 method for class 'PM_compare' print(x, ...)
x |
A PM_compare object. |
... |
Additional arguments (not used). |
Print the errors in a Pmetrics data file or PM_data object.
## S3 method for class 'PMerr' print(x, ...)## S3 method for class 'PMerr' print(x, ...)
x |
A PMerr object made by validation in PM_data. |
... |
Not used. |
A printed object.
Michael Neely
Print a Pmetrics NPC (Numerical Predictive Check) object, made by plot.PM_sim.
## S3 method for class 'PMnpc' print(x, ...)## S3 method for class 'PMnpc' print(x, ...)
x |
A PMnpc object made by plot.PM_sim. |
... |
Other parameters which are not necessary. |
A printed object.
Michael Neely
Print a Pmetrics Cycle Summary Object
## S3 method for class 'summary.PM_cycle' print(x, ...)## S3 method for class 'summary.PM_cycle' print(x, ...)
x |
An object made by summary.PM_cycle. |
... |
Not used. |
Print a summary a summary.PM_cycle object made by summary.PM_cycle. Users do not normally need to call this function directly, as it will be the default method to display the object.
A printed object.
Michael Neely
#' ## Not run: NPex$cycle$summary() ## End(Not run)#' ## Not run: NPex$cycle$summary() ## End(Not run)
## S3 method for class 'summary.PM_data' print(x, ...)## S3 method for class 'summary.PM_data' print(x, ...)
x |
An object made by summary.PM_data. |
... |
Not used. |
Print the summary of PM_data object.
Summarize the raw data used for a Pmetrics run.
A printed object
Michael Neely
## Not run: dataEx$summary() ## End(Not run)## Not run: dataEx$summary() ## End(Not run)
Print a Pmetrics Final Summary Object
## S3 method for class 'summary.PM_final' print(x, digits = 3, ...)## S3 method for class 'summary.PM_final' print(x, digits = 3, ...)
x |
A summary.PM_final object made by summary.PM_final. |
digits |
Integer, used for number of digits to print. |
... |
Not used. |
Print a summary of parameter medians and MAWD, with point estimates and credibilty intervals from an object made by summary.PM_final. Users do not normally need to call this function directly, as it will be the default method to display the object.
A printed object.
Michael Neely
## Not run: NPex$final$summary ## End(Not run)## Not run: NPex$final$summary ## End(Not run)
Print a Pmetrics Observed vs. Predicted Summary Object
## S3 method for class 'summary.PM_op' print(x, digits = getPMoptions("digits"), embed = FALSE, ...)## S3 method for class 'summary.PM_op' print(x, digits = getPMoptions("digits"), embed = FALSE, ...)
x |
An object made by summary.PM_op. |
digits |
Integer, used for number of digits to print. |
embed |
If |
... |
Not used. |
Print a summary of observations, predictions and errors in a summary.PM_op object made by summary.PM_op. Users do not normally need to call this function directly, as it will be the default method to display the object.
A printed object.
Michael Neely
## Not run: NPex$op$summary() ## End(Not run)## Not run: NPex$op$summary() ## End(Not run)
Print a Pmetrics Observed vs. Predicted Summary Object
## S3 method for class 'summary.PM_sim' print(x, ...)## S3 method for class 'summary.PM_sim' print(x, ...)
x |
An object made by summary.PM_sim. |
... |
Not used. |
Print a summary of simulations made by summary.PM_sim. Users do not normally need to call this print function directly, as it will be the default method to display the object.
A printed object.
Michael Neely
## Not run: simEx$summary() ## End(Not run)## Not run: simEx$summary() ## End(Not run)
Create an proportional (gamma) error model
proportional(initial, coeff, fixed = FALSE)proportional(initial, coeff, fixed = FALSE)
initial |
Initial value for gamma |
coeff |
Vector of coefficients defining assay error polynomial |
fixed |
Estimate if |
Will extract height, weight, and BMI for boys, girls or both for a given range of ages in months and percentiles. This can be useful for simulations in Pmetrics.
qgrowth(sex = "B", agemos = (seq(0, 18) * 12), percentile = 50)qgrowth(sex = "B", agemos = (seq(0, 18) * 12), percentile = 50)
sex |
A single quoted character: "M" for males, "F" for females, or "B" for both. Default is "B". |
agemos |
A vector of ages in months to return. The default is
|
percentile |
An integer vector of the percentile for each age/sex to return.
Default is 50, but could be, for example |
A dataframe with columns
agemos Age in months
ageyrs Age in years
wt Weight in kilograms
ht Height or length in centimeters
bmi Body mass index $kg/m^2$
sex The selected sex(es)
percentile The selected percentile(s)
Michael Neely
Converts a CSS
rgba() string to an RGB color string.
rgba_to_rgb(rgba_str, alpha = NULL)rgba_to_rgb(rgba_str, alpha = NULL)
rgba_str |
A string in the format |
alpha |
Optional numeric value to replace the alpha channel in the rgba string. |
Set user options for Pmetrics
setPMoptions(launch.app = TRUE)setPMoptions(launch.app = TRUE)
launch.app |
Launch the app to set options. Default |
When you call this function with the default launch.app = TRUE, it will start
a Shiny app to set options for the Pmetrics package.
Also, when the Pmetrics package is first loaded with library(Pmetrics),
this function will be called with launch.app = TRUE to read saved options from
a PMoptions.json file stored in a folder outside
of the Pmetrics package, so that your options will persist when Pmetrics is updated.
The user preferences file will be updated. This will persist from session to session and if stored in the external location, through Pmetrics versions.
Michael Neely
Example simulator output
simExsimEx
R6 PM_sim
This is an R6 Pmetrics PM_sim object created by
created by running $sim() on a PM_result object, e.g.
NPex$sim(include = 1:4, limits = NA, nsim = 100).
Michael Neely
This function calculates sample size based on a desired standard error of the mean, to a specified confidence, for a given mean and standard deviation.
ss.PK(n, mean, sd, precision, ci = 0.95)ss.PK(n, mean, sd, precision, ci = 0.95)
n |
Sample size. This value can be missing if sample size is desired, or
specified to calculate the maximum sd for given |
mean |
Mean prameter value. User value is mandatory. |
sd |
Standard deviation of parameter values. If present, the function will return |
precision |
Desired width of the standard error of the mean (SEM). Default is 0.2, i.e. 20% or
10% below and 10% above the mean. If missing, and |
ci |
Confidence for the desired width of the SEM. Default is 0.95. |
The formula is n = qnorm((1+ci)/2)**2 * sd**2 / (precision*mean)**2
The missing argument: n, sd or precision.
Michael Neely
Wrapper around plotly::subplot().
sub_plot( ..., nrows = 1, widths = NULL, heights = NULL, margin = 0.02, titles = NULL, shareX = FALSE, shareY = FALSE, titleX = shareX, titleY = shareY, which_layout = "merge", print = TRUE )sub_plot( ..., nrows = 1, widths = NULL, heights = NULL, margin = 0.02, titles = NULL, shareX = FALSE, shareY = FALSE, titleX = shareX, titleY = shareY, which_layout = "merge", print = TRUE )
... |
One of the following
|
nrows |
number of rows for laying out plots in a grid-like structure. Default is 1. |
widths, heights
|
Vector of relative column widths or heights
on a 0-1 scale. By default all columns have an equal relative width/height,
i.e. |
margin |
either a single value or a vector of four values (all between 0 and 1),
e.g. |
titles |
Include titles on individual subplots? Default is |
shareX, shareY
|
Should the x- or y- axis be shared amongst the subplots? |
titleX, titleY
|
Should x- or y- axis titles be retained? |
which_layout |
Adopt the layout of which plot? If the default value of "merge" is used, layout options found later in the sequence of plots will override options found earlier in the sequence. This argument also accepts a numeric vector specifying which plots to consider when merging. |
print |
If |
This function addresses the deficiency with the native plotly method of combining
multiple plots that prevents individualized titling of subplots. The function
has identical arguments to plotly::subplot() with the addition of a titles
argument. In addition to subplot, the behavior of this function is two-fold:
Fetch the titles (text and formatting) from each included plot
Include the titles with placement per the titles argument
A plot and plotly object combining all the plots in ...,
which can be further modified.
Michael Neely
## Not run: plot1 <- NPex$op$plot(title = "Posterior") plot2 <- NPex$op$plot(pred.type = "pop", title = "Population") sub_plot(plot1, plot2, titles = c(0, 0.95), nrows = 2) ## End(Not run)## Not run: plot1 <- NPex$op$plot(title = "Posterior") plot2 <- NPex$op$plot(pred.type = "pop", title = "Population") sub_plot(plot1, plot2, titles = c(0, 0.95), nrows = 2) ## End(Not run)
Summarize a Pmetrics Covariate object
## S3 method for class 'PM_cov' summary(object, icen = "median", ...)## S3 method for class 'PM_cov' summary(object, icen = "median", ...)
object |
A PM_cov object |
icen |
Summary function for covariates with time dependent values and posterior parameters. Default is "median", but can specify "mean". |
... |
Not used. |
This is a function usually called by the $summary() method for PM_cov objects
with a PM_result to summarize covariates and Bayesian posterior parameter
values for each subject. The function can
be called directly on a PM_cov object. See examples.Summarize .
A data frame with the summary of the PM_cov object for each subject's covariates and Bayesian posterior parameter values.
Michael Neely
## Not run: NPex$cov$summary() # preferred summary(NPex$cov) # alternative NPex$cov$summary(icen = "mean") # use mean as summary ## End(Not run)## Not run: NPex$cov$summary() # preferred summary(NPex$cov) # alternative NPex$cov$summary(icen = "mean") # use mean as summary ## End(Not run)
Summarize a Pmetrics Cycle object
## S3 method for class 'PM_cycle' summary(object, cycle = NULL, digits = 3, ...)## S3 method for class 'PM_cycle' summary(object, cycle = NULL, digits = 3, ...)
object |
A PM_cycle object |
cycle |
Cycle number to summarize. Default is last cycle. |
digits |
Number of digits to round to. Default is 3. |
... |
Not used. |
This is a function usually called by the $summary() method for PM_cycle objects
within a PM_result to summarize final cycle statistics. The function can
be called directly on a PM_cycle object. See examples.
A list of class summary.PM_cycle whose elements are the last cycle values for the following fields in a PM_cycle object.
cycle Maximum cycle number
ll Log likelihood
aic Akaike Information Criterion
bic Bayesian Information Criterion
gamlam Value of gamma or lambda for each output equation
mean Normalized mean parameter values compared to initial value
sd Normalized standard deviation of parameter values compared to initial value
median Normalized median parameter values compared to initial value
Michael Neely
#' ## Not run: NPex$cycle$summary() # preferred summary(NPex$cycle) # alternative ## End(Not run)#' ## Not run: NPex$cycle$summary() # preferred summary(NPex$cycle) # alternative ## End(Not run)
Summarizes the raw data (
class: PM_cycle_data) from a PM_cycle object in the same way as summarizing a PM_cycle object.
Both use summary.PM_cycle.
## S3 method for class 'PM_cycle_data' summary(object, ...)## S3 method for class 'PM_cycle_data' summary(object, ...)
object |
A |
... |
Additional arguments passed to summary.PM_cycle |
# There is no example we can think of to filter or otherwise process a PM_cycle object, # but we provide this function for completeness. NPex$cycle$data %>% summary() # all the below are the same # summary(NPex$cycle$data) # summary(NPex$cycle) # NPex$cycle$summary()# There is no example we can think of to filter or otherwise process a PM_cycle object, # but we provide this function for completeness. NPex$cycle$data %>% summary() # all the below are the same # summary(NPex$cycle$data) # summary(NPex$cycle) # NPex$cycle$summary()
Summarize the raw data used for a Pmetrics run.
## S3 method for class 'PM_data' summary(object, formula, FUN, include, exclude, ...)## S3 method for class 'PM_data' summary(object, formula, FUN, include, exclude, ...)
object |
A PM_data object. |
formula |
Optional formula for specifying custom summaries. See aggregate
and formula for details on how to specify formulae in R. If, for example, the data contain
a covariate for weight named 'wt', then to summarize the mean dose in mg/kg per subject specify
|
FUN |
The summary function to apply to formula, if specified. This is not quoted, and usual choices will be mean, median, max, or min. |
include |
A vector of subject IDs to include in the summary, e.g. |
exclude |
A vector of subject IDs to exclude in the summary, e.g. |
... |
Additional arguments to |
A list of class summary.PM_data with the following items:
nsub Number of subjects
ndrug Number of drug inputs
numeqt Number of outputs
nobsXouteq Number of observations by outeq
missObsXouteq Number of missing observations by outeq
loqObsXouteq Number of observations coded as below the limit of quantification by outeq
ncov Number of covariates
covnames Covariate names
ndoseXid Number of doses per input per subject
nobsXid Number of observations per outeq per subject
doseXid Doses per input per subject
obsXid Observations per outeq per subject
formula Results of including formula
Michael Neely
Generates summary statistics of final population model parameters.
## S3 method for class 'PM_final' summary(object, lower = 0.025, upper = 0.975, file = NULL, ...)## S3 method for class 'PM_final' summary(object, lower = 0.025, upper = 0.975, file = NULL, ...)
object |
The PM_final object made after an NPAG or IT2B run |
lower |
Desired lower confidence interval boundary. Default is 0.025. Ignored for IT2B objects. |
upper |
Desired upper confidence interval boundary. Default is 0.975. Ignored for IT2B objects. |
file |
Filename to save the summary. Include path if necessary. |
... |
Not used. |
#' This is a function usually called by the $summary() method for PM_final objects
within a PM_result. The function can be called directly on a PM_final object.
For NPAG runs, this function will generate weighted medians as central tendencies of the
population points with a 95% confidence interval (95% CI) around the median,
and the median absolute weighted deviation (MAWD) from the median as a measure
of the variance, with its 95% CI. These estimates correspond to weighted mean,
95% CI of the mean, variance, and 95% CI of the variance, respectively, for a
sample from a normal distribution.
To estimate these non-parametric summaries, the function uses a Monte Carlo simulation approach, creating 1000 x npoint samples with replacement from the weighted marginal distribution of each parameter, where npoint is the number of support points in the model. As an example, if there are 100 support points, npoint = 100, and for Ka, there will be 1000 sets of 100 samples drawn from the weighted marginal distribution of the values for Ka. For each of the 1,000 sets of npoint values, the median and MAWD are calculated, with MAWD equal to the median absolute difference between each point and the median of that set. The output is npoint estimates of the weighted median and npoint estimates of the MAWD for each parameter, from which the median, 2.5th, and 97.5th percentiles can be found as point estimates and 95% confidence interval limits, respectively, of both the weighted median and MAWD.
For IT2B runs, the function will return the mean and variance of each parameter, and the standard errors of these terms, using
.
The output is a data frame. For NPAG this has 4 columns:
value The value of the summary statistic
par The name of the parameter
type Either WtMed for weighted median, or MAWD for MAWD (see details)
percentile Requested lower, 0.5 (median), and upper quantiles
For IT2B this has 6 columns:
mean Parameter mean value
se.mean Standard error of the mean
cv.mean Error of the mean divided by mean
var Variance of the parameter values
se.var Standard error of the variance
summary Name of the summary statistic
Michael Neely
## Not run: NPex$final$summary() # preferred ITex$final$summary() summary(NPex$final) # alternate ## End(Not run)## Not run: NPex$final$summary() # preferred ITex$final$summary() summary(NPex$final) # alternate ## End(Not run)
Summarizes the raw data (
class: PM_final_data) from a PM_final object in the same way as summarizing a PM_final object.
Both use summary.PM_final.
## S3 method for class 'PM_final_data' summary(object, ...)## S3 method for class 'PM_final_data' summary(object, ...)
object |
A |
... |
Additional arguments passed to summary.PM_final |
NPex$final$data %>% summary()NPex$final$data %>% summary()
Summarize a Pmetrics Observed vs. Predicted object
## S3 method for class 'PM_op' summary( object, digits = max(3, getOption("digits") - 3), pred.type = "post", icen = "median", outeq = 1, ... )## S3 method for class 'PM_op' summary( object, digits = max(3, getOption("digits") - 3), pred.type = "post", icen = "median", outeq = 1, ... )
object |
A PM_op object |
digits |
Integer, used for number of digits to print. |
pred.type |
Either 'post' for a posterior object or 'pop' for a population object. Default is 'post'. |
icen |
Can be either "median" for the predictions based on medians of |
outeq |
Output equation number. Default is 1. |
... |
Not used. |
This is a function usually called by the $summary() method for PM_op objects
within a PM_result to summarize observations, predictions and errors. The function can
be called directly on a PM_op object. See examples.
A list with three elements of class summary.PM_op.
sumstat A data frame with the minimum, first quartile, median, third quartile, maximum,
mean and standard deviation for times, observations and predictions in x.
pe A named vector with mean prediction error (mpe), the mean weighted prediction error (mwpe), the percent mean weighted prediction error (percent_mwpe), the mean squared prediction error (mspe), root mean sqaured error (rmse), percent root mean squared error (percent_rmse), the mean weighted squared prediction error (mwspe), the bias-adjusted mean squared prediction error (bamspe), the bias- adjusted mean weighted squared prediction error (bamwspe), the percent root mean bias- adjusted weighted squared prediction error (percent_rmbawspe). The percent_mwpe is bias and the percent_rmbawspe is imprecision on plots of PM_op objects.
wtd.t A list of 6 elements based on a t test that the weighted mean prediction bias is different than zero
estimate: the weighted mean of the prediction bias for each observation
se: the standard error of the estimate
conf.int: the 95% confidence interval of the mean
statistic: the t statistic of the standardized difference between mean and zero
df: degrees of freedom equal to number of observations minus one
p.value: the probability that the weighted mean is different than zero
Michael Neely
## Not run: NPex$op$summary() # preferred summary(NPex$op) # alternative ## End(Not run)## Not run: NPex$op$summary() # preferred summary(NPex$op) # alternative ## End(Not run)
Summarizes the raw data (
class: PM_op_data) from a PM_op object in the same way as summarizing a PM_op object.
Both use summary.PM_op.
## S3 method for class 'PM_op_data' summary(object, ...)## S3 method for class 'PM_op_data' summary(object, ...)
object |
A |
... |
Additional arguments passed to summary.PM_op |
## Not run: NPex$op$data %>% dplyr::filter(pred > 5) %>% dplyr::filter(pred < 10) %>% summary() ## End(Not run)## Not run: NPex$op$data %>% dplyr::filter(pred > 5) %>% dplyr::filter(pred < 10) %>% summary() ## End(Not run)
Summarize a Pmetrics Observed vs. Predicted object
## S3 method for class 'PM_pop' summary( object, digits = max(3, getOption("digits") - 3), icen = "median", outeq = 1, ... )## S3 method for class 'PM_pop' summary( object, digits = max(3, getOption("digits") - 3), icen = "median", outeq = 1, ... )
object |
A PM_pop object |
digits |
Integer, used for number of digits to print. |
icen |
Can be either "median" for the predictions based on medians of the population parameter value distributions, or "mean". Default is "median". |
outeq |
Output equation number. Default is 1. |
... |
Not used. |
This is a function usually called by the $summary() method for PM_op objects
within a PM_result to summarize observations, predictions and errors. The function can
be called directly on a PM_op object. See examples.
A data frame with the minimum, first quartile, median, third quartile, maximum,
mean and standard deviation for times and predictions in x.
Michael Neely
## Not run: NPex$pop$summary() # preferred summary(NPex$pop) # alternative ## End(Not run)## Not run: NPex$pop$summary() # preferred summary(NPex$pop) # alternative ## End(Not run)
Summarize a Pmetrics Observed vs. Predicted object
## S3 method for class 'PM_post' summary( object, digits = max(3, getOption("digits") - 3), icen = "median", outeq = 1, ... )## S3 method for class 'PM_post' summary( object, digits = max(3, getOption("digits") - 3), icen = "median", outeq = 1, ... )
object |
A PM_post object |
digits |
Integer, used for number of digits to print. |
icen |
Can be either "median" for the predictions based on medians of the posterior parameter value distributions, or "mean". Default is "median". |
outeq |
Output equation number. Default is 1. |
... |
Not used. |
This is a function usually called by the $summary() method for PM_op objects
within a PM_result to summarize observations, predictions and errors. The function can
be called directly on a PM_op object. See examples.
A data frame with the minimum, first quartile, median, third quartile, maximum,
mean and standard deviation for times and predictions in x.
Michael Neely
## Not run: NPex$post$summary() # preferred summary(NPex$post) # alternative ## End(Not run)## Not run: NPex$post$summary() # preferred summary(NPex$post) # alternative ## End(Not run)
Summarize a Pmetrics Percent Target Attainment Object
## S3 method for class 'PM_pta' summary(object, at = "intersect", ci = 0.95, ...)## S3 method for class 'PM_pta' summary(object, at = "intersect", ci = 0.95, ...)
object |
A PM_pta object |
at |
Which object in the PM_pta result list to summarize. By default "intersect" if
an intersection is present due to creation of the object with multiple target types, or
1 if no intersection is present, which means only 1 target type was selected. If
"intersect" is present in the object, the default can be overridden with a number to
summarize one of the individual PTAs, e.g. |
ci |
Width of the interval for pharmacodynamic index reporting. Default is 0.95, i.e. 2.5th to 97.5th percentile. |
... |
Not used. |
Summarize Pharmacodynamic Index (PDI) statistics and success proportions in a PM_pta object. The PDI is the metric calculated by the target type and target, e.g. AUC/Target, or %time>target. Since a PDI cannot be calculated for intersections, summarizing the intersection object only provides the success proportion per simulation/target.
A tibble with the following columns (only the first five if at = "intersect"):
reg_num is the number of the simulation regimen
label is the simulation label, for reference
target is the target for the row, if targets are discrete, not used for simulated targets
type is the target type for the row, e.g. "auc", "time", "-min", etc.
prop_success is the proportion of simulated profiles that met the success definition
median is the median parmacodynamic index (PDI), i.e. the proportion or ratio depending on the target type
lower is the lower bound of the interval defined by ci
upper is the upper bound of the interval defined by ci
mean is the mean of the PDI
sd is the standard deviation of the PDI
min is the minimum PDI
max is the maximum PDI
Michael Neely
## Not run: ptaEx$summary() ## End(Not run)## Not run: ptaEx$summary() ## End(Not run)
Summarize simulation
## S3 method for class 'PM_sim' summary( object, include, exclude, field = "obs", group = NULL, statistics = c("mean", "sd", "median", "min", "max"), digits = getPMoptions("digits"), ... )## S3 method for class 'PM_sim' summary( object, include, exclude, field = "obs", group = NULL, statistics = c("mean", "sd", "median", "min", "max"), digits = getPMoptions("digits"), ... )
object |
The simulation object to summarize |
include |
A vector of subject IDs to include in the plot, e.g. c(1:3,5,15) . |
exclude |
A vector of subject IDs to exclude in the plot, e.g. c(4,6:14,16:20) . |
field |
Quoted character value, one of
|
group |
Optional quoted values to group by, e.g. |
statistics |
The summary statistics to report.
Default is |
digits |
Integer, used for number of digits to print. Default is value set with |
... |
Not used. |
Summarizes simulated observations, compartment amounts or parameter values.
Can be ungrouped (i.e. the entire simulation), average values grouped by simulated id,
outeq, or both, as well as summary statistics for each individual.
Default statistics reported
are mean, sd, median, min, max, but could include individual quantiles. See
statistics below.
If group is omitted, a data frame with rows for each data element except ID,
and columns labeled according to the selected statistics. If group is specified,
return will be a list with named elements according to the selected statistics,
each containing a data frame with the summaries for each group in group.
Michael Neely
## Not run: simEx$summary() # preferred summary(simEx) # alternative simEx$summary(include = 2, field = "amt", group = "comp") # group amounts by compartment ## End(Not run)## Not run: simEx$summary() # preferred summary(simEx) # alternative simEx$summary(include = 2, field = "amt", group = "comp") # group amounts by compartment ## End(Not run)
Prints NPDE distribution statistics and a Numerical Predictive Check (NPC)
for each output equation in the PM_valid object. TAD-based results are
included automatically when TAD validation was performed.
## S3 method for class 'PM_valid' summary(object, probs = c(0.05, 0.5, 0.95), ...)## S3 method for class 'PM_valid' summary(object, probs = c(0.05, 0.5, 0.95), ...)
object |
A PM_valid object. |
probs |
Numeric vector of quantile cut-points for the NPC.
Default is |
... |
Ignored; present for S3 compatibility. |
Create a PM_model object for the three_comp_bolus model template.
three_comp_bolus()three_comp_bolus()
A PM_model object.
Create a PM_model object for the three_comp_bolus_cl model template.
three_comp_bolus_cl()three_comp_bolus_cl()
A PM_model object.
Create a PM_model object for the three_comp_iv model template.
three_comp_iv()three_comp_iv()
A PM_model object.
Create a PM_model object for the three_comp_iv_cl model template.
three_comp_iv_cl()three_comp_iv_cl()
A PM_model object.
Create a PM_model object for the two_comp_bolus model template.
two_comp_bolus()two_comp_bolus()
A PM_model object.
Create a PM_model object for the two_comp_bolus_cl model template.
two_comp_bolus_cl()two_comp_bolus_cl()
A PM_model object.
Create a PM_model object for the two_comp_iv model template.
two_comp_iv()two_comp_iv()
A PM_model object.
Create a PM_model object for the two_comp_iv_cl model template.
two_comp_iv_cl()two_comp_iv_cl()
A PM_model object.
Will extract BMI z-scores based on a single age in months and sex. Overweight is a z-score of >1.04, and obese is a z-score > 1.64. Calculations are based on CDC formulae
For a z-score > 3, which indicates an extreme BMI, consider using the modified z-score and percentile.
zBMI(agemos, sex, bmi, wt, ht, data = "CDC")zBMI(agemos, sex, bmi, wt, ht, data = "CDC")
agemos |
The age in months. Should be between 24 and 240.5. |
sex |
A single quoted character: "M" for males, "F" for females. Default is "M". |
bmi |
The individual's BMI. If specified, |
wt |
The individual's weight in kg as an alternative to specifying |
ht |
The individual's height in centimeters. Required if |
data |
Source data for calculations. Default is "CDC" which uses the cdc_bmi dataset. The alternative is "NHANES", which uses the ger_bmi dataset. |
A list with objects calculated for agemos and sex.
z Z-score
mod_z Modified Z-score for extreme BMI
per BMI percentile
mod_per Modified BMI percentile
Michael Neely
## Not run: zBMI(agemos = 36, bmi = 15) ## End(Not run)## Not run: zBMI(agemos = 36, bmi = 15) ## End(Not run)