diff --git a/.github/workflows/R-CMD-check.yaml b/.github/workflows/R-CMD-check.yaml new file mode 100644 index 0000000..d992654 --- /dev/null +++ b/.github/workflows/R-CMD-check.yaml @@ -0,0 +1,56 @@ +# Runs R CMD check (including the unit tests in tests/testthat) on every push +# and pull request to main. Based on r-lib/actions/examples/check-standard.yaml. +name: R-CMD-check + +on: + push: + branches: [main] + pull_request: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +# Cancel superseded runs on the same branch or pull request +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + R-CMD-check: + name: ${{ matrix.config.os }} (R ${{ matrix.config.r }}) + runs-on: ${{ matrix.config.os }} + timeout-minutes: 60 + strategy: + fail-fast: false + matrix: + config: + - {os: macos-latest, r: 'release'} + - {os: windows-latest, r: 'release'} + - {os: ubuntu-latest, r: 'release'} + - {os: ubuntu-latest, r: 'oldrel-1'} + + env: + GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} + R_KEEP_PKG_SOURCE: yes + + steps: + - uses: actions/checkout@v4 + + - uses: r-lib/actions/setup-pandoc@v2 + + - uses: r-lib/actions/setup-r@v2 + with: + r-version: ${{ matrix.config.r }} + use-public-rspm: true + + - uses: r-lib/actions/setup-r-dependencies@v2 + with: + extra-packages: any::rcmdcheck + needs: check + + - uses: r-lib/actions/check-r-package@v2 + with: + upload-snapshots: true + build_args: 'c("--no-manual", "--compact-vignettes=gs+qpdf")' diff --git a/DESCRIPTION b/DESCRIPTION index b453d1b..1e2087a 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,7 +1,7 @@ Type: Package Package: darthtools Title: Decision Analysis Helper Tools for the 'DARTH' Workgroup -Version: 0.4.0 +Version: 0.4.1 Authors@R: c( person("Fernando", "Alarid-Escudero", , "falarid@stanford.edu", role = c("aut", "cre"), comment = c(ORCID = "0000-0001-5076-1172")), @@ -44,6 +44,7 @@ Imports: ggridges, reshape2, magrittr, + MASS, matrixStats, msm, muhaz, @@ -64,6 +65,7 @@ Suggests: rhub, rmarkdown, spelling, + testthat (>= 3.0.0), urlchecker VignetteBuilder: knitr @@ -71,4 +73,5 @@ Encoding: UTF-8 Language: en-US LazyData: true Roxygen: list(markdown = TRUE) -RoxygenNote: 7.3.3 +Config/testthat/edition: 3 +Config/roxygen2/version: 8.0.0 diff --git a/NAMESPACE b/NAMESPACE index 670e887..765b1de 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -94,6 +94,7 @@ importFrom(muhaz,muhaz) importFrom(rlang,.data) importFrom(scales,comma) importFrom(scales,dollar_format) +importFrom(stats,coef) importFrom(stats,density) importFrom(stats,model.frame) importFrom(stats,model.matrix) @@ -105,6 +106,7 @@ importFrom(stats,pweibull) importFrom(stats,quantile) importFrom(stats,runif) importFrom(stats,time) +importFrom(stats,vcov) importFrom(stringr,str_sub) importFrom(survHE,fit.models) importFrom(survival,Surv) diff --git a/NEWS.md b/NEWS.md index dd40cbe..5539f72 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,3 +1,34 @@ +# darthtools 0.4.1 + +## Bug fixes + +* `gen_wcc(method = "Simpson1/3")` assigned the 4/3 and 2/3 weights by + position in the 1-based R vector instead of by time t = 0, 1, ..., n. It + returned `1/3, 2/3, 4/3, 2/3, ..., 1/3` instead of `1/3, 4/3, 2/3, 4/3, ..., + 1/3`, and the weights summed to n - 2/3 (even n) or n - 1/3 (odd n) instead + of n. Weights are now indexed by time. Reported independently by Lauren N. + Steimle (Georgia Institute of Technology) and @ambtnhlr + (DARTH-git/cohort-modeling-tutorial-intro#2). Thank you both. + +## Changes in behaviour + +* For an odd number of cycles, `gen_wcc(method = "Simpson1/3")` now applies + the composite Simpson's 1/3 rule over the first n - 3 cycles and Simpson's + 3/8 rule over the last three, so polynomials up to degree three are still + integrated exactly. +* `gen_wcc()` now errors when `n_cycles` is not a single positive integer, and + when `n_cycles = 1` is used with Simpson's rule. + +## Infrastructure + +* Added unit tests with testthat (3rd edition), starting with `gen_wcc()`. +* Added a GitHub Actions workflow that runs `R CMD check` on every push and + pull request to `main`. +* Fixed pre-existing `R CMD check` warnings: `surv_prob()` no longer calls + `require("MASS")` (MASS is now in Imports), and the `B` argument of + `surv_prob()` and the `v_n_states` argument of `plot_trace_microsim()` are + now documented. + # darthtools 0.4.0 ### Breaking change (with deprecation) diff --git a/R/survival_functions.R b/R/survival_functions.R index dc860b9..90d50dc 100644 --- a/R/survival_functions.R +++ b/R/survival_functions.R @@ -537,14 +537,14 @@ partsurv <- function(pfs_survHE = NULL, os_survHE = NULL, l_d.data = NULL, l_vc. #' #' @param model survival model. #' @param times time horizon to calculate survival probabilities. -#' @param PA run probabilistic analysis. +#' @param PA run probabilistic analysis. Default = FALSE. #' @param rx determines which treatment arm (same order as factor levels of treatment variable). -#' Default = FALSE. +#' @param B number of parameter samples to draw from the multivariate normal +#' distribution of the model coefficients when \code{PA = TRUE}. #' @return #' vector of survival probabilities. #' @export surv_prob <- function(model, times = NULL, PA = FALSE, rx = 1, B = NULL) { - require("MASS") if (PA) { diff --git a/R/visualization.R b/R/visualization.R index 19597c6..64a6a83 100644 --- a/R/visualization.R +++ b/R/visualization.R @@ -27,6 +27,7 @@ plot_te <- function(te) { #' \code{plot_trace_microsim} plots cohort trace of a microsimulation model. #' #' @param m_M a cohort trace matrix +#' @param v_n_states vector of health state names. Defaults to \code{v_names_states}. #' @return a plot of the cohort trace #' @export plot_trace_microsim <- function(m_M, v_n_states = v_names_states) { diff --git a/R/within_cycle_corrections.R b/R/within_cycle_corrections.R index f5398b6..edfde58 100644 --- a/R/within_cycle_corrections.R +++ b/R/within_cycle_corrections.R @@ -2,15 +2,26 @@ #' #' \code{gen_wcc} generates a vector of within-cycle corrections (WCC). #' -#' @param n_cycles number of cycles +#' @param n_cycles number of cycles (a single positive integer). The returned +#' vector has one entry per time point \eqn{t = 0, 1, \ldots, n_T}. #' @param method The method to be used for within-cycle correction. #' -#' @return A vector of length \code{n_cycles + 1} with within-cycle corrections +#' @return A vector of length \code{n_cycles + 1} with within-cycle corrections, +#' where the \eqn{i}-th entry corresponds to time \eqn{t = i - 1}. #' #' @details -#' The default method is an implementation of Simpson's 1/3rd rule that -#' generates a vector with the first and last entry with 1/3 and the odd and -#' even entries with 4/3 and 2/3, respectively. +#' The default method, "\code{Simpson1/3}", is an implementation of Simpson's +#' 1/3rd rule. Weights are assigned by \emph{time} \eqn{t}, not by position in +#' the (1-based) R vector: the first (\eqn{t = 0}) and last (\eqn{t = n_T}) +#' entries get 1/3, entries at odd times (\eqn{t = 1, 3, 5, \ldots}) get 4/3, +#' and entries at even times (\eqn{t = 2, 4, \ldots}) get 2/3, i.e., +#' \deqn{wcc = [1/3, 4/3, 2/3, 4/3, \ldots, 4/3, 1/3].} +#' Simpson's 1/3rd rule requires an even number of cycles. When +#' \code{n_cycles} is odd, the composite Simpson's 1/3rd rule is applied over +#' the first \eqn{n_T - 3} cycles and Simpson's 3/8 rule (weights 3/8, 9/8, +#' 9/8, 3/8) over the last three cycles, adding the weights where the two rules +#' meet. Both variants integrate polynomials up to degree three exactly and the +#' weights always sum to \code{n_cycles}. #' #' Method "\code{half-cycle}" is the half-cycle correction method that #' generates a vector with the first and last entry with 1/2 and the rest equal @@ -19,6 +30,15 @@ #' Method "\code{none}" does not implement any within-cycle correction and #' generates a vector with ones. #' +#' @note \code{darthtools} versions up to v0.4.0 assigned the 4/3 and 2/3 +#' Simpson weights by vector position instead of by time, producing +#' \eqn{[1/3, 2/3, 4/3, \ldots, 1/3]}, whose weights sum to \eqn{n_T - 2/3} +#' (even \eqn{n_T}) or \eqn{n_T - 1/3} (odd \eqn{n_T}) instead of \eqn{n_T}. +#' This was fixed in v0.4.1. We +#' thank Lauren N. Steimle (Georgia Institute of Technology) and GitHub user +#' ambtnhlr, who independently identified and reported this error and proposed +#' the correction. +#' #' @references #' \enumerate{ #' \item Elbasha EH, Chhatwal J. Myths and misconceptions of within-cycle @@ -27,41 +47,59 @@ #' \item Elbasha EH, Chhatwal J. Theoretical foundations and practical #' applications of within-cycle correction methods. Med Decis Mak. #' 2016;36(1):115-131. +#' \item Burden RL, Faires JD. Numerical Analysis. 9th ed. Brooks/Cole; 2011. +#' Section 4.3 (Simpson's 1/3 and 3/8 rules). #' } #' #' @examples -#' # Number of cycles -#' n_cycles <- 10 -#' gen_wcc(n_cycles = n_cycles, method = "Simpson1/3") -#' gen_wcc(n_cycles = n_cycles, method = "half-cycle") -#' gen_wcc(n_cycles = n_cycles, method = "none") +#' # Even number of cycles: 1/3 4/3 2/3 4/3 1/3 +#' gen_wcc(n_cycles = 4, method = "Simpson1/3") +#' # Odd number of cycles: Simpson's 1/3 + 3/8 rules +#' gen_wcc(n_cycles = 5, method = "Simpson1/3") +#' # Weights sum to the number of cycles +#' sum(gen_wcc(n_cycles = 10)) +#' gen_wcc(n_cycles = 10, method = "half-cycle") +#' gen_wcc(n_cycles = 10, method = "none") #' #' @export -gen_wcc <- function(n_cycles, method = c("Simpson1/3", "half-cycle", "none")){ - if(n_cycles <= 0){ - stop("Number of cycles should be positive") - } - +gen_wcc <- function(n_cycles, method = c("Simpson1/3", "half-cycle", "none")) { method <- match.arg(method) - + if (length(n_cycles) != 1 || !is.numeric(n_cycles) || is.na(n_cycles) || + n_cycles < 1 || n_cycles != round(n_cycles)) { + stop("`n_cycles` should be a single positive integer") + } n_cycles <- as.integer(n_cycles) - - if (method == "Simpson1/3"){ - ## Vector with cycles - v_cycles <- seq(1, n_cycles + 1) - ## Generate 2/3 and 4/3 multipliers for even and odd entries, respectively - v_wcc <- ((v_cycles %% 2)==0)*(2/3) + ((v_cycles %% 2)!=0)*(4/3) - ## Substitute 1/3 in first and last entries - v_wcc[1] <- v_wcc[n_cycles + 1] <- 1/3 + + if (method == "Simpson1/3") { + if (n_cycles < 2) { + stop("Simpson's rule requires `n_cycles` >= 2; ", + "use method = \"half-cycle\" for a single cycle") + } + ## Composite Simpson's 1/3 weights for an even number of cycles `n`, + ## indexed by time t = 0, 1, ..., n + simpson13 <- function(n) { + v_t <- 0:n + v_w <- ifelse(v_t %% 2 == 1, 4/3, 2/3) # 4/3 at odd times, 2/3 at even times + v_w[c(1, n + 1)] <- 1/3 # 1/3 at t = 0 and t = n + v_w + } + if (n_cycles %% 2 == 0) { + v_wcc <- simpson13(n_cycles) + } else { + ## Odd number of cycles: Simpson's 1/3 on [0, n - 3] and 3/8 on [n - 3, n] + v_wcc <- numeric(n_cycles + 1) + if (n_cycles >= 5) { + v_wcc[1:(n_cycles - 2)] <- simpson13(n_cycles - 3) + } + v_idx_38 <- (n_cycles - 2):(n_cycles + 1) # positions of t = n-3, ..., n + v_wcc[v_idx_38] <- v_wcc[v_idx_38] + c(3/8, 9/8, 9/8, 3/8) + } } - if (method == "half-cycle"){ - ## Initialize within-cycle correction vector + if (method == "half-cycle") { v_wcc <- rep(1, n_cycles + 1) - ## Within-cycle correction weights for first and last cycle v_wcc[1] <- v_wcc[n_cycles + 1] <- 0.5 } - if (method == "none"){ - ## Initialize within-cycle correction vector + if (method == "none") { v_wcc <- rep(1, n_cycles + 1) } return(v_wcc) diff --git a/R/zzz_imports.R b/R/zzz_imports.R index 554b214..e96fcbf 100644 --- a/R/zzz_imports.R +++ b/R/zzz_imports.R @@ -12,6 +12,6 @@ #' @importFrom data.table rbindlist #' @importFrom msm msm prevalence.msm #' @importFrom graphics legend lines matlines matplot title -#' @importFrom stats density model.frame model.matrix na.omit pexp pgamma plnorm pweibull quantile runif time +#' @importFrom stats coef density model.frame model.matrix na.omit pexp pgamma plnorm pweibull quantile runif time vcov #' @importFrom utils capture.output modifyList getFromNamespace globalVariables NULL diff --git a/man/gen_wcc.Rd b/man/gen_wcc.Rd index 41e4d57..26e36a8 100644 --- a/man/gen_wcc.Rd +++ b/man/gen_wcc.Rd @@ -7,20 +7,31 @@ gen_wcc(n_cycles, method = c("Simpson1/3", "half-cycle", "none")) } \arguments{ -\item{n_cycles}{number of cycles} +\item{n_cycles}{number of cycles (a single positive integer). The returned +vector has one entry per time point \eqn{t = 0, 1, \ldots, n_T}.} \item{method}{The method to be used for within-cycle correction.} } \value{ -A vector of length \code{n_cycles + 1} with within-cycle corrections +A vector of length \code{n_cycles + 1} with within-cycle corrections, +where the \eqn{i}-th entry corresponds to time \eqn{t = i - 1}. } \description{ \code{gen_wcc} generates a vector of within-cycle corrections (WCC). } \details{ -The default method is an implementation of Simpson's 1/3rd rule that -generates a vector with the first and last entry with 1/3 and the odd and -even entries with 4/3 and 2/3, respectively. +The default method, "\code{Simpson1/3}", is an implementation of Simpson's +1/3rd rule. Weights are assigned by \emph{time} \eqn{t}, not by position in +the (1-based) R vector: the first (\eqn{t = 0}) and last (\eqn{t = n_T}) +entries get 1/3, entries at odd times (\eqn{t = 1, 3, 5, \ldots}) get 4/3, +and entries at even times (\eqn{t = 2, 4, \ldots}) get 2/3, i.e., +\deqn{wcc = [1/3, 4/3, 2/3, 4/3, \ldots, 4/3, 1/3].} +Simpson's 1/3rd rule requires an even number of cycles. When +\code{n_cycles} is odd, the composite Simpson's 1/3rd rule is applied over +the first \eqn{n_T - 3} cycles and Simpson's 3/8 rule (weights 3/8, 9/8, +9/8, 3/8) over the last three cycles, adding the weights where the two rules +meet. Both variants integrate polynomials up to degree three exactly and the +weights always sum to \code{n_cycles}. Method "\code{half-cycle}" is the half-cycle correction method that generates a vector with the first and last entry with 1/2 and the rest equal @@ -29,12 +40,25 @@ to 1. Method "\code{none}" does not implement any within-cycle correction and generates a vector with ones. } +\note{ +\code{darthtools} versions up to v0.4.0 assigned the 4/3 and 2/3 +Simpson weights by vector position instead of by time, producing +\eqn{[1/3, 2/3, 4/3, \ldots, 1/3]}, whose weights sum to \eqn{n_T - 2/3} +(even \eqn{n_T}) or \eqn{n_T - 1/3} (odd \eqn{n_T}) instead of \eqn{n_T}. +This was fixed in v0.4.1. We +thank Lauren N. Steimle (Georgia Institute of Technology) and GitHub user +ambtnhlr, who independently identified and reported this error and proposed +the correction. +} \examples{ -# Number of cycles -n_cycles <- 10 -gen_wcc(n_cycles = n_cycles, method = "Simpson1/3") -gen_wcc(n_cycles = n_cycles, method = "half-cycle") -gen_wcc(n_cycles = n_cycles, method = "none") +# Even number of cycles: 1/3 4/3 2/3 4/3 1/3 +gen_wcc(n_cycles = 4, method = "Simpson1/3") +# Odd number of cycles: Simpson's 1/3 + 3/8 rules +gen_wcc(n_cycles = 5, method = "Simpson1/3") +# Weights sum to the number of cycles +sum(gen_wcc(n_cycles = 10)) +gen_wcc(n_cycles = 10, method = "half-cycle") +gen_wcc(n_cycles = 10, method = "none") } \references{ @@ -45,5 +69,7 @@ correction: a guide for modelers and decision makers. Pharmacoeconomics. \item Elbasha EH, Chhatwal J. Theoretical foundations and practical applications of within-cycle correction methods. Med Decis Mak. 2016;36(1):115-131. +\item Burden RL, Faires JD. Numerical Analysis. 9th ed. Brooks/Cole; 2011. +Section 4.3 (Simpson's 1/3 and 3/8 rules). } } diff --git a/man/plot_trace_microsim.Rd b/man/plot_trace_microsim.Rd index 01f0740..9b2b3d0 100644 --- a/man/plot_trace_microsim.Rd +++ b/man/plot_trace_microsim.Rd @@ -8,6 +8,8 @@ plot_trace_microsim(m_M, v_n_states = v_names_states) } \arguments{ \item{m_M}{a cohort trace matrix} + +\item{v_n_states}{vector of health state names. Defaults to \code{v_names_states}.} } \value{ a plot of the cohort trace diff --git a/man/surv_prob.Rd b/man/surv_prob.Rd index 6fbe362..775460e 100644 --- a/man/surv_prob.Rd +++ b/man/surv_prob.Rd @@ -4,17 +4,19 @@ \alias{surv_prob} \title{Calculate survival probabilities.} \usage{ -surv_prob(model, times = NULL, PA = FALSE, rx = 1) +surv_prob(model, times = NULL, PA = FALSE, rx = 1, B = NULL) } \arguments{ \item{model}{survival model.} \item{times}{time horizon to calculate survival probabilities.} -\item{PA}{run probabilistic analysis.} +\item{PA}{run probabilistic analysis. Default = FALSE.} -\item{rx}{determines which treatment arm (same order as factor levels of treatment variable). -Default = FALSE.} +\item{rx}{determines which treatment arm (same order as factor levels of treatment variable).} + +\item{B}{number of parameter samples to draw from the multivariate normal +distribution of the model coefficients when \code{PA = TRUE}.} } \value{ vector of survival probabilities. diff --git a/tests/testthat.R b/tests/testthat.R new file mode 100644 index 0000000..0f25eb7 --- /dev/null +++ b/tests/testthat.R @@ -0,0 +1,12 @@ +# This file is part of the standard setup for testthat. +# It is recommended that you do not modify it. +# +# Where should you do additional test configuration? +# Learn more about the roles of various files in: +# * https://r-pkgs.org/testing-design.html#sec-tests-files-overview +# * https://testthat.r-lib.org/articles/special-files.html + +library(testthat) +library(darthtools) + +test_check("darthtools") diff --git a/tests/testthat/test-within_cycle_corrections.R b/tests/testthat/test-within_cycle_corrections.R new file mode 100644 index 0000000..20afac3 --- /dev/null +++ b/tests/testthat/test-within_cycle_corrections.R @@ -0,0 +1,64 @@ +# Tests for gen_wcc() +# Simpson's rules must integrate polynomials of degree <= 3 exactly on [0, n]: +# sum_t w_t * t^k == n^(k + 1) / (k + 1) + +test_that("Simpson 1/3 weights are assigned by time t, not vector position", { + expect_equal(gen_wcc(2, "Simpson1/3"), c(1, 4, 1) / 3) + expect_equal(gen_wcc(4, "Simpson1/3"), c(1, 4, 2, 4, 1) / 3) + expect_equal(gen_wcc(6, "Simpson1/3"), c(1, 4, 2, 4, 2, 4, 1) / 3) + # Entry for t = 1 (second position) must be 4/3 + expect_equal(gen_wcc(10)[2], 4/3) +}) + +test_that("Simpson 1/3 is the default method", { + expect_identical(gen_wcc(10), gen_wcc(10, "Simpson1/3")) +}) + +test_that("odd number of cycles uses Simpson 3/8 on the last three cycles", { + # n = 3: pure Simpson's 3/8 rule + expect_equal(gen_wcc(3), c(3, 9, 9, 3) / 8) + # n = 5: Simpson's 1/3 on [0, 2] plus 3/8 on [2, 5] + expect_equal(gen_wcc(5), c(1/3, 4/3, 1/3 + 3/8, 9/8, 9/8, 3/8)) +}) + +test_that("Simpson weights sum to n and integrate cubics exactly", { + for (n in c(2:12, 74, 75, 100)) { + w <- gen_wcc(n, "Simpson1/3") + v_t <- 0:n + expect_length(w, n + 1) + expect_true(all(w > 0)) + for (k in 0:3) { + expect_equal(sum(w * v_t^k), n^(k + 1) / (k + 1), + label = paste0("n = ", n, ", k = ", k)) + } + } +}) + +test_that("reported examples are fixed", { + w <- gen_wcc(4, "Simpson1/3") + expect_equal(sum(w), 4) # was 3.33 in darthtools <= 0.4.0 + expect_equal(sum(w * (0:4)^2), 64 / 3) # was 17.33 in darthtools <= 0.4.0 +}) + +test_that("half-cycle and none methods are unchanged", { + expect_equal(gen_wcc(4, "half-cycle"), c(0.5, 1, 1, 1, 0.5)) + expect_equal(gen_wcc(1, "half-cycle"), c(0.5, 0.5)) + expect_equal(gen_wcc(4, "none"), rep(1, 5)) + expect_equal(sum(gen_wcc(75, "half-cycle")), 75) +}) + +test_that("invalid inputs give informative errors", { + expect_error(gen_wcc(0), "positive integer") + expect_error(gen_wcc(-3), "positive integer") + expect_error(gen_wcc(7.5), "positive integer") + expect_error(gen_wcc(c(4, 6)), "positive integer") + expect_error(gen_wcc(NA_real_), "positive integer") + expect_error(gen_wcc("10"), "positive integer") + expect_error(gen_wcc(1, "Simpson1/3"), "n_cycles` >= 2") + expect_error(gen_wcc(10, "trapezoid")) +}) + +test_that("integer-valued doubles are accepted", { + # e.g., n_cycles <- (100 - 25) / 1 + expect_equal(gen_wcc((100 - 25) / 1), gen_wcc(75L)) +})