### Install DoseFinding Package Source: https://openpharma.github.io/DoseFinding/index.html Installs the development version of the DoseFinding package from GitHub. Requires the devtools package. ```r # install.packages("devtools") devtools::install_github("openpharma/DoseFinding") ``` -------------------------------- ### Calculate Starting Values for Dose-Finding Models Source: https://openpharma.github.io/DoseFinding/articles/mult_regimen.html Determines sensible starting values for fitting models with shared parameters (e.g., e0) by fitting separate models to each regimen. The 'index' argument specifies how to subset the dose and other data for each regimen. ```R calc_start_values <- function(model, full_mu, full_S, dose, index, bounds) { separate_coefs <- sapply(c("od", "bid"), function(regimen) { inds <- c(index$placebo, index[[regimen]]) coef(fitMod(dose[inds], full_mu[inds], S = full_S[inds, inds], type = "general", model = model, bnds = bounds))[-1] # drop e0 estimate }) ## remove names to prevent error in do.call() in eval_model_shared_e0; ## od, bid coefs are in 1st / second column start <- c(full_mu[1], as.numeric(separate_coefs), use.names=FALSE) return(start) } ``` -------------------------------- ### Example: Multiple Contrast Test without Covariates Source: https://openpharma.github.io/DoseFinding/reference/MCTtest.html Demonstrates how to use MCTtest with a predefined dataset and model list. This example shows the basic usage for calculating optimal contrasts without including additional covariates. ```R ## example without covariates data(biom) ## define shapes for which to calculate optimal contrasts modlist <- Mods(emax = 0.05, linear = NULL, logistic = c(0.5, 0.1), linInt = c(0, 1, 1, 1), doses = c(0, 0.05, 0.2, 0.6, 1)) m1 <- MCTtest(dose, resp, biom, models=modlist) ``` -------------------------------- ### Example of Completers Analysis Source: https://openpharma.github.io/DoseFinding/articles/longitudinal_data.html Demonstrates the usage of the `analyzeCompleters` function with sample data and an evaluation time. ```r # Let's try it out: resultCompleters <- analyzeCompleters( dat = int_dat$dat, eval.time = "Week10" ) resultCompleters ``` -------------------------------- ### Plan Dose-Finding Study with planMod Source: https://openpharma.github.io/DoseFinding/reference/planMod.html This example demonstrates how to set up and run a dose-finding study plan using the planMod function. It specifies multiple dose-response models, sample sizes, and simulation parameters. ```R if (FALSE) { # \dontrun{ doses <- c(0,10,25,50,100,150) fmodels <- Mods(linear = NULL, emax = 25, logistic = c(50, 10.88111), exponential= 85, betaMod=rbind(c(0.33,2.31),c(1.39,1.39)), doses = doses, addArgs=list(scal = 200), placEff = 0, maxEff = 0.4) sigma <- 1 n <- rep(62, 6)*2 model <- "quadratic" pObj <- planMod(model, fmodels, n, sigma, doses=doses, simulation = TRUE, alpha = 0.025, nSim = 200, p = 0.5, pLB = 0.25, pUB = 0.75) print(pObj) ## to get additional metrics (e.g. Eff-vs-ANOVA, cRMSE, lengthTDCI, ...) summary(pObj, p = 0.5, Delta = 0.3) plot(pObj) plot(pObj, type = "TD", Delta=0.3) plot(pObj, type = "ED", p = 0.5) } # } ``` -------------------------------- ### Execute estimation and plotting functions Source: https://openpharma.github.io/DoseFinding/articles/mult_regimen.html This code block demonstrates the usage of the previously defined `example_estimates` and `plot_estimates` functions. It first collects the example estimates and then generates the corresponding plot. ```R est <- example_estimates() plot_estimates(est) ``` -------------------------------- ### Example: Hand Over Pre-calculated Critical Value Source: https://openpharma.github.io/DoseFinding/reference/MCTtest.html Demonstrates how to provide a pre-calculated critical value to MCTtest. This can be used to bypass the internal calculation of the critical value and use a value determined externally. ```R ## now hand over critical value m3 <- MCTtest(dose, resp, biom, models=modlist, critV = 2.24) ``` -------------------------------- ### Generalized MCP-Mod Test Setup Source: https://openpharma.github.io/DoseFinding/articles/longitudinal_data.html Sets up dose levels and models for the generalized MCP-Mod analysis, then performs the analysis using the results from a repeated measures analysis. Requires the 'MCPMod' package. ```r doses <- c(0, 0.5, 1, 2, 4) models <- Mods( emax = 2, sigEmax = c(0.5, 3), quadratic = -0.2, doses = doses ) resultFinal <- analyzeRepeated( dat = dat, eval.time = "Week10" ) testFinal <- MCTtest( dose = doses, resp = resultFinal$mu0t, S = resultFinal$S0t, models = models, alternative = "one.sided", type = "general", critV = TRUE, pVal = TRUE, alpha = 0.025 ) testFinal ``` -------------------------------- ### Load DoseFinding Package Source: https://openpharma.github.io/DoseFinding/articles/longitudinal_data.html Loads the DoseFinding package for use in the R session. Ensure the package is installed before running. ```r library(DoseFinding) ``` -------------------------------- ### Examples for TD and ED Source: https://openpharma.github.io/DoseFinding/reference/targdose.html Illustrates how to use the TD and ED functions with different model types and parameters, including discrete calculations. ```APIDOC ## Examples ```R ## example for creating a "full-model" candidate set placebo response ## and maxEff already fixed in Mods call doses <- c(0, 10, 25, 50, 100, 150) fmodels <- Mods(linear = NULL, emax = 25, logistic = c(50, 10.88111), exponential = 85, betaMod = rbind(c(0.33, 2.31), c(1.39, 1.39)), linInt = rbind(c(0, 1, 1, 1, 1), c(0, 0, 1, 1, 0.8)), doses=doses, placEff = 0, maxEff = 0.4, addArgs=list(scal=200)) ## calculate doses giving an improvement of 0.3 over placebo TD(fmodels, Delta=0.3) #> linear emax logistic exponential betaMod1 betaMod2 #> 112.500000 45.000000 62.095220 130.265330 4.880978 56.762044 #> linInt1 linInt2 #> 21.250000 43.750000 ## discrete version TD(fmodels, Delta=0.3, TDtype = "discrete", doses=doses) #> linear emax logistic exponential betaMod1 betaMod2 #> 150 50 100 150 10 100 #> linInt1 linInt2 #> 25 50 ## doses giving 50% of the maximum effect ED(fmodels, p=0.5) #> linear emax logistic exponential betaMod1 betaMod2 #> 75.000000 18.750000 50.215409 104.517639 1.255838 37.337384 #> linInt1 linInt2 #> 17.500000 37.500000 ED(fmodels, p=0.5, EDtype = "discrete", doses=doses) #> linear emax logistic exponential betaMod1 betaMod2 #> 100 25 100 150 10 50 #> linInt1 linInt2 #> 25 50 plot(fmodels, plotTD = TRUE, Delta = 0.3) ``` ``` -------------------------------- ### Load DoseFinding and Inspect Data Source: https://openpharma.github.io/DoseFinding/articles/overview.html Loads the DoseFinding package and displays the first few rows of the IBScovars dataset. Ensure the package is installed and loaded before use. ```R library(DoseFinding) data(IBScovars) head(IBScovars) ``` -------------------------------- ### Example: Calculate Critical Value Only Source: https://openpharma.github.io/DoseFinding/reference/MCTtest.html This example shows how to use MCTtest to calculate only the critical value for the test, by setting pVal to FALSE. This is useful when only the threshold for significance is needed. ```R ## now calculate critical value (but not p-values) m2 <- MCTtest(dose, resp, biom, models=modlist, critV = TRUE, pVal = FALSE) ``` -------------------------------- ### Start DesignMCPMod Shiny App Source: https://openpharma.github.io/DoseFinding/reference/DesignMCPModApp.html Launches the externally hosted DesignMCPMod Shiny App in a browser window. This app is used for power and sample size calculations for multiple contrast tests. ```R DesignMCPModApp() ``` -------------------------------- ### Summarize planMod Objects Source: https://openpharma.github.io/DoseFinding/reference/planMod.html Use the summary method to get detailed performance metrics for fitted dose-response models, including cRMSE, Eff-vs-ANOVA, and EDp/TD confidence interval lengths. ```R summary( object, digits = 3, len = 101, Delta = NULL, p = NULL, dLB = 0.05, dUB = 0.95, ... ) ``` -------------------------------- ### Example of Repeated Measures Analysis Source: https://openpharma.github.io/DoseFinding/articles/longitudinal_data.html Demonstrates the usage of the `analyzeRepeated` function with sample data and an evaluation time. ```r # Let's try it out: resultRepeated <- analyzeRepeated( dat = int_dat$dat, eval.time = "Week10" ) resultRepeated ``` -------------------------------- ### Calculate TD-optimal design with solnp optimizer and lower bounds Source: https://openpharma.github.io/DoseFinding/reference/optDesign.html Calculates the TD-optimal design using the `solnp` optimizer, which is the default and supports lower and upper bounds. This example demonstrates setting lower bounds for the design proportions. ```R doses <- c(0, 10, 100) emodel <- Mods(emax = 15, doses=doses, placEff = 0, maxEff = 1) optDesign(emodel, probs=1, designCrit = "TD", Delta=0.5, optimizer="solnp", lowbnd = rep(0.2,3)) ``` -------------------------------- ### Investigate Power of Contrasts under General Alternatives Source: https://openpharma.github.io/DoseFinding/reference/powMCT.html Investigate the power of specific contrasts under more general alternative models. This example defines alternative models with linear interpolation and then calculates power using powMCT. ```R ## now investigate power of the contrasts in contMat under "general" alternatives altFmods <- Mods(linInt = rbind(c(0, 1, 1, 1, 1), c(0.5, 1, 1, 1, 0.5)), doses=doses, placEff=0, maxEff=0.5) plot(altFmods) powMCT(contMat, altModels = altFmods, n = 50, alpha = 0.05, sigma = 1) ``` -------------------------------- ### Plotting fitted models with original data Source: https://openpharma.github.io/DoseFinding/reference/maFitMod.html Example of plotting a fitted maFit object, including the original data with confidence intervals. ```R plot(mFit, plotData = "meansCI") ``` -------------------------------- ### Datasets Source: https://openpharma.github.io/DoseFinding/reference/index.html Available datasets within the DoseFinding package for use in examples and analyses. ```APIDOC ## Datasets `biom` Biometrics Dose Response data `glycobrom` Glycopyrronium Bromide dose-response data `IBScovars` Irritable Bowel Syndrome Dose Response data with covariates `migraine` Migraine Dose Response data `neurodeg` Neurodegenerative disease simulated longitudinal dose-finding data set ``` -------------------------------- ### Calculate Constrained Optimal Contrasts Source: https://openpharma.github.io/DoseFinding/reference/optContr.html Calculates optimal contrasts using the 'optContr' function with the 'constrained' type. Requires the 'quadprog' package to be installed. The 'w' argument specifies weights for each model. ```R if(requireNamespace("quadprog", quietly = TRUE)){ optContr(models, w = rep(50,6), type = "constrained") } ``` -------------------------------- ### Generate Binary Data with Covariates Source: https://openpharma.github.io/DoseFinding/articles/binary_data.html Generates example binary data for a dose-finding study, simulating response rates based on dose, placebo effect, and covariates. Ensures reproducibility with set seed. ```R library(DoseFinding) library(ggplot2) logit <- function(p) log(p / (1 - p)) inv_logit <- function(y) 1 / (1 + exp(-y)) doses <- c(0, 0.5, 1.5, 2.5, 4) ## set seed and ensure reproducibility across R versions set.seed(1, kind = "Mersenne-Twister", sample.kind = "Rejection", normal.kind = "Inversion") group_size <- 100 dose_vector <- rep(doses, each = group_size) N <- length(dose_vector) ## generate covariates x1 <- rnorm(N, 0, 1) x2 <- factor(sample(c("A", "B"), N, replace = TRUE, prob = c(0.6, 0.4))) ## assume approximately logit(10%) placebo and logit(35%) asymptotic response with ED50=0.5 prob <- inv_logit(emax(dose_vector, -2.2, 1.6, 0.5) + 0.3 * x1 + 0.3 * (x2 == "B")) dat <- data.frame(y = rbinom(N, 1, prob), dose = dose_vector, x1 = x1, x2 = x2) ``` -------------------------------- ### Roxygen2 Documentation for Simulation Function Source: https://openpharma.github.io/DoseFinding/articles/longitudinal_data.html This is the argument documentation for the `sim_one_trial` function, written in roxygen2 format. It details the parameters required for setting up a simulation study. ```r ##' @param times Vector assessment times ##' @param bslMean Mean at baseline ##' @param errSD Residual standard deviation (on absolute scale) ##' @param rho Correlation of measurements over time (within patient) ##' @param maxEff Maximum effect achieved at last time-point for the highest dose ##' @param RecrDist Recruitment distribution (see function datGen) ##' @param LPFV.t Time for the last patient first visit ##' @param models DoseFinding::Mods object ##' @param ia_timing Information time when IAs are performed (% of patients having last visit) ##' @param N Overall sample size ##' @param doses doses to use ##' @param alRatio allocation ratios to the different doses ##' @param eval.time Name of final ##' @param alpha Type 1 error for test ##' @param nSim Number of simulations ##' @param delta_assumed Vector of treatment effects assumed at the different doses ##' @return Data frame with all results sim_one_trial <- function(times, bslMean, errSD, rho, maxEff, RecrDist, LPFV.t, models, ia_timing = seq(0.3, 0.8, 0.05), N = 531, doses = c(0, 0.5, 1, 2, 4, 8), alRatio = c(2, 1, 1, 1, 2, 2), eval.time = "Week12", alpha = 0.025, nSim = 1000, delta_assumed) { ``` -------------------------------- ### Simulate Dose-Finding Trial with planMod (n=93) Source: https://openpharma.github.io/DoseFinding/articles/sample_size.html Initializes a dose-finding trial simulation with a sample size of 93. Use this to assess initial operating characteristics. ```R pm <- planMod("sigEmax", Mods(sigEmax=c(30.5, 3.5), placEff=1.25, maxEff=0.15, doses=doses), n=93, sigma = 0.34, doses=doses, simulation=TRUE, nSim=5000, showSimProgress = FALSE, bnds = defBnds(max(doses))) ``` -------------------------------- ### Get variance-covariance matrix of a DRMod object Source: https://openpharma.github.io/DoseFinding/reference/fitMod.html Extracts the variance-covariance matrix of the estimated parameters from a fitted dose-response model object. ```R vcov(object, ...) ``` -------------------------------- ### Get Response from Dose-Response Models Source: https://openpharma.github.io/DoseFinding/reference/Mods.html The `getResp` function calculates the mean response for a given set of doses based on a previously defined `Mods` object. ```R getResp(fmodels, doses) ``` -------------------------------- ### Package Index Source: https://openpharma.github.io/DoseFinding/reference/index.html Overview of the DoseFinding package and its main functionalities. ```APIDOC ## Package `DoseFinding` `DoseFinding-package` DoseFinding: Planning and Analyzing Dose Finding Experiments ``` -------------------------------- ### Define candidate models and plot them Source: https://openpharma.github.io/DoseFinding/articles/sample_size.html Sets up candidate models for MCP-Mod analysis and visualizes them. Requires DoseFinding and ggplot2 libraries. ```R library(DoseFinding) library(ggplot2) doses <- c(0, 12.5, 25, 50, 100) guess <- list(emax = c(2.6, 12.5), sigEmax = c(30.5, 3.5), quadratic = -0.00776) mods <- do.call(Mods, append(guess, list(placEff = 1.25, maxEff = 0.15, doses = doses))) plotMods(mods) ``` -------------------------------- ### Calculate Sample Size with Balanced Allocations Source: https://openpharma.github.io/DoseFinding/reference/sampSize.html Use `sampSize` for balanced allocations when the target function and allocation ratios are known. Set `verbose = TRUE` for detailed output. ```R sSize <- sampSize(upperN = 80, targFunc = tFunc, target=0.8, alRatio = rep(1,6), verbose = TRUE) sSize ``` -------------------------------- ### Define Dose-Finding Models and Contrast Matrix Source: https://openpharma.github.io/DoseFinding/reference/sampSize.html This section defines the alternative models (`fmodels`) and the corresponding contrast matrix (`contMat`) used for power calculations. Ensure `doses`, `placEff`, and `maxEff` are appropriately set for your study. ```R fmodels <- Mods(linear = NULL, emax = c(25), logistic = c(50, 10.88111), exponential=c(85), betaMod=matrix(c(0.33,2.31,1.39,1.39), byrow=TRUE, nrow=2), doses = c(0,10,25,50,100,150), placEff=0, maxEff=0.4, addArgs = list(scal=200)) ## corresponding contrast matrix contMat <- optContr(fmodels, w=1) ``` -------------------------------- ### Define dose-finding models with all parameters Source: https://openpharma.github.io/DoseFinding/reference/Mods.html Create dose-finding models by specifying all model parameters using the Mods function with fullMod = TRUE. This allows for detailed model configuration. ```R fmods <- Mods(emax = c(0, 1, 0.1), linear = cbind(c(-0.4,0), c(0.2,0.1)), sigEmax = c(0, 1.1, 0.5, 3), doses = 0:4, fullMod = TRUE) ``` -------------------------------- ### Get responses for specified doses from a model Source: https://openpharma.github.io/DoseFinding/reference/Mods.html Use getResp to calculate the responses for a given set of doses based on the defined model parameters. The output includes the calculated responses and model parameters. ```R getResp(fmods, doses=seq(0,4,length=11)) ``` -------------------------------- ### sampSize Source: https://openpharma.github.io/DoseFinding/reference/sampSize.html Implements a bisection search algorithm for sample size calculation. It allows users to provide a target function that is iterated to achieve a specific target value. ```APIDOC ## sampSize ### Description Implements a bisection search algorithm for sample size calculation. The user can hand over a general target function (via targFunc) that is then iterated so that a certain target is achieved. ### Usage ```R sampSize( upperN, lowerN = floor(upperN/2), targFunc, target, tol = 0.001, alRatio, Ntype = c("arm", "total"), verbose = FALSE ) ``` ### Arguments * `upperN`, `lowerN`: Upper and lower bound for the target sample size. `lowerN` defaults to `floor(upperN/2)`. * `targFunc`: The target function needs to take as an input the vector of sample sizes in the different dose groups. For `sampSize` it needs to return a univariate number. For function `targN` it should return a numerical vector. Example: `targFunc` could be a function that calculates the power of a test, and `target` the desired target power value. For function `sampSize` the bisection search iterates the sample size so that a specific target value is achieved (the implicit assumption is that `targFunc` is monotonically increasing in the sample size). * `target`: The desired target value for the `targFunc`. * `tol`: A positive numeric value specifying the tolerance level for the bisection search algorithm. Bisection is stopped if the `targFunc` value is within `tol` of `target`. * `alRatio`: Vector describing the relative patient allocations to the dose groups up to proportionality, e.g. `rep(1, length(doses))` corresponds to balanced allocations. * `Ntype`: One of "arm" or "total". Determines, whether the sample size in the smallest arm or the total sample size is iterated in bisection search algorithm. * `verbose`: Logical value indicating if a trace of the iteration progress of the bisection search algorithm should be displayed. ``` -------------------------------- ### Plot General Model Fit on Logit Scale Source: https://openpharma.github.io/DoseFinding/reference/fitMod.html Plots the fitted dose-response model using the 'general' approach, specifically on the logit scale for a binary regression example. Displays means and confidence intervals. ```R plot(gfit, plotData = "meansCI", CI = TRUE) ``` -------------------------------- ### summary Method for planMod Objects Source: https://openpharma.github.io/DoseFinding/reference/planMod.html Provides a summary of the performance metrics calculated by the planMod function. ```APIDOC ## summary.planMod ### Description Provides a summary of the performance metrics calculated by the planMod function. ### Usage ```R summary( object, digits = 3, len = 101, Delta = NULL, p = NULL, dLB = 0.05, dUB = 0.95, ... ) ``` ``` -------------------------------- ### sampSizeMCT Source: https://openpharma.github.io/DoseFinding/reference/sampSize.html A convenience wrapper of sampSize for multiple contrast tests using the power as the target function. ```APIDOC ## sampSizeMCT ### Description A convenience wrapper of `sampSize` for multiple contrast tests using the power as the target function. ### Usage ```R sampSizeMCT( upperN, lowerN = floor(upperN/2), ..., power, sumFct = mean, tol = 0.001, alRatio, Ntype = c("arm", "total"), verbose = FALSE ) ``` ### Arguments * `upperN`, `lowerN`: Upper and lower bound for the target sample size. `lowerN` defaults to `floor(upperN/2)`. * `...`: Arguments directly passed to the `powMCT()` function. * `power`: A numeric defining the desired summary power to achieve. * `sumFct`: Function to summarize the power values (e.g., `mean`). * `tol`: A positive numeric value specifying the tolerance level for the bisection search algorithm. * `alRatio`: Vector describing the relative patient allocations to the dose groups. * `Ntype`: One of "arm" or "total". Determines, whether the sample size in the smallest arm or the total sample size is iterated. * `verbose`: Logical value indicating if a trace of the iteration progress should be displayed. ``` -------------------------------- ### Calculate power for multiple contrast test vs. sample size Source: https://openpharma.github.io/DoseFinding/articles/sample_size.html Calculates how power varies with sample size for a multiple contrast test. Uses `optContr` to get optimal contrasts and `powN` to compute power for a range of sample sizes. ```R contMat <- optContr(mods, w=1) pows <- powN(upperN = 100, lowerN = 10, step = 10, contMat = contMat, sigma = 0.34, altModels = mods, alpha = 0.05, alRatio = rep(1, 5)) plot(pows) ``` -------------------------------- ### Load and Print Glycobrom Dataset Source: https://openpharma.github.io/DoseFinding/articles/analysis_normal.html Loads the glycobrom dataset from the DoseFinding package and prints its contents to the console. This dataset contains summary statistics for FEV1 measurements across different dose groups. ```R library(DoseFinding) data(glycobrom) print(glycobrom) ``` -------------------------------- ### Calculate Power for Multiple Contrast Test Source: https://openpharma.github.io/DoseFinding/reference/powMCT.html Calculate the power for detecting a trend using a multiple contrast test. This example uses a contrast matrix derived from the defined dose-response models and specifies sample size, significance level, and standard deviation. ```R ## power for to detect a trend contMat <- optContr(fmodels, w = 1) powMCT(contMat, altModels = fmodels, n = 50, alpha = 0.05, sigma = 1) ``` -------------------------------- ### Load Biometrics Dose Response Data Source: https://openpharma.github.io/DoseFinding/reference/biom.html Loads the 'biom' dataset, which is an example data set for dose response studies. This dataset was used in Bretz et al. (2005) to illustrate the MCPMod methodology. It is a data frame with 100 observations on 'resp' (numeric vector of response values) and 'dose' (numeric vector of dose values). ```R data(biom) ``` -------------------------------- ### mvtnorm.control Source: https://openpharma.github.io/DoseFinding/reference/mvtnorm-control.html Returns a list (an object of class "GenzBretz") with control parameters for the pmvt and qmvt functions from the mvtnorm package. The DoseFinding package always uses the "GenzBretz" algorithm. ```APIDOC ## mvtnorm.control ### Description Returns a list (an object of class "GenzBretz") with control parameters for the pmvt and qmvt functions from the mvtnorm package. Note that the DoseFinding package always uses "GenzBretz" algorithm. See the mvtnorm documentation for more information. ### Usage ``` mvtnorm.control(maxpts = 30000, abseps = 0.001, releps = 0, interval = NULL) ``` ### Arguments * **maxpts** (integer) - Maximum number of function values. * **abseps** (double) - Absolute error tolerance. * **releps** (double) - Relative error tolerance. * **interval** (numeric or NULL) - Interval to be searched, when the quantile is calculated. ``` -------------------------------- ### MCTtest with General Alternatives (Contrast Matrix) Source: https://openpharma.github.io/DoseFinding/reference/MCTtest.html Perform a multiple contrast test using a custom contrast matrix derived from general alternative models. This allows for testing specific dose-response shapes. ```R data(biom) ## calculate contrast matrix for the step-contrasts ## represent them as linInt models models <- Mods(linInt=rbind(c(1,1,1,1), c(0,1,1,1), c(0,0,1,1), c(0,0,0,1)), doses=c(0,0.05,0.2,0.6,1)) plot(models) ## now calculate optimal contrasts for these means ## use weights from actual sample sizes weights <- as.numeric(table(biom$dose)) contMat <- optContr(models, w = weights) ## plot contrasts plot(contMat) ## perform multiple contrast test MCTtest(dose, resp, data=biom, contMat = contMat) ``` -------------------------------- ### Summarize and Extract Coefficients from DRMod Object Source: https://openpharma.github.io/DoseFinding/reference/fitMod.html Demonstrates how to obtain a summary of the fitted dose-response model and extract its coefficients. The summary provides model details, residuals, and coefficient estimates with standard errors. ```R summary(fitemax) coef(fitemax) ``` -------------------------------- ### Reproduce analysis from Pinheiro et al. (2014) Source: https://openpharma.github.io/DoseFinding/reference/neurodeg.html Reproduces the analysis of the neurodeg data set as presented in Pinheiro et al. (2014). This involves fitting a linear mixed-effects model and then using MCP-Mod methodology for dose-finding. ```R library(nlme) fm <- lme(resp ~ as.factor(dose):time, neurodeg, ~time|id, method = "ML") muH <- fixef(fm)[-1] # extract estimates covH <- vcov(fm)[-1,-1] ``` ```R doses <- c(0, 1, 3, 10, 30) mod <- Mods(emax = 1.11, quadratic= -0.022, exponential = 8.867, linear = NULL, doses = doses) # contMat <- optContr(mod, S=covH) # calculate optimal contrasts ``` ```R MCTtest(doses, muH, S=covH, type = "general", critV = TRUE, contMat=contMat) ``` ```R fitMod(doses, muH, S=covH, model="emax", type = "general", bnds=c(0.1, 10)) ``` -------------------------------- ### Define Prior List for Bayesian Fitting Source: https://openpharma.github.io/DoseFinding/reference/bFitMod.html Demonstrates how to define a prior list for Bayesian fitting with normal priors for E0 and Emax parameters. ```R ## define prior list ## normal prior for E0 (mean=0 and sdev=10) ## normal prior for Emax (mean=0 and sdev=100) ``` -------------------------------- ### Simulate full dataset from summary estimates Source: https://openpharma.github.io/DoseFinding/reference/glycobrom.html A function to simulate a full dataset with specified means, standard deviations, and participant counts per dose. It can optionally generate data with observed means and standard deviations. ```r simData <- function(mn, sd, n, doses, fixed = TRUE){ ## simulate data with means (mns) and standard deviations (sd), for ## fixed = TRUE, the data set will have observed means and standard ## deviations as given in mns and sd resp <- numeric(sum(n)) uppind <- cumsum(n) lowind <- c(0,uppind)+1 for(i in 1:length(n)){ rv <- rnorm(n[i]) if(fixed) rv <- scale(rv) resp[lowind[i]:uppind[i]] <- mn[i] + sd[i]*rv } data.frame(doses=rep(doses, n), resp=resp) } data(glycobrom) fullDat <- simData(glycobrom$fev1, glycobrom$sdev, glycobrom$n, glycobrom$dose) ``` -------------------------------- ### Set mvtnorm control parameters Source: https://openpharma.github.io/DoseFinding/reference/mvtnorm-control.html Use this function to set control parameters for the pmvt and qmvt functions. The DoseFinding package defaults to the 'GenzBretz' algorithm. Adjust maxpts, abseps, and releps for error tolerance. ```R mvtnorm.control(maxpts = 30000, abseps = 0.001, releps = 0, interval = NULL) ``` -------------------------------- ### Bootstrap Simulation and Plotting Source: https://openpharma.github.io/DoseFinding/articles/mult_regimen.html Performs bootstrap simulations, summarizes results, and generates a plot visualizing population response with confidence bands for once-daily and twice-daily regimens. Requires 'est' object and plotting libraries. ```r dose_seq_od <- seq(0, 150, length.out = 21) # do include placebo! dose_seq_bid <- seq(0, 100, length.out = 21) set.seed(1, kind = "Mersenne-Twister", sample.kind = "Rejection", normal.kind = "Inversion") reps <- replicate(1000, one_bootstrap_sample(est, dose_seq_od, dose_seq_bid)) bs_sum <- summarize_bootstrap_samples(reps) bs_sum$daily_dose <- c(dose_seq_od, dose_seq_bid) bs_sum$regimen <- c(rep("od", length(dose_seq_od)), rep("bid", length(dose_seq_bid))) ggplot(bs_sum) + geom_ribbon(aes(daily_dose, ymin=low_out, ymax=high_out), alpha = 0.2) + geom_ribbon(aes(daily_dose, ymin=low_in, ymax=high_in), alpha = 0.2) + geom_line(aes(daily_dose, median)) + geom_point(aes(daily_dose, mu_hat), tidy_estimates(est)) + facet_wrap(vars(regimen), labeller = label_both) + labs(title = "Bootstrap estimates for population response", subtitle = "Least squares estimates plus 50% and 95% confidence bands") + xlab("daily dose") + ylab("percent body weigh change") + coord_cartesian(ylim = c(-6, 0)) ``` -------------------------------- ### View Posterior Samples Source: https://openpharma.github.io/DoseFinding/reference/bFitMod.html Inspect the first few rows of posterior samples generated by the bFitMod function. ```r head(gsample$samples) ``` -------------------------------- ### Calculate Multiple Contrast Matrix Source: https://openpharma.github.io/DoseFinding/articles/mult_regimen.html Calculates a full contrast matrix for multiple regimens, comparing 'od' and 'bid' responses against a common placebo. The function requires estimated S_hat and model indices. ```R calculate_contrasts <- function(est, mods) { S_hat <- est$S_hat i <- est$index cm_od <- optContr(mods$od, S=S_hat[c(i$placebo, i$od), c(i$placebo, i$od)])$contMat cm_bid <- optContr(mods$bid, S=S_hat[c(i$placebo, i$bid), c(i$placebo, i$bid)])$contMat colnames(cm_od) <- paste0("od_", colnames(cm_od)) rownames(cm_od)[-1] <- paste0("od_", rownames(cm_od)[-1]) colnames(cm_bid) <- paste0("bid_", colnames(cm_bid)) rownames(cm_bid)[-1] <- paste0("bid_", rownames(cm_bid)[-1]) # now build a block matrix (contrasts in columns) like this: # [ row of placebo coefficients od | row of placebo coefficients bid ] # [----------------------------------+-----------------------------------] # [ remaining doses' coefficents od | fill with all zeros ] # [----------------------------------+-----------------------------------] # [ fill with all zeros | remaining doses' coefficients bid ] cm_full <- rbind( "0"=c(cm_od[1,], cm_bid[1,] ), cbind(cm_od[-1,], matrix(0, nrow(cm_od) - 1, ncol(cm_bid))), cbind(matrix(0, nrow(cm_bid) - 1, ncol(cm_od)), cm_bid[-1, ] )) return(cm_full) } cont_mat <- calculate_contrasts(est, mods) print(round(cont_mat, 2)) ``` -------------------------------- ### MCTtest General Approach (Placebo-Adjusted) Source: https://openpharma.github.io/DoseFinding/reference/MCTtest.html Utilize a general approach for MCTtest by fitting a linear model and extracting estimates and variance-covariance matrix. This method is useful when direct dose-response modeling is not feasible. ```R ancMod <- lm(resp~factor(dose)+gender, data=IBScovars) ## extract estimates and information to feed into MCTtest drEst <- coef(ancMod)[2:5] vc <- vcov(ancMod)[2:5, 2:5] doses <- 1:4 MCTtest(doses, drEst, S = vc, models = modlist, placAdj = TRUE, type = "general", df = Inf) ``` -------------------------------- ### Run Multiple Contrast Test (General Type) Source: https://openpharma.github.io/DoseFinding/articles/analysis_normal.html Performs a multiple contrast test using pre-calculated model estimates and covariance matrix. This approach is used for generalized MCP-Mod when `type = "general"` is specified. ```r test_general <- MCTtest(dose = doses, resp = mu_hat, S = S_hat, df = anova_df, models = mods, type = "general") print(test_general) ``` -------------------------------- ### Calculate Optimal Contrasts for Binary Data Source: https://openpharma.github.io/DoseFinding/articles/binary_data.html Use `optContr` to calculate optimal contrasts and `MCTtest` to perform the multiple contrast test. This is suitable when sample sizes are balanced across groups. ```R ## here we have balanced sample sizes across groups, so we select w = 1 ## otherwise would select w proportional to group sample sizes optCont <- optContr(mods, doses, w = 1) MCTtest(doses, ca$mu_star, S = ca$S_star, type = "general", contMat = optCont) ``` -------------------------------- ### Specify Candidate Models with Guesstimates Source: https://openpharma.github.io/DoseFinding/reference/Mods.html Define a set of candidate dose-response models with initial guesstimates for parameters. Default placebo and max effects are assumed if not specified. ```R models <- Mods(linear = NULL, linlog = NULL, emax = c(0.05, 0.3), exponential = 0.7, quadratic = -0.85, logistic = rbind(c(0.4, 0.09), c(0.3, 0.1)), betaMod = c(0.3, 1.3), sigEmax = c(0.5, 2), linInt = rbind(c(0.5, 0.75, 1, 1), c(0.5, 1, 0.7, 0.5)), doses = c(0, 0.05, 0.2, 0.6, 1), addArgs = list(scal=1.2, off=0.1)) ``` -------------------------------- ### Simulate FEV1 Data and Visualize Source: https://openpharma.github.io/DoseFinding/articles/analysis_normal.html Generates simulated FEV1 measurements for a parallel group design based on the glycobrom dataset. It uses MASS::mvrnorm to create random numbers with specified sample mean and standard deviation, then visualizes the simulated data using ggplot2. ```R set.seed(1, kind = "Mersenne-Twister", sample.kind = "Rejection", normal.kind = "Inversion") rand <- rep(MASS::mvrnorm(60, 0, 60 * 0.015^2, empirical = TRUE), 5) NVA <- data.frame(dose = rep(glycobrom$dose, each = 60), FEV1 = rep(glycobrom$fev1, each = 60) + rand) ggplot(NVA) + geom_jitter(aes(dose, FEV1), height = 0, width = 4) + labs(title = "Simulated FEV1 by dose (jittered horizontally)") + xlab("dose [μg]") + ylab("FEV1 [l]") ``` -------------------------------- ### Simulate Dose-Finding Trial with planMod (n=1650) Source: https://openpharma.github.io/DoseFinding/articles/sample_size.html Simulates a dose-finding trial with an increased sample size of 1650 to evaluate its impact on estimation precision. ```R pm <- planMod("sigEmax", Mods(sigEmax=c(30.5, 3.5), placEff=1.25, maxEff=0.15, doses=doses), n=1650, sigma = 0.34, doses=doses, simulation=TRUE, nSim=5000, showSimProgress = FALSE, bnds = defBnds(max(doses))) ``` -------------------------------- ### Model Averaging with maFitMod Source: https://openpharma.github.io/DoseFinding/articles/analysis_normal.html Apply the generalized MCP-Mod framework using maFitMod for model averaging. Boundaries must be supplied to the fitting algorithm. ```r fit_mod_av <- maFitMod(dose, mu_hat, S = S_hat, models = c("emax", "sigEmax", "quadratic")) ``` -------------------------------- ### Model Summary and Coefficient Extraction Source: https://openpharma.github.io/DoseFinding/reference/fitMod.html Provides a summary of the fitted dose-response model, including coefficients and their standard errors. Also demonstrates how to extract coefficients and the variance-covariance matrix. ```r summary(gfit2) ``` ```r coef(gfit2) ``` ```r vcov(gfit2) ``` -------------------------------- ### Plot Candidate Models (lattice) Source: https://openpharma.github.io/DoseFinding/reference/Mods.html Display the specified candidate model set using the default lattice plotting system. ```R plot(models) ``` -------------------------------- ### Summarize Bootstrap Samples Source: https://openpharma.github.io/DoseFinding/articles/mult_regimen.html Calculates median and quantiles from bootstrap samples to create confidence intervals. Assumes samples are arranged such that rows correspond to dose levels. ```r summarize_bootstrap_samples <- function(samples, probs = c(0.025, 0.25, 0.75, 0.975)) { stopifnot(length(probs) == 4) med <- apply(samples, 1, median) quants <- apply(samples, 1, quantile, probs = probs) bs_df <- as.data.frame(cbind(med, t(quants))) names(bs_df) <- c("median", "low_out", "low_in", "high_in", "high_out") return(bs_df) } ``` -------------------------------- ### Specify Dose-Response Models with Mods Source: https://openpharma.github.io/DoseFinding/articles/analysis_normal.html Define multiple dose-response models (Emax, Sigmoid Emax, Quadratic) with specified parameters and placebo/max effects. Requires the 'doses' argument. ```R doses <- c(0, 12.5, 25, 50, 100) mods <- Mods(emax = c(2.6, 12.5), sigEmax = c(30.5, 3.5), quadratic = -0.00776, placEff = 1.25, maxEff = 0.15, doses = doses) ``` -------------------------------- ### Calculate Constrained Optimal Contrasts with Dose Adjustments Source: https://openpharma.github.io/DoseFinding/reference/optContr.html Calculates constrained optimal contrasts with dose adjustments. This variant uses specific doses, a design matrix 'S', and applies a placebo adjustment. Requires the 'quadprog' package. ```R if(requireNamespace("quadprog", quietly = TRUE)){ optContr(models, doses=dosPlac, S = S, placAdj = TRUE, type = "constrained") } ``` -------------------------------- ### Local Approach with SigEmax Model Source: https://openpharma.github.io/DoseFinding/reference/guesst.html Fits a sigEmax model using the local approach. Requires specifying doses, probabilities, model type, and optionally Maxd. The output can be used to predict effects at different doses. ```r sgE2 <- guesst(d = c(0.2, 0.6), p = c(0.2, 0.95), "sigEmax", local = TRUE, Maxd = 1) sigEmax(c(0.2,0.6), 0, 1, sgE2[1], sgE2[2])/sigEmax(1, 0, 1, sgE2[1], sgE2[2]) ``` ```r models <- Mods(sigEmax = rbind(sgE1, sgE2), doses=c(0,1)) plot(models) ``` -------------------------------- ### Calculate Doses for Target Improvement (Discrete) Source: https://openpharma.github.io/DoseFinding/reference/Mods.html Find the discrete doses from a predefined set that achieve a specified improvement over placebo, considering the direction of the response. ```R TD(fmodels, Delta=0.3, TDtype = "discrete", doses=doses, direction = "decreasing") ```