## ----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)

## -----------------------------------------------------------------------------
# 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

## -----------------------------------------------------------------------------
# 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

## -----------------------------------------------------------------------------
# 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

## -----------------------------------------------------------------------------
# mod <- mvp_model(file = "run12.ctl")            # uses run12.ext
# mvp_nonmem_estimates("run12.ext")               # the final THETA, OMEGA and SIGMA, to compare

## -----------------------------------------------------------------------------
# mod <- mvp_translate("run12.ctl", chat = ellmer::chat_anthropic())
# mvp_params(mod)                                 # check the translation before simulating

## -----------------------------------------------------------------------------
# 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

## -----------------------------------------------------------------------------
# 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

## -----------------------------------------------------------------------------
# # 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 = 168, every = 0.5)

## -----------------------------------------------------------------------------
# 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")

## -----------------------------------------------------------------------------
# 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

## -----------------------------------------------------------------------------
# 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

## -----------------------------------------------------------------------------
# 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))

## -----------------------------------------------------------------------------
# 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
#   ))

## -----------------------------------------------------------------------------
# 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

## -----------------------------------------------------------------------------
# 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_plot(popsim, "CP", observed = mvp_observed(obs, cmt = 2, median = TRUE),
#          target = 0.1, target_time = 168)

## -----------------------------------------------------------------------------
# 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

## -----------------------------------------------------------------------------
# mvp_bundle(list("200 mg QD" = qd, "100 mg BID" = bid), "qd_vs_bid.zip",
#            var = "CP", start = 144, end = 168, target = 0.5)

## -----------------------------------------------------------------------------
# mvp_open_in_app(qd, x2 = bid, observed = obs)

## -----------------------------------------------------------------------------
# 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))

## -----------------------------------------------------------------------------
# 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))

## -----------------------------------------------------------------------------
# mvp_plot(b, "CP", type = "spider", metric = "Cmax", window = c(144, 168))

## -----------------------------------------------------------------------------
# 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

## -----------------------------------------------------------------------------
# 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

## -----------------------------------------------------------------------------
# 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)

## -----------------------------------------------------------------------------
# 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")

## -----------------------------------------------------------------------------
# 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

