The hardware and bandwidth for this mirror is donated by METANET, the Webhosting and Full Service-Cloud Provider.
If you wish to report a bug, or if you are interested in having us mirror your free-software or open-source project, please feel free to contact us at mirror[@]metanet.ch.

Package {MVPapp}


Title: Interactive Platform for Pharmacometrics Model Visualization and Simulation
Version: 1.1.0
Description: An interactive 'shiny' application for exploring pharmacometrics models with minimal setup. Users can explore model structures, parameters and dosing regimens with 'mrgsolve', and compare simulations with observed data. Additional features include parameter sensitivity analysis, non-compartmental analysis (NCA), data exploration, variability assessment with virtual populations, and optional AI-assisted model translation. For design considerations of the app, see Choy et al. (2025) <doi:10.1002/psp4.70023>.
License: GPL (≥ 3)
URL: https://github.com/stevechoy/MVPapp, https://stevechoy.github.io/MVPapp/
BugReports: https://github.com/stevechoy/MVPapp/issues
Encoding: UTF-8
Imports: bslib (≥ 0.5.1), cowplot, data.table (≥ 1.14.2), dplyr (≥ 1.1.0), DT, flextable (≥ 0.6.10), ggplot2 (≥ 3.4.4), grid, graphics, grDevices, htmltools (≥ 0.5.5), magrittr, mrgsolve (≥ 1.5.0), plotly (≥ 4.10.1), rhandsontable (≥ 0.3.8), rlang (≥ 1.0.0), scales, shiny (≥ 1.7.4.1), shinyAce, shinyBS (≥ 0.61.1), shinycssloaders, shinydashboard (≥ 0.7.2), shinyFiles, shinyjs (≥ 1.0), shinythemes, shinyWidgets (≥ 0.8.0), stats, stringr, tidyr, tools, utils, zip
Suggests: curl, ellmer (≥ 0.4.0), GGally, httr2, jsonlite, knitr, mcptools, mime, ncar, NonCompart, nonmem2mrgsolve, nonmem2rx, pdftools, rmarkdown, rxode2, shinyalert, spelling, testthat (≥ 3.0.0)
Additional_repositories: https://stevechoy.r-universe.dev
Depends: R (≥ 4.1)
LazyData: true
Collate: "utils-pipe.R" "utils.R" "ui_settings.R" "code_templates.R" "shiny_helpers.R" "plot_helpers.R" "data_utils.R" "plots_data.R" "simulation.R" "variability.R" "nca.R" "sensitivity.R" "llm.R" "session_state.R" "repro_bundle.R" "run_mvp.R" "api_checks.R" "api.R" "api_plots.R" "api_data.R" "fetch.R" "compare.R" "app_session.R" "translate.R" "mcp.R" "zzz.R" "data.R"
VignetteBuilder: knitr
Config/testthat/edition: 3
Language: en-US
Config/roxygen2/version: 8.0.0
NeedsCompilation: no
Packaged: 2026-12-04 01:44:42 UTC; magnu
Author: Steve Choy [aut, cre, cph], Jin Gyu Kim [aut], Matthew Fidler [ctb], Jason Bryer [ctb, cph] (Author of the ShinyDemo package, from which run_mvp() is adapted)
Maintainer: Steve Choy <steve.choy@outlook.com>
Repository: CRAN
Date/Publication: 2026-12-04 03:22:14 UTC

Pipe operator

Description

See magrittr::%>% for details.

Usage

lhs %>% rhs

Arguments

lhs

A value or the magrittr placeholder.

rhs

A function call using the magrittr semantics.

Value

The result of calling rhs(lhs).


CDC pediatric virtual population

Description

A virtual pediatric population (birth to 20 years) simulated from the US Centers for Disease Control and Prevention (CDC) growth charts. Used by the app to sample age, weight and height when the "CDC" database is selected for variability simulations.

Usage

cdc.expand

Format

A data frame with 97,177 rows and 6 columns:

SEX

Sex: 0 = male, 1 = female.

AGEMO

Age (months).

AGEYR

Age (years).

WT

Body weight (kg).

HT

Length/stature (cm).

BMI

Body mass index (kg/m^2).

Details

Body weight and stature were simulated from the published LMS parameters (Box-Cox power, median and coefficient of variation) of the weight-for-age and stature-for-age charts for each sex and month of age, by drawing standard normal Z-scores and applying X = M (1 + L S Z)^{1/L}. Rows with implausible BMI (outside 10 to 50 kg/m^2) were removed. See data-raw/databases.R in the GitHub repository for the code.

Source

CDC growth charts, percentile data files with LMS values: https://www.cdc.gov/growthcharts/percentile_data_files.htm.

See Also

nhanes.filtered, who.expand


Batch sensitivity runs (tornado and spider plots)

Description

Simulates a typical subject with each parameter in turn set to a lower and an upper value, as the app's "Batch Run" (Model 1/2 (All Parameters)).

Usage

mvp_batch(
  model,
  dose = NULL,
  times = mvp_times(),
  params = NULL,
  include = NULL,
  exclude = NULL,
  lower = 0.5,
  upper = 1.5,
  ranges = NULL,
  gradient = TRUE,
  dose_options = NULL,
  time_unit = "hours"
)

Arguments

model

A model from mvp_model() (or an mrgsolve model, or a template id).

dose

Dosing from mvp_dose() (several combined with c()), or an mrgsolve event object. NULL simulates without a dose.

times

Sampling times from mvp_times() (default: hourly to 24 h).

params

Named list of parameter values to change, e.g. list(CL = 3).

include

Parameters to vary (default: all parameters of the model).

exclude

Parameters to leave out (the app's "Fix Parameters").

lower, upper

Multipliers of each parameter's value for its lower and upper bound.

ranges

Optional data frame with columns Name, Lower, Upper (and optionally Reference) giving bounds for some parameters, instead of the multipliers.

gradient

If TRUE (default, as the app's checkbox), also run three values evenly spaced between the reference and each bound, so spider plots show the curve between the bounds: 8 runs per parameter instead of 2. FALSE runs the bounds only (enough for tornado plots, and faster).

dose_options

Options for all doses from mvp_dose_options(): weight-based dosing, conversion by molecular weight, infusion settings in the model code. NULL (default): doses as given.

time_unit

Unit of the TIMEADJ column and of plot x-axes: "hours" (default), "days", "weeks" or "months" (4 weeks, as in the app), or a number to divide the model time by. The model itself runs in its own time units.

Value

An mvp_sim object of type "batch"; data has the columns .desc, .cat ("Reference", "Lower", "Upper", ...), .paramname, .value and .ratio, and batch_table holds the parameter table used. Use mvp_plot() (tornado or spider) and mvp_exposures().

See Also

mvp_sensitivity()

Examples


if (interactive()) {
  mod <- mvp_model("1cmt")
  b <- mvp_batch(mod, dose = mvp_dose(100, ii = 24, n = 7), times = mvp_times(168),
                 exclude = c("WTCL", "WTV"))
  mvp_plot(b, "CP", type = "tornado", metric = "AUC")
}


Reproducible bundle

Description

Writes the app's reproducible bundle (".zip": the model code, a standalone simulation.R script, the dosing events and, for a population, the covariates) for a simulation from mvp_simulate(). Give several simulations (e.g. two regimens or two models that were compared) to get one bundle for all of them: a folder per simulation with its own standalone bundle, a compare.R script that runs them and redraws the comparison (profiles, exposure table, percentage above a target), and a README that says how the simulations differ.

Usage

mvp_bundle(
  x,
  file,
  var = NULL,
  start = NULL,
  end = NULL,
  target = NULL,
  at = NULL
)

Arguments

x

An mvp_sim object from mvp_simulate(), or a named list of them (as for mvp_compare(); unnamed ones become "Model 1", "Model 2", ...).

file

Path of the .zip file to write (required; nothing is written by default).

var, start, end, target, at

Several simulations only: the comparison that compare.R redraws: the output (default: the first output), the exposure window (default: the whole simulation), a target value and the times at which to count subjects above it (default: the last sampling time).

Value

Invisibly, file.

See Also

mvp_compare(), mvp_target()

Examples


if (interactive()) {
  mod <- mvp_model("1cmt")
  sim <- mvp_simulate(mod, dose = mvp_dose(100), times = mvp_times(24))
  mvp_bundle(sim, file.path(tempdir(), "scenario.zip"))

  qd  <- mvp_simulate(mod, dose = mvp_dose(200, ii = 24, n = 7), times = mvp_times(168),
                      population = 50)
  bid <- mvp_simulate(mod, dose = mvp_dose(100, ii = 12, n = 14), times = mvp_times(168),
                      population = 50)
  mvp_bundle(list("200 mg QD" = qd, "100 mg BID" = bid), file.path(tempdir(), "comparison.zip"),
             start = 144, end = 168, target = 0.5)
}


Compare simulations

Description

Compares two or more simulations, as the app does for Model 1 and Model 2: profiles overlaid in one plot (Simulation and Variability pages), box plots of an exposure metric (the Variability page's "Exposure Box Plots"), or a table of exposure metrics. Use it to compare doses, regimens, populations or models.

Usage

mvp_compare(
  ...,
  var = NULL,
  type = c("profile", "exposure", "table"),
  metric = "AUC",
  start = NULL,
  end = NULL,
  interval = c(0.025, 0.975),
  log_y = FALSE,
  log_x = FALSE,
  window = NULL,
  target = NULL,
  target_time = NULL,
  observed = NULL,
  title = NULL,
  xlab = NULL,
  ylab = NULL,
  show_stats = TRUE
)

Arguments

...

Results of mvp_simulate() to compare, named as they should appear (e.g. ⁠"50 mg" = sim_50, "100 mg" = sim_100⁠), or one named list.

var

Output to compare (default: each model's first output). Give a vector to use a different output for each simulation.

type

"profile" (default), "exposure" (box plots) or "table".

metric

Exposure metric for type = "exposure": "AUC", "Cmax", "Cmin", "Cavg", "Clast", "Tmax" or "Tmin".

start, end

Time window of the exposure metrics (model time units).

interval

Population profiles: quantiles of the prediction interval.

log_y, log_x

Log scale for the profile plot axes.

window

Profile plot: the part of the x axis shown, c(start, end).

target

Optional value drawn as a dashed horizontal line (e.g. a target concentration).

target_time

Optional time drawn as a dashed vertical line.

observed

Optional observed data overlaid on the profile plot: mvp_observed() (its color and median_by are not used here), or a data frame.

title, xlab, ylab

Plot title and axis labels.

show_stats

Exposure box plots: label the statistics, as in the app.

Value

A ggplot object, or for type = "table" a data frame with the median, mean, 5th and 95th percentiles of each metric per simulation.

See Also

mvp_simulate(), mvp_target()

Examples


if (interactive()) {
  mod <- mvp_model("1cmt")
  tt  <- mvp_times(168)
  low  <- mvp_simulate(mod, dose = mvp_dose(50, ii = 24, n = 7), times = tt, population = 100)
  high <- mvp_simulate(mod, dose = mvp_dose(100, ii = 24, n = 7), times = tt, population = 100)
  mvp_compare("50 mg" = low, "100 mg" = high)
  mvp_compare("50 mg" = low, "100 mg" = high, type = "exposure", metric = "Cmin",
              start = 144, end = 168)
}


Correlation and histogram plots of a dataset

Description

The Data Exploration page's "Corr. Plot" (pairs plot with linear fits; needs the GGally package) and "Covariate Histograms", with one row per subject. They also work on a population from mvp_population(), e.g. to look at the sampled covariates.

Usage

mvp_corr_plot(data, columns, color = NULL)

mvp_hist_plot(data, columns, binwidth = 5)

Arguments

data

A data frame (e.g. from mvp_data() or mvp_population()), or the path of a file.

columns

Columns to plot.

color

Optional column to colour by (correlation plot).

binwidth

Width of the histogram bars.

Value

A ggplot (GGally ggmatrix for the correlation plot).

See Also

mvp_data(), mvp_data_plot()

Examples

d <- data.frame(ID = 1:30, WT = seq(50, 108, 2), AGE = rep(c(30, 40, 50), 10))
mvp_hist_plot(d, c("WT", "AGE"), binwidth = 5)
if (requireNamespace("GGally", quietly = TRUE)) mvp_corr_plot(d, c("WT", "AGE"))

A covariate distribution

Description

A covariate drawn for each subject of mvp_population(), as on the app's "Covariate Distributions" tab.

Usage

mvp_covariate(
  dist = c("normal", "lognormal", "uniform", "binary"),
  mean = NULL,
  sd = NULL,
  gmean = NULL,
  gsd = NULL,
  min = NULL,
  max = NULL,
  percent = 50,
  values = c(1, 0)
)

Arguments

dist

"normal", "lognormal", "uniform" or "binary".

mean, sd

Normal: mean and standard deviation.

gmean, gsd

Log-normal: geometric mean (median) and geometric standard deviation (>= 1), on the normal scale, as in the app.

min, max

Uniform: limits.

percent, values

Binary: percentage of subjects (0-100) with values[1]; the others get values[2].

Details

Values are rounded to 2 decimals, as in the app. With the same seed, the first three covariates are the same as the app's covariates 1-3.

Value

An object of class mvp_covariate.

See Also

mvp_population()

Examples

pop <- mvp_population(50, db = "NHANES", seed = 1,
  covariates = list(CRCL = mvp_covariate("normal", mean = 110, sd = 20),
                    ALB  = mvp_covariate("lognormal", gmean = 40, gsd = 1.1),
                    JAPANESE = mvp_covariate("binary", percent = 30)))
summary(pop[c("CRCL", "ALB", "JAPANESE")])

Prepare a dataset as the app's Data Input page

Description

Reads a NONMEM-style dataset and applies the Data Input page's options, so that plots, NCA and overlays see the same data as in the app: column names in upper case and without ⁠#⁠/@, CMT, ID and TIME columns created when missing (from e.g. USUBJID or TAFD), BLQ rows removed, change from baseline columns (DV_CFB, DV_CFBPCT) added, and optional filters (the app's code editor).

Usage

mvp_data(
  data,
  ...,
  remove_dosing = FALSE,
  remove_blq = TRUE,
  cfb = TRUE,
  one_per_subject = FALSE,
  numeric = FALSE
)

Arguments

data

A data frame, or the path of a .csv (or tab-delimited .txt) file.

...

Filters, as in dplyr::filter(), e.g. ⁠DOSE == 100, CMT == 2⁠.

remove_dosing

Remove dosing rows (EVID >= 1).

remove_blq

Remove BLQ observations (BLQ >= 1).

cfb

Add change from baseline columns: DV_CFB and DV_CFBPCT from the first observed DV per ID and CMT.

one_per_subject

Keep one row per ID.

numeric

Convert all columns to numbers (text becomes NA).

Value

A data frame.

See Also

mvp_data_summary(), mvp_data_plot(), mvp_corr_plot(), mvp_hist_plot(), mvp_nca()

Examples

d <- data.frame(id = rep(1:2, each = 3), time = rep(c(0, 1, 2), 2),
                dv = c(10, 8, 5, 12, 9, 7), dose = rep(c(50, 100), each = 3))
mvp_data(d)
mvp_data(d, DOSE == 100)

General plot of a dataset

Description

The Data Exploration page's general plot: a scatter/line plot of y against x for all subjects, with optional colouring, facets, median line, regression line, smoother, box plots or quantile bins of x.

Usage

mvp_data_plot(
  data,
  x,
  y,
  color = NULL,
  facet = NULL,
  median_line = FALSE,
  median_by = NULL,
  boxplot = FALSE,
  quantize = 0,
  lm = FALSE,
  smoother = FALSE,
  log_x = FALSE,
  log_y = FALSE,
  cmt = NULL,
  title = NULL,
  label_size = 3
)

Arguments

data

A data frame (e.g. from mvp_data()) with an ID column, or the path of a .csv (or tab-delimited .txt) file. Dosing rows (EVID >= 1) are left out.

x, y

Column names for the axes.

color

Optional column to colour by.

facet

Optional column(s) to facet by.

median_line

Add a median line over binned x; median_by splits it by a column.

median_by

Optional column to split the median line by.

boxplot

Box plots of y per x value (one row per subject).

quantize

Number of quantile bins for a continuous x (0 = off); shown as box plots.

lm

Add a linear regression line and its equation.

smoother

Add a smoother.

log_x, log_y

Log scale for the axes.

cmt

Optional compartment(s) to keep (CMT column).

title

Optional plot title.

label_size

Size of count and equation labels (0 hides them).

Value

A ggplot object.

See Also

mvp_ind_plot()

Examples

d <- data.frame(ID = rep(1:3, each = 4), TIME = rep(c(0, 1, 2, 4), 3),
                DV = c(0, 5, 4, 2, 0, 6, 5, 3, 0, 4, 3, 1), DOSE = rep(c(10, 20, 30), each = 4))
mvp_data_plot(d, x = "TIME", y = "DV", color = "DOSE")

Summary statistics of a dataset

Description

The Data Exploration page's summary statistics: one row per subject (the first row of each ID), then the minimum, percentiles, median, mean, maximum, CV% and geometric mean of each numeric column.

Usage

mvp_data_summary(data, columns = NULL)

Arguments

data

A data frame (e.g. from mvp_data()) or the path of a file.

columns

Columns to summarise (default: all numeric columns).

Value

A data frame with one row per column of data.

See Also

mvp_population_summary()

Examples

d <- data.frame(ID = 1:20, WT = seq(50, 107, 3), AGE = 31:50)
mvp_data_summary(d)

A dosing regimen

Description

One dosing regimen, as a row of the app's dosing table. Combine several with c(), e.g. a loading dose followed by maintenance doses.

Usage

mvp_dose(amt, ii = 0, n = 1, start = 0, cmt = NULL, tinf = 0)

Arguments

amt

Dose amount, in the model's amount units.

ii

Dosing interval (time between doses). Needed when n > 1.

n

Total number of doses.

start

Time of the first dose.

cmt

Dosing compartment: a name or number. NULL (default) uses the model's first compartment (the depot for models with an absorption compartment, the central compartment otherwise).

tinf

Infusion duration; 0 for a bolus or oral dose.

Value

A data frame of class mvp_dose, one row per regimen.

See Also

mvp_simulate()

Examples

# 100 mg loading dose, then 50 mg once weekly for 12 weeks (time in hours)
c(mvp_dose(100), mvp_dose(50, ii = 168, n = 12, start = 168))

Dosing options

Description

Options that apply to all doses of a simulation, as on the app's Simulation page ("Transform Dose" and the infusion settings), for mvp_simulate(), mvp_sensitivity() and mvp_batch().

Usage

mvp_dose_options(
  weight_based = FALSE,
  wt_name = "WT",
  mw = NULL,
  mw_factor = 1e+06,
  model_duration = NULL,
  model_rate = NULL
)

Arguments

weight_based

If TRUE, doses are per kg: each dose is multiplied by the subject's weight (wt_name).

wt_name

Name of the weight parameter or covariate.

mw

Molecular weight (g/mol) to convert doses: each dose is divided by mw and multiplied by mw_factor. NULL (default): doses are used as given.

mw_factor

Multiplication factor for mw. The default, 1e6, converts mg to nmol (and mg/kg to nmol/kg).

model_duration, model_rate

Infusion duration (D_) or rate (R_) set in the model code. NULL (default) turns them on when the model code sets them, as the app does.

Value

An mvp_dose_options object.

Examples

mvp_dose_options(weight_based = TRUE)    # doses in mg/kg
mvp_dose_options(mw = 150000)            # doses in mg, model amounts in nmol

Exposure metrics

Description

Cmin, Cmax, Cavg, Clast, AUC (linear trapezoidal), Tmax and Tmin per subject (or per run) in a time window, from observation records, as in the app's exposure tables.

Usage

mvp_exposures(x, var = NULL, start = NULL, end = NULL, summarise = FALSE)

Arguments

x

An mvp_sim object from mvp_simulate(), mvp_sensitivity() or mvp_batch().

var

Output to summarise (default: the model's first captured output).

start, end

Time window in model time units (default: the whole simulation).

summarise

For a population simulation, TRUE returns the median, mean, 5th and 95th percentiles of each metric across subjects instead of one row per subject.

Value

A data frame. Times (Tmax, Tmin) are in model time units.

Examples


if (interactive()) {
  sim <- mvp_simulate(mvp_model("1cmt"), dose = mvp_dose(100), times = mvp_times(48))
  mvp_exposures(sim, "CP", start = 0, end = 24)
}


Get a model from a publication

Description

Downloads a paper and its supplementary files from a DOI, a PubMed Central or PubMed id, a link to the article, or a link to a model file, so that the model can be loaded with mvp_model() (or translated, see mvp_translate()) and simulated with the study's dosing. Open-access papers come from Europe PMC (full text and supplementary files); for other papers the publisher's PDF is downloaded if this computer has access to it. Supplementary ZIP files are unpacked, and each file is classified: NONMEM control streams and their .ext estimates, mrgsolve code, documents (PDF, Word, text) and data.

Usage

mvp_fetch_paper(source, dir = NULL)

Arguments

source

A DOI ("10.1002/psp4.70023" or a doi.org link), a PubMed Central id ("PMC1234567"), a PubMed id, a link to the article page, or a link to a file (.ctl, .mod, .txt, .cpp, .pdf, .docx, .zip).

dir

Folder to save the files in (default: a new temporary folder). If it already holds files, a new subfolder of it is used, so that only this paper's files are listed.

Value

An mvp_paper object: a list with title, doi, pmcid, open_access, text (the paper as plain text, without references, also saved as paper.txt), files (a data frame of the files with kind and path), dir and notes (what could not be found). Load a model file with mvp_model(file = files$path[i]).

See Also

mvp_model(), mvp_translation_prompt()

Examples

## Not run: 
paper <- mvp_fetch_paper("PMC1234567")   # needs internet access
paper                                    # title, files found
ctl <- paper$files$path[paper$files$kind == "NONMEM model"][1]
mod <- mvp_model(file = ctl)             # translated with nonmem2mrgsolve if the .ext is there

## End(Not run)

Individual plots of a dataset

Description

The Data Exploration page's individual plots: one panel per subject, with optional dose bars, LLOQ line, sorting and highlighting. Draws one page, or writes all pages to a PDF file.

Usage

mvp_ind_plot(
  data,
  x,
  y,
  page = 1,
  nrow = 4,
  ncol = 4,
  ids = NULL,
  sort_by = NULL,
  color = NULL,
  dose = NULL,
  dose_units = "",
  lloq = NULL,
  same_scale = FALSE,
  highlight = NULL,
  highlight_values = NULL,
  lm = FALSE,
  log_x = FALSE,
  log_y = FALSE,
  cmt = NULL,
  title = NULL,
  label_size = 3,
  file = NULL,
  width = 16,
  height = 9
)

Arguments

data

A data frame (e.g. from mvp_data()) with an ID column, or the path of a .csv (or tab-delimited .txt) file. Dosing rows (EVID >= 1) are left out.

x, y

Column names for the axes.

page

Page to draw.

nrow, ncol

Panels per page (rows and columns).

ids

Optional subject IDs to show (instead of a page).

sort_by

Optional column(s) to sort and label the panels by.

color

Optional column to colour by.

dose

Optional dose column for dose bars (needs EVID in the data).

dose_units

Text after the dose labels, e.g. " mg".

lloq

Optional LLOQ column, drawn as a dashed line.

same_scale

Use the same axes on every panel.

highlight, highlight_values

Optional column, and its values, whose records are highlighted.

lm

Add a linear regression line and its equation.

log_x, log_y

Log scale for the axes.

cmt

Optional compartment(s) to keep (CMT column).

title

Optional plot title.

label_size

Size of count and equation labels (0 hides them).

file

Optional path of a PDF file: all pages are written to it, as the app's "Download All Pages"; nothing is written by default.

width, height

Page size of the PDF, in inches.

Value

A ggplot object (the page), or, with file, invisibly the path.

See Also

mvp_data_plot()

Examples

d <- data.frame(ID = rep(1:3, each = 4), TIME = rep(c(0, 1, 2, 4), 3),
                DV = c(0, 5, 4, 2, 0, 6, 5, 3, 0, 4, 3, 1))
mvp_ind_plot(d, x = "TIME", y = "DV", nrow = 1, ncol = 3)

Set up MVPapp's MCP server in Claude

Description

Gives the settings that connect Claude Desktop or Claude Code to MVPapp's MCP server, with the full path of this computer's Rscript, and can add them to Claude Desktop's configuration file for you.

Usage

mvp_mcp_config(
  output_dir = "~/MVP-outputs",
  install = FALSE,
  config_file = NULL
)

Arguments

output_dir

Folder for the files the tools write (plots, data, bundles). Created if needed when the server writes its first file.

install

If TRUE, add (or update) the mvpapp server in Claude Desktop's configuration file, keeping its other settings (the previous file is kept with .bak added to its name). Restart Claude Desktop afterwards. Needs the 'jsonlite' package.

config_file

Claude Desktop's configuration file (default: its usual place on Windows and macOS).

Details

The easiest way to get the server and the assistant guide together is the MVPapp plugin: in Claude, Customize > Plugins > Add > Add marketplace, stevechoy/MVPapp; in Claude Code, ⁠claude plugin marketplace add stevechoy/MVPapp⁠ then ⁠claude plugin install mvpapp@mvpapp⁠. Use this function when you set up the server by hand, or to find the Rscript path the plugin asks for.

Value

Invisibly, a list with rscript, desktop_json (the mcpServers entry for Claude Desktop), claude_code (the command for Claude Code) and config_file. The settings are also printed.

See Also

mvp_mcp_server()

Examples

cfg <- mvp_mcp_config(output_dir = "~/MVP-outputs")

MVPapp tools for AI assistants (MCP)

Description

mvp_mcp_server() starts a Model Context Protocol (MCP) server whose tools run MVPapp's simulations, sensitivity analyses, NCA and plots, so that an AI assistant (e.g. Claude Desktop or Claude Code) can answer requests such as "simulate a 2-compartment model in 100 NHANES children and give me the plot and the reproducible bundle". mvp_mcp_tools() returns the tools, e.g. to use them with an 'ellmer' chat directly.

Usage

mvp_mcp_tools(
  output_dir = file.path(tempdir(), "mvp-mcp"),
  prompts_path = NULL,
  max_retries = 3
)

mvp_mcp_server(
  output_dir = file.path(tempdir(), "mvp-mcp"),
  prompts_path = NULL,
  max_retries = 3,
  ...
)

Arguments

output_dir

Folder for the files the tools write (plots, data, bundles, NCA reports). Defaults to a folder in tempdir(), which is deleted when the server stops; set it to keep the files.

prompts_path

Path to an R file with the AI-translation prompts, as in run_mvp(). Default: the prompts installed with MVPapp. Used when a model has to be translated to mrgsolve (see Details).

max_retries

How many times the assistant is asked to fix code that does not compile before it is told to stop and ask the user.

...

Passed to mcptools::mcp_server(), e.g. type = "http".

Details

Needs the 'mcptools' and 'ellmer' packages. Models are compiled on the computer running the server, which needs a C++ compiler (as for the app). Compiled models and results are kept in memory while the server runs and are referred to by ids (m1, s1, ...).

Your own models. mvp_load_model takes a template, mrgsolve code, or a model file: an mrgsolve .cpp file, code saved from the app's editor, a NONMEM control stream, or a PDF/text file describing a model. A NONMEM model with its .ext file is translated with 'nonmem2mrgsolve' (if installed), as in the app. Otherwise the tool returns the app's translation prompts, so the assistant translates the model itself (no API key needed), and code that does not compile comes back with the compiler's errors and the app's fixing prompt. A paper or model file attached to the conversation (which the server cannot open) is translated the same way: attachment = its name returns the instructions, and the assistant translates what it reads. For NONMEM models, the loaded model is compared with the final estimates in the .ext file. Translated code is saved in output_dir. mvp_translate writes NONMEM or rxode2 code with the app's prompts and checks it before saving it.

Model code runs on this computer. Compiling mrgsolve code (and checking rxode2 code with rxode2) runs that code in the server's R session, as running it yourself would. Code translated by an assistant from a paper or file of unknown origin should be read before it is used, as the app's AI translation should.

Files. Plots, data, bundles and reports are saved in output_dir, and an existing file is never replaced (-2, -3, ... is added to the name), so a folder kept between sessions keeps earlier results. Populations are limited to 5000 subjects, as in the app.

The tools: mvp_guide, mvp_list_templates, mvp_load_model, mvp_translate, mvp_simulate, mvp_population, mvp_sensitivity, mvp_batch, mvp_exposures, mvp_target, mvp_compare, mvp_plot, mvp_save_data, mvp_bundle, mvp_open_in_app, mvp_fetch_paper, mvp_prepare_data, mvp_data_summary, mvp_plot_dataset and mvp_nca. Most call the scripting function of the same name (see mvp_simulate()); mvp_population gives mvp_population_summary() and mvp_population_plot(), mvp_prepare_data mvp_data(), and mvp_plot_dataset also draws mvp_corr_plot() and mvp_hist_plot(). mvp_guide returns the assistant guide (SKILL.md).

Data files are read as on the app's Data Input page (mvp_data(): upper-case column names, BLQ rows removed, ...). Filters are given as text, e.g. "DOSE == 100 & CMT == 2", and are parsed, never evaluated as R code.

Value

mvp_mcp_tools(): a list of ellmer tool definitions. mvp_mcp_server(): does not return while the server runs.

Configuration

Claude Desktop (claude_desktop_config.json):

{
  "mcpServers": {
    "mvpapp": {
      "command": "Rscript",
      "args": ["-e", "MVPapp::mvp_mcp_server(output_dir = '~/MVP-outputs')"]
    }
  }
}

On Windows, R is usually not on the PATH: use the full path of Rscript.exe. mvp_mcp_config() writes these settings for you.

Claude Code (in a terminal):

claude mcp add mvpapp -- Rscript -e "MVPapp::mvp_mcp_server(output_dir = '~/MVP-outputs')"

The SKILL.md shipped in system.file("ai", package = "MVPapp") tells an assistant how to use the tools (or the R functions) well.

See Also

mvp_simulate() and the other scripting functions.

Examples


if (requireNamespace("ellmer", quietly = TRUE)) {
  tools <- mvp_mcp_tools()
  vapply(tools, function(t) t@name, character(1))
}


Compile a model

Description

Compiles one of the built-in templates, your own mrgsolve code, or a model file, as the app's "Generate Model" button does.

Usage

mvp_model(
  template = NULL,
  code = NULL,
  file = NULL,
  params = NULL,
  ext_file = NULL,
  quiet = TRUE
)

Arguments

template

A template id or name from mvp_templates(), e.g. "2cmt".

code

mrgsolve model code (a single string).

file

Path to a model file: an mrgsolve .cpp (or .mod/text) file, code saved from the app's editor, or a NONMEM control stream. A NONMEM model is translated with 'nonmem2mrgsolve' when its .ext file is next to it (or given as ext_file) and the package is installed; otherwise use mvp_translate() (AI translation).

params

Optional named list of parameter values, e.g. list(CL = 3, VC = 10). Names must be parameters of the model (see mvp_params()).

ext_file

For a NONMEM file: its .ext file, if not next to it.

quiet

If FALSE, show mrgsolve's build messages.

Details

Give exactly one of template, code or file. Compiling needs a C++ compiler (Rtools on Windows) and takes a few seconds. Each compiled model gets a unique name, so several models can be used side by side; a template is compiled once per R session and then reused. If the code does not compile, the error message holds the compiler's errors (also in the condition's details, class mvp_compile_error).

Value

An mrgsolve model object (mrgmod), which can also be used with mrgsolve directly.

See Also

mvp_templates(), mvp_params(), mvp_simulate()

Examples


if (interactive()) {
  mod <- mvp_model("2cmt", params = list(CL = 3, VC = 10))
  mvp_params(mod)
}


Non-compartmental analysis of a dataset

Description

The Data Exploration page's NCA (via the 'NonCompart' and 'ncar' packages, which need to be installed): one row of NCA parameters per subject (and group), optionally with the PDF report.

Usage

mvp_nca(
  data,
  subject = "ID",
  time = "TIME",
  conc = "DV",
  dose = "AMT",
  keys = NULL,
  route = c("Extravascular", "Bolus", "Infusion"),
  dur = 0,
  down = c("Linear", "Log"),
  dose_unit = "mg",
  time_unit = "h",
  conc_unit = "ug/L",
  mw = 0,
  report = NULL
)

Arguments

data

A data frame with one row per record, or the path of a .csv (or tab-delimited .txt) file. Dosing rows (EVID >= 1) are only used to find the doses. When there are several compartments, the most frequent one is used, as in the app.

subject, time, conc

Column names of the subject, time and concentration.

dose

Column with the dose (taken from each subject's first positive dosing record, or from the observation rows), or a single number for all subjects.

keys

Optional extra grouping column (e.g. a period or dose group).

route

"Extravascular", "Bolus" or "Infusion".

dur

Infusion duration.

down

AUC method: "Linear" or "Log" (linear-up log-down).

dose_unit, time_unit, conc_unit

Units, used for the units of the results.

mw

Molecular weight, needed for clearance and volume when the dose and concentration units differ in mass/mole (0 = not used).

report

Optional path of a PDF report to write (nothing is written by default).

Value

A data frame of NCA parameters (columns as in NonCompart::tblNCA()).

Examples


if (requireNamespace("NonCompart", quietly = TRUE) && requireNamespace("ncar", quietly = TRUE)) {
  d <- data.frame(ID = rep(1:2, each = 6), TIME = rep(c(0.5, 1, 2, 4, 8, 12), 2),
                  DV = c(4, 6, 5, 3, 1.5, 0.7, 5, 7, 6, 3.5, 1.6, 0.8), AMT = 100)
  mvp_nca(d, dose = "AMT")
}


Final parameter estimates of a NONMEM run

Description

Reads the final estimates (THETA, OMEGA, SIGMA) from a NONMEM .ext file, e.g. to check a model translated to mrgsolve.

Usage

mvp_nonmem_estimates(ext_file)

Arguments

ext_file

Path to a NONMEM .ext file.

Value

A data frame with name (e.g. THETA1, OMEGA(1,1)), value and fixed, from the last estimation step. Zero off-diagonal elements are left out.

See Also

mvp_model()

Examples

ext <- tempfile(fileext = ".ext")
writeLines(c("TABLE NO.     1: First Order Conditional Estimation",
             " ITERATION THETA1 THETA2 OMEGA(1,1) OMEGA(2,1) OMEGA(2,2) SIGMA(1,1) OBJ",
             "  -1000000000 2.5E+00 3.0E+01 9.0E-02 0.0E+00 4.0E-02 1.0E-02 100.0",
             "  -1000000006 0 1 0 1 0 0 0"), ext)
mvp_nonmem_estimates(ext)

Observed data to overlay on simulation plots

Description

Observed data and how to show it, as the app's "Overlay Dataset" options: for mvp_plot(), mvp_compare() and mvp_open_in_app().

Usage

mvp_observed(
  data,
  y = "DV",
  cmt = NULL,
  color = NULL,
  median = FALSE,
  median_by = NULL,
  points = TRUE
)

Arguments

data

A NONMEM-style data frame (columns ID, TIME in model time units, and y), or the path of a .csv file (read with mvp_data()).

y

Column to plot.

cmt

Only show rows with these CMT values (e.g. the plasma compartment), as the app's "Filter CMT".

color

Typical subject: colour the data by this column (e.g. "DOSE").

median

Add the median of the data over time.

median_by

Typical subject: one median line per value of this column (e.g. "DOSE").

points

Show the data as points (default) as well as lines.

Value

An mvp_observed object. A plain data frame given as observed is used as mvp_observed(data).

Examples

d <- data.frame(ID = rep(1:2, each = 3), TIME = rep(c(1, 4, 12), 2),
                DV = c(5, 3, 1, 6, 4, 2), CMT = 2, DOSE = c(50, 50, 50, 100, 100, 100))
mvp_observed(d, cmt = 2, median = TRUE)

Open a simulation in the app

Description

Opens MVPapp with a scripted simulation already loaded, so you can carry on in the app: the model code and parameter values, OMEGA and SIGMA, dosing, sampling, the population settings and, optionally, observed data. A second simulation becomes the app's Model 2. mvp_save_session() writes the same as a session file for the app's "Load Session" button.

Usage

mvp_open_in_app(
  x,
  x2 = NULL,
  observed = NULL,
  target = NULL,
  target_time = NULL,
  background = FALSE,
  ...
)

mvp_save_session(
  x,
  file,
  x2 = NULL,
  observed = NULL,
  target = NULL,
  target_time = NULL
)

Arguments

x

A result of mvp_simulate() (Model 1).

x2

Optional second result (Model 2).

observed

Optional observed data, loaded as the app's dataset and overlaid on the simulation plots: mvp_observed() (its y and cmt), or a data frame.

target, target_time

Optional target value and time, shown in the app's threshold calculations (Variability page).

background

If TRUE, start the app in a separate R process and return at once (used by the MCP tools); if FALSE (default), run it in this session, like run_mvp().

...

Passed to run_mvp(), e.g. insert_watermark = FALSE.

file

Path of the session file (.rds) to write.

Details

The app has 5 dosing regimens and 3 custom covariates per model; anything beyond that is left out, with a warning. Populations made with mvp_population() are sampled again by the app with the same settings and seed.

Value

mvp_save_session(): invisibly, file. mvp_open_in_app(): with background = TRUE, invisibly the app's address; otherwise runs the app.

See Also

run_mvp()

Examples


if (interactive()) {
  sim <- mvp_simulate(mvp_model("1cmt"), dose = mvp_dose(100, ii = 24, n = 7),
                      times = mvp_times(168))
  mvp_open_in_app(sim)
}


Parameters, outputs and variability of a model

Description

What an mvp_model() contains: parameter names, values and descriptions, compartments, captured outputs, and the OMEGA and SIGMA matrices.

Usage

mvp_params(model)

Arguments

model

A model from mvp_model() (or an mrgsolve model).

Value

A list with parameters (data frame: name, value, description, unit), compartments (data frame: number, name, description), outputs (names that can be plotted: captured variables and compartments), omega and sigma (matrices, labelled when the model labels them).

See Also

mvp_model()

Examples


if (interactive()) mvp_params(mvp_model("1cmt"))


Plot a simulation

Description

Draws the app's plot for a result of mvp_simulate(), mvp_sensitivity() or mvp_batch():

Usage

mvp_plot(
  x,
  var = NULL,
  log_y = FALSE,
  log_x = FALSE,
  title = NULL,
  xlab = NULL,
  ylab = NULL,
  points = FALSE,
  observed = NULL,
  interval = c(0.025, 0.975),
  individuals = FALSE,
  mean = FALSE,
  window = NULL,
  target = NULL,
  target_time = NULL,
  type = c("tornado", "spider"),
  metric = "AUC",
  display = c("Percentage", "Ratio", "Value"),
  top = 20
)

Arguments

x

An mvp_sim object.

var

Output to plot (default: the model's first captured output).

log_y, log_x

Log scale for the y / x axis.

title, xlab, ylab

Plot title and axis labels (defaults as in the app).

points

Also show the sampling times as points: on the profile (typical subject, sensitivity) or on the median (population). Useful with sparse or custom sampling, where the lines between samples are not simulated.

observed

Optional observed data to overlay: mvp_observed(), or a data frame (columns ID, TIME in model time units, DV).

interval

Population: lower and upper quantiles of the prediction interval (default 2.5th to 97.5th percentile, as in the app).

individuals

Population: show individual profiles instead of the prediction interval.

mean

Population: add a dashed line for the mean.

window

Time window c(start, end) in model time units. Typical subject and population: the part of the x axis shown (e.g. the last dosing interval); sensitivity: shaded under each curve; batch: the window of the exposure metric.

target

Optional value drawn as a dashed horizontal line, e.g. a target concentration (see mvp_target() for the percentage of subjects above it).

target_time

Optional time (model time units) drawn as a dashed vertical line, e.g. the time of a target, as the app's "Show X-intercept".

type

Batch: "tornado" or "spider".

metric

Batch: exposure metric, one of "AUC", "Cmax", "Cmin", "Cavg", "Clast", "Tmax", "Tmin".

display

Batch: show the metric as "Percentage" change from the reference, "Ratio" to the reference, or "Value".

top

Batch: show the most sensitive top parameters.

Value

A ggplot object.

See Also

mvp_simulate(), mvp_sensitivity(), mvp_batch()

Examples


if (interactive()) {
  sim <- mvp_simulate(mvp_model("1cmt"), dose = mvp_dose(100, ii = 24, n = 5),
                      times = mvp_times(120), population = 50)
  mvp_plot(sim, "CP", log_y = TRUE)
}


A virtual population

Description

Samples subjects from one of the app's virtual patient databases (NHANES, CDC or WHO growth data), or makes n subjects without covariates (db = "None"), as on the app's Variability page.

Usage

mvp_population(
  n = 20,
  db = c("None", "NHANES", "CDC", "WHO"),
  age = NULL,
  wt = c(0, 200),
  bmi = c(0, 70),
  prop_male = 0.5,
  seed = 1234,
  covariates = NULL,
  data = NULL,
  data_columns = NULL
)

Arguments

n

Number of subjects.

db

"None", "NHANES", "CDC" or "WHO". See nhanes.filtered, cdc.expand and who.expand.

age

Age range in years, c(lower, upper). Bounds are inclusive and compared in months (age * 12), as in the app. Defaults: 18 to 65 years for NHANES (as in the app), the whole database for CDC and WHO.

wt

Weight range in kg.

bmi

Body mass index range in kg/m^2.

prop_male

Proportion of males (SEX = 0), between 0 and 1.

seed

Random seed for the sampling. The random number state of the R session is left unchanged.

covariates

Extra covariates drawn from distributions, as the app's "Covariate Distributions" tab: a named list of mvp_covariate(), e.g. list(CRCL = mvp_covariate("normal", mean = 110, sd = 20)).

data, data_columns

Covariates sampled from a dataset's subjects, as the app's "Use dataset covariate distributions": a data frame with an ID column (one value per subject is used) and the columns to take. Sampled without replacement when the dataset has exactly n subjects, otherwise with replacement. They replace database columns of the same name.

Value

A data frame with one row per subject: ID (1 to n) and, from a database, SEX, AGEMO, AGE (years), WT (kg), HT (cm), BMI and BSA (m^2), plus any extra covariates. Columns named as model parameters replace those parameters in mvp_simulate() (e.g. WT, CRCL).

See Also

mvp_simulate()

Examples

pop <- mvp_population(100, db = "NHANES", age = c(6, 12), seed = 1)
summary(pop$WT)

Summary and plots of a virtual population

Description

The Variability page's "Summary Statistics" and "Plots" tabs: summary statistics of the sampled subjects (all, and males and females), the age and weight distributions by sex, and the distribution of a custom covariate with its median and 95% range.

Usage

mvp_population_summary(x, by_sex = TRUE)

mvp_population_plot(x, var = NULL)

Arguments

x

A population from mvp_population(), or a population result of mvp_simulate().

by_sex

Also summarise males and females separately (when both are present).

var

NULL (default) for the age and weight plot (needs a database population); or a covariate, e.g. "CRCL", for its distribution.

Value

mvp_population_summary(): a data frame with a group column ("All (n = 200)", "Males (n = 98)", ...) and one row per covariate. mvp_population_plot(): a plot.

See Also

mvp_population(), mvp_covariate(), mvp_corr_plot()

Examples

pop <- mvp_population(100, db = "NHANES", seed = 1,
                      covariates = list(CRCL = mvp_covariate("normal", mean = 100, sd = 20)))
mvp_population_summary(pop)
mvp_population_plot(pop)
mvp_population_plot(pop, "CRCL")

Single-parameter sensitivity analysis

Description

Simulates a typical subject once for each value of one parameter, as on the app's Parameter Sensitivity Analysis page (min / mid / max).

Usage

mvp_sensitivity(
  model,
  param,
  values,
  dose = NULL,
  times = mvp_times(),
  params = NULL,
  dose_options = NULL,
  time_unit = "hours"
)

Arguments

model

A model from mvp_model() (or an mrgsolve model, or a template id).

param

Name of the parameter to vary.

values

Values of param to simulate (usually 3: min, mid, max).

dose

Dosing from mvp_dose() (several combined with c()), or an mrgsolve event object. NULL simulates without a dose.

times

Sampling times from mvp_times() (default: hourly to 24 h).

params

Named list of parameter values to change, e.g. list(CL = 3).

dose_options

Options for all doses from mvp_dose_options(): weight-based dosing, conversion by molecular weight, infusion settings in the model code. NULL (default): doses as given.

time_unit

Unit of the TIMEADJ column and of plot x-axes: "hours" (default), "days", "weeks" or "months" (4 weeks, as in the app), or a number to divide the model time by. The model itself runs in its own time units.

Value

An mvp_sim object of type "sensitivity"; data has the columns .param and .value. Use mvp_plot() and mvp_exposures().

See Also

mvp_batch() for all parameters at once (tornado and spider plots).

Examples


if (interactive()) {
  mod <- mvp_model("1cmt")
  sens <- mvp_sensitivity(mod, "CL", values = c(1, 2, 4),
                          dose = mvp_dose(100, ii = 24, n = 7), times = mvp_times(168))
  mvp_plot(sens, "CP")
  mvp_exposures(sens, "CP")
}


Simulate a model

Description

Simulates a typical subject (no variability), as on the app's Simulation page, or a population with between-subject and residual variability, as on the Variability page.

Usage

mvp_simulate(
  model,
  dose = NULL,
  times = mvp_times(),
  params = NULL,
  population = NULL,
  omega = NULL,
  sigma = NULL,
  dose_options = NULL,
  seed = 1000,
  time_unit = "hours"
)

Arguments

model

A model from mvp_model() (or an mrgsolve model, or a template id).

dose

Dosing from mvp_dose() (several combined with c()), or an mrgsolve event object. NULL simulates without a dose.

times

Sampling times from mvp_times() (default: hourly to 24 h).

params

Named list of parameter values to change, e.g. list(CL = 3).

population

NULL (default) for a typical subject without variability. A number of subjects, or a data frame from mvp_population(), for a population simulation with variability; the population's covariates (e.g. WT) replace the model parameters of the same name.

omega, sigma

Optional changes to the variability: named variances (diagonal elements), e.g. c(ECL = 0.1), or a full matrix.

dose_options

Options for all doses from mvp_dose_options(): weight-based dosing, conversion by molecular weight, infusion settings in the model code. NULL (default): doses as given.

seed

Random seed for the variability. The random number state of the R session is left unchanged.

time_unit

Unit of the TIMEADJ column and of plot x-axes: "hours" (default), "days", "weeks" or "months" (4 weeks, as in the app), or a number to divide the model time by. The model itself runs in its own time units.

Details

As in the app, the output has observation records only, and TIME is in model time units. Population simulations use mrgsolve with 5 significant digits.

Value

An object of class mvp_sim: a list with data (the simulated data frame: USUBJID, ID, TIME, outputs, covariates and TIMEADJ), type ("typical" or "population"), model, events, times, settings and population. Use mvp_plot(), mvp_exposures(), mvp_bundle() or as.data.frame().

See Also

mvp_model(), mvp_dose(), mvp_times(), mvp_population(), mvp_plot(), mvp_exposures(), mvp_bundle()

Examples


if (interactive()) {
  mod <- mvp_model("2cmt", params = list(CL = 3, VC = 10))
  sim <- mvp_simulate(mod,
    dose       = c(mvp_dose(100), mvp_dose(50, ii = 168, n = 12, start = 168)),
    times      = mvp_times(end = 13 * 168, every = 1),
    population = mvp_population(100, db = "NHANES", age = c(6, 12), seed = 1000),
    time_unit  = "weeks")
  sim
  mvp_plot(sim, "CP")
}


Target attainment

Description

The percentage of subjects above (or below) a target, as the app's "Threshold Calculations" on the Variability page: at given times (e.g. the trough before the next dose), or for an exposure metric in a time window (e.g. Cmin over the last dosing interval).

Usage

mvp_target(
  x,
  target,
  var = NULL,
  at = NULL,
  metric = NULL,
  start = NULL,
  end = NULL,
  above = TRUE
)

Arguments

x

A result of mvp_simulate() (usually a population), or several to compare, as a named list.

target

The target value (in the output's units).

var

Output (default: the model's first output).

at

Times (model time units) at which to count subjects above the target. They must be sampling times.

metric

Instead of at: an exposure metric ("Cmin", "Cmax", "Cavg", "AUC", "Clast") computed in ⁠[start, end]⁠.

start, end

Time window for metric (default: the whole simulation).

above

TRUE (default) counts values above the target (as the app, strictly greater); FALSE counts values below it.

Value

A data frame with one row per time (or for the metric) and simulation: n_above (or n_below), n and percent.

See Also

mvp_plot() (target draws the line), mvp_compare()

Examples


if (interactive()) {
  sim <- mvp_simulate(mvp_model("1cmt"), dose = mvp_dose(100, ii = 24, n = 7),
                      times = mvp_times(168), population = 200)
  mvp_target(sim, target = 1, at = c(144, 168))                  # above 1 at these times
  mvp_target(sim, target = 1, metric = "Cmin", start = 144, end = 168)
}


Built-in model templates

Description

The model templates of the app's "Select Model" list, by id. Pass an id to mvp_model().

Usage

mvp_templates()

Value

A data frame with columns id, name (as in the app) and description (the template's ⁠$PROB⁠ line).

See Also

mvp_model(), mvp_params()

Examples

mvp_templates()

Sampling times

Description

Times at which the model output is recorded, as the app's "Max Sampling Time" and "Sampling Frequency" options, or given explicitly.

Usage

mvp_times(end = 24, every = 1, times = NULL, add_zero = TRUE)

Arguments

end

Last sampling time (model time units, usually hours).

every

Time between samples.

times

Explicit sampling times (used instead of end and every).

add_zero

Also sample at time 0 (as the app's "Add Sampling at Time 0").

Value

A sorted numeric vector of sampling times.

See Also

mvp_simulate()

Examples

mvp_times(end = 24, every = 4)
# hourly for 13 weeks
length(mvp_times(end = 13 * 168, every = 1))

Translate a model to mrgsolve with an AI model

Description

The app's AI translation from R: sends a model file (a NONMEM control stream, or a PDF or text file describing a model) to an AI model through an 'ellmer' chat, compiles the answer, and sends the compiler's errors back for fixing (up to max_retries times), with the app's prompts.

Usage

mvp_translate(
  file,
  chat,
  ext_file = NULL,
  max_retries = 3,
  params = NULL,
  prompts_path = NULL,
  quiet = FALSE
)

Arguments

file

Path to the model to translate.

chat

An 'ellmer' chat, e.g. ellmer::chat_anthropic() (with your API key set up as for 'ellmer'). It uses the provider's default model unless you choose one, e.g. ellmer::chat_anthropic(model = "..."); any temperature is set in the chat as well (params = ellmer::params(temperature = 0)).

ext_file

For a NONMEM model: its .ext file (default: found next to file), whose final estimates are used.

max_retries

Attempts to fix code that does not compile.

params

Optional parameter values to set after translating.

prompts_path

Path to your own prompts file (default: MVPapp's).

quiet

If FALSE, report each step.

Details

Check the translation before using it: print mvp_params(mod) and the code (mrgsolve::see(mod)), and compare with the source. For a NONMEM model with an .ext file and the 'nonmem2mrgsolve' package installed, mvp_model() translates without an AI model.

Value

A compiled model, as from mvp_model(). The translated code is in attr(mod, "mrgsolve_code").

See Also

mvp_model(), mvp_translation_prompt()

Examples


if (interactive() && requireNamespace("ellmer", quietly = TRUE)) {
  mod <- mvp_translate("run1.ctl", chat = ellmer::chat_anthropic())
  mvp_params(mod)
}


Prompts for translating a model with an AI model

Description

The app's AI-translation prompts (from prompts.R, or your own prompts file), filled in for a model file, for a model description given as text, for a document attached to an AI chat, or for fixing code that did not compile. Use them with any AI model; mvp_translate() does the whole loop with an 'ellmer' chat, and the MCP tools give them to the assistant. Translations are to mrgsolve by default (the language MVPapp simulates with); the app's NONMEM and rxode2 prompts are used with target.

Usage

mvp_translation_prompt(
  file = NULL,
  code = NULL,
  error = NULL,
  ext_file = NULL,
  prompts_path = NULL,
  text = NULL,
  attachment = NULL,
  target = c("mrgsolve", "nonmem", "rxode2")
)

Arguments

file

Path to the model to translate: a NONMEM control stream, a PDF or text file describing the model.

code, error

For fixing code instead: the mrgsolve code and the compiler's error message (from mvp_model()). mrgsolve only.

ext_file

For a NONMEM model: its .ext file (default: found next to file). Its final estimates are added to the prompt, so the translation uses them instead of the initial estimates.

prompts_path

Path to an R file defining the prompts, as in run_mvp(). Default: the prompts installed with MVPapp.

text

Instead of file: the model description (or NONMEM code) as text, e.g. pasted from a paper.

attachment

Instead of file: the name of a document attached to the AI chat (e.g. "Smith2021.pdf"). The prompt then asks the AI model to translate that attachment, which it reads itself (tables and figures included); nothing is read from disk.

target

The language to translate to: "mrgsolve" (default), "nonmem" or "rxode2". MVPapp can only load and simulate mrgsolve models; NONMEM and rxode2 code is for use elsewhere.

Value

A list of class mvp_prompt with system (the system prompt), user (the user message, with the file contents or the code and error) and target.

See Also

mvp_translate()

Examples

ctl <- tempfile(fileext = ".ctl")
writeLines(c("$PROBLEM one compartment", "$INPUT ID TIME AMT DV", "$SUBROUTINE ADVAN1 TRANS2",
             "$PK", "CL = THETA(1)*EXP(ETA(1))", "V = THETA(2)", "S1 = V",
             "$ERROR", "Y = F*(1 + EPS(1))", "$THETA 2 20", "$OMEGA 0.09", "$SIGMA 0.01"), ctl)
p <- mvp_translation_prompt(ctl)
cat(substr(p$user, 1, 200))
p_rx <- mvp_translation_prompt(ctl, target = "rxode2")   # the app's rxode2 prompts

NHANES population (1999-2023)

Description

Sex, age, body weight and height of participants in the US National Health and Nutrition Examination Survey (NHANES), cycles 1999-2000 to 2021-2023, aged 2 years and older. Used by the app to sample age, weight and height when the "NHANES" database is selected for variability simulations.

Usage

nhanes.filtered

Format

A data frame with 101,400 rows and 5 columns:

SEX

Sex: 0 = male, 1 = female.

AGEMO

Age (months), derived from AGEYR.

AGEYR

Age (years).

WT

Body weight (kg).

HT

Standing height (cm).

Details

Demographics and body measures files were merged by participant and only complete records were kept. Age is recorded in whole years, so AGEMO is AGEYR * 12. See data-raw/databases.R in the GitHub repository for the code.

Source

Centers for Disease Control and Prevention (CDC), National Center for Health Statistics, National Health and Nutrition Examination Survey: https://wwwn.cdc.gov/nchs/nhanes/Default.aspx.

See Also

cdc.expand, who.expand


Launch Model Visualization Platform App

Description

run_mvp() launches the MVP app. mvp_app() returns the app as a Shiny app object without running it, e.g. for deployment on Posit Connect or shinyapps.io (an app.R containing MVPapp::mvp_app() is sufficient).

The app is evaluated in its own environment (whose parent gives access to MVPapp and its key dependencies), so neither the global environment nor the search path is modified. Global options changed by the app are set when it starts and restored when it stops.

Usage

mvp_app(
  appDir = system.file("shiny", package = "MVPapp"),
  insert_watermark = TRUE,
  max_dataset_size = 200,
  authentication_code = NA_character_,
  internal_version = TRUE,
  pw_models_path = NA_character_,
  llm_choices = c("Claude", "Gemini", "OpenAI", "OpenRouter", "OpenAI-Compatible",
    "DeepSeek", "Azure OpenAI", "AWS Bedrock"),
  api_upload = NA_character_,
  api_chat = NA_character_,
  user_id = "MVP_user",
  reuse_context = FALSE,
  model_gemini = NA_character_,
  model_openai = NA_character_,
  model_anthropic = NA_character_,
  model_openrouter = "openrouter/free",
  model_openai_compatible = NA_character_,
  model_deepseek = NA_character_,
  model_apollo = "claude_4_6_sonnet",
  model_azure = NA_character_,
  model_aws = NA_character_,
  temperature = NA_real_,
  llm_seed = 42,
  model_lang = c("mrgsolve", "nonmem", "rxode2"),
  prompts_path = system.file("shiny/prompts.R", package = "MVPapp"),
  show_debugging_msg = FALSE,
  brand_color = NULL,
  brand_text_color = NULL,
  brand_logo = NULL,
  brand_favicon = NULL,
  page_title = NULL,
  session_file = NA_character_,
  ...
)

run_mvp(
  appDir = system.file("shiny", package = "MVPapp"),
  insert_watermark = TRUE,
  max_dataset_size = 200,
  authentication_code = NA_character_,
  internal_version = TRUE,
  pw_models_path = NA_character_,
  llm_choices = c("Claude", "Gemini", "OpenAI", "OpenRouter", "OpenAI-Compatible",
    "DeepSeek", "Azure OpenAI", "AWS Bedrock"),
  api_upload = NA_character_,
  api_chat = NA_character_,
  user_id = "MVP_user",
  reuse_context = FALSE,
  model_gemini = NA_character_,
  model_openai = NA_character_,
  model_anthropic = NA_character_,
  model_openrouter = "openrouter/free",
  model_openai_compatible = NA_character_,
  model_deepseek = NA_character_,
  model_apollo = "claude_4_6_sonnet",
  model_azure = NA_character_,
  model_aws = NA_character_,
  temperature = NA_real_,
  llm_seed = 42,
  model_lang = c("mrgsolve", "nonmem", "rxode2"),
  prompts_path = system.file("shiny/prompts.R", package = "MVPapp"),
  show_debugging_msg = FALSE,
  brand_color = NULL,
  brand_text_color = NULL,
  brand_logo = NULL,
  brand_favicon = NULL,
  page_title = NULL,
  session_file = NA_character_,
  ...
)

Arguments

appDir

Character. Directory containing the app's app.R. Defaults to the copy installed with MVPapp and rarely needs changing.

insert_watermark

Logical. Default TRUE. Set to FALSE to remove the "For Internal Use Only" watermark from simulation plots and NCA reports.

max_dataset_size

Numeric. Default 200. Maximum upload dataset size in MB.

authentication_code

Character. Default NA_character_. Provide a string (e.g., password) to password-lock the entire app.

internal_version

Logical. Default TRUE. Set to FALSE when hosting the app outside an internal deployment (e.g. on AWS or shinyapps.io): the help text for locked models then points to GitHub instead, and it selects the external Apollo endpoint (internal deployments only).

pw_models_path

Character. Default NA_character_. Path to an R file defining password-gated models (see system.file("shiny/passworded_models_example.R", package = "MVPapp") and vignette("supply-passwords")).

llm_choices

Character vector of LLM providers offered in the app; the first one is selected by default. Defaults to all supported providers: "Claude", "Gemini", "OpenAI", "OpenRouter", "OpenAI-Compatible", "DeepSeek", "Azure OpenAI" and "AWS Bedrock". Internal-deployment providers (e.g. "PMx Co-Modeler", "Apollo") are also accepted.

api_upload

Character. Default NA_character_. API upload URL when using Dify-based workflows (internal deployment only)

api_chat

Character. Default NA_character_. Base URL required when using OpenAI-Compatible providers, e.g. "https://api.moonshot.ai/v1" ("/chat/completions" is appended automatically)

user_id

Character. Default MVP_user. User ID for LLMs

reuse_context

Logical. Default FALSE. Set to TRUE to re-use same conversation during retries.

model_gemini, model_openai, model_anthropic, model_deepseek, model_aws

Character. Default NA: the provider's current default model, as chosen by the 'ellmer' package. Model for Gemini, OpenAI / ChatGPT, Anthropic / Claude, DeepSeek and AWS Bedrock. See "AI translation models" in Details.

model_openrouter

Character. Default "openrouter/free" (OpenRouter's router to its free models). Model for OpenRouter.

model_openai_compatible, model_azure

Character. Default NA. Model (deployment) name for OpenAI-compatible providers and Azure OpenAI; these have no default model, so set it here, in the app or as described in "AI translation models" in Details.

model_apollo

Character. Default claude_4_6_sonnet. Model for Apollo (internal deployment only).

temperature

Numeric. Default NA: not sent, so the model's own default applies. Between 0 (more deterministic) and 1 (more creative). Many newer models do not accept it: the request is then sent without it, with a notification.

llm_seed

Numeric. Default 42. Seed number for LLMs (not all models support this).

model_lang

Character. Default "mrgsolve" (the first element). Model translation language: "mrgsolve", "nonmem" (for testing only) or "rxode2" (for testing only).

prompts_path

Character. Path to an R file defining the LLM prompts. Defaults to the prompts installed with MVPapp. See vignette("automatic-translation") for more information.

show_debugging_msg

Logical. Default FALSE. Set to TRUE to output verbose working messages in the console, useful for debugging. AI translation responses are then also kept for review (see Details).

brand_color

Character. Default NULL (the default navy). A colour, e.g. "#F36633" or "orange", used for the navbar, active tab, box headers, table headers and loading spinners. See "Branding" in Details.

brand_text_color

Character. Default NULL. Colour of the text on brand_color (navbar and box headers). By default white or black is chosen for readability. Ignored if brand_color is NULL.

Character. Default NULL (no logo). Path to an image file (png, jpg, svg, ...) or a web URL, shown in the navbar in front of the page title.

brand_favicon

Character. Default NULL (the MVP icon shipped with the package). Path to an image file (png, ico, svg) or a web URL, used as the browser tab icon.

page_title

Character. Default NULL ("Model Visualization Platform (MVP)"). Title shown in the navbar. When set, it is also used as the browser tab title.

session_file

Character. Optional path to a session file (.rds) to load when the app starts, as with the "Load Session" button, e.g. from mvp_save_session(). mvp_open_in_app() uses it.

...

For run_mvp(), shiny::runApp() arguments (e.g. launch.browser, port). launch.browser defaults to TRUE here, so the app opens in your web browser (also from RStudio, which would otherwise use its viewer pane); use launch.browser = FALSE to turn that off. Any other named arguments are passed to the app.

Details

Objects kept for debugging. MVPapp does not write to the global environment. Objects useful for debugging are kept in an internal environment, MVPapp:::.mvp_state, and remain available in the R session after the app is closed. List them with ls(MVPapp:::.mvp_state):

AI translation models. MVPapp does not fix model names, which change every few months. For each provider, the model used is, in order: the one entered in the app's translation settings (gear button) or given as the ⁠model_*⁠ argument; the R option ⁠MVPapp.<argument>⁠ (e.g. options(MVPapp.model_anthropic = "...")); the environment variable ⁠MVPAPP_<ARGUMENT>⁠ (e.g. MVPAPP_MODEL_ANTHROPIC in .Renviron, convenient for deployments); otherwise the provider's current default model chosen by 'ellmer'. OpenAI-compatible providers and Azure OpenAI have no default model, so one of these must be set for them.

Branding. For a company deployment, the title, colour, logo and favicon can be set when launching, without editing any package files. Each is optional; with all of them left at NULL the app looks as it always did.

run_mvp(brand_color   = "#F36633",
        brand_logo    = "path/to/company_logo.png",
        brand_favicon = "path/to/favicon.png",
        page_title    = "Company Model Visualization Platform")

Image files are read from where they are and served by the app, so they do not need to be inside the package (a web URL also works). A logo with a transparent background and a height of about 30 pixels or more works best. brand_color replaces the navy in the navbar, the active tab, the headers and borders of the panels, the data table headers and the loading spinners. The same arguments work with mvp_app() for hosted deployments.

Hosting and security. MVPapp evaluates R and C++ model code supplied in the browser, so anyone who can open the app can run code on the server under the server account. authentication_code and the model passwords are a convenience to limit access to the interface and to hide models, not a security boundary: host the app only for trusted users, in a sandboxed account or container. The same applies to AI translation: its output is compiled automatically, and compiling mrgsolve code can itself run commands, so do not translate documents from untrusted sources on a shared server.

Without installing MVPapp (e.g. where package installation is restricted), the development version can also be launched from GitHub, provided its dependencies are installed: shiny::runGitHub("MVPapp", "stevechoy", subdir = "inst/shiny").

Value

run_mvp() is called for its side effect of launching the app and returns the value of shiny::runApp() invisibly once the app is closed. mvp_app() returns a Shiny app object (class shiny.appobj).

See Also

https://stevechoy.github.io/MVPapp/articles/supply-passwords.html https://stevechoy.github.io/MVPapp/articles/automatic-translation.html chat for LLM chat interface.

Examples

if (interactive()) {
  run_mvp(insert_watermark = FALSE) # remove watermarks

  # Other examples:
  # run_mvp(launch.browser = FALSE) # do not open a browser (argument passed to runApp)
  # run_mvp(authentication_code = "some_password") # Password-lock the site,
  #                                                # could be useful in deployment
  # run_mvp(pw_models_path = "path/to/your/private/models.R") # see
  #   system.file("shiny/passworded_models_example.R", package = "MVPapp")
  # run_mvp(llm_choices = "Claude", temperature = 0) # Claude only, with its default model
  #   and a temperature of 0 (where the model accepts it)
}

# App object, e.g. as the only line of an app.R file for deployment:
app <- mvp_app(insert_watermark = FALSE)

WHO pediatric virtual population

Description

A virtual pediatric population (birth to 10 years) simulated from the World Health Organization (WHO) Child Growth Standards and Growth Reference. Used by the app to sample age, weight and height when the "WHO" database is selected for variability simulations.

Usage

who.expand

Format

A data frame with 77,744 rows and 6 columns:

SEX

Sex: 0 = male, 1 = female.

AGEMO

Age (months).

AGEYR

Age (years).

WT

Body weight (kg).

HT

Length/height (cm).

BMI

Body mass index (kg/m^2).

Details

Body weight and height were simulated from the published LMS parameters (Box-Cox power, median and coefficient of variation) for each sex and month of age, by drawing standard normal Z-scores and applying X = M (1 + L S Z)^{1/L}. Sources:

Rows with implausible BMI (outside 10 to 50 kg/m^2) were removed. See data-raw/databases.R in the GitHub repository for the code.

Source

WHO Child Growth Standards: https://www.who.int/toolkits/child-growth-standards/standards/weight-for-age, https://www.who.int/toolkits/child-growth-standards/standards/length-height-for-age. WHO Growth Reference 5-19 years: https://www.who.int/toolkits/growth-reference-data-for-5to19-years/indicators/height-for-age.

See Also

cdc.expand, nhanes.filtered

These binaries (installable software) and packages are in development.
They may not be fully stable and should be used with caution. We make no claims about them.