---
title: "Scripting MVPapp"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Scripting MVPapp}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
# Compiling models needs a C++ compiler and takes a few seconds, so the code below is
# not run when the vignette is built; the outputs and figures were made with MVPapp 1.1.0.
knitr::opts_chunk$set(collapse = TRUE, comment = "#>", eval = FALSE)
```

_Last updated: 2026-12-02_

## Why script MVPapp?

The app is the quickest way to explore a model interactively. Since version 1.1.0 the same
analyses can also be run from R code, without the app:

* **Reproducible reports**: put simulations in an R Markdown or Quarto document.
* **Many scenarios at once**: loop over doses, populations or parameter values.
* **AI assistants**: an assistant such as Claude can turn a plain-language request into these
  function calls (see `vignette("using-ai")`). This is the most important benefit.

The functions call the app's own simulation, exposure, plotting and bundle code, so the
results are the same as in the app.

| App page | Functions |
|---|---|
| Simulation | `mvp_model()`, `mvp_dose()`, `mvp_times()`, `mvp_simulate()`, `mvp_plot()`, `mvp_bundle()` |
| Variability | `mvp_population()`, `mvp_simulate(population = ...)`, `mvp_exposures()` |
| Parameter Sensitivity Analysis | `mvp_sensitivity()`, `mvp_batch()`, `mvp_plot(type = "tornado" / "spider")` |
| Data Input (exploration, NCA) | `mvp_data_plot()`, `mvp_ind_plot()`, `mvp_nca()` |

## Models

`mvp_templates()` lists the built-in models of the app's "Select Model" list:

```{r}
library(MVPapp)
head(mvp_templates()[, 1:2], 6)   # also has a description column
#>             id                                         name
#> 1         1cmt                             1 Compartment PK
#> 2     1cmt_lag               1 Compartment PK with Lag time
#> 3     1cmt_abs 1 Compartment PK with Absorption Compartment
#> 4 1cmt_transit        1 Compartment PK (Transit Absorption)
#> 5         2cmt                             2 Compartment PK
#> 6     2cmt_abs 2 Compartment PK with Absorption Compartment
```

`mvp_model()` compiles a template (or your own mrgsolve code with `code =`, or a `.cpp` file
with `file =`), optionally with new parameter values. `mvp_params()` shows what the model
contains, so you know the exact parameter and output names:

```{r}
mod <- mvp_model("2cmt_abs", params = list(CL = 3, VC = 10, KA = 1))
mvp_params(mod)$parameters
#>   name value                     description        unit
#> 1   KA  1.00        Absorption rate constant      1/time
#> 2   CL  3.00                       Clearance volume/time
#> 3   VC 10.00                  Central volume      volume
#> 4   VP  2.00               Peripheral volume      volume
#> 5    Q  1.00    Intercompartmental clearance volume/time
#> 6   WT 70.00                          Weight          kg
#> 7 WTCL  0.75 Exponent of weight effect on CL
#> 8  WTV  1.00  Exponent of weight effect on V
#> 9    F  1.00                 Bioavailability    fraction
```

`mvp_params()` also lists the compartments, the outputs that can be plotted (here `CP` and
`CT`), and the OMEGA and SIGMA matrices. The templates scale clearance and volumes by
`(WT/70)^exponent`, so a population with its own body weights gets weight-adjusted
parameters.

## Your own model

Your own models work the same way as the templates:

```{r}
mod <- mvp_model(code = my_mrgsolve_code)       # mrgsolve code as a string
mod <- mvp_model(file = "my_model.cpp")         # an mrgsolve file, or code saved from the app's editor
```

A **NONMEM model** is translated to mrgsolve first, as in the app. When its `.ext` file is
next to the control stream and the nonmem2mrgsolve package is installed, `mvp_model()` does
this for you, using the final estimates:

```{r}
mod <- mvp_model(file = "run12.ctl")            # uses run12.ext
mvp_nonmem_estimates("run12.ext")               # the final THETA, OMEGA and SIGMA, to compare
```

Otherwise (no `.ext` file, or a model described in a paper), `mvp_translate()` runs the app's
AI translation from R: it sends the file to an AI model with the app's prompts, compiles the
answer, and sends any compiler errors back for fixing. It takes an 'ellmer' chat, set up with
your own API key:

```{r}
mod <- mvp_translate("run12.ctl", chat = ellmer::chat_anthropic())
mvp_params(mod)                                 # check the translation before simulating
```

`mvp_translation_prompt()` gives the same prompts to use with any other AI tool, including
a chat where you attach the paper yourself (no API key needed): `mvp_translation_prompt(attachment
= "Smith2021.pdf")` gives the instructions for an attached file, and `text =` for a description
you paste in. If code does not compile, the error message of `mvp_model()` shows the compiler's
errors. Always check a translated model against its source (parameters, compartments, units)
before using it.

**A model from a publication.** `mvp_fetch_paper()` downloads a paper and its supplementary
files from a DOI, a PubMed Central id or a link: open-access papers from Europe PMC, other papers
from the publisher if your computer has access. Supplementary ZIP files are unpacked, and the
model files found are listed (NONMEM control streams with their `.ext`, mrgsolve code, Word and
PDF documents). The paper's text is saved too, for its dosing and sampling schedule:

```{r}
paper <- mvp_fetch_paper("10.1002/psp4.12345")
paper$files                                     # e.g. supplementary/run7.ctl "NONMEM model"
mod <- mvp_model(file = paper$files$path[1])    # translated if its .ext is next to it
mod <- mvp_translate(paper$text_file, chat = ellmer::chat_anthropic())  # or from the text
```

With an AI assistant connected to MVPapp (see `vignette("using-ai")`), the most convenient
route is to attach the paper to the conversation and ask for the simulation: the assistant
reads the paper, tables and figures included, translates it with the app's prompts, and
simulates. No API key is needed.

## Dosing and sampling

A dosing regimen is one row of the app's dosing table; combine several with `c()`. Time is in
the model's time units (hours for the templates):

```{r}
dose <- mvp_dose(100, ii = 24, n = 7)            # 100 mg once daily for a week
# a loading dose, then 50 mg once weekly for 12 weeks from week 1
c(mvp_dose(100), mvp_dose(50, ii = 168, n = 12, start = 168))
#>   amt  ii  n start  cmt tinf
#> 1 100   0  1     0 <NA>    0
#> 2  50 168 12   168 <NA>    0
```

`cmt = NULL` (shown as `NA`) doses into the model's first compartment: the absorption
compartment for oral templates, the central compartment otherwise. Use `tinf` for infusions.

The app's "Transform Dose" options are given to `mvp_simulate()` (and `mvp_sensitivity()` and
`mvp_batch()`) as `dose_options = mvp_dose_options()`: `weight_based = TRUE` for doses per kg,
and `mw` to convert doses by molecular weight, e.g. mg to nmol for a model in nmol (each dose is
divided by `mw` and multiplied by `mw_factor`, 10^6 by default):

```{r}
# mod_nmol: a model with amounts in nmol; 10 mg Q2W of a 150 kDa antibody
mvp_simulate(mod_nmol, dose = mvp_dose(10, ii = 336, n = 6),
             dose_options = mvp_dose_options(mw = 150000))
```

`mvp_times(end, every)` gives the sampling times, as the app's "Max Sampling Time" and
"Sampling Frequency" options (with time 0 added):

```{r}
mvp_times(end = 168, every = 0.5)
```

## Typical subject

Without a population, `mvp_simulate()` simulates a typical subject without variability, as
on the Simulation page. The result prints a short summary; the data are in `as.data.frame(sim)`:

```{r}
sim <- mvp_simulate(mod, dose = dose, times = mvp_times(end = 168, every = 0.5), time_unit = "days")
sim
#> <mvp_sim> Typical subject (no variability)
#>   Subjects/runs: 1   Rows: 337
#>   Time: 0 to 168 (model time units)
#>   Outputs: CP, CT
#>   Use mvp_plot(), mvp_exposures(), as.data.frame() or mvp_bundle()

mvp_plot(sim, "CP")
```

![](figures/scripting-typical.png){width=100%}

`time_unit = "days"` only changes the x axis (and the `TIMEADJ` column); `TIME` stays in
hours. Exposure metrics over a time window (here the last dosing interval) come from
`mvp_exposures()`, with times in model units:

```{r}
mvp_exposures(sim, "CP", start = 144, end = 168)
#>   USUBJID ID    Cmin  Cmax Cavg   Clast   AUC  Tmax Tmin .varname
#> 1    m1-1  1 0.03918 5.577 1.38 0.03918 33.13 145.5  144       CP
```

`mvp_bundle(sim, "scenario.zip")` writes the app's reproducible bundle: the model code and a
standalone mrgsolve script with every setting. Nothing is written unless you give a path.

## Population with variability

`mvp_population()` samples subjects from the app's virtual patient databases (NHANES, CDC
or WHO), as on the Variability page. Ages are in years:

```{r}
pop <- mvp_population(200, db = "NHANES", age = c(18, 65), seed = 42)
head(pop, 3)
#>   ID SEX AGEMO AGE    WT    HT   BMI  BSA
#> 1  1   0   216  18  71.5 180.8 21.87 1.91
#> 2  2   0   216  18  72.4 166.1 26.24 1.81
#> 3  3   0   216  18 122.9 176.6 39.41 2.36
```

With a population, `mvp_simulate()` includes between-subject variability (OMEGA) and residual
error (SIGMA), and each subject's covariates (e.g. `WT`) replace the model parameters of the
same name. Use `population = 100` for 100 subjects without covariates, and `omega = c(ECL =
0.1)` to change a variance:

```{r}
popsim <- mvp_simulate(mod, dose = dose, times = mvp_times(end = 168, every = 1),
                       population = pop, time_unit = "days")
mvp_exposures(popsim, "CP", start = 144, end = 168, summarise = TRUE)
#>   metric    median      mean       p05      p95   n .varname
#> 1   Cmin   0.02998   0.05238 3.089e-03   0.1586 200       CP
#> 2   Cmax   5.54350   5.91931 3.247e+00   9.6762 200       CP
#> 3   Cavg   1.22824   1.29177 7.212e-01   2.1817 200       CP
#> 4  Clast   0.04462   0.07901 3.899e-03   0.2624 200       CP
#> 5    AUC  29.47780  31.00247 1.731e+01  52.3619 200       CP
#> 6   Tmax 146.00000 146.02000 1.450e+02 148.0000 200       CP
#> 7   Tmin 167.00000 159.75000 1.440e+02 168.0000 200       CP

mvp_plot(popsim, "CP", interval = c(0.05, 0.95))
```

![](figures/scripting-population.png){width=100%}

Without `summarise = TRUE`, `mvp_exposures()` returns one row per subject, ready to join with
the covariates. Random seeds (`seed` in both functions) make the results reproducible and
leave the random number state of your R session unchanged. As in the app, population outputs
are rounded to 5 significant digits to keep large simulations small.

### Your own covariates

The app's "Covariate Distributions" are `mvp_covariate()`: give each extra covariate a name
(as in the model) and a distribution. They are added to the database covariates:

```{r}
pop2 <- mvp_population(200, db = "NHANES", age = c(18, 65), seed = 42,
  covariates = list(
    CRCL = mvp_covariate("normal", mean = 100, sd = 20),       # mL/min
    ALB  = mvp_covariate("lognormal", gmean = 40, gsd = 1.1),  # median 40 g/L
    JAP  = mvp_covariate("binary", percent = 30)                # 30% have 1, the rest 0
  ))
```

To use the covariates of real subjects instead, sample them from a dataset (one row per
subject is used): `mvp_population(200, data = my_data, data_columns = c("WT", "CRCL"))`.

To check what was sampled, as on the Variability page's "Summary Statistics" and "Plots"
tabs (also for a population simulation, e.g. `mvp_population_summary(popsim)`):

```{r}
s <- mvp_population_summary(pop2)               # all subjects, then males and females
s[s$group == "All (n = 200)", c("group", "variable", "Min", "Median", "Mean", "Max", "CV%")]
#>           group    variable   Min Median  Mean   Max   CV%
#> 1 All (n = 200)     AGE (y)  18.0   41.0  40.6  65.0  36.0
#> 2 All (n = 200)     WT (kg)  37.7   80.3  82.5 162.1  26.3
#> 3 All (n = 200)     HT (cm) 133.0  167.5 167.3 191.8   6.2
#> 4 All (n = 200) BMI (kg/m2)  15.9   28.5  29.5  57.9  24.8
#> 5 All (n = 200)    BSA (m2)   1.3    1.9   1.9   2.7  13.4
#> 6 All (n = 200)        CRCL  52.4   96.6  98.1 149.2  20.1
#> 7 All (n = 200)         ALB  28.3   38.9  39.3  52.0  10.3
#> 8 All (n = 200)         JAP   0.0    0.0   0.3   1.0 153.1
mvp_population_plot(pop2)                       # age and weight by sex
mvp_population_plot(pop2, "CRCL")               # one covariate: median and 95% range
```

![](figures/scripting-demographics.png){width=100%}

Custom covariates are drawn independently of each other and of age and weight.
`mvp_corr_plot(pop2, c("AGE", "WT", "CRCL"))` shows this (see "Datasets" below).

### Observed data and targets

`observed` overlays a NONMEM-style dataset (columns `ID`, `TIME` and `DV`) on the plot, and
`target` draws a dashed line. `mvp_target()` is the app's "Threshold Calculations": the
percentage of subjects above a target at given times, or for an exposure metric in a time
window:

```{r}
obs <- mvp_data("my_observed_data.csv")      # columns ID, TIME, DV (see "Datasets" below)
mvp_plot(popsim, "CP", observed = obs, target = 0.1)
mvp_target(popsim, target = 0.1, at = c(144, 168))
#>   simulation output time target n_above   n percent
#> 1 Simulation     CP  144    0.1      43 200    21.5
#> 2 Simulation     CP  168    0.1      48 200    24.0
mvp_target(popsim, target = 0.1, metric = "Cmin", start = 144, end = 168)
#>   simulation output metric     window target n_above   n percent
#> 1 Simulation     CP   Cmin [144, 168]    0.1      31 200    15.5
```

`mvp_observed()` gives the overlay the app's options: `cmt` keeps only some compartments (e.g.
plasma), `median = TRUE` adds the median of the observed data, `points = FALSE` hides the
points, and, for a typical subject, `color = "DOSE"` colours the data by dose and
`median_by = "DOSE"` draws one median per dose. The same object works in `mvp_compare()` and
`mvp_open_in_app()`. `target_time` draws a dashed vertical line, e.g. at the time of a target:

```{r}
mvp_plot(popsim, "CP", observed = mvp_observed(obs, cmt = 2, median = TRUE),
         target = 0.1, target_time = 168)
```

## Comparing simulations (Model 1 vs Model 2)

`mvp_compare()` puts two or more simulations in one plot, as the app does with Model 1 and
Model 2: different doses, regimens, populations or models. Give each a name for the legend.
Use the same population and sampling times so that only what you compare differs:

```{r}
qd  <- mvp_simulate(mod, dose = mvp_dose(200, ii = 24, n = 7), times = mvp_times(168, 1),
                    population = pop, seed = 1)
bid <- mvp_simulate(mod, dose = mvp_dose(100, ii = 12, n = 14), times = mvp_times(168, 1),
                    population = pop, seed = 1)
mvp_compare("200 mg QD" = qd, "100 mg BID" = bid, var = "CP", target = 0.5)
mvp_compare("200 mg QD" = qd, "100 mg BID" = bid, var = "CP", type = "exposure",
            metric = "Cmin", start = 144, end = 168)            # box plots
mvp_compare("200 mg QD" = qd, "100 mg BID" = bid, var = "CP", type = "table",
            start = 144, end = 168)                              # numbers
mvp_target(list("200 mg QD" = qd, "100 mg BID" = bid), target = 0.5,
           metric = "Cmin", start = 144, end = 168)
#>   simulation output metric     window target n_above   n percent
#> 1  200 mg QD     CP   Cmin [144, 168]    0.5      10 200     5.0
#> 2 100 mg BID     CP   Cmin [144, 168]    0.5      57 200    28.5
```

The same daily dose gives a similar AUC either way, but splitting it keeps more subjects above
0.5 at the trough.

To share the comparison, write one reproducible bundle for all simulations. It holds a folder per
simulation (each with its standalone `model.cpp` and `simulation.R`), a `compare.R` script that
runs them and redraws the profiles, the exposure table and the percentage above the target, and a
README that says what differs between them (dosing, parameters, model, virtual subjects):

```{r}
mvp_bundle(list("200 mg QD" = qd, "100 mg BID" = bid), "qd_vs_bid.zip",
           var = "CP", start = 144, end = 168, target = 0.5)
```

## Carry on in the app

`mvp_open_in_app()` opens the app with a simulation already loaded: the model code and
parameter values, OMEGA and SIGMA, dosing, sampling, the population settings and, optionally,
observed data. A second simulation becomes Model 2:

```{r}
mvp_open_in_app(qd, x2 = bid, observed = obs)
```

`mvp_save_session(qd, "qd.rds")` writes the same as a session file for the app's "Load
Session" button, e.g. to send to a colleague.

## Parameter sensitivity

`mvp_sensitivity()` varies one parameter (the min / mid / max of the Parameter Sensitivity
page); `window` shades the area under each curve in a time window:

```{r}
s <- mvp_sensitivity(mod, "CL", values = c(1.5, 3, 6), dose = dose,
                     times = mvp_times(168, 0.5), time_unit = "days")
mvp_plot(s, "CP", window = c(144, 168))
```

![](figures/scripting-sensitivity.png){width=100%}

`mvp_batch()` is the app's "Batch Run": every parameter in turn at 0.5 and 1.5 times its value
(change with `lower`, `upper`, or `ranges` for your own bounds). As with the app's gradient
checkbox, three values between the reference and each bound are also run, so the spider plot
shows the curve between the bounds; `gradient = FALSE` runs the bounds only, which is enough for
a tornado plot and four times faster. The tornado and spider plots show the effect on an
exposure metric:

```{r}
b <- mvp_batch(mod, dose = dose, times = mvp_times(168, 0.5), exclude = c("WTCL", "WTV", "F"))
mvp_plot(b, "CP", type = "tornado", metric = "AUC", window = c(144, 168))
```

![](figures/scripting-tornado.png){width=100%}

```{r}
mvp_plot(b, "CP", type = "spider", metric = "Cmax", window = c(144, 168))
```

![](figures/scripting-spider.png){width=100%}

## Datasets: plots and NCA

`mvp_data()` reads a dataset (a `.csv` file or a data frame) and prepares it as the app's Data
Input page: column names in upper case and without `#` or `@`; `ID`, `TIME` and `CMT` created
when missing (from e.g. `USUBJID` and `TAFD`); BLQ rows removed (`remove_blq = FALSE` keeps
them); change from baseline columns `DV_CFB` and `DV_CFBPCT` added. Filters work as in
`dplyr::filter()`, like the app's code editor:

```{r}
d <- mvp_data("my_data.csv")
d100 <- mvp_data("my_data.csv", DOSE == 100, CMT == 2)
d_obs <- mvp_data("my_data.csv", remove_dosing = TRUE)     # observations only
```

The Data Exploration page's summary statistics, correlation plot and covariate histograms use
one row per subject. They work on a population too:

```{r}
mvp_data_summary(d, c("WT", "AGE"))
mvp_hist_plot(d, c("WT", "AGE"), binwidth = 5)
mvp_corr_plot(pop2, c("AGE", "WT", "CRCL"))      # needs the GGally package
```

![](figures/scripting-corr.png){width=80%}

The Data Exploration plots work on any data frame with an `ID` column (dosing rows with
`EVID >= 1` are left out of the general plot). As an example dataset, take sparse samples
of the first 12 subjects of the population simulation above (in practice, read your own data
with `mvp_data()`):

```{r}
obs <- as.data.frame(popsim)
obs <- obs[obs$ID <= 12 & obs$TIME %in% c(0.5, 1, 2, 4, 8, 12, 24), c("ID", "TIME", "CP")]
names(obs)[3] <- "DV"
obs$AMT <- 100

mvp_data_plot(obs, x = "TIME", y = "DV", median_line = TRUE, log_y = TRUE)
```

![](figures/scripting-general.png){width=100%}

```{r}
mvp_ind_plot(obs, x = "TIME", y = "DV", nrow = 2, ncol = 3)
# all pages in one PDF (with `dose = "AMT"`, datasets with EVID get dose bars):
mvp_ind_plot(obs, x = "TIME", y = "DV", file = "individual_plots.pdf")
```

![](figures/scripting-individual.png){width=100%}

`mvp_nca()` runs the app's non-compartmental analysis (with the NonCompart and ncar packages
installed), with an optional PDF report:

```{r}
nca <- mvp_nca(obs, subject = "ID", time = "TIME", conc = "DV", dose = "AMT", report = "nca.pdf")
nca[1:3, c("ID", "CMAX", "TMAX", "AUCLST", "LAMZHL")]
#>   ID  CMAX TMAX AUCLST LAMZHL
#> 1  1 4.292    1  31.33  2.771
#> 2  2 4.311    2  21.58  2.402
#> 3  3 4.237    2  20.36  3.682
```

## AI assistants

An AI assistant such as Claude can run these functions for you from a plain-language request,
also for users without R. Setup, example requests and the technical details are in
`vignette("using-ai")` ([Using MVPapp with AI](https://stevechoy.github.io/MVPapp/articles/using-ai.html)).
